This is autoconf.info, produced by makeinfo version 4.8 fromautoconf.texi.This manual is for GNU Autoconf (version 2.61, 16 November 2006), apackage for creating scripts to configure source code packages usingtemplates and an M4 macro package.Copyright (C) 1992, 1993, 1994, 1995, 1996, 1998, 1999, 2000, 2001,2002, 2003, 2004, 2005, 2006 Free Software Foundation, Inc.Permission is granted to copy, distribute and/or modify thisdocument under the terms of the GNU Free Documentation License,Version 1.2 or any later version published by the Free SoftwareFoundation; with no Invariant Sections, with the Front-Cover textsbeing "A GNU Manual," and with the Back-Cover Texts as in (a)below. A copy of the license is included in the section entitled"GNU Free Documentation License."(a) The FSF's Back-Cover Text is: "You have freedom to copy andmodify this GNU Manual, like GNU software. Copies published bythe Free Software Foundation raise funds for GNU development."INFO-DIR-SECTION Software developmentSTART-INFO-DIR-ENTRY* Autoconf: (autoconf). Create source code configuration scripts.END-INFO-DIR-ENTRYINFO-DIR-SECTION Individual utilitiesSTART-INFO-DIR-ENTRY* autoscan: (autoconf)autoscan Invocation.Semi-automatic `configure.ac' writing* ifnames: (autoconf)ifnames Invocation. Listing conditionals in source.* autoconf: (autoconf)autoconf Invocation.How to create configuration scripts* autoreconf: (autoconf)autoreconf Invocation.Remaking multiple `configure' scripts* autoheader: (autoconf)autoheader Invocation.How to create configuration templates* autom4te: (autoconf)autom4te Invocation.The Autoconf executables backbone* configure: (autoconf)configure Invocation. Configuring a package.* autoupdate: (autoconf)autoupdate Invocation.Automatic update of `configure.ac'* config.status: (autoconf)config.status Invocation. Recreating configurations.* testsuite: (autoconf)testsuite Invocation. Running an Autotest test suite.END-INFO-DIR-ENTRYFile: autoconf.info, Node: Top, Next: Introduction, Up: (dir)Autoconf********This manual is for GNU Autoconf (version 2.61, 16 November 2006), apackage for creating scripts to configure source code packages usingtemplates and an M4 macro package.Copyright (C) 1992, 1993, 1994, 1995, 1996, 1998, 1999, 2000, 2001,2002, 2003, 2004, 2005, 2006 Free Software Foundation, Inc.Permission is granted to copy, distribute and/or modify thisdocument under the terms of the GNU Free Documentation License,Version 1.2 or any later version published by the Free SoftwareFoundation; with no Invariant Sections, with the Front-Cover textsbeing "A GNU Manual," and with the Back-Cover Texts as in (a)below. A copy of the license is included in the section entitled"GNU Free Documentation License."(a) The FSF's Back-Cover Text is: "You have freedom to copy andmodify this GNU Manual, like GNU software. Copies published bythe Free Software Foundation raise funds for GNU development."* Menu:* Introduction:: Autoconf's purpose, strengths, and weaknesses* The GNU Build System:: A set of tools for portable software packages* Making configure Scripts:: How to organize and produce Autoconf scripts* Setup:: Initialization and output* Existing Tests:: Macros that check for particular features* Writing Tests:: How to write new feature checks* Results:: What to do with results from feature checks* Programming in M4:: Layers on top of which Autoconf is written* Writing Autoconf Macros:: Adding new macros to Autoconf* Portable Shell:: Shell script portability pitfalls* Portable Make:: Makefile portability pitfalls* Portable C and C++:: C and C++ portability pitfalls* Manual Configuration:: Selecting features that can't be guessed* Site Configuration:: Local defaults for `configure'* Running configure Scripts:: How to use the Autoconf output* config.status Invocation:: Recreating a configuration* Obsolete Constructs:: Kept for backward compatibility* Using Autotest:: Creating portable test suites* FAQ:: Frequent Autoconf Questions, with answers* History:: History of Autoconf* Copying This Manual:: How to make copies of this manual* Indices:: Indices of symbols, concepts, etc.--- The Detailed Node Listing ---The GNU Build System* Automake:: Escaping makefile hell* Gnulib:: The GNU portability library* Libtool:: Building libraries portably* Pointers:: More info on the GNU build systemMaking `configure' Scripts* Writing configure.ac:: What to put in an Autoconf input file* autoscan Invocation:: Semi-automatic `configure.ac' writing* ifnames Invocation:: Listing the conditionals in source code* autoconf Invocation:: How to create configuration scripts* autoreconf Invocation:: Remaking multiple `configure' scriptsWriting `configure.ac'* Shell Script Compiler:: Autoconf as solution of a problem* Autoconf Language:: Programming in Autoconf* configure.ac Layout:: Standard organization of `configure.ac'Initialization and Output Files* Initializing configure:: Option processing etc.* Notices:: Copyright, version numbers in `configure'* Input:: Where Autoconf should find files* Output:: Outputting results from the configuration* Configuration Actions:: Preparing the output based on results* Configuration Files:: Creating output files* Makefile Substitutions:: Using output variables in makefiles* Configuration Headers:: Creating a configuration header file* Configuration Commands:: Running arbitrary instantiation commands* Configuration Links:: Links depending on the configuration* Subdirectories:: Configuring independent packages together* Default Prefix:: Changing the default installation prefixSubstitutions in Makefiles* Preset Output Variables:: Output variables that are always set* Installation Directory Variables:: Other preset output variables* Changed Directory Variables:: Warnings about `datarootdir'* Build Directories:: Supporting multiple concurrent compiles* Automatic Remaking:: Makefile rules for configuringConfiguration Header Files* Header Templates:: Input for the configuration headers* autoheader Invocation:: How to create configuration templates* Autoheader Macros:: How to specify CPP templatesExisting Tests* Common Behavior:: Macros' standard schemes* Alternative Programs:: Selecting between alternative programs* Files:: Checking for the existence of files* Libraries:: Library archives that might be missing* Library Functions:: C library functions that might be missing* Header Files:: Header files that might be missing* Declarations:: Declarations that may be missing* Structures:: Structures or members that might be missing* Types:: Types that might be missing* Compilers and Preprocessors:: Checking for compiling programs* System Services:: Operating system services* Posix Variants:: Special kludges for specific Posix variants* Erlang Libraries:: Checking for the existence of Erlang librariesCommon Behavior* Standard Symbols:: Symbols defined by the macros* Default Includes:: Includes used by the generic macrosAlternative Programs* Particular Programs:: Special handling to find certain programs* Generic Programs:: How to find other programsLibrary Functions* Function Portability:: Pitfalls with usual functions* Particular Functions:: Special handling to find certain functions* Generic Functions:: How to find other functionsHeader Files* Header Portability:: Collected knowledge on common headers* Particular Headers:: Special handling to find certain headers* Generic Headers:: How to find other headersDeclarations* Particular Declarations:: Macros to check for certain declarations* Generic Declarations:: How to find other declarationsStructures* Particular Structures:: Macros to check for certain structure members* Generic Structures:: How to find other structure membersTypes* Particular Types:: Special handling to find certain types* Generic Types:: How to find other typesCompilers and Preprocessors* Specific Compiler Characteristics:: Some portability issues* Generic Compiler Characteristics:: Language independent tests and features* C Compiler:: Checking its characteristics* C++ Compiler:: Likewise* Objective C Compiler:: Likewise* Erlang Compiler and Interpreter:: Likewise* Fortran Compiler:: LikewiseWriting Tests* Language Choice:: Selecting which language to use for testing* Writing Test Programs:: Forging source files for compilers* Running the Preprocessor:: Detecting preprocessor symbols* Running the Compiler:: Detecting language or header features* Running the Linker:: Detecting library features* Runtime:: Testing for runtime features* Systemology:: A zoology of operating systems* Multiple Cases:: Tests for several possible valuesWriting Test Programs* Guidelines:: General rules for writing test programs* Test Functions:: Avoiding pitfalls in test programs* Generating Sources:: Source program boilerplateResults of Tests* Defining Symbols:: Defining C preprocessor symbols* Setting Output Variables:: Replacing variables in output files* Special Chars in Variables:: Characters to beware of in variables* Caching Results:: Speeding up subsequent `configure' runs* Printing Messages:: Notifying `configure' usersCaching Results* Cache Variable Names:: Shell variables used in caches* Cache Files:: Files `configure' uses for caching* Cache Checkpointing:: Loading and saving the cache fileProgramming in M4* M4 Quotation:: Protecting macros from unwanted expansion* Using autom4te:: The Autoconf executables backbone* Programming in M4sugar:: Convenient pure M4 macros* Programming in M4sh:: Common shell Constructs* File Descriptor Macros:: File descriptor macros for input and outputM4 Quotation* Active Characters:: Characters that change the behavior of M4* One Macro Call:: Quotation and one macro call* Quotation and Nested Macros:: Macros calling macros* Changequote is Evil:: Worse than INTERCAL: M4 + changequote* Quadrigraphs:: Another way to escape special characters* Quotation Rule Of Thumb:: One parenthesis, one quoteUsing `autom4te'* autom4te Invocation:: A GNU M4 wrapper* Customizing autom4te:: Customizing the Autoconf packageProgramming in M4sugar* Redefined M4 Macros:: M4 builtins changed in M4sugar* Looping constructs:: Iteration in M4* Evaluation Macros:: More quotation and evaluation control* Text processing Macros:: String manipulation in M4* Forbidden Patterns:: Catching unexpanded macrosWriting Autoconf Macros* Macro Definitions:: Basic format of an Autoconf macro* Macro Names:: What to call your new macros* Reporting Messages:: Notifying `autoconf' users* Dependencies Between Macros:: What to do when macros depend on other macros* Obsoleting Macros:: Warning about old ways of doing things* Coding Style:: Writing Autoconf macros a` la AutoconfDependencies Between Macros* Prerequisite Macros:: Ensuring required information* Suggested Ordering:: Warning about possible ordering problems* One-Shot Macros:: Ensuring a macro is called only oncePortable Shell Programming* Shellology:: A zoology of shells* Here-Documents:: Quirks and tricks* File Descriptors:: FDs and redirections* File System Conventions:: File names* Shell Substitutions:: Variable and command expansions* Assignments:: Varying side effects of assignments* Parentheses:: Parentheses in shell scripts* Slashes:: Slashes in shell scripts* Special Shell Variables:: Variables you should not change* Limitations of Builtins:: Portable use of not so portable /bin/sh* Limitations of Usual Tools:: Portable use of portable toolsPortable Make Programming* $< in Ordinary Make Rules:: $< in ordinary rules* Failure in Make Rules:: Failing portably in rules* Special Chars in Names:: Special Characters in Macro Names* Backslash-Newline-Newline:: Empty last lines in macro definitions* Backslash-Newline Comments:: Spanning comments across line boundaries* Long Lines in Makefiles:: Line length limitations* Macros and Submakes:: `make macro=value' and submakes* The Make Macro MAKEFLAGS:: `$(MAKEFLAGS)' portability issues* The Make Macro SHELL:: `$(SHELL)' portability issues* Comments in Make Rules:: Other problems with Make comments* obj/ and Make:: Don't name a subdirectory `obj'* make -k Status:: Exit status of `make -k'* VPATH and Make:: `VPATH' woes* Single Suffix Rules:: Single suffix rules and separated dependencies* Timestamps and Make:: Subsecond timestamp resolution`VPATH' and Make* VPATH and Double-colon:: Problems with `::' on ancient hosts* $< in Explicit Rules:: `$<' does not work in ordinary rules* Automatic Rule Rewriting:: `VPATH' goes wild on Solaris* Tru64 Directory Magic:: `mkdir' goes wild on Tru64* Make Target Lookup:: More details about `VPATH' lookupPortable C and C++ Programming* Varieties of Unportability:: How to make your programs unportable* Integer Overflow:: When integers get too large* Null Pointers:: Properties of null pointers* Buffer Overruns:: Subscript errors and the like* Volatile Objects:: `volatile' and signals* Floating Point Portability:: Portable floating-point arithmetic* Exiting Portably:: Exiting and the exit statusManual Configuration* Specifying Names:: Specifying the system type* Canonicalizing:: Getting the canonical system type* Using System Type:: What to do with the system typeSite Configuration* Help Formatting:: Customizing `configure --help'* External Software:: Working with other optional software* Package Options:: Selecting optional features* Pretty Help Strings:: Formatting help string* Site Details:: Configuring site details* Transforming Names:: Changing program names when installing* Site Defaults:: Giving `configure' local defaultsTransforming Program Names When Installing* Transformation Options:: `configure' options to transform names* Transformation Examples:: Sample uses of transforming names* Transformation Rules:: Makefile uses of transforming namesRunning `configure' Scripts* Basic Installation:: Instructions for typical cases* Compilers and Options:: Selecting compilers and optimization* Multiple Architectures:: Compiling for multiple architectures at once* Installation Names:: Installing in different directories* Optional Features:: Selecting optional features* System Type:: Specifying the system type* Sharing Defaults:: Setting site-wide defaults for `configure'* Defining Variables:: Specifying the compiler etc.* configure Invocation:: Changing how `configure' runsObsolete Constructs* Obsolete config.status Use:: Different calling convention* acconfig.h:: Additional entries in `config.h.in'* autoupdate Invocation:: Automatic update of `configure.ac'* Obsolete Macros:: Backward compatibility macros* Autoconf 1:: Tips for upgrading your files* Autoconf 2.13:: Some fresher tipsUpgrading From Version 1* Changed File Names:: Files you might rename* Changed Makefiles:: New things to put in `Makefile.in'* Changed Macros:: Macro calls you might replace* Changed Results:: Changes in how to check test results* Changed Macro Writing:: Better ways to write your own macrosUpgrading From Version 2.13* Changed Quotation:: Broken code which used to work* New Macros:: Interaction with foreign macros* Hosts and Cross-Compilation:: Bugward compatibility kludges* AC_LIBOBJ vs LIBOBJS:: LIBOBJS is a forbidden token* AC_FOO_IFELSE vs AC_TRY_FOO:: A more generic scheme for testing sourcesGenerating Test Suites with Autotest* Using an Autotest Test Suite:: Autotest and the user* Writing testsuite.at:: Autotest macros* testsuite Invocation:: Running `testsuite' scripts* Making testsuite Scripts:: Using autom4te to create `testsuite'Using an Autotest Test Suite* testsuite Scripts:: The concepts of Autotest* Autotest Logs:: Their contentsFrequent Autoconf Questions, with answers* Distributing:: Distributing `configure' scripts* Why GNU M4:: Why not use the standard M4?* Bootstrapping:: Autoconf and GNU M4 require each other?* Why Not Imake:: Why GNU uses `configure' instead of Imake* Defining Directories:: Passing `datadir' to program* autom4te.cache:: What is it? Can I remove it?* Present But Cannot Be Compiled:: Compiler and Preprocessor DisagreeHistory of Autoconf* Genesis:: Prehistory and naming of `configure'* Exodus:: The plagues of M4 and Perl* Leviticus:: The priestly code of portability arrives* Numbers:: Growth and contributors* Deuteronomy:: Approaching the promises of easy configurationCopying This Manual* GNU Free Documentation License:: License for copying this manualIndices* Environment Variable Index:: Index of environment variables used* Output Variable Index:: Index of variables set in output files* Preprocessor Symbol Index:: Index of C preprocessor symbols defined* Autoconf Macro Index:: Index of Autoconf macros* M4 Macro Index:: Index of M4, M4sugar, and M4sh macros* Autotest Macro Index:: Index of Autotest macros* Program & Function Index:: Index of those with portability problems* Concept Index:: General indexFile: autoconf.info, Node: Introduction, Next: The GNU Build System, Prev: Top, Up: Top1 Introduction**************A physicist, an engineer, and a computer scientist were discussing thenature of God. "Surely a Physicist," said the physicist, "becauseearly in the Creation, God made Light; and you know, Maxwell'sequations, the dual nature of electromagnetic waves, the relativisticconsequences..." "An Engineer!," said the engineer, "becausebefore making Light, God split the Chaos into Land and Water; it takes ahell of an engineer to handle that big amount of mud, and orderlyseparation of solids from liquids..." The computer scientistshouted: "And the Chaos, where do you think it was coming from, hmm?"--AnonymousAutoconf is a tool for producing shell scripts that automaticallyconfigure software source code packages to adapt to many kinds ofPosix-like systems. The configuration scripts produced by Autoconf areindependent of Autoconf when they are run, so their users do not needto have Autoconf.The configuration scripts produced by Autoconf require no manual userintervention when run; they do not normally even need an argumentspecifying the system type. Instead, they individually test for thepresence of each feature that the software package they are for mightneed. (Before each check, they print a one-line message stating whatthey are checking for, so the user doesn't get too bored while waitingfor the script to finish.) As a result, they deal well with systemsthat are hybrids or customized from the more common Posix variants.There is no need to maintain files that list the features supported byeach release of each variant of Posix.For each software package that Autoconf is used with, it creates aconfiguration script from a template file that lists the system featuresthat the package needs or can use. After the shell code to recognizeand respond to a system feature has been written, Autoconf allows it tobe shared by many software packages that can use (or need) that feature.If it later turns out that the shell code needs adjustment for somereason, it needs to be changed in only one place; all of theconfiguration scripts can be regenerated automatically to take advantageof the updated code.The Metaconfig package is similar in purpose to Autoconf, but thescripts it produces require manual user intervention, which is quiteinconvenient when configuring large source trees. Unlike Metaconfigscripts, Autoconf scripts can support cross-compiling, if some care istaken in writing them.Autoconf does not solve all problems related to making portablesoftware packages--for a more complete solution, it should be used inconcert with other GNU build tools like Automake and Libtool. Theseother tools take on jobs like the creation of a portable, recursivemakefile with all of the standard targets, linking of shared libraries,and so on. *Note The GNU Build System::, for more information.Autoconf imposes some restrictions on the names of macros used with`#if' in C programs (*note Preprocessor Symbol Index::).Autoconf requires GNU M4 in order to generate the scripts. It usesfeatures that some versions of M4, including GNU M4 1.3, do not have.You should use version 1.4.7 or later of GNU M4.*Note Autoconf 1::, for information about upgrading from version 1.*Note History::, for the story of Autoconf's development. *Note FAQ::,for answers to some common questions about Autoconf.See the Autoconf web page (http://www.gnu.org/software/autoconf/)for up-to-date information, details on the mailing lists, pointers to alist of known bugs, etc.Mail suggestions to the Autoconf mailing list <autoconf@gnu.org>.Past suggestions are archived(http://lists.gnu.org/archive/html/autoconf/).Mail bug reports to the Autoconf Bugs mailing list<bug-autoconf@gnu.org>. Past bug reports are archived(http://lists.gnu.org/archive/html/bug-autoconf/).If possible, first check that your bug is not already solved incurrent development versions, and that it has not been reported yet.Be sure to include all the needed information and a short`configure.ac' that demonstrates the problem.Autoconf's development tree is accessible via anonymous CVS; see theAutoconf Summary (http://savannah.gnu.org/projects/autoconf/) fordetails. Patches relative to the current CVS version can be sent forreview to the Autoconf Patches mailing list <autoconf-patches@gnu.org>.Past patches are archived(http://lists.gnu.org/archive/html/autoconf-patches/).Because of its mission, the Autoconf package itself includes only aset of often-used macros that have already demonstrated theirusefulness. Nevertheless, if you wish to share your macros, or findexisting ones, see the Autoconf Macro Archive(http://autoconf-archive.cryp.to/), which is kindly run by Peter Simons<simons@cryp.to>.File: autoconf.info, Node: The GNU Build System, Next: Making configure Scripts, Prev: Introduction, Up: Top2 The GNU Build System**********************Autoconf solves an important problem--reliable discovery ofsystem-specific build and runtime information--but this is only onepiece of the puzzle for the development of portable software. To thisend, the GNU project has developed a suite of integrated utilities tofinish the job Autoconf started: the GNU build system, whose mostimportant components are Autoconf, Automake, and Libtool. In thischapter, we introduce you to those tools, point you to sources of moreinformation, and try to convince you to use the entire GNU build systemfor your software.* Menu:* Automake:: Escaping makefile hell* Gnulib:: The GNU portability library* Libtool:: Building libraries portably* Pointers:: More info on the GNU build systemFile: autoconf.info, Node: Automake, Next: Gnulib, Up: The GNU Build System2.1 Automake============The ubiquity of `make' means that a makefile is almost the only viableway to distribute automatic build rules for software, but one quicklyruns into its numerous limitations. Its lack of support for automaticdependency tracking, recursive builds in subdirectories, reliabletimestamps (e.g., for network file systems), and so on, mean thatdevelopers must painfully (and often incorrectly) reinvent the wheelfor each project. Portability is non-trivial, thanks to the quirks of`make' on many systems. On top of all this is the manual laborrequired to implement the many standard targets that users have come toexpect (`make install', `make distclean', `make uninstall', etc.).Since you are, of course, using Autoconf, you also have to insertrepetitive code in your `Makefile.in' to recognize `@CC@', `@CFLAGS@',and other substitutions provided by `configure'. Into this mess steps"Automake".Automake allows you to specify your build needs in a `Makefile.am'file with a vastly simpler and more powerful syntax than that of a plainmakefile, and then generates a portable `Makefile.in' for use withAutoconf. For example, the `Makefile.am' to build and install a simple"Hello world" program might look like:bin_PROGRAMS = hellohello_SOURCES = hello.cThe resulting `Makefile.in' (~400 lines) automatically supports all thestandard targets, the substitutions provided by Autoconf, automaticdependency tracking, `VPATH' building, and so on. `make' builds the`hello' program, and `make install' installs it in `/usr/local/bin' (orwhatever prefix was given to `configure', if not `/usr/local').The benefits of Automake increase for larger packages (especiallyones with subdirectories), but even for small programs the addedconvenience and portability can be substantial. And that's not all....File: autoconf.info, Node: Gnulib, Next: Libtool, Prev: Automake, Up: The GNU Build System2.2 Gnulib==========GNU software has a well-deserved reputation for running on manydifferent types of systems. While our primary goal is to writesoftware for the GNU system, many users and developers have beenintroduced to us through the systems that they were already using.Gnulib is a central location for common GNU code, intended to beshared among free software packages. Its components are typicallyshared at the source level, rather than being a library that gets built,installed, and linked against. The idea is to copy files from Gnulibinto your own source tree. There is no distribution tarball; developersshould just grab source modules from the repository. The source filesare available online, under various licenses, mostly GNU GPL or GNULGPL.Gnulib modules typically contain C source code along with Autoconfmacros used to configure the source code. For example, the Gnulib`stdbool' module implements a `stdbool.h' header that nearly conformsto C99, even on old-fashioned hosts that lack `stdbool.h'. This modulecontains a source file for the replacement header, along with anAutoconf macro that arranges to use the replacement header onold-fashioned systems.File: autoconf.info, Node: Libtool, Next: Pointers, Prev: Gnulib, Up: The GNU Build System2.3 Libtool===========Often, one wants to build not only programs, but libraries, so thatother programs can benefit from the fruits of your labor. Ideally, onewould like to produce _shared_ (dynamically linked) libraries, whichcan be used by multiple programs without duplication on disk or inmemory and can be updated independently of the linked programs.Producing shared libraries portably, however, is the stuff ofnightmares--each system has its own incompatible tools, compiler flags,and magic incantations. Fortunately, GNU provides a solution:"Libtool".Libtool handles all the requirements of building shared libraries foryou, and at this time seems to be the _only_ way to do so with anyportability. It also handles many other headaches, such as: theinteraction of Make rules with the variable suffixes of sharedlibraries, linking reliably with shared libraries before they areinstalled by the superuser, and supplying a consistent versioning system(so that different versions of a library can be installed or upgradedwithout breaking binary compatibility). Although Libtool, likeAutoconf, can be used without Automake, it is most simply utilized inconjunction with Automake--there, Libtool is used automaticallywhenever shared libraries are needed, and you need not know its syntax.File: autoconf.info, Node: Pointers, Prev: Libtool, Up: The GNU Build System2.4 Pointers============Developers who are used to the simplicity of `make' for small projectson a single system might be daunted at the prospect of learning to useAutomake and Autoconf. As your software is distributed to more andmore users, however, you otherwise quickly find yourself putting lotsof effort into reinventing the services that the GNU build toolsprovide, and making the same mistakes that they once made and overcame.(Besides, since you're already learning Autoconf, Automake is a pieceof cake.)There are a number of places that you can go to for more informationon the GNU build tools.- WebThe home pages for Autoconf(http://www.gnu.org/software/autoconf/), Automake(http://www.gnu.org/software/automake/), Gnulib(http://www.gnu.org/software/gnulib/), and Libtool(http://www.gnu.org/software/libtool/).- Automake Manual*Note Automake: (automake)Top, for more information on Automake.- BooksThe book `GNU Autoconf, Automake and Libtool'(1) describes thecomplete GNU build environment. You can also find the entire bookon-line (http://sources.redhat.com/autobook/).---------- Footnotes ----------(1) `GNU Autoconf, Automake and Libtool', by G. V. Vaughan, B.Elliston, T. Tromey, and I. L. Taylor. SAMS (originally New Riders),2000, ISBN 1578701902.File: autoconf.info, Node: Making configure Scripts, Next: Setup, Prev: The GNU Build System, Up: Top3 Making `configure' Scripts****************************The configuration scripts that Autoconf produces are by conventioncalled `configure'. When run, `configure' creates several files,replacing configuration parameters in them with appropriate values.The files that `configure' creates are:- one or more `Makefile' files, usually one in each subdirectory ofthe package (*note Makefile Substitutions::);- optionally, a C header file, the name of which is configurable,containing `#define' directives (*note Configuration Headers::);- a shell script called `config.status' that, when run, recreatesthe files listed above (*note config.status Invocation::);- an optional shell script normally called `config.cache' (createdwhen using `configure --config-cache') that saves the results ofrunning many of the tests (*note Cache Files::);- a file called `config.log' containing any messages produced bycompilers, to help debugging if `configure' makes a mistake.To create a `configure' script with Autoconf, you need to write anAutoconf input file `configure.ac' (or `configure.in') and run`autoconf' on it. If you write your own feature tests to supplementthose that come with Autoconf, you might also write files called`aclocal.m4' and `acsite.m4'. If you use a C header file to contain`#define' directives, you might also run `autoheader', and you candistribute the generated file `config.h.in' with the package.Here is a diagram showing how the files that can be used inconfiguration are produced. Programs that are executed are suffixed by`*'. Optional files are enclosed in square brackets (`[]').`autoconf' and `autoheader' also read the installed Autoconf macrofiles (by reading `autoconf.m4').Files used in preparing a software package for distribution:your source files --> [autoscan*] --> [configure.scan] --> configure.acconfigure.ac --.| .------> autoconf* -----> configure[aclocal.m4] --+---+| `-----> [autoheader*] --> [config.h.in][acsite.m4] ---'Makefile.in -------------------------------> Makefile.inFiles used in configuring a software package:.-------------> [config.cache]configure* ------------+-------------> config.log|[config.h.in] -. v .-> [config.h] -.+--> config.status* -+ +--> make*Makefile.in ---' `-> Makefile ---'* Menu:* Writing configure.ac:: What to put in an Autoconf input file* autoscan Invocation:: Semi-automatic `configure.ac' writing* ifnames Invocation:: Listing the conditionals in source code* autoconf Invocation:: How to create configuration scripts* autoreconf Invocation:: Remaking multiple `configure' scriptsFile: autoconf.info, Node: Writing configure.ac, Next: autoscan Invocation, Up: Making configure Scripts3.1 Writing `configure.ac'==========================To produce a `configure' script for a software package, create a filecalled `configure.ac' that contains invocations of the Autoconf macrosthat test the system features your package needs or can use. Autoconfmacros already exist to check for many features; see *Note ExistingTests::, for their descriptions. For most other features, you can useAutoconf template macros to produce custom checks; see *Note WritingTests::, for information about them. For especially tricky orspecialized features, `configure.ac' might need to contain somehand-crafted shell commands; see *Note Portable Shell::. The`autoscan' program can give you a good start in writing `configure.ac'(*note autoscan Invocation::, for more information).Previous versions of Autoconf promoted the name `configure.in',which is somewhat ambiguous (the tool needed to process this file is notdescribed by its extension), and introduces a slight confusion with`config.h.in' and so on (for which `.in' means "to be processed by`configure'"). Using `configure.ac' is now preferred.* Menu:* Shell Script Compiler:: Autoconf as solution of a problem* Autoconf Language:: Programming in Autoconf* configure.ac Layout:: Standard organization of `configure.ac'File: autoconf.info, Node: Shell Script Compiler, Next: Autoconf Language, Up: Writing configure.ac3.1.1 A Shell Script Compiler-----------------------------Just as for any other computer language, in order to properly program`configure.ac' in Autoconf you must understand _what_ problem thelanguage tries to address and _how_ it does so.The problem Autoconf addresses is that the world is a mess. Afterall, you are using Autoconf in order to have your package compileeasily on all sorts of different systems, some of them being extremelyhostile. Autoconf itself bears the price for these differences:`configure' must run on all those systems, and thus `configure' mustlimit itself to their lowest common denominator of features.Naturally, you might then think of shell scripts; who needs`autoconf'? A set of properly written shell functions is enough tomake it easy to write `configure' scripts by hand. Sigh!Unfortunately, shell functions do not belong to the least commondenominator; therefore, where you would like to define a function anduse it ten times, you would instead need to copy its body ten times.So, what is really needed is some kind of compiler, `autoconf', thattakes an Autoconf program, `configure.ac', and transforms it into aportable shell script, `configure'.How does `autoconf' perform this task?There are two obvious possibilities: creating a brand new language orextending an existing one. The former option is attractive: all sortsof optimizations could easily be implemented in the compiler and manyrigorous checks could be performed on the Autoconf program (e.g.,rejecting any non-portable construct). Alternatively, you can extendan existing language, such as the `sh' (Bourne shell) language.Autoconf does the latter: it is a layer on top of `sh'. It wastherefore most convenient to implement `autoconf' as a macro expander:a program that repeatedly performs "macro expansions" on text input,replacing macro calls with macro bodies and producing a pure `sh'script in the end. Instead of implementing a dedicated Autoconf macroexpander, it is natural to use an existing general-purpose macrolanguage, such as M4, and implement the extensions as a set of M4macros.File: autoconf.info, Node: Autoconf Language, Next: configure.ac Layout, Prev: Shell Script Compiler, Up: Writing configure.ac3.1.2 The Autoconf Language---------------------------The Autoconf language differs from many other computer languagesbecause it treats actual code the same as plain text. Whereas in C,for instance, data and instructions have different syntactic status, inAutoconf their status is rigorously the same. Therefore, we need ameans to distinguish literal strings from text to be expanded:quotation.When calling macros that take arguments, there must not be any whitespace between the macro name and the open parenthesis. Arguments shouldbe enclosed within the M4 quote characters `[' and `]', and beseparated by commas. Any leading blanks or newlines in arguments areignored, unless they are quoted. You should always quote an argumentthat might contain a macro name, comma, parenthesis, or a leading blankor newline. This rule applies recursively for every macro call,including macros called from other macros.For instance:AC_CHECK_HEADER([stdio.h],[AC_DEFINE([HAVE_STDIO_H], [1],[Define to 1 if you have <stdio.h>.])],[AC_MSG_ERROR([Sorry, can't do anything for you])])is quoted properly. You may safely simplify its quotation to:AC_CHECK_HEADER([stdio.h],[AC_DEFINE([HAVE_STDIO_H], 1,[Define to 1 if you have <stdio.h>.])],[AC_MSG_ERROR([Sorry, can't do anything for you])])because `1' cannot contain a macro call. Here, the argument of`AC_MSG_ERROR' must be quoted; otherwise, its comma would beinterpreted as an argument separator. Also, the second and thirdarguments of `AC_CHECK_HEADER' must be quoted, since they contain macrocalls. The three arguments `HAVE_STDIO_H', `stdio.h', and `Define to 1if you have <stdio.h>.' do not need quoting, but if you unwiselydefined a macro with a name like `Define' or `stdio' then they wouldneed quoting. Cautious Autoconf users would keep the quotes, but manyAutoconf users find such precautions annoying, and would rewrite theexample as follows:AC_CHECK_HEADER(stdio.h,[AC_DEFINE(HAVE_STDIO_H, 1,[Define to 1 if you have <stdio.h>.])],[AC_MSG_ERROR([Sorry, can't do anything for you])])This is safe, so long as you adopt good naming conventions and do notdefine macros with names like `HAVE_STDIO_H', `stdio', or `h'. Thoughit is also safe here to omit the quotes around `Define to 1 if you have<stdio.h>.' this is not recommended, as message strings are more likelyto inadvertently contain commas.The following example is wrong and dangerous, as it is underquoted:AC_CHECK_HEADER(stdio.h,AC_DEFINE(HAVE_STDIO_H, 1,Define to 1 if you have <stdio.h>.),AC_MSG_ERROR([Sorry, can't do anything for you]))In other cases, you may have to use text that also resembles a macrocall. You must quote that text even when it is not passed as a macroargument:echo "Hard rock was here! --[AC_DC]"which results in:echo "Hard rock was here! --AC_DC"When you use the same text in a macro argument, you must therefore havean extra quotation level (since one is stripped away by the macrosubstitution). In general, then, it is a good idea to _use doublequoting for all literal string arguments_:AC_MSG_WARN([[AC_DC stinks --Iron Maiden]])You are now able to understand one of the constructs of Autoconf thathas been continually misunderstood... The rule of thumb is that_whenever you expect macro expansion, expect quote expansion_; i.e.,expect one level of quotes to be lost. For instance:AC_COMPILE_IFELSE([char b[10];], [], [AC_MSG_ERROR([you lose])])is incorrect: here, the first argument of `AC_COMPILE_IFELSE' is `charb[10];' and is expanded once, which results in `char b10;'. (There wasan idiom common in Autoconf's past to address this issue via the M4`changequote' primitive, but do not use it!) Let's take a closer look:the author meant the first argument to be understood as a literal, andtherefore it must be quoted twice:AC_COMPILE_IFELSE([[char b[10];]], [], [AC_MSG_ERROR([you lose])])Voila`, you actually produce `char b[10];' this time!On the other hand, descriptions (e.g., the last parameter of`AC_DEFINE' or `AS_HELP_STRING') are not literals--they are subject toline breaking, for example--and should not be double quoted. Even ifthese descriptions are short and are not actually broken, doublequoting them yields weird results.Some macros take optional arguments, which this documentationrepresents as [ARG] (not to be confused with the quote characters).You may just leave them empty, or use `[]' to make the emptiness of theargument explicit, or you may simply omit the trailing commas. Thethree lines below are equivalent:AC_CHECK_HEADERS([stdio.h], [], [], [])AC_CHECK_HEADERS([stdio.h],,,)AC_CHECK_HEADERS([stdio.h])It is best to put each macro call on its own line in `configure.ac'.Most of the macros don't add extra newlines; they rely on the newlineafter the macro call to terminate the commands. This approach makesthe generated `configure' script a little easier to read by notinserting lots of blank lines. It is generally safe to set shellvariables on the same line as a macro call, because the shell allowsassignments without intervening newlines.You can include comments in `configure.ac' files by starting themwith the `#'. For example, it is helpful to begin `configure.ac' fileswith a line like this:# Process this file with autoconf to produce a configure script.File: autoconf.info, Node: configure.ac Layout, Prev: Autoconf Language, Up: Writing configure.ac3.1.3 Standard `configure.ac' Layout------------------------------------The order in which `configure.ac' calls the Autoconf macros is notimportant, with a few exceptions. Every `configure.ac' must contain acall to `AC_INIT' before the checks, and a call to `AC_OUTPUT' at theend (*note Output::). Additionally, some macros rely on other macroshaving been called first, because they check previously set values ofsome variables to decide what to do. These macros are noted in theindividual descriptions (*note Existing Tests::), and they also warnyou when `configure' is created if they are called out of order.To encourage consistency, here is a suggested order for calling theAutoconf macros. Generally speaking, the things near the end of thislist are those that could depend on things earlier in it. For example,library functions could be affected by types and libraries.Autoconf requirements`AC_INIT(PACKAGE, VERSION, BUG-REPORT-ADDRESS)'information on the packagechecks for programschecks for librarieschecks for header fileschecks for typeschecks for structureschecks for compiler characteristicschecks for library functionschecks for system services`AC_CONFIG_FILES([FILE...])'`AC_OUTPUT'File: autoconf.info, Node: autoscan Invocation, Next: ifnames Invocation, Prev: Writing configure.ac, Up: Making configure Scripts3.2 Using `autoscan' to Create `configure.ac'=============================================The `autoscan' program can help you create and/or maintain a`configure.ac' file for a software package. `autoscan' examines sourcefiles in the directory tree rooted at a directory given as a commandline argument, or the current directory if none is given. It searchesthe source files for common portability problems and creates a file`configure.scan' which is a preliminary `configure.ac' for thatpackage, and checks a possibly existing `configure.ac' for completeness.When using `autoscan' to create a `configure.ac', you shouldmanually examine `configure.scan' before renaming it to `configure.ac';it probably needs some adjustments. Occasionally, `autoscan' outputs amacro in the wrong order relative to another macro, so that `autoconf'produces a warning; you need to move such macros manually. Also, ifyou want the package to use a configuration header file, you must add acall to `AC_CONFIG_HEADERS' (*note Configuration Headers::). You mightalso have to change or add some `#if' directives to your program inorder to make it work with Autoconf (*note ifnames Invocation::, forinformation about a program that can help with that job).When using `autoscan' to maintain a `configure.ac', simply consideradding its suggestions. The file `autoscan.log' contains detailedinformation on why a macro is requested.`autoscan' uses several data files (installed along with Autoconf)to determine which macros to output when it finds particular symbols ina package's source files. These data files all have the same format:each line consists of a symbol, one or more blanks, and the Autoconfmacro to output if that symbol is encountered. Lines starting with `#'are comments.`autoscan' accepts the following options:`--help'`-h'Print a summary of the command line options and exit.`--version'`-V'Print the version number of Autoconf and exit.`--verbose'`-v'Print the names of the files it examines and the potentiallyinteresting symbols it finds in them. This output can bevoluminous.`--include=DIR'`-I DIR'Append DIR to the include path. Multiple invocations accumulate.`--prepend-include=DIR'`-B DIR'Prepend DIR to the include path. Multiple invocations accumulate.File: autoconf.info, Node: ifnames Invocation, Next: autoconf Invocation, Prev: autoscan Invocation, Up: Making configure Scripts3.3 Using `ifnames' to List Conditionals========================================`ifnames' can help you write `configure.ac' for a software package. Itprints the identifiers that the package already uses in C preprocessorconditionals. If a package has already been set up to have someportability, `ifnames' can thus help you figure out what its`configure' needs to check for. It may help fill in some gaps in a`configure.ac' generated by `autoscan' (*note autoscan Invocation::).`ifnames' scans all of the C source files named on the command line(or the standard input, if none are given) and writes to the standardoutput a sorted list of all the identifiers that appear in those filesin `#if', `#elif', `#ifdef', or `#ifndef' directives. It prints eachidentifier on a line, followed by a space-separated list of the filesin which that identifier occurs.`ifnames' accepts the following options:`--help'`-h'Print a summary of the command line options and exit.`--version'`-V'Print the version number of Autoconf and exit.File: autoconf.info, Node: autoconf Invocation, Next: autoreconf Invocation, Prev: ifnames Invocation, Up: Making configure Scripts3.4 Using `autoconf' to Create `configure'==========================================To create `configure' from `configure.ac', run the `autoconf' programwith no arguments. `autoconf' processes `configure.ac' with the M4macro processor, using the Autoconf macros. If you give `autoconf' anargument, it reads that file instead of `configure.ac' and writes theconfiguration script to the standard output instead of to `configure'.If you give `autoconf' the argument `-', it reads from the standardinput instead of `configure.ac' and writes the configuration script tothe standard output.The Autoconf macros are defined in several files. Some of the filesare distributed with Autoconf; `autoconf' reads them first. Then itlooks for the optional file `acsite.m4' in the directory that containsthe distributed Autoconf macro files, and for the optional file`aclocal.m4' in the current directory. Those files can contain yoursite's or the package's own Autoconf macro definitions (*note WritingAutoconf Macros::, for more information). If a macro is defined inmore than one of the files that `autoconf' reads, the last definitionit reads overrides the earlier ones.`autoconf' accepts the following options:`--help'`-h'Print a summary of the command line options and exit.`--version'`-V'Print the version number of Autoconf and exit.`--verbose'`-v'Report processing steps.`--debug'`-d'Don't remove the temporary files.`--force'`-f'Remake `configure' even if newer than its input files.`--include=DIR'`-I DIR'Append DIR to the include path. Multiple invocations accumulate.`--prepend-include=DIR'`-B DIR'Prepend DIR to the include path. Multiple invocations accumulate.`--output=FILE'`-o FILE'Save output (script or trace) to FILE. The file `-' stands forthe standard output.`--warnings=CATEGORY'`-W CATEGORY'Report the warnings related to CATEGORY (which can actually be acomma separated list). *Note Reporting Messages::, macro`AC_DIAGNOSE', for a comprehensive list of categories. Specialvalues include:`all'report all the warnings`none'report none`error'treats warnings as errors`no-CATEGORY'disable warnings falling into CATEGORYWarnings about `syntax' are enabled by default, and the environmentvariable `WARNINGS', a comma separated list of categories, ishonored as well. Passing `-W CATEGORY' actually behaves as if youhad passed `--warnings=syntax,$WARNINGS,CATEGORY'. If you want todisable the defaults and `WARNINGS', but (for example) enable thewarnings about obsolete constructs, you would use `-Wnone,obsolete'.Because `autoconf' uses `autom4te' behind the scenes, it displaysa back trace for errors, but not for warnings; if you want them,just pass `-W error'. *Note autom4te Invocation::, for someexamples.`--trace=MACRO[:FORMAT]'`-t MACRO[:FORMAT]'Do not create the `configure' script, but list the calls to MACROaccording to the FORMAT. Multiple `--trace' arguments can be usedto list several macros. Multiple `--trace' arguments for a singlemacro are not cumulative; instead, you should just make FORMAT aslong as needed.The FORMAT is a regular string, with newlines if desired, andseveral special escape codes. It defaults to `$f:$l:$n:$%'; see*Note autom4te Invocation::, for details on the FORMAT.`--initialization'`-i'By default, `--trace' does not trace the initialization of theAutoconf macros (typically the `AC_DEFUN' definitions). Thisresults in a noticeable speedup, but can be disabled by thisoption.It is often necessary to check the content of a `configure.ac' file,but parsing it yourself is extremely fragile and error-prone. It issuggested that you rely upon `--trace' to scan `configure.ac'. Forinstance, to find the list of variables that are substituted, use:$ autoconf -t AC_SUBSTconfigure.ac:2:AC_SUBST:ECHO_Cconfigure.ac:2:AC_SUBST:ECHO_Nconfigure.ac:2:AC_SUBST:ECHO_TMore traces deletedThe example below highlights the difference between `$@', `$*', and`$%'.$ cat configure.acAC_DEFINE(This, is, [an[example]])$ autoconf -t 'AC_DEFINE:@: $@*: $*%: $%'@: [This],[is],[an[example]]*: This,is,an[example]%: This:is:an [example]The FORMAT gives you a lot of freedom:$ autoconf -t 'AC_SUBST:$$ac_subst{"$1"} = "$f:$l";'$ac_subst{"ECHO_C"} = "configure.ac:2";$ac_subst{"ECHO_N"} = "configure.ac:2";$ac_subst{"ECHO_T"} = "configure.ac:2";More traces deletedA long SEPARATOR can be used to improve the readability of complexstructures, and to ease their parsing (for instance when no singlecharacter is suitable as a separator):$ autoconf -t 'AM_MISSING_PROG:${|:::::|}*'ACLOCAL|:::::|aclocal|:::::|$missing_dirAUTOCONF|:::::|autoconf|:::::|$missing_dirAUTOMAKE|:::::|automake|:::::|$missing_dirMore traces deletedFile: autoconf.info, Node: autoreconf Invocation, Prev: autoconf Invocation, Up: Making configure Scripts3.5 Using `autoreconf' to Update `configure' Scripts====================================================Installing the various components of the GNU Build System can betedious: running `autopoint' for Gettext, `automake' for `Makefile.in'etc. in each directory. It may be needed either because some toolssuch as `automake' have been updated on your system, or because some ofthe sources such as `configure.ac' have been updated, or finally,simply in order to install the GNU Build System in a fresh tree.`autoreconf' runs `autoconf', `autoheader', `aclocal', `automake',`libtoolize', and `autopoint' (when appropriate) repeatedly to updatethe GNU Build System in the specified directories and theirsubdirectories (*note Subdirectories::). By default, it only remakesthose files that are older than their sources.If you install a new version of some tool, you can make `autoreconf'remake _all_ of the files by giving it the `--force' option.*Note Automatic Remaking::, for Make rules to automatically remake`configure' scripts when their source files change. That methodhandles the timestamps of configuration header templates properly, butdoes not pass `--autoconf-dir=DIR' or `--localdir=DIR'.Gettext supplies the `autopoint' command to add translationinfrastructure to a source package. If you use `autopoint', your`configure.ac' should invoke both `AM_GNU_GETTEXT' and`AM_GNU_GETTEXT_VERSION(GETTEXT-VERSION)'. *Note Invoking the`autopoint' Program: (gettext)autopoint Invocation, for further details.`autoreconf' accepts the following options:`--help'`-h'Print a summary of the command line options and exit.`--version'`-V'Print the version number of Autoconf and exit.`--verbose'Print the name of each directory `autoreconf' examines and thecommands it runs. If given two or more times, pass `--verbose' tosubordinate tools that support it.`--debug'`-d'Don't remove the temporary files.`--force'`-f'Remake even `configure' scripts and configuration headers that arenewer than their input files (`configure.ac' and, if present,`aclocal.m4').`--install'`-i'Install the missing auxiliary files in the package. By default,files are copied; this can be changed with `--symlink'.If deemed appropriate, this option triggers calls to `automake--add-missing', `libtoolize', `autopoint', etc.`--no-recursive'Do not rebuild files in subdirectories to configure (see *NoteSubdirectories::, macro `AC_CONFIG_SUBDIRS').`--symlink'`-s'When used with `--install', install symbolic links to the missingauxiliary files instead of copying them.`--make'`-m'When the directories were configured, update the configuration byrunning `./config.status --recheck && ./config.status', and thenrun `make'.`--include=DIR'`-I DIR'Append DIR to the include path. Multiple invocations accumulate.Passed on to `autoconf' and `autoheader' internally.`--prepend-include=DIR'`-B DIR'Prepend DIR to the include path. Multiple invocations accumulate.Passed on to `autoconf' and `autoheader' internally.`--warnings=CATEGORY'`-W CATEGORY'Report the warnings related to CATEGORY (which can actually be acomma separated list).`cross'related to cross compilation issues.`obsolete'report the uses of obsolete constructs.`portability'portability issues`syntax'dubious syntactic constructs.`all'report all the warnings`none'report none`error'treats warnings as errors`no-CATEGORY'disable warnings falling into CATEGORYWarnings about `syntax' are enabled by default, and the environmentvariable `WARNINGS', a comma separated list of categories, ishonored as well. Passing `-W CATEGORY' actually behaves as if youhad passed `--warnings=syntax,$WARNINGS,CATEGORY'. If you want todisable the defaults and `WARNINGS', but (for example) enable thewarnings about obsolete constructs, you would use `-Wnone,obsolete'.If you want `autoreconf' to pass flags that are not listed here onto `aclocal', set `ACLOCAL_AMFLAGS' in your `Makefile.am'.File: autoconf.info, Node: Setup, Next: Existing Tests, Prev: Making configure Scripts, Up: Top4 Initialization and Output Files*********************************Autoconf-generated `configure' scripts need some information about howto initialize, such as how to find the package's source files and aboutthe output files to produce. The following sections describe theinitialization and the creation of output files.* Menu:* Initializing configure:: Option processing etc.* Notices:: Copyright, version numbers in `configure'* Input:: Where Autoconf should find files* Output:: Outputting results from the configuration* Configuration Actions:: Preparing the output based on results* Configuration Files:: Creating output files* Makefile Substitutions:: Using output variables in makefiles* Configuration Headers:: Creating a configuration header file* Configuration Commands:: Running arbitrary instantiation commands* Configuration Links:: Links depending on the configuration* Subdirectories:: Configuring independent packages together* Default Prefix:: Changing the default installation prefixFile: autoconf.info, Node: Initializing configure, Next: Notices, Up: Setup4.1 Initializing `configure'============================Every `configure' script must call `AC_INIT' before doing anythingelse. The only other required macro is `AC_OUTPUT' (*note Output::).-- Macro: AC_INIT (PACKAGE, VERSION, [BUG-REPORT], [TARNAME])Process any command-line arguments and perform variousinitializations and verifications.Set the name of the PACKAGE and its VERSION. These are typicallyused in `--version' support, including that of `configure'. Theoptional argument BUG-REPORT should be the email to which usersshould send bug reports. The package TARNAME differs fromPACKAGE: the latter designates the full package name (e.g., `GNUAutoconf'), while the former is meant for distribution tar ballnames (e.g., `autoconf'). It defaults to PACKAGE with `GNU 'stripped, lower-cased, and all characters other than alphanumericsand underscores are changed to `-'.It is preferable that the arguments of `AC_INIT' be static, i.e.,there should not be any shell computation, but they can becomputed by M4.The following M4 macros (e.g., `AC_PACKAGE_NAME'), output variables(e.g., `PACKAGE_NAME'), and preprocessor symbols (e.g.,`PACKAGE_NAME') are defined by `AC_INIT':`AC_PACKAGE_NAME', `PACKAGE_NAME'Exactly PACKAGE.`AC_PACKAGE_TARNAME', `PACKAGE_TARNAME'Exactly TARNAME.`AC_PACKAGE_VERSION', `PACKAGE_VERSION'Exactly VERSION.`AC_PACKAGE_STRING', `PACKAGE_STRING'Exactly `PACKAGE VERSION'.`AC_PACKAGE_BUGREPORT', `PACKAGE_BUGREPORT'Exactly BUG-REPORT.If your `configure' script does its own option processing, it shouldinspect `$@' or `$*' immediately after calling `AC_INIT', because otherAutoconf macros liberally use the `set' command to process strings, andthis has the side effect of updating `$@' and `$*'. However, wesuggest that you use standard macros like `AC_ARG_ENABLE' instead ofattempting to implement your own option processing. *Note SiteConfiguration::.File: autoconf.info, Node: Notices, Next: Input, Prev: Initializing configure, Up: Setup4.2 Notices in `configure'==========================The following macros manage version numbers for `configure' scripts.Using them is optional.-- Macro: AC_PREREQ (VERSION)Ensure that a recent enough version of Autoconf is being used. Ifthe version of Autoconf being used to create `configure' isearlier than VERSION, print an error message to the standard erroroutput and exit with failure (exit status is 63). For example:AC_PREREQ([2.61])This macro is the only macro that may be used before `AC_INIT', butfor consistency, you are invited not to do so.-- Macro: AC_COPYRIGHT (COPYRIGHT-NOTICE)State that, in addition to the Free Software Foundation'scopyright on the Autoconf macros, parts of your `configure' arecovered by the COPYRIGHT-NOTICE.The COPYRIGHT-NOTICE shows up in both the head of `configure' andin `configure --version'.-- Macro: AC_REVISION (REVISION-INFO)Copy revision stamp REVISION-INFO into the `configure' script,with any dollar signs or double-quotes removed. This macro letsyou put a revision stamp from `configure.ac' into `configure'without RCS or CVS changing it when you check in `configure'.That way, you can determine easily which revision of`configure.ac' a particular `configure' corresponds to.For example, this line in `configure.ac':AC_REVISION([$Revision: 1.30 $])produces this in `configure':#!/bin/sh# From configure.ac Revision: 1.30File: autoconf.info, Node: Input, Next: Output, Prev: Notices, Up: Setup4.3 Finding `configure' Input=============================-- Macro: AC_CONFIG_SRCDIR (UNIQUE-FILE-IN-SOURCE-DIR)UNIQUE-FILE-IN-SOURCE-DIR is some file that is in the package'ssource directory; `configure' checks for this file's existence tomake sure that the directory that it is told contains the sourcecode in fact does. Occasionally people accidentally specify thewrong directory with `--srcdir'; this is a safety check. *Noteconfigure Invocation::, for more information.Packages that do manual configuration or use the `install' programmight need to tell `configure' where to find some other shell scriptsby calling `AC_CONFIG_AUX_DIR', though the default places it looks arecorrect for most cases.-- Macro: AC_CONFIG_AUX_DIR (DIR)Use the auxiliary build tools (e.g., `install-sh', `config.sub',`config.guess', Cygnus `configure', Automake and Libtool scripts,etc.) that are in directory DIR. These are auxiliary files usedin configuration. DIR can be either absolute or relative to`SRCDIR'. The default is `SRCDIR' or `SRCDIR/..' or`SRCDIR/../..', whichever is the first that contains `install-sh'.The other files are not checked for, so that using`AC_PROG_INSTALL' does not automatically require distributing theother auxiliary files. It checks for `install.sh' also, but thatname is obsolete because some `make' have a rule that creates`install' from it if there is no makefile.The auxiliary directory is commonly named `build-aux'. If youneed portability to DOS variants, do not name the auxiliarydirectory `aux'. *Note File System Conventions::.-- Macro: AC_REQUIRE_AUX_FILE (FILE)Declares that FILE is expected in the directory defined above. InAutoconf proper, this macro does nothing: its sole purpose is to betraced by third-party tools to produce a list of expected auxiliaryfiles. For instance it is called by macros like `AC_PROG_INSTALL'(*note Particular Programs::) or `AC_CANONICAL_BUILD' (*noteCanonicalizing::) to register the auxiliary files they need.Similarly, packages that use `aclocal' should declare where localmacros can be found using `AC_CONFIG_MACRO_DIR'.-- Macro: AC_CONFIG_MACRO_DIR (DIR)Specify DIR as the location of additional local Autoconf macros.This macro is intended for use by future versions of commands like`autoreconf' that trace macro calls. It should be called directlyfrom `configure.ac' so that tools that install macros for`aclocal' can find the macros' declarations.File: autoconf.info, Node: Output, Next: Configuration Actions, Prev: Input, Up: Setup4.4 Outputting Files====================Every Autoconf script, e.g., `configure.ac', should finish by calling`AC_OUTPUT'. That is the macro that generates and runs`config.status', which in turn creates the makefiles and any otherfiles resulting from configuration. This is the only required macrobesides `AC_INIT' (*note Input::).-- Macro: AC_OUTPUTGenerate `config.status' and launch it. Call this macro once, atthe end of `configure.ac'.`config.status' performs all the configuration actions: all theoutput files (see *Note Configuration Files::, macro`AC_CONFIG_FILES'), header files (see *Note ConfigurationHeaders::, macro `AC_CONFIG_HEADERS'), commands (see *NoteConfiguration Commands::, macro `AC_CONFIG_COMMANDS'), links (see*Note Configuration Links::, macro `AC_CONFIG_LINKS'),subdirectories to configure (see *Note Subdirectories::, macro`AC_CONFIG_SUBDIRS') are honored.The location of your `AC_OUTPUT' invocation is the exact pointwhere configuration actions are taken: any code afterwards isexecuted by `configure' once `config.status' was run. If you wantto bind actions to `config.status' itself (independently ofwhether `configure' is being run), see *Note Running ArbitraryConfiguration Commands: Configuration Commands.Historically, the usage of `AC_OUTPUT' was somewhat different.*Note Obsolete Macros::, for a description of the arguments that`AC_OUTPUT' used to support.If you run `make' in subdirectories, you should run it using the`make' variable `MAKE'. Most versions of `make' set `MAKE' to the nameof the `make' program plus any options it was given. (But many do notinclude in it the values of any variables set on the command line, sothose are not passed on automatically.) Some old versions of `make' donot set this variable. The following macro allows you to use it evenwith those versions.-- Macro: AC_PROG_MAKE_SETIf the Make command, `$MAKE' if set or else `make', predefines`$(MAKE)', define output variable `SET_MAKE' to be empty.Otherwise, define `SET_MAKE' to a macro definition that sets`$(MAKE)', such as `MAKE=make'. Calls `AC_SUBST' for `SET_MAKE'.If you use this macro, place a line like this in each `Makefile.in'that runs `MAKE' on other directories:@SET_MAKE@File: autoconf.info, Node: Configuration Actions, Next: Configuration Files, Prev: Output, Up: Setup4.5 Performing Configuration Actions====================================`configure' is designed so that it appears to do everything itself, butthere is actually a hidden slave: `config.status'. `configure' is incharge of examining your system, but it is `config.status' thatactually takes the proper actions based on the results of `configure'.The most typical task of `config.status' is to _instantiate_ files.This section describes the common behavior of the four standardinstantiating macros: `AC_CONFIG_FILES', `AC_CONFIG_HEADERS',`AC_CONFIG_COMMANDS' and `AC_CONFIG_LINKS'. They all have thisprototype:AC_CONFIG_FOOS(TAG..., [COMMANDS], [INIT-CMDS])where the arguments are:TAG...A blank-or-newline-separated list of tags, which are typically thenames of the files to instantiate.You are encouraged to use literals as TAGS. In particular, youshould avoid... && my_foos="$my_foos fooo"... && my_foos="$my_foos foooo"AC_CONFIG_FOOS([$my_foos])and use this instead:... && AC_CONFIG_FOOS([fooo])... && AC_CONFIG_FOOS([foooo])The macros `AC_CONFIG_FILES' and `AC_CONFIG_HEADERS' use specialTAG values: they may have the form `OUTPUT' or `OUTPUT:INPUTS'.The file OUTPUT is instantiated from its templates, INPUTS(defaulting to `OUTPUT.in').`AC_CONFIG_FILES([Makefile:boiler/top.mk:boiler/bot.mk)]', forexample, asks for the creation of the file `Makefile' thatcontains the expansion of the output variables in theconcatenation of `boiler/top.mk' and `boiler/bot.mk'.The special value `-' might be used to denote the standard outputwhen used in OUTPUT, or the standard input when used in theINPUTS. You most probably don't need to use this in`configure.ac', but it is convenient when using the command lineinterface of `./config.status', see *Note config.statusInvocation::, for more details.The INPUTS may be absolute or relative file names. In the lattercase they are first looked for in the build tree, and then in thesource tree.COMMANDSShell commands output literally into `config.status', andassociated with a tag that the user can use to tell `config.status'which the commands to run. The commands are run each time a TAGrequest is given to `config.status', typically each time the file`TAG' is created.The variables set during the execution of `configure' are _not_available here: you first need to set them via the INIT-CMDS.Nonetheless the following variables are precomputed:`srcdir'The name of the top source directory, assuming that theworking directory is the top build directory. This is whatthe `configure' option `--srcdir' sets.`ac_top_srcdir'The name of the top source directory, assuming that theworking directory is the current build directory.`ac_top_build_prefix'The name of the top build directory, assuming that the workingdirectory is the current build directory. It can be empty,or else ends with a slash, so that you may concatenate it.`ac_srcdir'The name of the corresponding source directory, assuming thatthe working directory is the current build directory.The "current" directory refers to the directory (orpseudo-directory) containing the input part of TAGS. Forinstance, runningAC_CONFIG_COMMANDS([deep/dir/out:in/in.in], [...], [...])with `--srcdir=../package' produces the following values:# Argument of --srcdirsrcdir='../package'# Reversing deep/dirac_top_build_prefix='../../'# Concatenation of $ac_top_build_prefix and srcdirac_top_srcdir='../../../package'# Concatenation of $ac_top_srcdir and deep/dirac_srcdir='../../../package/deep/dir'independently of `in/in.in'.INIT-CMDSShell commands output _unquoted_ near the beginning of`config.status', and executed each time `config.status' runs(regardless of the tag). Because they are unquoted, for example,`$var' is output as the value of `var'. INIT-CMDS is typicallyused by `configure' to give `config.status' some variables itneeds to run the COMMANDS.You should be extremely cautious in your variable names: all theINIT-CMDS share the same name space and may overwrite each otherin unpredictable ways. Sorry....All these macros can be called multiple times, with different TAGvalues, of course!File: autoconf.info, Node: Configuration Files, Next: Makefile Substitutions, Prev: Configuration Actions, Up: Setup4.6 Creating Configuration Files================================Be sure to read the previous section, *Note Configuration Actions::.-- Macro: AC_CONFIG_FILES (FILE..., [CMDS], [INIT-CMDS])Make `AC_OUTPUT' create each `FILE' by copying an input file (bydefault `FILE.in'), substituting the output variable values. Thismacro is one of the instantiating macros; see *Note ConfigurationActions::. *Note Makefile Substitutions::, for more informationon using output variables. *Note Setting Output Variables::, formore information on creating them. This macro creates thedirectory that the file is in if it doesn't exist. Usually,makefiles are created this way, but other files, such as`.gdbinit', can be specified as well.Typical calls to `AC_CONFIG_FILES' look like this:AC_CONFIG_FILES([Makefile src/Makefile man/Makefile X/Imakefile])AC_CONFIG_FILES([autoconf], [chmod +x autoconf])You can override an input file name by appending to FILE acolon-separated list of input files. Examples:AC_CONFIG_FILES([Makefile:boiler/top.mk:boiler/bot.mk][lib/Makefile:boiler/lib.mk])Doing this allows you to keep your file names acceptable to DOSvariants, or to prepend and/or append boilerplate to the file.File: autoconf.info, Node: Makefile Substitutions, Next: Configuration Headers, Prev: Configuration Files, Up: Setup4.7 Substitutions in Makefiles==============================Each subdirectory in a distribution that contains something to becompiled or installed should come with a file `Makefile.in', from which`configure' creates a file `Makefile' in that directory. To create`Makefile', `configure' performs a simple variable substitution,replacing occurrences of `@VARIABLE@' in `Makefile.in' with the valuethat `configure' has determined for that variable. Variables that aresubstituted into output files in this way are called "outputvariables". They are ordinary shell variables that are set in`configure'. To make `configure' substitute a particular variable intothe output files, the macro `AC_SUBST' must be called with thatvariable name as an argument. Any occurrences of `@VARIABLE@' forother variables are left unchanged. *Note Setting Output Variables::,for more information on creating output variables with `AC_SUBST'.A software package that uses a `configure' script should bedistributed with a file `Makefile.in', but no makefile; that way, theuser has to properly configure the package for the local system beforecompiling it.*Note Makefile Conventions: (standards)Makefile Conventions, formore information on what to put in makefiles.* Menu:* Preset Output Variables:: Output variables that are always set* Installation Directory Variables:: Other preset output variables* Changed Directory Variables:: Warnings about `datarootdir'* Build Directories:: Supporting multiple concurrent compiles* Automatic Remaking:: Makefile rules for configuringFile: autoconf.info, Node: Preset Output Variables, Next: Installation Directory Variables, Up: Makefile Substitutions4.7.1 Preset Output Variables-----------------------------Some output variables are preset by the Autoconf macros. Some of theAutoconf macros set additional output variables, which are mentioned inthe descriptions for those macros. *Note Output Variable Index::, for acomplete list of output variables. *Note Installation DirectoryVariables::, for the list of the preset ones related to installationdirectories. Below are listed the other preset ones. They all areprecious variables (*note Setting Output Variables::, `AC_ARG_VAR').-- Variable: CFLAGSDebugging and optimization options for the C compiler. If it isnot set in the environment when `configure' runs, the defaultvalue is set when you call `AC_PROG_CC' (or empty if you don't).`configure' uses this variable when compiling or linking programsto test for C features.If a compiler option affects only the behavior of the preprocessor(e.g., `-D NAME'), it should be put into `CPPFLAGS' instead. Ifit affects only the linker (e.g., `-L DIRECTORY'), it should beput into `LDFLAGS' instead. If it affects only the compilerproper, `CFLAGS' is the natural home for it. If an option affectsmultiple phases of the compiler, though, matters get tricky. Oneapproach to put such options directly into `CC', e.g., `CC='gcc-m64''. Another is to put them into both `CPPFLAGS' and`LDFLAGS', but not into `CFLAGS'.-- Variable: configure_inputA comment saying that the file was generated automatically by`configure' and giving the name of the input file. `AC_OUTPUT'adds a comment line containing this variable to the top of everymakefile it creates. For other files, you should reference thisvariable in a comment at the top of each input file. For example,an input shell script should begin like this:#!/bin/sh# @configure_input@The presence of that line also reminds people editing the filethat it needs to be processed by `configure' in order to be used.-- Variable: CPPFLAGSPreprocessor options for the C, C++, and Objective C preprocessorsand compilers. If it is not set in the environment when`configure' runs, the default value is empty. `configure' usesthis variable when preprocessing or compiling programs to test forC, C++, and Objective C features.This variable's contents should contain options like `-I', `-D',and `-U' that affect only the behavior of the preprocessor.Please see the explanation of `CFLAGS' for what you can do if anoption affects other phases of the compiler as well.Currently, `configure' always links as part of a single invocationof the compiler that also preprocesses and compiles, so it usesthis variable also when linking programs. However, it is unwise todepend on this behavior because the GNU coding standards do notrequire it and many packages do not use `CPPFLAGS' when linkingprograms.*Note Special Chars in Variables::, for limitations that `CPPFLAGS'might run into.-- Variable: CXXFLAGSDebugging and optimization options for the C++ compiler. It actslike `CFLAGS', but for C++ instead of C.-- Variable: DEFS`-D' options to pass to the C compiler. If `AC_CONFIG_HEADERS' iscalled, `configure' replaces `@DEFS@' with `-DHAVE_CONFIG_H'instead (*note Configuration Headers::). This variable is notdefined while `configure' is performing its tests, only whencreating the output files. *Note Setting Output Variables::, forhow to check the results of previous tests.-- Variable: ECHO_C-- Variable: ECHO_N-- Variable: ECHO_THow does one suppress the trailing newline from `echo' forquestion-answer message pairs? These variables provide a way:echo $ECHO_N "And the winner is... $ECHO_C"sleep 100000000000echo "${ECHO_T}dead."Some old and uncommon `echo' implementations offer no means toachieve this, in which case `ECHO_T' is set to tab. You might notwant to use it.-- Variable: ERLCFLAGSDebugging and optimization options for the Erlang compiler. If itis not set in the environment when `configure' runs, the defaultvalue is empty. `configure' uses this variable when compilingprograms to test for Erlang features.-- Variable: FCFLAGSDebugging and optimization options for the Fortran compiler. If itis not set in the environment when `configure' runs, the defaultvalue is set when you call `AC_PROG_FC' (or empty if you don't).`configure' uses this variable when compiling or linking programsto test for Fortran features.-- Variable: FFLAGSDebugging and optimization options for the Fortran 77 compiler.If it is not set in the environment when `configure' runs, thedefault value is set when you call `AC_PROG_F77' (or empty if youdon't). `configure' uses this variable when compiling or linkingprograms to test for Fortran 77 features.-- Variable: LDFLAGSOptions for the linker. If it is not set in the environment when`configure' runs, the default value is empty. `configure' usesthis variable when linking programs to test for C, C++, ObjectiveC, and Fortran features.This variable's contents should contain options like `-s' and `-L'that affect only the behavior of the linker. Please see theexplanation of `CFLAGS' for what you can do if an option alsoaffects other phases of the compiler.Don't use this variable to pass library names (`-l') to thelinker; use `LIBS' instead.-- Variable: LIBS`-l' options to pass to the linker. The default value is empty,but some Autoconf macros may prepend extra libraries to thisvariable if those libraries are found and provide necessaryfunctions, see *Note Libraries::. `configure' uses this variablewhen linking programs to test for C, C++, and Fortran features.-- Variable: OBJCFLAGSDebugging and optimization options for the Objective C compiler.It acts like `CFLAGS', but for Objective C instead of C.-- Variable: builddirRigorously equal to `.'. Added for symmetry only.-- Variable: abs_builddirAbsolute name of `builddir'.-- Variable: top_builddirThe relative name of the top level of the current build tree. Inthe top-level directory, this is the same as `builddir'.-- Variable: abs_top_builddirAbsolute name of `top_builddir'.-- Variable: srcdirThe name of the directory that contains the source code for thatmakefile.-- Variable: abs_srcdirAbsolute name of `srcdir'.-- Variable: top_srcdirThe name of the top-level source code directory for the package.In the top-level directory, this is the same as `srcdir'.-- Variable: abs_top_srcdirAbsolute name of `top_srcdir'.File: autoconf.info, Node: Installation Directory Variables, Next: Changed Directory Variables, Prev: Preset Output Variables, Up: Makefile Substitutions4.7.2 Installation Directory Variables--------------------------------------The following variables specify the directories for packageinstallation, see *Note Variables for Installation Directories:(standards)Directory Variables, for more information. See the end ofthis section for details on when and how to use these variables.-- Variable: bindirThe directory for installing executables that users run.-- Variable: datadirThe directory for installing idiosyncratic read-onlyarchitecture-independent data.-- Variable: datarootdirThe root of the directory tree for read-onlyarchitecture-independent data files.-- Variable: docdirThe directory for installing documentation files (other than Infoand man).-- Variable: dvidirThe directory for installing documentation files in DVI format.-- Variable: exec_prefixThe installation prefix for architecture-dependent files. Bydefault it's the same as PREFIX. You should avoid installinganything directly to EXEC_PREFIX. However, the default value fordirectories containing architecture-dependent files should berelative to EXEC_PREFIX.-- Variable: htmldirThe directory for installing HTML documentation.-- Variable: includedirThe directory for installing C header files.-- Variable: infodirThe directory for installing documentation in Info format.-- Variable: libdirThe directory for installing object code libraries.-- Variable: libexecdirThe directory for installing executables that other programs run.-- Variable: localedirThe directory for installing locale-dependent butarchitecture-independent data, such as message catalogs. Thisdirectory usually has a subdirectory per locale.-- Variable: localstatedirThe directory for installing modifiable single-machine data.-- Variable: mandirThe top-level directory for installing documentation in man format.-- Variable: oldincludedirThe directory for installing C header files for non-GCC compilers.-- Variable: pdfdirThe directory for installing PDF documentation.-- Variable: prefixThe common installation prefix for all files. If EXEC_PREFIX isdefined to a different value, PREFIX is used only forarchitecture-independent files.-- Variable: psdirThe directory for installing PostScript documentation.-- Variable: sbindirThe directory for installing executables that systemadministrators run.-- Variable: sharedstatedirThe directory for installing modifiable architecture-independentdata.-- Variable: sysconfdirThe directory for installing read-only single-machine data.Most of these variables have values that rely on `prefix' or`exec_prefix'. It is deliberate that the directory output variableskeep them unexpanded: typically `@datarootdir@' is replaced by`${prefix}/share', not `/usr/local/share', and `@datadir@' is replacedby `${datarootdir}'.This behavior is mandated by the GNU coding standards, so that whenthe user runs:`make'she can still specify a different prefix from the one specified to`configure', in which case, if needed, the package should hardcode dependencies corresponding to the make-specified prefix.`make install'she can specify a different installation location, in which casethe package _must_ still depend on the location which was compiledin (i.e., never recompile when `make install' is run). This is anextremely important feature, as many people may decide to installall the files of a package grouped together, and then installlinks from the final locations to there.In order to support these features, it is essential that`datarootdir' remains being defined as `${prefix}/share' to depend uponthe current value of `prefix'.A corollary is that you should not use these variables except inmakefiles. For instance, instead of trying to evaluate `datadir' in`configure' and hard-coding it in makefiles using e.g.,`AC_DEFINE_UNQUOTED([DATADIR], ["$datadir"], [Data directory.])', youshould add `-DDATADIR='$(datadir)'' to your makefile's definition of`CPPFLAGS' (`AM_CPPFLAGS' if you are also using Automake).Similarly, you should not rely on `AC_CONFIG_FILES' to replace`datadir' and friends in your shell scripts and other files; instead,let `make' manage their replacement. For instance Autoconf shipstemplates of its shell scripts ending with `.in', and uses a makefilesnippet similar to the following to build scripts like `autoheader' and`autom4te':edit = sed \-e 's|@datadir[@]|$(pkgdatadir)|g' \-e 's|@prefix[@]|$(prefix)|g'autoheader autom4te: Makefilerm -f $@ $@.tmp$(edit) '$(srcdir)/$@.in' >$@.tmpchmod +x $@.tmpchmod a-w $@.tmpmv $@.tmp $@autoheader: $(srcdir)/autoheader.inautom4te: $(srcdir)/autom4te.inSome details are noteworthy:`@datadir[@]'The brackets prevent `configure' from replacing `@datadir@' in theSed expression itself. Brackets are preferable to a backslashhere, since Posix says `\@' is not portable.`$(pkgdatadir)'Don't use `@pkgdatadir@'! Use the matching makefile variableinstead.`/'Don't use `/' in the Sed expressions that replace file names sincemost likely the variables you use, such as `$(pkgdatadir)',contain `/'. Use a shell metacharacter instead, such as `|'.special charactersFile names, file name components, and the value of `VPATH' shouldnot contain shell metacharacters or white space. *Note SpecialChars in Variables::.dependency on `Makefile'Since `edit' uses values that depend on the configuration specificvalues (`prefix', etc.) and not only on `VERSION' and so forth,the output depends on `Makefile', not `configure.ac'.`$@'The main rule is generic, and uses `$@' extensively to avoid theneed for multiple copies of the rule.Separated dependencies and single suffix rulesYou can't use them! The above snippet cannot be (portably)rewritten as:autoconf autoheader: Makefile.in:rm -f $@ $@.tmp$(edit) $< >$@.tmpchmod +x $@.tmpmv $@.tmp $@*Note Single Suffix Rules::, for details.`$(srcdir)'Be sure to specify the name of the source directory, otherwise thepackage won't support separated builds.For the more specific installation of Erlang libraries, thefollowing variables are defined:-- Variable: ERLANG_INSTALL_LIB_DIRThe common parent directory of Erlang library installationdirectories. This variable is set by calling the`AC_ERLANG_SUBST_INSTALL_LIB_DIR' macro in `configure.ac'.-- Variable: ERLANG_INSTALL_LIB_DIR_LIBRARYThe installation directory for Erlang library LIBRARY. Thisvariable is set by calling the`AC_ERLANG_SUBST_INSTALL_LIB_SUBDIR(LIBRARY, VERSION' macro in`configure.ac'.*Note Erlang Libraries::, for details.File: autoconf.info, Node: Changed Directory Variables, Next: Build Directories, Prev: Installation Directory Variables, Up: Makefile Substitutions4.7.3 Changed Directory Variables---------------------------------In Autoconf 2.60, the set of directory variables has changed, and thedefaults of some variables have been adjusted (*note InstallationDirectory Variables::) to changes in the GNU Coding Standards.Notably, `datadir', `infodir', and `mandir' are now expressed in termsof `datarootdir'. If you are upgrading from an earlier Autoconfversion, you may need to adjust your files to ensure that the directoryvariables are substituted correctly (*note Defining Directories::), andthat a definition of `datarootdir' is in place. For example, in a`Makefile.in', addingdatarootdir = @datarootdir@is usually sufficient. If you use Automake to create `Makefile.in', itwill add this for you.To help with the transition, Autoconf warns about files that seem touse `datarootdir' without defining it. In some cases, it then expandsthe value of `$datarootdir' in substitutions of the directoryvariables. The following example shows such a warning:$ cat configure.acAC_INITAC_CONFIG_FILES([Makefile])AC_OUTPUT$ cat Makefile.inprefix = @prefix@datadir = @datadir@$ autoconf$ configureconfigure: creating ./config.statusconfig.status: creating Makefileconfig.status: WARNING:Makefile.in seems to ignore the --datarootdir setting$ cat Makefileprefix = /usr/localdatadir = ${prefix}/shareUsually one can easily change the file to accommodate both older andnewer Autoconf releases:$ cat Makefile.inprefix = @prefix@datarootdir = @datarootdir@datadir = @datadir@$ configureconfigure: creating ./config.statusconfig.status: creating Makefile$ cat Makefileprefix = /usr/localdatarootdir = ${prefix}/sharedatadir = ${datarootdir}In some cases, however, the checks may not be able to detect that asuitable initialization of `datarootdir' is in place, or they may failto detect that such an initialization is necessary in the output file.If, after auditing your package, there are still spurious `configure'warnings about `datarootdir', you may add the lineAC_DEFUN([AC_DATAROOTDIR_CHECKED])to your `configure.ac' to disable the warnings. This is an exceptionto the usual rule that you should not define a macro whose name beginswith `AC_' (*note Macro Names::).File: autoconf.info, Node: Build Directories, Next: Automatic Remaking, Prev: Changed Directory Variables, Up: Makefile Substitutions4.7.4 Build Directories-----------------------You can support compiling a software package for several architecturessimultaneously from the same copy of the source code. The object filesfor each architecture are kept in their own directory.To support doing this, `make' uses the `VPATH' variable to find thefiles that are in the source directory. GNU Make and most other recent`make' programs can do this. Older `make' programs do not support`VPATH'; when using them, the source code must be in the same directoryas the object files.To support `VPATH', each `Makefile.in' should contain two lines thatlook like:srcdir = @srcdir@VPATH = @srcdir@Do not set `VPATH' to the value of another variable, for example`VPATH = $(srcdir)', because some versions of `make' do not do variablesubstitutions on the value of `VPATH'.`configure' substitutes the correct value for `srcdir' when itproduces `Makefile'.Do not use the `make' variable `$<', which expands to the file nameof the file in the source directory (found with `VPATH'), except inimplicit rules. (An implicit rule is one such as `.c.o', which tellshow to create a `.o' file from a `.c' file.) Some versions of `make'do not set `$<' in explicit rules; they expand it to an empty value.Instead, Make command lines should always refer to source files byprefixing them with `$(srcdir)/'. For example:time.info: time.texinfo$(MAKEINFO) '$(srcdir)/time.texinfo'File: autoconf.info, Node: Automatic Remaking, Prev: Build Directories, Up: Makefile Substitutions4.7.5 Automatic Remaking------------------------You can put rules like the following in the top-level `Makefile.in' fora package to automatically update the configuration information whenyou change the configuration files. This example includes all of theoptional files, such as `aclocal.m4' and those related to configurationheader files. Omit from the `Makefile.in' rules for any of these filesthat your package does not use.The `$(srcdir)/' prefix is included because of limitations in the`VPATH' mechanism.The `stamp-' files are necessary because the timestamps of`config.h.in' and `config.h' are not changed if remaking them does notchange their contents. This feature avoids unnecessary recompilation.You should include the file `stamp-h.in' your package's distribution,so that `make' considers `config.h.in' up to date. Don't use `touch'(*note Limitations of Usual Tools::); instead, use `echo' (using `date'would cause needless differences, hence CVS conflicts, etc.).$(srcdir)/configure: configure.ac aclocal.m4cd '$(srcdir)' && autoconf# autoheader might not change config.h.in, so touch a stamp file.$(srcdir)/config.h.in: stamp-h.in$(srcdir)/stamp-h.in: configure.ac aclocal.m4cd '$(srcdir)' && autoheaderecho timestamp > '$(srcdir)/stamp-h.in'config.h: stamp-hstamp-h: config.h.in config.status./config.statusMakefile: Makefile.in config.status./config.statusconfig.status: configure./config.status --recheck(Be careful if you copy these lines directly into your makefile, as youneed to convert the indented lines to start with the tab character.)In addition, you should useAC_CONFIG_FILES([stamp-h], [echo timestamp > stamp-h])so `config.status' ensures that `config.h' is considered up to date.*Note Output::, for more information about `AC_OUTPUT'.*Note config.status Invocation::, for more examples of handlingconfiguration-related dependencies.File: autoconf.info, Node: Configuration Headers, Next: Configuration Commands, Prev: Makefile Substitutions, Up: Setup4.8 Configuration Header Files==============================When a package contains more than a few tests that define C preprocessorsymbols, the command lines to pass `-D' options to the compiler can getquite long. This causes two problems. One is that the `make' outputis hard to visually scan for errors. More seriously, the command linescan exceed the length limits of some operating systems. As analternative to passing `-D' options to the compiler, `configure'scripts can create a C header file containing `#define' directives.The `AC_CONFIG_HEADERS' macro selects this kind of output. Though itcan be called anywhere between `AC_INIT' and `AC_OUTPUT', it iscustomary to call it right after `AC_INIT'.The package should `#include' the configuration header file beforeany other header files, to prevent inconsistencies in declarations (forexample, if it redefines `const').To provide for VPATH builds, remember to pass the C compiler a `-I.'option (or `-I..'; whichever directory contains `config.h'). Even ifyou use `#include "config.h"', the preprocessor searches only thedirectory of the currently read file, i.e., the source directory, notthe build directory.With the appropriate `-I' option, you can use `#include <config.h>'.Actually, it's a good habit to use it, because in the rare case whenthe source directory contains another `config.h', the build directoryshould be searched first.-- Macro: AC_CONFIG_HEADERS (HEADER ..., [CMDS], [INIT-CMDS])This macro is one of the instantiating macros; see *NoteConfiguration Actions::. Make `AC_OUTPUT' create the file(s) inthe blank-or-newline-separated list HEADER containing Cpreprocessor `#define' statements, and replace `@DEFS@' ingenerated files with `-DHAVE_CONFIG_H' instead of the value of`DEFS'. The usual name for HEADER is `config.h'.If HEADER already exists and its contents are identical to what`AC_OUTPUT' would put in it, it is left alone. Doing this allowsmaking some changes in the configuration without needlessly causingobject files that depend on the header file to be recompiled.Usually the input file is named `HEADER.in'; however, you canoverride the input file name by appending to HEADER acolon-separated list of input files. Examples:AC_CONFIG_HEADERS([config.h:config.hin])AC_CONFIG_HEADERS([defines.h:defs.pre:defines.h.in:defs.post])Doing this allows you to keep your file names acceptable to DOSvariants, or to prepend and/or append boilerplate to the file.-- Macro: AH_HEADERThis macro is defined as the name of the first declared configheader and undefined if no config headers have been declared up tothis point. A third-party macro may, for example, require use ofa config header without invoking AC_CONFIG_HEADERS twice, likethis:AC_CONFIG_COMMANDS_PRE([m4_ifndef([AH_HEADER], [AC_CONFIG_HEADERS([config.h])])])*Note Configuration Actions::, for more details on HEADER.* Menu:* Header Templates:: Input for the configuration headers* autoheader Invocation:: How to create configuration templates* Autoheader Macros:: How to specify CPP templatesFile: autoconf.info, Node: Header Templates, Next: autoheader Invocation, Up: Configuration Headers4.8.1 Configuration Header Templates------------------------------------Your distribution should contain a template file that looks as you wantthe final header file to look, including comments, with `#undef'statements which are used as hooks. For example, suppose your`configure.ac' makes these calls:AC_CONFIG_HEADERS([conf.h])AC_CHECK_HEADERS([unistd.h])Then you could have code like the following in `conf.h.in'. On systemsthat have `unistd.h', `configure' defines `HAVE_UNISTD_H' to 1. Onother systems, the whole line is commented out (in case the systempredefines that symbol)./* Define as 1 if you have unistd.h. */#undef HAVE_UNISTD_HPay attention that `#undef' is in the first column, and there isnothing after `HAVE_UNISTD_H', not even white space. You can thendecode the configuration header using the preprocessor directives:#include <conf.h>#ifdef HAVE_UNISTD_H# include <unistd.h>#else/* We are in trouble. */#endifThe use of old form templates, with `#define' instead of `#undef' isstrongly discouraged. Similarly with old templates with comments onthe same line as the `#undef'. Anyway, putting comments inpreprocessor macros has never been a good idea.Since it is a tedious task to keep a template header up to date, youmay use `autoheader' to generate it, see *Note autoheader Invocation::.File: autoconf.info, Node: autoheader Invocation, Next: Autoheader Macros, Prev: Header Templates, Up: Configuration Headers4.8.2 Using `autoheader' to Create `config.h.in'------------------------------------------------The `autoheader' program can create a template file of C `#define'statements for `configure' to use. If `configure.ac' invokes`AC_CONFIG_HEADERS(FILE)', `autoheader' creates `FILE.in'; if multiplefile arguments are given, the first one is used. Otherwise,`autoheader' creates `config.h.in'.In order to do its job, `autoheader' needs you to document all ofthe symbols that you might use. Typically this is done via an`AC_DEFINE' or `AC_DEFINE_UNQUOTED' call whose first argument is aliteral symbol and whose third argument describes the symbol (*noteDefining Symbols::). Alternatively, you can use `AH_TEMPLATE' (*noteAutoheader Macros::), or you can supply a suitable input file for asubsequent configuration header file. Symbols defined by Autoconf'sbuiltin tests are already documented properly; you need to documentonly those that you define yourself.You might wonder why `autoheader' is needed: after all, why would`configure' need to "patch" a `config.h.in' to produce a `config.h'instead of just creating `config.h' from scratch? Well, wheneverything rocks, the answer is just that we are wasting our timemaintaining `autoheader': generating `config.h' directly is all that isneeded. When things go wrong, however, you'll be thankful for theexistence of `autoheader'.The fact that the symbols are documented is important in order to_check_ that `config.h' makes sense. The fact that there is awell-defined list of symbols that should be defined (or not) is alsoimportant for people who are porting packages to environments where`configure' cannot be run: they just have to _fill in the blanks_.But let's come back to the point: the invocation of `autoheader'...If you give `autoheader' an argument, it uses that file instead of`configure.ac' and writes the header file to the standard outputinstead of to `config.h.in'. If you give `autoheader' an argument of`-', it reads the standard input instead of `configure.ac' and writesthe header file to the standard output.`autoheader' accepts the following options:`--help'`-h'Print a summary of the command line options and exit.`--version'`-V'Print the version number of Autoconf and exit.`--verbose'`-v'Report processing steps.`--debug'`-d'Don't remove the temporary files.`--force'`-f'Remake the template file even if newer than its input files.`--include=DIR'`-I DIR'Append DIR to the include path. Multiple invocations accumulate.`--prepend-include=DIR'`-B DIR'Prepend DIR to the include path. Multiple invocations accumulate.`--warnings=CATEGORY'`-W CATEGORY'Report the warnings related to CATEGORY (which can actually be acomma separated list). Current categories include:`obsolete'report the uses of obsolete constructs`all'report all the warnings`none'report none`error'treats warnings as errors`no-CATEGORY'disable warnings falling into CATEGORYFile: autoconf.info, Node: Autoheader Macros, Prev: autoheader Invocation, Up: Configuration Headers4.8.3 Autoheader Macros-----------------------`autoheader' scans `configure.ac' and figures out which C preprocessorsymbols it might define. It knows how to generate templates forsymbols defined by `AC_CHECK_HEADERS', `AC_CHECK_FUNCS' etc., but ifyou `AC_DEFINE' any additional symbol, you must define a template forit. If there are missing templates, `autoheader' fails with an errormessage.The template for a SYMBOL is created by `autoheader' from theDESCRIPTION argument to an `AC_DEFINE'; see *Note Defining Symbols::.For special needs, you can use the following macros.-- Macro: AH_TEMPLATE (KEY, DESCRIPTION)Tell `autoheader' to generate a template for KEY. This macrogenerates standard templates just like `AC_DEFINE' when aDESCRIPTION is given.For example:AH_TEMPLATE([CRAY_STACKSEG_END],[Define to one of _getb67, GETB67, getb67for Cray-2 and Cray-YMP systems. Thisfunction is required for alloca.c supporton those systems.])generates the following template, with the description properlyjustified./* Define to one of _getb67, GETB67, getb67 for Cray-2 andCray-YMP systems. This function is required for alloca.csupport on those systems. */#undef CRAY_STACKSEG_END-- Macro: AH_VERBATIM (KEY, TEMPLATE)Tell `autoheader' to include the TEMPLATE as-is in the headertemplate file. This TEMPLATE is associated with the KEY, which isused to sort all the different templates and guarantee theiruniqueness. It should be a symbol that can be defined via`AC_DEFINE'.-- Macro: AH_TOP (TEXT)Include TEXT at the top of the header template file.-- Macro: AH_BOTTOM (TEXT)Include TEXT at the bottom of the header template file.Please note that TEXT gets included "verbatim" to the template file,not to the resulting config header, so it can easily get mangled whenthe template is processed. There is rarely a need for something otherthanAH_BOTTOM([#include <custom.h>])File: autoconf.info, Node: Configuration Commands, Next: Configuration Links, Prev: Configuration Headers, Up: Setup4.9 Running Arbitrary Configuration Commands============================================You can execute arbitrary commands before, during, and after`config.status' is run. The three following macros accumulate thecommands to run when they are called multiple times.`AC_CONFIG_COMMANDS' replaces the obsolete macro `AC_OUTPUT_COMMANDS';see *Note Obsolete Macros::, for details.-- Macro: AC_CONFIG_COMMANDS (TAG..., [CMDS], [INIT-CMDS])Specify additional shell commands to run at the end of`config.status', and shell commands to initialize any variablesfrom `configure'. Associate the commands with TAG. Sincetypically the CMDS create a file, TAG should naturally be the nameof that file. If needed, the directory hosting TAG is created.This macro is one of the instantiating macros; see *NoteConfiguration Actions::.Here is an unrealistic example:fubar=42AC_CONFIG_COMMANDS([fubar],[echo this is extra $fubar, and so on.],[fubar=$fubar])Here is a better one:AC_CONFIG_COMMANDS([timestamp], [date >timestamp])The following two macros look similar, but in fact they are not ofthe same breed: they are executed directly by `configure', so youcannot use `config.status' to rerun them.-- Macro: AC_CONFIG_COMMANDS_PRE (CMDS)Execute the CMDS right before creating `config.status'.This macro presents the last opportunity to call `AC_SUBST',`AC_DEFINE', or `AC_CONFIG_FOOS' macros.-- Macro: AC_CONFIG_COMMANDS_POST (CMDS)Execute the CMDS right after creating `config.status'.File: autoconf.info, Node: Configuration Links, Next: Subdirectories, Prev: Configuration Commands, Up: Setup4.10 Creating Configuration Links=================================You may find it convenient to create links whose destinations dependupon results of tests. One can use `AC_CONFIG_COMMANDS' but thecreation of relative symbolic links can be delicate when the package isbuilt in a directory different from the source directory.-- Macro: AC_CONFIG_LINKS (DEST:SOURCE..., [CMDS], [INIT-CMDS])Make `AC_OUTPUT' link each of the existing files SOURCE to thecorresponding link name DEST. Makes a symbolic link if possible,otherwise a hard link if possible, otherwise a copy. The DEST andSOURCE names should be relative to the top level source or builddirectory. This macro is one of the instantiating macros; see*Note Configuration Actions::.For example, this call:AC_CONFIG_LINKS([host.h:config/$machine.hobject.h:config/$obj_format.h])creates in the current directory `host.h' as a link to`SRCDIR/config/$machine.h', and `object.h' as a link to`SRCDIR/config/$obj_format.h'.The tempting value `.' for DEST is invalid: it makes it impossiblefor `config.status' to guess the links to establish.One can then run:./config.status host.h object.hto create the links.File: autoconf.info, Node: Subdirectories, Next: Default Prefix, Prev: Configuration Links, Up: Setup4.11 Configuring Other Packages in Subdirectories=================================================In most situations, calling `AC_OUTPUT' is sufficient to producemakefiles in subdirectories. However, `configure' scripts that controlmore than one independent package can use `AC_CONFIG_SUBDIRS' to run`configure' scripts for other packages in subdirectories.-- Macro: AC_CONFIG_SUBDIRS (DIR ...)Make `AC_OUTPUT' run `configure' in each subdirectory DIR in thegiven blank-or-newline-separated list. Each DIR should be aliteral, i.e., please do not use:if test "$package_foo_enabled" = yes; then$my_subdirs="$my_subdirs foo"fiAC_CONFIG_SUBDIRS([$my_subdirs])because this prevents `./configure --help=recursive' fromdisplaying the options of the package `foo'. Instead, you shouldwrite:if test "$package_foo_enabled" = yes; thenAC_CONFIG_SUBDIRS([foo])fiIf a given DIR is not found, an error is reported: if thesubdirectory is optional, write:if test -d "$srcdir/foo"; thenAC_CONFIG_SUBDIRS([foo])fiIf a given DIR contains `configure.gnu', it is run instead of`configure'. This is for packages that might use a non-Autoconfscript `Configure', which can't be called through a wrapper`configure' since it would be the same file on case-insensitivefile systems. Likewise, if a DIR contains `configure.in' but no`configure', the Cygnus `configure' script found by`AC_CONFIG_AUX_DIR' is used.The subdirectory `configure' scripts are given the same commandline options that were given to this `configure' script, with minorchanges if needed, which include:- adjusting a relative name for the cache file;- adjusting a relative name for the source directory;- propagating the current value of `$prefix', including if itwas defaulted, and if the default values of the top level andof the subdirectory `configure' differ.This macro also sets the output variable `subdirs' to the list ofdirectories `DIR ...'. Make rules can use this variable todetermine which subdirectories to recurse into.This macro may be called multiple times.File: autoconf.info, Node: Default Prefix, Prev: Subdirectories, Up: Setup4.12 Default Prefix===================By default, `configure' sets the prefix for files it installs to`/usr/local'. The user of `configure' can select a different prefixusing the `--prefix' and `--exec-prefix' options. There are two waysto change the default: when creating `configure', and when running it.Some software packages might want to install in a directory otherthan `/usr/local' by default. To accomplish that, use the`AC_PREFIX_DEFAULT' macro.-- Macro: AC_PREFIX_DEFAULT (PREFIX)Set the default installation prefix to PREFIX instead of`/usr/local'.It may be convenient for users to have `configure' guess theinstallation prefix from the location of a related program that theyhave already installed. If you wish to do that, you can call`AC_PREFIX_PROGRAM'.-- Macro: AC_PREFIX_PROGRAM (PROGRAM)If the user did not specify an installation prefix (using the`--prefix' option), guess a value for it by looking for PROGRAM in`PATH', the way the shell does. If PROGRAM is found, set theprefix to the parent of the directory containing PROGRAM, elsedefault the prefix as described above (`/usr/local' or`AC_PREFIX_DEFAULT'). For example, if PROGRAM is `gcc' and the`PATH' contains `/usr/local/gnu/bin/gcc', set the prefix to`/usr/local/gnu'.File: autoconf.info, Node: Existing Tests, Next: Writing Tests, Prev: Setup, Up: Top5 Existing Tests****************These macros test for particular system features that packages mightneed or want to use. If you need to test for a kind of feature thatnone of these macros check for, you can probably do it by callingprimitive test macros with appropriate arguments (*note WritingTests::).These tests print messages telling the user which feature they'rechecking for, and what they find. They cache their results for future`configure' runs (*note Caching Results::).Some of these macros set output variables. *Note MakefileSubstitutions::, for how to get their values. The phrase "define NAME"is used below as a shorthand to mean "define the C preprocessor symbolNAME to the value 1". *Note Defining Symbols::, for how to get thosesymbol definitions into your program.* Menu:* Common Behavior:: Macros' standard schemes* Alternative Programs:: Selecting between alternative programs* Files:: Checking for the existence of files* Libraries:: Library archives that might be missing* Library Functions:: C library functions that might be missing* Header Files:: Header files that might be missing* Declarations:: Declarations that may be missing* Structures:: Structures or members that might be missing* Types:: Types that might be missing* Compilers and Preprocessors:: Checking for compiling programs* System Services:: Operating system services* Posix Variants:: Special kludges for specific Posix variants* Erlang Libraries:: Checking for the existence of Erlang librariesFile: autoconf.info, Node: Common Behavior, Next: Alternative Programs, Up: Existing Tests5.1 Common Behavior===================Much effort has been expended to make Autoconf easy to learn. The mostobvious way to reach this goal is simply to enforce standard interfacesand behaviors, avoiding exceptions as much as possible. Because ofhistory and inertia, unfortunately, there are still too many exceptionsin Autoconf; nevertheless, this section describes some of the commonrules.* Menu:* Standard Symbols:: Symbols defined by the macros* Default Includes:: Includes used by the generic macrosFile: autoconf.info, Node: Standard Symbols, Next: Default Includes, Up: Common Behavior5.1.1 Standard Symbols----------------------All the generic macros that `AC_DEFINE' a symbol as a result of theirtest transform their ARGUMENT values to a standard alphabet. First,ARGUMENT is converted to upper case and any asterisks (`*') are eachconverted to `P'. Any remaining characters that are not alphanumericare converted to underscores.For instance,AC_CHECK_TYPES([struct $Expensive*])defines the symbol `HAVE_STRUCT__EXPENSIVEP' if the check succeeds.File: autoconf.info, Node: Default Includes, Prev: Standard Symbols, Up: Common Behavior5.1.2 Default Includes----------------------Several tests depend upon a set of header files. Since these headersare not universally available, tests actually have to provide a set ofprotected includes, such as:#ifdef TIME_WITH_SYS_TIME# include <sys/time.h># include <time.h>#else# ifdef HAVE_SYS_TIME_H# include <sys/time.h># else# include <time.h># endif#endifUnless you know exactly what you are doing, you should avoid usingunconditional includes, and check the existence of the headers youinclude beforehand (*note Header Files::).Most generic macros use the following macro to provide the defaultset of includes:-- Macro: AC_INCLUDES_DEFAULT ([INCLUDE-DIRECTIVES])Expand to INCLUDE-DIRECTIVES if defined, otherwise to:#include <stdio.h>#ifdef HAVE_SYS_TYPES_H# include <sys/types.h>#endif#ifdef HAVE_SYS_STAT_H# include <sys/stat.h>#endif#ifdef STDC_HEADERS# include <stdlib.h># include <stddef.h>#else# ifdef HAVE_STDLIB_H# include <stdlib.h># endif#endif#ifdef HAVE_STRING_H# if !defined STDC_HEADERS && defined HAVE_MEMORY_H# include <memory.h># endif# include <string.h>#endif#ifdef HAVE_STRINGS_H# include <strings.h>#endif#ifdef HAVE_INTTYPES_H# include <inttypes.h>#endif#ifdef HAVE_STDINT_H# include <stdint.h>#endif#ifdef HAVE_UNISTD_H# include <unistd.h>#endifIf the default includes are used, then check for the presence ofthese headers and their compatibility, i.e., you don't need to run`AC_HEADER_STDC', nor check for `stdlib.h' etc.These headers are checked for in the same order as they areincluded. For instance, on some systems `string.h' and`strings.h' both exist, but conflict. Then `HAVE_STRING_H' isdefined, not `HAVE_STRINGS_H'.File: autoconf.info, Node: Alternative Programs, Next: Files, Prev: Common Behavior, Up: Existing Tests5.2 Alternative Programs========================These macros check for the presence or behavior of particular programs.They are used to choose between several alternative programs and todecide what to do once one has been chosen. If there is no macrospecifically defined to check for a program you need, and you don't needto check for any special properties of it, then you can use one of thegeneral program-check macros.* Menu:* Particular Programs:: Special handling to find certain programs* Generic Programs:: How to find other programsFile: autoconf.info, Node: Particular Programs, Next: Generic Programs, Up: Alternative Programs5.2.1 Particular Program Checks-------------------------------These macros check for particular programs--whether they exist, and insome cases whether they support certain features.-- Macro: AC_PROG_AWKCheck for `gawk', `mawk', `nawk', and `awk', in that order, andset output variable `AWK' to the first one that is found. Ittries `gawk' first because that is reported to be the bestimplementation.-- Macro: AC_PROG_GREPLook for the best available `grep' or `ggrep' that accepts thelongest input lines possible, and that supports multiple `-e'options. Set the output variable `GREP' to whatever is chosen.*Note Limitations of Usual Tools::, for more information aboutportability problems with the `grep' command family.-- Macro: AC_PROG_EGREPCheck whether `$GREP -E' works, or else look for the best available`egrep' or `gegrep' that accepts the longest input lines possible.Set the output variable `EGREP' to whatever is chosen.-- Macro: AC_PROG_FGREPCheck whether `$GREP -F' works, or else look for the best available`fgrep' or `gfgrep' that accepts the longest input lines possible.Set the output variable `FGREP' to whatever is chosen.-- Macro: AC_PROG_INSTALLSet output variable `INSTALL' to the name of a BSD-compatible`install' program, if one is found in the current `PATH'.Otherwise, set `INSTALL' to `DIR/install-sh -c', checking thedirectories specified to `AC_CONFIG_AUX_DIR' (or its defaultdirectories) to determine DIR (*note Output::). Also set thevariables `INSTALL_PROGRAM' and `INSTALL_SCRIPT' to `${INSTALL}'and `INSTALL_DATA' to `${INSTALL} -m 644'.`@INSTALL@' is special, as its value may vary for differentconfiguration files.This macro screens out various instances of `install' known not towork. It prefers to find a C program rather than a shell script,for speed. Instead of `install-sh', it can also use `install.sh',but that name is obsolete because some `make' programs have a rulethat creates `install' from it if there is no makefile.Autoconf comes with a copy of `install-sh' that you can use. Ifyou use `AC_PROG_INSTALL', you must include either `install-sh' or`install.sh' in your distribution; otherwise `configure' producesan error message saying it can't find them--even if the systemyou're on has a good `install' program. This check is a safetymeasure to prevent you from accidentally leaving that file out,which would prevent your package from installing on systems thatdon't have a BSD-compatible `install' program.If you need to use your own installation program because it hasfeatures not found in standard `install' programs, there is noreason to use `AC_PROG_INSTALL'; just put the file name of yourprogram into your `Makefile.in' files.-- Macro: AC_PROG_MKDIR_PSet output variable `MKDIR_P' to a program that ensures that foreach argument, a directory named by this argument exists, creatingit and its parent directories if needed, and without raceconditions when two instances of the program attempt to make thesame directory at nearly the same time.This macro uses the `mkdir -p' command if possible. Otherwise, itfalls back on invoking `install-sh' with the `-d' option, so yourpackage should contain `install-sh' as described under`AC_PROG_INSTALL'. An `install-sh' file that predates Autoconf2.60 or Automake 1.10 is vulnerable to race conditions, so if youwant to support parallel installs from different packages into thesame directory you need to make sure you have an up-to-date`install-sh'. In particular, be careful about using `autoreconf-if' if your Automake predates Automake 1.10.This macro is related to the `AS_MKDIR_P' macro (*note Programmingin M4sh::), but it sets an output variable intended for use inother files, whereas `AS_MKDIR_P' is intended for use in scriptslike `configure'. Also, `AS_MKDIR_P' does not accept options, but`MKDIR_P' supports the `-m' option, e.g., a makefile might invoke`$(MKDIR_P) -m 0 dir' to create an inaccessible directory, andconversely a makefile should use `$(MKDIR_P) -- $(FOO)' if FOOmight yield a value that begins with `-'. Finally, `AS_MKDIR_P'does not check for race condition vulnerability, whereas`AC_PROG_MKDIR_P' does.`@MKDIR_P@' is special, as its value may vary for differentconfiguration files.-- Macro: AC_PROG_LEXIf `flex' is found, set output variable `LEX' to `flex' and`LEXLIB' to `-lfl', if that library is in a standard place.Otherwise set `LEX' to `lex' and `LEXLIB' to `-ll'.Define `YYTEXT_POINTER' if `yytext' defaults to `char *' insteadof to `char []'. Also set output variable `LEX_OUTPUT_ROOT' tothe base of the file name that the lexer generates; usually`lex.yy', but sometimes something else. These results varyaccording to whether `lex' or `flex' is being used.You are encouraged to use Flex in your sources, since it is bothmore pleasant to use than plain Lex and the C source it producesis portable. In order to ensure portability, however, you musteither provide a function `yywrap' or, if you don't use it (e.g.,your scanner has no `#include'-like feature), simply include a`%noyywrap' statement in the scanner's source. Once this done,the scanner is portable (unless _you_ felt free to use nonportableconstructs) and does not depend on any library. In this case, andin this case only, it is suggested that you use this Autoconfsnippet:AC_PROG_LEXif test "$LEX" != flex; thenLEX="$SHELL $missing_dir/missing flex"AC_SUBST([LEX_OUTPUT_ROOT], [lex.yy])AC_SUBST([LEXLIB], [''])fiThe shell script `missing' can be found in the Automakedistribution.To ensure backward compatibility, Automake's `AM_PROG_LEX' invokes(indirectly) this macro twice, which causes an annoying but benign"`AC_PROG_LEX' invoked multiple times" warning. Future versionsof Automake will fix this issue; meanwhile, just ignore thismessage.As part of running the test, this macro may delete any file in theconfiguration directory named `lex.yy.c' or `lexyy.c'.-- Macro: AC_PROG_LN_SIf `ln -s' works on the current file system (the operating systemand file system support symbolic links), set the output variable`LN_S' to `ln -s'; otherwise, if `ln' works, set `LN_S' to `ln',and otherwise set it to `cp -p'.If you make a link in a directory other than the currentdirectory, its meaning depends on whether `ln' or `ln -s' is used.To safely create links using `$(LN_S)', either find out whichform is used and adjust the arguments, or always invoke `ln' inthe directory where the link is to be created.In other words, it does not work to do:$(LN_S) foo /x/barInstead, do:(cd /x && $(LN_S) foo bar)-- Macro: AC_PROG_RANLIBSet output variable `RANLIB' to `ranlib' if `ranlib' is found, andotherwise to `:' (do nothing).-- Macro: AC_PROG_SEDSet output variable `SED' to a Sed implementation that conforms toPosix and does not have arbitrary length limits. Report an errorif no acceptable Sed is found. *Note Limitations of UsualTools::, for more information about portability problems with Sed.-- Macro: AC_PROG_YACCIf `bison' is found, set output variable `YACC' to `bison -y'.Otherwise, if `byacc' is found, set `YACC' to `byacc'. Otherwiseset `YACC' to `yacc'.File: autoconf.info, Node: Generic Programs, Prev: Particular Programs, Up: Alternative Programs5.2.2 Generic Program and File Checks-------------------------------------These macros are used to find programs not covered by the "particular"test macros. If you need to check the behavior of a program as well asfind out whether it is present, you have to write your own test for it(*note Writing Tests::). By default, these macros use the environmentvariable `PATH'. If you need to check for a program that might not bein the user's `PATH', you can pass a modified path to use instead, likethis:AC_PATH_PROG([INETD], [inetd], [/usr/libexec/inetd],[$PATH:/usr/libexec:/usr/sbin:/usr/etc:/etc])You are strongly encouraged to declare the VARIABLE passed to`AC_CHECK_PROG' etc. as precious, *Note Setting Output Variables::,`AC_ARG_VAR', for more details.-- Macro: AC_CHECK_PROG (VARIABLE, PROG-TO-CHECK-FOR, VALUE-IF-FOUND,[VALUE-IF-NOT-FOUND], [PATH], [REJECT])Check whether program PROG-TO-CHECK-FOR exists in `PATH'. If itis found, set VARIABLE to VALUE-IF-FOUND, otherwise toVALUE-IF-NOT-FOUND, if given. Always pass over REJECT (anabsolute file name) even if it is the first found in the searchpath; in that case, set VARIABLE using the absolute file name ofthe PROG-TO-CHECK-FOR found that is not REJECT. If VARIABLE wasalready set, do nothing. Calls `AC_SUBST' for VARIABLE.-- Macro: AC_CHECK_PROGS (VARIABLE, PROGS-TO-CHECK-FOR,[VALUE-IF-NOT-FOUND], [PATH])Check for each program in the blank-separated listPROGS-TO-CHECK-FOR existing in the `PATH'. If one is found, setVARIABLE to the name of that program. Otherwise, continuechecking the next program in the list. If none of the programs inthe list are found, set VARIABLE to VALUE-IF-NOT-FOUND; ifVALUE-IF-NOT-FOUND is not specified, the value of VARIABLE is notchanged. Calls `AC_SUBST' for VARIABLE.-- Macro: AC_CHECK_TARGET_TOOL (VARIABLE, PROG-TO-CHECK-FOR,[VALUE-IF-NOT-FOUND], [PATH])Like `AC_CHECK_PROG', but first looks for PROG-TO-CHECK-FOR with aprefix of the target type as determined by `AC_CANONICAL_TARGET',followed by a dash (*note Canonicalizing::). If the tool cannotbe found with a prefix, and if the build and target types areequal, then it is also searched for without a prefix.As noted in *Note Specifying the system type: Specifying Names, thetarget is rarely specified, because most of the time it is the sameas the host: it is the type of system for which any compiler toolin the package produces code. What this macro looks for is, forexample, _a tool (assembler, linker, etc.) that the compilerdriver (`gcc' for the GNU C Compiler) uses to produce objects,archives or executables_.-- Macro: AC_CHECK_TOOL (VARIABLE, PROG-TO-CHECK-FOR,[VALUE-IF-NOT-FOUND], [PATH])Like `AC_CHECK_PROG', but first looks for PROG-TO-CHECK-FOR with aprefix of the host type as determined by `AC_CANONICAL_HOST',followed by a dash (*note Canonicalizing::). For example, if theuser runs `configure --host=i386-gnu', then this call:AC_CHECK_TOOL([RANLIB], [ranlib], [:])sets `RANLIB' to `i386-gnu-ranlib' if that program exists in`PATH', or otherwise to `ranlib' if that program exists in `PATH',or to `:' if neither program exists.In the future, when cross-compiling this macro will _only_ acceptprogram names that are prefixed with the host type. For moreinformation, see *Note Specifying the system type: SpecifyingNames.-- Macro: AC_CHECK_TARGET_TOOLS (VARIABLE, PROGS-TO-CHECK-FOR,[VALUE-IF-NOT-FOUND], [PATH])Like `AC_CHECK_TARGET_TOOL', each of the tools in the listPROGS-TO-CHECK-FOR are checked with a prefix of the target type asdetermined by `AC_CANONICAL_TARGET', followed by a dash (*noteCanonicalizing::). If none of the tools can be found with aprefix, and if the build and target types are equal, then thefirst one without a prefix is used. If a tool is found, setVARIABLE to the name of that program. If none of the tools in thelist are found, set VARIABLE to VALUE-IF-NOT-FOUND; ifVALUE-IF-NOT-FOUND is not specified, the value of VARIABLE is notchanged. Calls `AC_SUBST' for VARIABLE.-- Macro: AC_CHECK_TOOLS (VARIABLE, PROGS-TO-CHECK-FOR,[VALUE-IF-NOT-FOUND], [PATH])Like `AC_CHECK_TOOL', each of the tools in the listPROGS-TO-CHECK-FOR are checked with a prefix of the host type asdetermined by `AC_CANONICAL_HOST', followed by a dash (*noteCanonicalizing::). If none of the tools can be found with aprefix, then the first one without a prefix is used. If a tool isfound, set VARIABLE to the name of that program. If none of thetools in the list are found, set VARIABLE to VALUE-IF-NOT-FOUND; ifVALUE-IF-NOT-FOUND is not specified, the value of VARIABLE is notchanged. Calls `AC_SUBST' for VARIABLE.In the future, when cross-compiling this macro will _not_ acceptprogram names that are not prefixed with the host type.-- Macro: AC_PATH_PROG (VARIABLE, PROG-TO-CHECK-FOR,[VALUE-IF-NOT-FOUND], [PATH])Like `AC_CHECK_PROG', but set VARIABLE to the absolute name ofPROG-TO-CHECK-FOR if found.-- Macro: AC_PATH_PROGS (VARIABLE, PROGS-TO-CHECK-FOR,[VALUE-IF-NOT-FOUND], [PATH])Like `AC_CHECK_PROGS', but if any of PROGS-TO-CHECK-FOR are found,set VARIABLE to the absolute name of the program found.-- Macro: AC_PATH_TARGET_TOOL (VARIABLE, PROG-TO-CHECK-FOR,[VALUE-IF-NOT-FOUND], [PATH])Like `AC_CHECK_TARGET_TOOL', but set VARIABLE to the absolute nameof the program if it is found.-- Macro: AC_PATH_TOOL (VARIABLE, PROG-TO-CHECK-FOR,[VALUE-IF-NOT-FOUND], [PATH])Like `AC_CHECK_TOOL', but set VARIABLE to the absolute name of theprogram if it is found.In the future, when cross-compiling this macro will _not_ acceptprogram names that are not prefixed with the host type.File: autoconf.info, Node: Files, Next: Libraries, Prev: Alternative Programs, Up: Existing Tests5.3 Files=========You might also need to check for the existence of files. Before usingthese macros, ask yourself whether a runtime test might not be a bettersolution. Be aware that, like most Autoconf macros, they test a featureof the host machine, and therefore, they die when cross-compiling.-- Macro: AC_CHECK_FILE (FILE, [ACTION-IF-FOUND],[ACTION-IF-NOT-FOUND])Check whether file FILE exists on the native system. If it isfound, execute ACTION-IF-FOUND, otherwise do ACTION-IF-NOT-FOUND,if given.-- Macro: AC_CHECK_FILES (FILES, [ACTION-IF-FOUND],[ACTION-IF-NOT-FOUND])Executes `AC_CHECK_FILE' once for each file listed in FILES.Additionally, defines `HAVE_FILE' (*note Standard Symbols::) foreach file found.File: autoconf.info, Node: Libraries, Next: Library Functions, Prev: Files, Up: Existing Tests5.4 Library Files=================The following macros check for the presence of certain C, C++, orFortran library archive files.-- Macro: AC_CHECK_LIB (LIBRARY, FUNCTION, [ACTION-IF-FOUND],[ACTION-IF-NOT-FOUND], [OTHER-LIBRARIES])Test whether the library LIBRARY is available by trying to link atest program that calls function FUNCTION with the library.FUNCTION should be a function provided by the library. Use thebase name of the library; e.g., to check for `-lmp', use `mp' asthe LIBRARY argument.ACTION-IF-FOUND is a list of shell commands to run if the linkwith the library succeeds; ACTION-IF-NOT-FOUND is a list of shellcommands to run if the link fails. If ACTION-IF-FOUND is notspecified, the default action prepends `-lLIBRARY' to `LIBS' anddefines `HAVE_LIBLIBRARY' (in all capitals). This macro isintended to support building `LIBS' in a right-to-left(least-dependent to most-dependent) fashion such that librarydependencies are satisfied as a natural side effect of consecutivetests. Linkers are sensitive to library ordering so the order inwhich `LIBS' is generated is important to reliable detection oflibraries.If linking with LIBRARY results in unresolved symbols that wouldbe resolved by linking with additional libraries, give thoselibraries as the OTHER-LIBRARIES argument, separated by spaces:e.g., `-lXt -lX11'. Otherwise, this macro fails to detect thatLIBRARY is present, because linking the test program always failswith unresolved symbols. The OTHER-LIBRARIES argument should belimited to cases where it is desirable to test for one library inthe presence of another that is not already in `LIBS'.`AC_CHECK_LIB' requires some care in usage, and should be avoidedin some common cases. Many standard functions like `gethostbyname'appear the standard C library on some hosts, and in speciallibraries like `nsl' on other hosts. On some hosts the speciallibraries contain variant implementations that you may not want touse. These days it is normally better to use`AC_SEARCH_LIBS([gethostbyname], [nsl])' instead of`AC_CHECK_LIB([nsl], [gethostbyname])'.-- Macro: AC_SEARCH_LIBS (FUNCTION, SEARCH-LIBS, [ACTION-IF-FOUND],[ACTION-IF-NOT-FOUND], [OTHER-LIBRARIES])Search for a library defining FUNCTION if it's not alreadyavailable. This equates to calling`AC_LINK_IFELSE([AC_LANG_CALL([], [FUNCTION])])' first with nolibraries, then for each library listed in SEARCH-LIBS.Add `-lLIBRARY' to `LIBS' for the first library found to containFUNCTION, and run ACTION-IF-FOUND. If the function is not found,run ACTION-IF-NOT-FOUND.If linking with LIBRARY results in unresolved symbols that wouldbe resolved by linking with additional libraries, give thoselibraries as the OTHER-LIBRARIES argument, separated by spaces:e.g., `-lXt -lX11'. Otherwise, this macro fails to detect thatFUNCTION is present, because linking the test program always failswith unresolved symbols.File: autoconf.info, Node: Library Functions, Next: Header Files, Prev: Libraries, Up: Existing Tests5.5 Library Functions=====================The following macros check for particular C library functions. Ifthere is no macro specifically defined to check for a function you need,and you don't need to check for any special properties of it, then youcan use one of the general function-check macros.* Menu:* Function Portability:: Pitfalls with usual functions* Particular Functions:: Special handling to find certain functions* Generic Functions:: How to find other functionsFile: autoconf.info, Node: Function Portability, Next: Particular Functions, Up: Library Functions5.5.1 Portability of C Functions--------------------------------Most usual functions can either be missing, or be buggy, or be limitedon some architectures. This section tries to make an inventory of theseportability issues. By definition, this list always requiresadditions. Please help us keeping it as complete as possible.`exit'On ancient hosts, `exit' returned `int'. This is because `exit'predates `void', and there was a long tradition of it returning`int'.On current hosts, the problem more likely is that `exit' is notdeclared, due to C++ problems of some sort or another. For thisreason we suggest that test programs not invoke `exit', but returnfrom `main' instead.`free'The C standard says a call `free (NULL)' does nothing, but someold systems don't support this (e.g., NextStep).`isinf'`isnan'The C99 standard says that `isinf' and `isnan' are macros. Onsome systems just macros are available (e.g., HP-UX and Solaris10), on some systems both macros and functions (e.g., glibc2.3.2), and on some systems only functions (e.g., IRIX 6 andSolaris 9). In some cases these functions are declared innonstandard headers like `<sunmath.h>' and defined in non-defaultlibraries like `-lm' or `-lsunmath'.The C99 `isinf' and `isnan' macros work correctly with `longdouble' arguments, but pre-C99 systems that use functionstypically assume `double' arguments. On such a system, `isinf'incorrectly returns true for a finite `long double' argument thatis outside the range of `double'.To work around this porting mess, you can use code like thefollowing.#include <math.h>#ifndef isnan# define isnan(x) \(sizeof (x) == sizeof (long double) ? isnan_ld (x) \: sizeof (x) == sizeof (double) ? isnan_d (x) \: isnan_f (x))static inline int isnan_f (float x) { return x != x; }static inline int isnan_d (double x) { return x != x; }static inline int isnan_ld (long double x) { return x != x; }#endif#ifndef isinf# define isinf(x) \(sizeof (x) == sizeof (long double) ? isinf_ld (x) \: sizeof (x) == sizeof (double) ? isinf_d (x) \: isinf_f (x))static inline int isinf_f (float x) { return isnan (x - x); }static inline int isinf_d (double x) { return isnan (x - x); }static inline int isinf_ld (long double x) { return isnan (x - x); }#endifUse `AC_C_INLINE' (*note C Compiler::) so that this code works oncompilers that lack the `inline' keyword. Some optimizingcompilers mishandle these definitions, but systems with that bugtypically have missing or broken `isnan' functions anyway, so it'sprobably not worth worrying about.`malloc'The C standard says a call `malloc (0)' is implementationdependent. It can return either `NULL' or a new non-null pointer.The latter is more common (e.g., the GNU C Library) but is by nomeans universal. `AC_FUNC_MALLOC' can be used to insist onnon-`NULL' (*note Particular Functions::).`putenv'Posix prefers `setenv' to `putenv'; among other things, `putenv'is not required of all Posix implementations, but `setenv' is.Posix specifies that `putenv' puts the given string directly in`environ', but some systems make a copy of it instead (e.g., glibc2.0, or BSD). And when a copy is made, `unsetenv' might not freeit, causing a memory leak (e.g., FreeBSD 4).On some systems `putenv ("FOO")' removes `FOO' from theenvironment, but this is not standard usage and it dumps core onsome systems (e.g., AIX).On MinGW, a call `putenv ("FOO=")' removes `FOO' from theenvironment, rather than inserting it with an empty value.`realloc'The C standard says a call `realloc (NULL, size)' is equivalent to`malloc (size)', but some old systems don't support this (e.g.,NextStep).`signal' handlerNormally `signal' takes a handler function with a return type of`void', but some old systems required `int' instead. Any actual`int' value returned is not used; this is only a difference in thefunction prototype demanded.All systems we know of in current use return `void'. The `int'was to support K&R C, where of course `void' is not available.`AC_TYPE_SIGNAL' (*note Particular Types::) can be used toestablish the correct type in all cases.`snprintf'The C99 standard says that if the output array isn't big enoughand if no other errors occur, `snprintf' and `vsnprintf' truncatethe output and return the number of bytes that ought to have beenproduced. Some older systems return the truncated length (e.g.,GNU C Library 2.0.x or IRIX 6.5), some a negative value (e.g.,earlier GNU C Library versions), and some the buffer lengthwithout truncation (e.g., 32-bit Solaris 7). Also, some buggyolder systems ignore the length and overrun the buffer (e.g.,64-bit Solaris 7).`sprintf'The C standard says `sprintf' and `vsprintf' return the number ofbytes written. On some ancient systems (SunOS 4 for instance)they return the buffer pointer instead, but these no longer needto be worried about.`sscanf'On various old systems, e.g., HP-UX 9, `sscanf' requires that itsinput string be writable (though it doesn't actually change it).This can be a problem when using `gcc' since it normally putsconstant strings in read-only memory (*note Incompatibilities ofGCC: (gcc)Incompatibilities.). Apparently in some cases evenhaving format strings read-only can be a problem.`strerror_r'Posix specifies that `strerror_r' returns an `int', but manysystems (e.g., GNU C Library version 2.2.4) provide a differentversion returning a `char *'. `AC_FUNC_STRERROR_R' can detectwhich is in use (*note Particular Functions::).`strnlen'AIX 4.3 provides a broken version which produces the followingresults:strnlen ("foobar", 0) = 0strnlen ("foobar", 1) = 3strnlen ("foobar", 2) = 2strnlen ("foobar", 3) = 1strnlen ("foobar", 4) = 0strnlen ("foobar", 5) = 6strnlen ("foobar", 6) = 6strnlen ("foobar", 7) = 6strnlen ("foobar", 8) = 6strnlen ("foobar", 9) = 6`sysconf'`_SC_PAGESIZE' is standard, but some older systems (e.g., HP-UX 9)have `_SC_PAGE_SIZE' instead. This can be tested with `#ifdef'.`unlink'The Posix spec says that `unlink' causes the given file to beremoved only after there are no more open file handles for it.Some non-Posix hosts have trouble with this requirement, though,and some DOS variants even corrupt the file system.`unsetenv'On MinGW, `unsetenv' is not available, but a variable `FOO' can beremoved with a call `putenv ("FOO=")', as described under `putenv'above.`va_copy'The C99 standard provides `va_copy' for copying `va_list'variables. It may be available in older environments too, thoughpossibly as `__va_copy' (e.g., `gcc' in strict pre-C99 mode).These can be tested with `#ifdef'. A fallback to `memcpy (&dst,&src, sizeof (va_list))' gives maximum portability.`va_list'`va_list' is not necessarily just a pointer. It can be a `struct'(e.g., `gcc' on Alpha), which means `NULL' is not portable. Or itcan be an array (e.g., `gcc' in some PowerPC configurations),which means as a function parameter it can be effectivelycall-by-reference and library routines might modify the value backin the caller (e.g., `vsnprintf' in the GNU C Library 2.1).Signed `>>'Normally the C `>>' right shift of a signed type replicates thehigh bit, giving a so-called "arithmetic" shift. But care shouldbe taken since Standard C doesn't require that behavior. On thosefew processors without a native arithmetic shift (for instance Crayvector systems) zero bits may be shifted in, the same as a shiftof an unsigned type.Integer `/'C divides signed integers by truncating their quotient toward zero,yielding the same result as Fortran. However, before C99 thestandard allowed C implementations to take the floor or ceiling ofthe quotient in some cases. Hardly any implementations tookadvantage of this freedom, though, and it's probably not worthworrying about this issue nowadays.File: autoconf.info, Node: Particular Functions, Next: Generic Functions, Prev: Function Portability, Up: Library Functions5.5.2 Particular Function Checks--------------------------------These macros check for particular C functions--whether they exist, andin some cases how they respond when given certain arguments.-- Macro: AC_FUNC_ALLOCACheck how to get `alloca'. Tries to get a builtin version bychecking for `alloca.h' or the predefined C preprocessor macros`__GNUC__' and `_AIX'. If this macro finds `alloca.h', it defines`HAVE_ALLOCA_H'.If those attempts fail, it looks for the function in the standard Clibrary. If any of those methods succeed, it defines`HAVE_ALLOCA'. Otherwise, it sets the output variable `ALLOCA' to`${LIBOBJDIR}alloca.o' and defines `C_ALLOCA' (so programs canperiodically call `alloca (0)' to garbage collect). This variableis separate from `LIBOBJS' so multiple programs can share thevalue of `ALLOCA' without needing to create an actual library, incase only some of them use the code in `LIBOBJS'. The`${LIBOBJDIR}' prefix serves the same purpose as in `LIBOBJS'(*note AC_LIBOBJ vs LIBOBJS::).This macro does not try to get `alloca' from the System V R3`libPW' or the System V R4 `libucb' because those librariescontain some incompatible functions that cause trouble. Someversions do not even contain `alloca' or contain a buggy version.If you still want to use their `alloca', use `ar' to extract`alloca.o' from them instead of compiling `alloca.c'.Source files that use `alloca' should start with a piece of codelike the following, to declare it properly.#ifdef HAVE_ALLOCA_H# include <alloca.h>#elif defined __GNUC__# define alloca __builtin_alloca#elif defined _AIX# define alloca __alloca#elif defined _MSC_VER# include <malloc.h># define alloca _alloca#else# include <stddef.h># ifdef __cplusplusextern "C"# endifvoid *alloca (size_t);#endif-- Macro: AC_FUNC_CHOWNIf the `chown' function is available and works (in particular, itshould accept `-1' for `uid' and `gid'), define `HAVE_CHOWN'.-- Macro: AC_FUNC_CLOSEDIR_VOIDIf the `closedir' function does not return a meaningful value,define `CLOSEDIR_VOID'. Otherwise, callers ought to check itsreturn value for an error indicator.Currently this test is implemented by running a test program. Whencross compiling the pessimistic assumption that `closedir' does notreturn a meaningful value is made.This macro is obsolescent, as `closedir' returns a meaningful valueon current systems. New programs need not use this macro.-- Macro: AC_FUNC_ERROR_AT_LINEIf the `error_at_line' function is not found, require an`AC_LIBOBJ' replacement of `error'.-- Macro: AC_FUNC_FNMATCHIf the `fnmatch' function conforms to Posix, define`HAVE_FNMATCH'. Detect common implementation bugs, for example,the bugs in Solaris 2.4.Unlike the other specific `AC_FUNC' macros, `AC_FUNC_FNMATCH' doesnot replace a broken/missing `fnmatch'. This is for historicalreasons. See `AC_REPLACE_FNMATCH' below.This macro is obsolescent. New programs should use Gnulib's`fnmatch-posix' module. *Note Gnulib::.-- Macro: AC_FUNC_FNMATCH_GNUBehave like `AC_REPLACE_FNMATCH' (_replace_) but also test whether`fnmatch' supports GNU extensions. Detect common implementationbugs, for example, the bugs in the GNU C Library 2.1.This macro is obsolescent. New programs should use Gnulib's`fnmatch-gnu' module. *Note Gnulib::.-- Macro: AC_FUNC_FORKThis macro checks for the `fork' and `vfork' functions. If aworking `fork' is found, define `HAVE_WORKING_FORK'. This macrochecks whether `fork' is just a stub by trying to run it.If `vfork.h' is found, define `HAVE_VFORK_H'. If a working`vfork' is found, define `HAVE_WORKING_VFORK'. Otherwise, define`vfork' to be `fork' for backward compatibility with previousversions of `autoconf'. This macro checks for several knownerrors in implementations of `vfork' and considers the system tonot have a working `vfork' if it detects any of them. It is notconsidered to be an implementation error if a child's invocationof `signal' modifies the parent's signal handler, since childprocesses rarely change their signal handlers.Since this macro defines `vfork' only for backward compatibilitywith previous versions of `autoconf' you're encouraged to define ityourself in new code:#ifndef HAVE_WORKING_VFORK# define vfork fork#endif-- Macro: AC_FUNC_FSEEKOIf the `fseeko' function is available, define `HAVE_FSEEKO'.Define `_LARGEFILE_SOURCE' if necessary to make the prototypevisible on some systems (e.g., glibc 2.2). Otherwise linkageproblems may occur when compiling with `AC_SYS_LARGEFILE' onlargefile-sensitive systems where `off_t' does not default to a64bit entity.-- Macro: AC_FUNC_GETGROUPSIf the `getgroups' function is available and works (unlike onUltrix 4.3, where `getgroups (0, 0)' always fails), define`HAVE_GETGROUPS'. Set `GETGROUPS_LIBS' to any libraries needed toget that function. This macro runs `AC_TYPE_GETGROUPS'.-- Macro: AC_FUNC_GETLOADAVGCheck how to get the system load averages. To perform its testsproperly, this macro needs the file `getloadavg.c'; therefore, besure to set the `AC_LIBOBJ' replacement directory properly (see*Note Generic Functions::, `AC_CONFIG_LIBOBJ_DIR').If the system has the `getloadavg' function, define`HAVE_GETLOADAVG', and set `GETLOADAVG_LIBS' to any librariesnecessary to get that function. Also add `GETLOADAVG_LIBS' to`LIBS'. Otherwise, require an `AC_LIBOBJ' replacement for`getloadavg' with source code in `DIR/getloadavg.c', and possiblydefine several other C preprocessor macros and output variables:1. Define `C_GETLOADAVG'.2. Define `SVR4', `DGUX', `UMAX', or `UMAX4_3' if on thosesystems.3. If `nlist.h' is found, define `HAVE_NLIST_H'.4. If `struct nlist' has an `n_un.n_name' member, define`HAVE_STRUCT_NLIST_N_UN_N_NAME'. The obsolete symbol`NLIST_NAME_UNION' is still defined, but do not depend uponit.5. Programs may need to be installed set-group-ID (orset-user-ID) for `getloadavg' to work. In this case, define`GETLOADAVG_PRIVILEGED', set the output variable `NEED_SETGID'to `true' (and otherwise to `false'), and set `KMEM_GROUP' tothe name of the group that should own the installed program.The `AC_FUNC_GETLOADVG' macro is obsolescent. New programs shoulduse Gnulib's `getloadavg' module. *Note Gnulib::.-- Macro: AC_FUNC_GETMNTENTCheck for `getmntent' in the standard C library, and then in the`sun', `seq', and `gen' libraries, for UNICOS, IRIX 4, PTX, andUnixWare, respectively. Then, if `getmntent' is available, define`HAVE_GETMNTENT'.-- Macro: AC_FUNC_GETPGRPDefine `GETPGRP_VOID' if it is an error to pass 0 to `getpgrp';this is the Posix behavior. On older BSD systems, you must pass 0to `getpgrp', as it takes an argument and behaves like Posix's`getpgid'.#ifdef GETPGRP_VOIDpid = getpgrp ();#elsepid = getpgrp (0);#endifThis macro does not check whether `getpgrp' exists at all; if youneed to work in that situation, first call `AC_CHECK_FUNC' for`getpgrp'.This macro is obsolescent, as current systems have a `getpgrp'whose signature conforms to Posix. New programs need not use thismacro.-- Macro: AC_FUNC_LSTAT_FOLLOWS_SLASHED_SYMLINKIf `link' is a symbolic link, then `lstat' should treat `link/'the same as `link/.'. However, many older `lstat' implementationsincorrectly ignore trailing slashes.It is safe to assume that if `lstat' incorrectly ignores trailingslashes, then other symbolic-link-aware functions like `unlink'also incorrectly ignore trailing slashes.If `lstat' behaves properly, define`LSTAT_FOLLOWS_SLASHED_SYMLINK', otherwise require an `AC_LIBOBJ'replacement of `lstat'.-- Macro: AC_FUNC_MALLOCIf the `malloc' function is compatible with the GNU C library`malloc' (i.e., `malloc (0)' returns a valid pointer), define`HAVE_MALLOC' to 1. Otherwise define `HAVE_MALLOC' to 0, ask foran `AC_LIBOBJ' replacement for `malloc', and define `malloc' to`rpl_malloc' so that the native `malloc' is not used in the mainproject.Typically, the replacement file `malloc.c' should look like (notethe `#undef malloc'):#ifdef HAVE_CONFIG_H# include <config.h>#endif#undef malloc#include <sys/types.h>void *malloc ();/* Allocate an N-byte block of memory from the heap.If N is zero, allocate a 1-byte block. */void *rpl_malloc (size_t n){if (n == 0)n = 1;return malloc (n);}-- Macro: AC_FUNC_MEMCMPIf the `memcmp' function is not available, or does not work on8-bit data (like the one on SunOS 4.1.3), or fails when comparing16 bytes or more and with at least one buffer not starting on a4-byte boundary (such as the one on NeXT x86 OpenStep), require an`AC_LIBOBJ' replacement for `memcmp'.This macro is obsolescent, as current systems have a working`memcmp'. New programs need not use this macro.-- Macro: AC_FUNC_MBRTOWCDefine `HAVE_MBRTOWC' to 1 if the function `mbrtowc' and the type`mbstate_t' are properly declared.-- Macro: AC_FUNC_MKTIMEIf the `mktime' function is not available, or does not workcorrectly, require an `AC_LIBOBJ' replacement for `mktime'. Forthe purposes of this test, `mktime' should conform to the Posixstandard and should be the inverse of `localtime'.-- Macro: AC_FUNC_MMAPIf the `mmap' function exists and works correctly, define`HAVE_MMAP'. This checks only private fixed mapping ofalready-mapped memory.-- Macro: AC_FUNC_OBSTACKIf the obstacks are found, define `HAVE_OBSTACK', else require an`AC_LIBOBJ' replacement for `obstack'.-- Macro: AC_FUNC_REALLOCIf the `realloc' function is compatible with the GNU C library`realloc' (i.e., `realloc (NULL, 0)' returns a valid pointer),define `HAVE_REALLOC' to 1. Otherwise define `HAVE_REALLOC' to 0,ask for an `AC_LIBOBJ' replacement for `realloc', and define`realloc' to `rpl_realloc' so that the native `realloc' is notused in the main project. See `AC_FUNC_MALLOC' for details.-- Macro: AC_FUNC_SELECT_ARGTYPESDetermines the correct type to be passed for each of the `select'function's arguments, and defines those types in`SELECT_TYPE_ARG1', `SELECT_TYPE_ARG234', and `SELECT_TYPE_ARG5'respectively. `SELECT_TYPE_ARG1' defaults to `int',`SELECT_TYPE_ARG234' defaults to `int *', and `SELECT_TYPE_ARG5'defaults to `struct timeval *'.This macro is obsolescent, as current systems have a `select' whosesignature conforms to Posix. New programs need not use this macro.-- Macro: AC_FUNC_SETPGRPIf `setpgrp' takes no argument (the Posix version), define`SETPGRP_VOID'. Otherwise, it is the BSD version, which takes twoprocess IDs as arguments. This macro does not check whether`setpgrp' exists at all; if you need to work in that situation,first call `AC_CHECK_FUNC' for `setpgrp'.This macro is obsolescent, as current systems have a `setpgrp'whose signature conforms to Posix. New programs need not use thismacro.-- Macro: AC_FUNC_STAT-- Macro: AC_FUNC_LSTATDetermine whether `stat' or `lstat' have the bug that it succeedswhen given the zero-length file name as argument. The `stat' and`lstat' from SunOS 4.1.4 and the Hurd (as of 1998-11-01) do this.If it does, then define `HAVE_STAT_EMPTY_STRING_BUG' (or`HAVE_LSTAT_EMPTY_STRING_BUG') and ask for an `AC_LIBOBJ'replacement of it.These macros are obsolescent, as no current systems have the bug.New programs need not use these macros.-- Macro: AC_FUNC_SETVBUF_REVERSEDIf `setvbuf' takes the buffering type as its second argument andthe buffer pointer as the third, instead of the other way around,define `SETVBUF_REVERSED'.This macro is obsolescent, as no current systems have the bug.New programs need not use this macro.-- Macro: AC_FUNC_STRCOLLIf the `strcoll' function exists and works correctly, define`HAVE_STRCOLL'. This does a bit more than`AC_CHECK_FUNCS(strcoll)', because some systems have incorrectdefinitions of `strcoll' that should not be used.-- Macro: AC_FUNC_STRERROR_RIf `strerror_r' is available, define `HAVE_STRERROR_R', and if itis declared, define `HAVE_DECL_STRERROR_R'. If it returns a `char*' message, define `STRERROR_R_CHAR_P'; otherwise it returns an`int' error number. The Thread-Safe Functions option of Posixrequires `strerror_r' to return `int', but many systems(including, for example, version 2.2.4 of the GNU C Library)return a `char *' value that is not necessarily equal to thebuffer argument.-- Macro: AC_FUNC_STRFTIMECheck for `strftime' in the `intl' library, for SCO Unix. Then,if `strftime' is available, define `HAVE_STRFTIME'.This macro is obsolescent, as no current systems require the `intl'library for `strftime'. New programs need not use this macro.-- Macro: AC_FUNC_STRTODIf the `strtod' function does not exist or doesn't work correctly,ask for an `AC_LIBOBJ' replacement of `strtod'. In this case,because `strtod.c' is likely to need `pow', set the outputvariable `POW_LIB' to the extra library needed.-- Macro: AC_FUNC_STRTOLDIf the `strtold' function exists and conforms to C99, define`HAVE_STRTOLD'.-- Macro: AC_FUNC_STRNLENIf the `strnlen' function is not available, or is buggy (like theone from AIX 4.3), require an `AC_LIBOBJ' replacement for it.-- Macro: AC_FUNC_UTIME_NULLIf `utime (FILE, NULL)' sets FILE's timestamp to the present,define `HAVE_UTIME_NULL'.This macro is obsolescent, as all current systems have a `utime'that behaves this way. New programs need not use this macro.-- Macro: AC_FUNC_VPRINTFIf `vprintf' is found, define `HAVE_VPRINTF'. Otherwise, if`_doprnt' is found, define `HAVE_DOPRNT'. (If `vprintf' isavailable, you may assume that `vfprintf' and `vsprintf' are alsoavailable.)This macro is obsolescent, as all current systems have `vprintf'.New programs need not use this macro.-- Macro: AC_REPLACE_FNMATCHIf the `fnmatch' function does not conform to Posix (see`AC_FUNC_FNMATCH'), ask for its `AC_LIBOBJ' replacement.The files `fnmatch.c', `fnmatch_loop.c', and `fnmatch_.h' in the`AC_LIBOBJ' replacement directory are assumed to contain a copy ofthe source code of GNU `fnmatch'. If necessary, this source codeis compiled as an `AC_LIBOBJ' replacement, and the `fnmatch_.h'file is linked to `fnmatch.h' so that it can be included in placeof the system `<fnmatch.h>'.This macro is obsolescent, as it assumes the use of particularsource files. New programs should use Gnulib's `fnmatch-posix'module, which provides this macro along with the source files.*Note Gnulib::.File: autoconf.info, Node: Generic Functions, Prev: Particular Functions, Up: Library Functions5.5.3 Generic Function Checks-----------------------------These macros are used to find functions not covered by the "particular"test macros. If the functions might be in libraries other than thedefault C library, first call `AC_CHECK_LIB' for those libraries. Ifyou need to check the behavior of a function as well as find outwhether it is present, you have to write your own test for it (*noteWriting Tests::).-- Macro: AC_CHECK_FUNC (FUNCTION, [ACTION-IF-FOUND],[ACTION-IF-NOT-FOUND])If C function FUNCTION is available, run shell commandsACTION-IF-FOUND, otherwise ACTION-IF-NOT-FOUND. If you just wantto define a symbol if the function is available, consider using`AC_CHECK_FUNCS' instead. This macro checks for functions with Clinkage even when `AC_LANG(C++)' has been called, since C is morestandardized than C++. (*note Language Choice::, for moreinformation about selecting the language for checks.)-- Macro: AC_CHECK_FUNCS (FUNCTION..., [ACTION-IF-FOUND],[ACTION-IF-NOT-FOUND])For each FUNCTION enumerated in the blank-or-newline-separatedargument list, define `HAVE_FUNCTION' (in all capitals) if it isavailable. If ACTION-IF-FOUND is given, it is additional shellcode to execute when one of the functions is found. You can giveit a value of `break' to break out of the loop on the first match.If ACTION-IF-NOT-FOUND is given, it is executed when one of thefunctions is not found.-- Macro: AC_CHECK_FUNCS_ONCE (FUNCTION...)For each FUNCTION enumerated in the blank-or-newline-separatedargument list, define `HAVE_FUNCTION' (in all capitals) if it isavailable. This is a once-only variant of `AC_CHECK_FUNCS'. Itgenerates the checking code at most once, so that `configure' issmaller and faster; but the checks cannot be conditionalized andare always done once, early during the `configure' run.Autoconf follows a philosophy that was formed over the years by thosewho have struggled for portability: isolate the portability issues inspecific files, and then program as if you were in a Posix environment.Some functions may be missing or unfixable, and your package must beready to replace them.Suitable replacements for many such problem functions are availablefrom Gnulib (*note Gnulib::).-- Macro: AC_LIBOBJ (FUNCTION)Specify that `FUNCTION.c' must be included in the executables toreplace a missing or broken implementation of FUNCTION.Technically, it adds `FUNCTION.$ac_objext' to the output variable`LIBOBJS' if it is not already in, and calls `AC_LIBSOURCE' for`FUNCTION.c'. You should not directly change `LIBOBJS', sincethis is not traceable.-- Macro: AC_LIBSOURCE (FILE)Specify that FILE might be needed to compile the project. If youneed to know what files might be needed by a `configure.ac', youshould trace `AC_LIBSOURCE'. FILE must be a literal.This macro is called automatically from `AC_LIBOBJ', but you mustcall it explicitly if you pass a shell variable to `AC_LIBOBJ'. Inthat case, since shell variables cannot be traced statically, youmust pass to `AC_LIBSOURCE' any possible files that the shellvariable might cause `AC_LIBOBJ' to need. For example, if youwant to pass a variable `$foo_or_bar' to `AC_LIBOBJ' that holdseither `"foo"' or `"bar"', you should do:AC_LIBSOURCE([foo.c])AC_LIBSOURCE([bar.c])AC_LIBOBJ([$foo_or_bar])There is usually a way to avoid this, however, and you areencouraged to simply call `AC_LIBOBJ' with literal arguments.Note that this macro replaces the obsolete `AC_LIBOBJ_DECL', withslightly different semantics: the old macro took the function name,e.g., `foo', as its argument rather than the file name.-- Macro: AC_LIBSOURCES (FILES)Like `AC_LIBSOURCE', but accepts one or more FILES in acomma-separated M4 list. Thus, the above example might berewritten:AC_LIBSOURCES([foo.c, bar.c])AC_LIBOBJ([$foo_or_bar])-- Macro: AC_CONFIG_LIBOBJ_DIR (DIRECTORY)Specify that `AC_LIBOBJ' replacement files are to be found inDIRECTORY, a name relative to the top level of the source tree.The replacement directory defaults to `.', the top leveldirectory, and the most typical value is `lib', corresponding to`AC_CONFIG_LIBOBJ_DIR([lib])'.`configure' might need to know the replacement directory for thefollowing reasons: (i) some checks use the replacement files, (ii)some macros bypass broken system headers by installing links to thereplacement headers (iii) when used in conjunction with Automake,within each makefile, DIRECTORY is used as a relative path from`$(top_srcdir)' to each object named in `LIBOBJS' and `LTLIBOBJS',etc.It is common to merely check for the existence of a function, and askfor its `AC_LIBOBJ' replacement if missing. The following macro is aconvenient shorthand.-- Macro: AC_REPLACE_FUNCS (FUNCTION...)Like `AC_CHECK_FUNCS', but uses `AC_LIBOBJ(FUNCTION)' asACTION-IF-NOT-FOUND. You can declare your replacement function byenclosing the prototype in `#ifndef HAVE_FUNCTION'. If the systemhas the function, it probably declares it in a header file youshould be including, so you shouldn't redeclare it lest yourdeclaration conflict.File: autoconf.info, Node: Header Files, Next: Declarations, Prev: Library Functions, Up: Existing Tests5.6 Header Files================The following macros check for the presence of certain C header files.If there is no macro specifically defined to check for a header fileyou need, and you don't need to check for any special properties of it,then you can use one of the general header-file check macros.* Menu:* Header Portability:: Collected knowledge on common headers* Particular Headers:: Special handling to find certain headers* Generic Headers:: How to find other headersFile: autoconf.info, Node: Header Portability, Next: Particular Headers, Up: Header Files5.6.1 Portability of Headers----------------------------This section tries to collect knowledge about common headers, and theproblems they cause. By definition, this list always requiresadditions. Please help us keeping it as complete as possible.`limits.h'C99 says that `limits.h' defines `LLONG_MIN', `LLONG_MAX', and`ULLONG_MAX', but many almost-C99 environments (e.g., default GCC4.0.2 + glibc 2.4) do not define them.`inttypes.h' vs. `stdint.h'The C99 standard says that `inttypes.h' includes `stdint.h', sothere's no need to include `stdint.h' separately in a standardenvironment. Some implementations have `inttypes.h' but not`stdint.h' (e.g., Solaris 7), but we don't know of anyimplementation that has `stdint.h' but not `inttypes.h'.`linux/irda.h'It requires `linux/types.h' and `sys/socket.h'.`linux/random.h'It requires `linux/types.h'.`net/if.h'On Darwin, this file requires that `sys/socket.h' be includedbeforehand. One should run:AC_CHECK_HEADERS([sys/socket.h])AC_CHECK_HEADERS([net/if.h], [], [],[#include <stdio.h>#ifdef STDC_HEADERS# include <stdlib.h># include <stddef.h>#else# ifdef HAVE_STDLIB_H# include <stdlib.h># endif#endif#ifdef HAVE_SYS_SOCKET_H# include <sys/socket.h>#endif])`netinet/if_ether.h'On Darwin, this file requires that `stdio.h' and `sys/socket.h' beincluded beforehand. One should run:AC_CHECK_HEADERS([sys/socket.h])AC_CHECK_HEADERS([netinet/if_ether.h], [], [],[#include <stdio.h>#ifdef STDC_HEADERS# include <stdlib.h># include <stddef.h>#else# ifdef HAVE_STDLIB_H# include <stdlib.h># endif#endif#ifdef HAVE_SYS_SOCKET_H# include <sys/socket.h>#endif])`stdint.h'See above, item `inttypes.h' vs. `stdint.h'.`stdlib.h'On many systems (e.g., Darwin), `stdio.h' is a prerequisite.`sys/mount.h'On FreeBSD 4.8 on ia32 and using gcc version 2.95.4,`sys/params.h' is a prerequisite.`sys/ptem.h'On Solaris 8, `sys/stream.h' is a prerequisite.`sys/socket.h'On Darwin, `stdlib.h' is a prerequisite.`sys/ucred.h'On Tru64 5.1, `sys/types.h' is a prerequisite.`X11/extensions/scrnsaver.h'Using XFree86, this header requires `X11/Xlib.h', which is probablyso required that you might not even consider looking for it.AC_CHECK_HEADERS([X11/extensions/scrnsaver.h], [], [],[[#include <X11/Xlib.h>]])File: autoconf.info, Node: Particular Headers, Next: Generic Headers, Prev: Header Portability, Up: Header Files5.6.2 Particular Header Checks------------------------------These macros check for particular system header files--whether theyexist, and in some cases whether they declare certain symbols.-- Macro: AC_HEADER_ASSERTCheck whether to enable assertions in the style of `assert.h'.Assertions are enabled by default, but the user can override thisby invoking `configure' with the `--disable-assert' option.-- Macro: AC_HEADER_DIRENTCheck for the following header files. For the first one that isfound and defines `DIR', define the listed C preprocessor macro:`dirent.h' `HAVE_DIRENT_H'`sys/ndir.h' `HAVE_SYS_NDIR_H'`sys/dir.h' `HAVE_SYS_DIR_H'`ndir.h' `HAVE_NDIR_H'The directory-library declarations in your source code should looksomething like the following:#include <sys/types.h>#ifdef HAVE_DIRENT_H# include <dirent.h># define NAMLEN(dirent) strlen ((dirent)->d_name)#else# define dirent direct# define NAMLEN(dirent) ((dirent)->d_namlen)# ifdef HAVE_SYS_NDIR_H# include <sys/ndir.h># endif# ifdef HAVE_SYS_DIR_H# include <sys/dir.h># endif# ifdef HAVE_NDIR_H# include <ndir.h># endif#endifUsing the above declarations, the program would declare variablesto be of type `struct dirent', not `struct direct', and wouldaccess the length of a directory entry name by passing a pointerto a `struct dirent' to the `NAMLEN' macro.This macro also checks for the SCO Xenix `dir' and `x' libraries.This macro is obsolescent, as all current systems with directorylibraries have `<dirent.h>'. New programs need not use this macro.Also see `AC_STRUCT_DIRENT_D_INO' and `AC_STRUCT_DIRENT_D_TYPE'(*note Particular Structures::).-- Macro: AC_HEADER_MAJORIf `sys/types.h' does not define `major', `minor', and `makedev',but `sys/mkdev.h' does, define `MAJOR_IN_MKDEV'; otherwise, if`sys/sysmacros.h' does, define `MAJOR_IN_SYSMACROS'.-- Macro: AC_HEADER_RESOLVChecks for header `resolv.h', checking for prerequisites first.To properly use `resolv.h', your code should contain something likethe following:#ifdef HAVE_SYS_TYPES_H# include <sys/types.h>#endif#ifdef HAVE_NETINET_IN_H# include <netinet/in.h> /* inet_ functions / structs */#endif#ifdef HAVE_ARPA_NAMESER_H# include <arpa/nameser.h> /* DNS HEADER struct */#endif#ifdef HAVE_NETDB_H# include <netdb.h>#endif#include <resolv.h>-- Macro: AC_HEADER_STATIf the macros `S_ISDIR', `S_ISREG', etc. defined in `sys/stat.h'do not work properly (returning false positives), define`STAT_MACROS_BROKEN'. This is the case on Tektronix UTekV, AmdahlUTS and Motorola System V/88.This macro is obsolescent, as no current systems have the bug.New programs need not use this macro.-- Macro: AC_HEADER_STDBOOLIf `stdbool.h' exists and conforms to C99, define `HAVE_STDBOOL_H'to 1; if the type `_Bool' is defined, define `HAVE__BOOL' to 1.To fulfill the C99 requirements, your `system.h' could contain thefollowing code:#ifdef HAVE_STDBOOL_H# include <stdbool.h>#else# ifndef HAVE__BOOL# ifdef __cplusplustypedef bool _Bool;# else# define _Bool signed char# endif# endif# define bool _Bool# define false 0# define true 1# define __bool_true_false_are_defined 1#endifAlternatively you can use the `stdbool' package of Gnulib (*noteGnulib::); it packages the above code into a replacement headerand contains a few other bells and whistles.-- Macro: AC_HEADER_STDCDefine `STDC_HEADERS' if the system has C header files conformingto ANSI C89 (ISO C90). Specifically, this macro checks for`stdlib.h', `stdarg.h', `string.h', and `float.h'; if the systemhas those, it probably has the rest of the C89 header files. Thismacro also checks whether `string.h' declares `memchr' (and thuspresumably the other `mem' functions), whether `stdlib.h' declare`free' (and thus presumably `malloc' and other related functions),and whether the `ctype.h' macros work on characters with the highbit set, as the C standard requires.If you use this macro, your code can refer to `STDC_HEADERS' todetermine whether the system has conforming header files (andprobably C library functions).This macro is obsolescent, as current systems have conformingheader files. New programs need not use this macro.Nowadays `string.h' is part of the C standard and declaresfunctions like `strcpy', and `strings.h' is standardized by Posixand declares BSD functions like `bcopy'; but historically, stringfunctions were a major sticking point in this area. If you stillwant to worry about portability to ancient systems withoutstandard headers, there is so much variation that it is probablyeasier to declare the functions you use than to figure out exactlywhat the system header files declare. Some ancient systemscontained a mix of functions from the C standard and from BSD;some were mostly standard but lacked `memmove'; some defined theBSD functions as macros in `string.h' or `strings.h'; some hadonly the BSD functions but `string.h'; some declared the memoryfunctions in `memory.h', some in `string.h'; etc. It is probablysufficient to check for one string function and one memoryfunction; if the library had the standard versions of those thenit probably had most of the others. If you put the following in`configure.ac':# This example is obsolescent.# Nowadays you can omit these macro calls.AC_HEADER_STDCAC_CHECK_FUNCS([strchr memcpy])then, in your code, you can use declarations like this:/* This example is obsolescent.Nowadays you can just #include <string.h>. */#ifdef STDC_HEADERS# include <string.h>#else# ifndef HAVE_STRCHR# define strchr index# define strrchr rindex# endifchar *strchr (), *strrchr ();# ifndef HAVE_MEMCPY# define memcpy(d, s, n) bcopy ((s), (d), (n))# define memmove(d, s, n) bcopy ((s), (d), (n))# endif#endifIf you use a function like `memchr', `memset', `strtok', or`strspn', which have no BSD equivalent, then macros don't sufficeto port to ancient hosts; you must provide an implementation ofeach function. An easy way to incorporate your implementationsonly when needed (since the ones in system C libraries may be handoptimized) is to, taking `memchr' for example, put it in`memchr.c' and use `AC_REPLACE_FUNCS([memchr])'.-- Macro: AC_HEADER_SYS_WAITIf `sys/wait.h' exists and is compatible with Posix, define`HAVE_SYS_WAIT_H'. Incompatibility can occur if `sys/wait.h' doesnot exist, or if it uses the old BSD `union wait' instead of `int'to store a status value. If `sys/wait.h' is not Posix compatible,then instead of including it, define the Posix macros with theirusual interpretations. Here is an example:#include <sys/types.h>#ifdef HAVE_SYS_WAIT_H# include <sys/wait.h>#endif#ifndef WEXITSTATUS# define WEXITSTATUS(stat_val) ((unsigned int) (stat_val) >> 8)#endif#ifndef WIFEXITED# define WIFEXITED(stat_val) (((stat_val) & 255) == 0)#endifThis macro is obsolescent, as current systems are compatible withPosix. New programs need not use this macro.`_POSIX_VERSION' is defined when `unistd.h' is included on Posixsystems. If there is no `unistd.h', it is definitely not a Posixsystem. However, some non-Posix systems do have `unistd.h'.The way to check whether the system supports Posix is:#ifdef HAVE_UNISTD_H# include <sys/types.h># include <unistd.h>#endif#ifdef _POSIX_VERSION/* Code for Posix systems. */#endif-- Macro: AC_HEADER_TIMEIf a program may include both `time.h' and `sys/time.h', define`TIME_WITH_SYS_TIME'. On some ancient systems, `sys/time.h'included `time.h', but `time.h' was not protected against multipleinclusion, so programs could not explicitly include both files.This macro is useful in programs that use, for example, `structtimeval' as well as `struct tm'. It is best used in conjunctionwith `HAVE_SYS_TIME_H', which can be checked for using`AC_CHECK_HEADERS([sys/time.h])'.#ifdef TIME_WITH_SYS_TIME# include <sys/time.h># include <time.h>#else# ifdef HAVE_SYS_TIME_H# include <sys/time.h># else# include <time.h># endif#endifThis macro is obsolescent, as current systems can include bothfiles when they exist. New programs need not use this macro.-- Macro: AC_HEADER_TIOCGWINSZIf the use of `TIOCGWINSZ' requires `<sys/ioctl.h>', then define`GWINSZ_IN_SYS_IOCTL'. Otherwise `TIOCGWINSZ' can be found in`<termios.h>'.Use:#ifdef HAVE_TERMIOS_H# include <termios.h>#endif#ifdef GWINSZ_IN_SYS_IOCTL# include <sys/ioctl.h>#endifFile: autoconf.info, Node: Generic Headers, Prev: Particular Headers, Up: Header Files5.6.3 Generic Header Checks---------------------------These macros are used to find system header files not covered by the"particular" test macros. If you need to check the contents of a headeras well as find out whether it is present, you have to write your owntest for it (*note Writing Tests::).-- Macro: AC_CHECK_HEADER (HEADER-FILE, [ACTION-IF-FOUND],[ACTION-IF-NOT-FOUND], [INCLUDES = `default-includes'])If the system header file HEADER-FILE is compilable, execute shellcommands ACTION-IF-FOUND, otherwise execute ACTION-IF-NOT-FOUND.If you just want to define a symbol if the header file isavailable, consider using `AC_CHECK_HEADERS' instead.For compatibility issues with older versions of Autoconf, pleaseread below.-- Macro: AC_CHECK_HEADERS (HEADER-FILE..., [ACTION-IF-FOUND],[ACTION-IF-NOT-FOUND], [INCLUDES = `default-includes'])For each given system header file HEADER-FILE in theblank-separated argument list that exists, define`HAVE_HEADER-FILE' (in all capitals). If ACTION-IF-FOUND isgiven, it is additional shell code to execute when one of theheader files is found. You can give it a value of `break' tobreak out of the loop on the first match. If ACTION-IF-NOT-FOUNDis given, it is executed when one of the header files is not found.For compatibility issues with older versions of Autoconf, pleaseread below.Previous versions of Autoconf merely checked whether the header wasaccepted by the preprocessor. This was changed because the old test wasinappropriate for typical uses. Headers are typically used to compile,not merely to preprocess, and the old behavior sometimes acceptedheaders that clashed at compile-time. If you need to check whether aheader is preprocessable, you can use `AC_PREPROC_IFELSE' (*noteRunning the Preprocessor::).This scheme, which improves the robustness of the test, also requiresthat you make sure that headers that must be included before theHEADER-FILE be part of the INCLUDES, (*note Default Includes::). Iflooking for `bar.h', which requires that `foo.h' be included before ifit exists, we suggest the following scheme:AC_CHECK_HEADERS([foo.h])AC_CHECK_HEADERS([bar.h], [], [],[#ifdef HAVE_FOO_H# include <foo.h># endif])The following variant generates smaller, faster `configure' files ifyou do not need the full power of `AC_CHECK_HEADERS'.-- Macro: AC_CHECK_HEADERS_ONCE (HEADER-FILE...)For each given system header file HEADER-FILE in theblank-separated argument list that exists, define`HAVE_HEADER-FILE' (in all capitals). This is a once-only variantof `AC_CHECK_HEADERS'. It generates the checking code at mostonce, so that `configure' is smaller and faster; but the checkscannot be conditionalized and are always done once, early duringthe `configure' run.File: autoconf.info, Node: Declarations, Next: Structures, Prev: Header Files, Up: Existing Tests5.7 Declarations================The following macros check for the declaration of variables andfunctions. If there is no macro specifically defined to check for asymbol you need, then you can use the general macros (*note GenericDeclarations::) or, for more complex tests, you may use`AC_COMPILE_IFELSE' (*note Running the Compiler::).* Menu:* Particular Declarations:: Macros to check for certain declarations* Generic Declarations:: How to find other declarationsFile: autoconf.info, Node: Particular Declarations, Next: Generic Declarations, Up: Declarations5.7.1 Particular Declaration Checks-----------------------------------There are no specific macros for declarations.File: autoconf.info, Node: Generic Declarations, Prev: Particular Declarations, Up: Declarations5.7.2 Generic Declaration Checks--------------------------------These macros are used to find declarations not covered by the"particular" test macros.-- Macro: AC_CHECK_DECL (SYMBOL, [ACTION-IF-FOUND],[ACTION-IF-NOT-FOUND], [INCLUDES = `default-includes'])If SYMBOL (a function, variable, or constant) is not declared inINCLUDES and a declaration is needed, run the shell commandsACTION-IF-NOT-FOUND, otherwise ACTION-IF-FOUND. If no INCLUDESare specified, the default includes are used (*note DefaultIncludes::).This macro actually tests whether SYMBOL is defined as a macro orcan be used as an r-value, not whether it is really declared,because it is much safer to avoid introducing extra declarationswhen they are not needed.-- Macro: AC_CHECK_DECLS (SYMBOLS, [ACTION-IF-FOUND],[ACTION-IF-NOT-FOUND], [INCLUDES = `default-includes'])For each of the SYMBOLS (_comma_-separated list), define`HAVE_DECL_SYMBOL' (in all capitals) to `1' if SYMBOL is declared,otherwise to `0'. If ACTION-IF-NOT-FOUND is given, it isadditional shell code to execute when one of the functiondeclarations is needed, otherwise ACTION-IF-FOUND is executed.This macro uses an M4 list as first argument:AC_CHECK_DECLS([strdup])AC_CHECK_DECLS([strlen])AC_CHECK_DECLS([malloc, realloc, calloc, free])Unlike the other `AC_CHECK_*S' macros, when a SYMBOL is notdeclared, `HAVE_DECL_SYMBOL' is defined to `0' instead of leaving`HAVE_DECL_SYMBOL' undeclared. When you are _sure_ that the checkwas performed, use `HAVE_DECL_SYMBOL' in `#if':#if !HAVE_DECL_SYMBOLextern char *symbol;#endifIf the test may have not been performed, however, because it issafer _not_ to declare a symbol than to use a declaration thatconflicts with the system's one, you should use:#if defined HAVE_DECL_MALLOC && !HAVE_DECL_MALLOCvoid *malloc (size_t *s);#endifYou fall into the second category only in extreme situations:either your files may be used without being configured, or theyare used during the configuration. In most cases the traditionalapproach is enough.-- Macro: AC_CHECK_DECLS_ONCE (SYMBOLS)For each of the SYMBOLS (_comma_-separated list), define`HAVE_DECL_SYMBOL' (in all capitals) to `1' if SYMBOL is declaredin the default include files, otherwise to `0'. This is aonce-only variant of `AC_CHECK_DECLS'. It generates the checkingcode at most once, so that `configure' is smaller and faster; butthe checks cannot be conditionalized and are always done once,early during the `configure' run.File: autoconf.info, Node: Structures, Next: Types, Prev: Declarations, Up: Existing Tests5.8 Structures==============The following macros check for the presence of certain members in Cstructures. If there is no macro specifically defined to check for amember you need, then you can use the general structure-member macros(*note Generic Structures::) or, for more complex tests, you may use`AC_COMPILE_IFELSE' (*note Running the Compiler::).* Menu:* Particular Structures:: Macros to check for certain structure members* Generic Structures:: How to find other structure membersFile: autoconf.info, Node: Particular Structures, Next: Generic Structures, Up: Structures5.8.1 Particular Structure Checks---------------------------------The following macros check for certain structures or structure members.-- Macro: AC_STRUCT_DIRENT_D_INOPerform all the actions of `AC_HEADER_DIRENT' (*note ParticularHeaders::). Then, if `struct dirent' contains a `d_ino' member,define `HAVE_STRUCT_DIRENT_D_INO'.`HAVE_STRUCT_DIRENT_D_INO' indicates only the presence of `d_ino',not whether its contents are always reliable. Traditionally, azero `d_ino' indicated a deleted directory entry, though currentsystems hide this detail from the user and never return zero`d_ino' values. Many current systems report an incorrect `d_ino'for a directory entry that is a mount point.-- Macro: AC_STRUCT_DIRENT_D_TYPEPerform all the actions of `AC_HEADER_DIRENT' (*note ParticularHeaders::). Then, if `struct dirent' contains a `d_type' member,define `HAVE_STRUCT_DIRENT_D_TYPE'.-- Macro: AC_STRUCT_ST_BLKSIZEIf `struct stat' contains an `st_blksize' member, define`HAVE_STRUCT_STAT_ST_BLKSIZE'. The former name, `HAVE_ST_BLKSIZE'is to be avoided, as its support will cease in the future. Thismacro is obsoleted, and should be replaced byAC_CHECK_MEMBERS([struct stat.st_blksize])-- Macro: AC_STRUCT_ST_BLOCKSIf `struct stat' contains an `st_blocks' member, define`HAVE_STRUCT_STAT_ST_BLOCKS'. Otherwise, require an `AC_LIBOBJ'replacement of `fileblocks'. The former name, `HAVE_ST_BLOCKS' isto be avoided, as its support will cease in the future.-- Macro: AC_STRUCT_ST_RDEVIf `struct stat' contains an `st_rdev' member, define`HAVE_STRUCT_STAT_ST_RDEV'. The former name for this macro,`HAVE_ST_RDEV', is to be avoided as it will cease to be supportedin the future. Actually, even the new macro is obsolete andshould be replaced by:AC_CHECK_MEMBERS([struct stat.st_rdev])-- Macro: AC_STRUCT_TMIf `time.h' does not define `struct tm', define `TM_IN_SYS_TIME',which means that including `sys/time.h' had better define `structtm'.This macro is obsolescent, as `time.h' defines `struct tm' incurrent systems. New programs need not use this macro.-- Macro: AC_STRUCT_TIMEZONEFigure out how to get the current timezone. If `struct tm' has a`tm_zone' member, define `HAVE_STRUCT_TM_TM_ZONE' (and theobsoleted `HAVE_TM_ZONE'). Otherwise, if the external array`tzname' is found, define `HAVE_TZNAME'; if it is declared, define`HAVE_DECL_TZNAME'.File: autoconf.info, Node: Generic Structures, Prev: Particular Structures, Up: Structures5.8.2 Generic Structure Checks------------------------------These macros are used to find structure members not covered by the"particular" test macros.-- Macro: AC_CHECK_MEMBER (AGGREGATE.MEMBER, [ACTION-IF-FOUND],[ACTION-IF-NOT-FOUND], [INCLUDES = `default-includes'])Check whether MEMBER is a member of the aggregate AGGREGATE. Ifno INCLUDES are specified, the default includes are used (*noteDefault Includes::).AC_CHECK_MEMBER([struct passwd.pw_gecos], [],[AC_MSG_ERROR([We need `passwd.pw_gecos'!])],[#include <pwd.h>])You can use this macro for submembers:AC_CHECK_MEMBER(struct top.middle.bot)-- Macro: AC_CHECK_MEMBERS (MEMBERS, [ACTION-IF-FOUND],[ACTION-IF-NOT-FOUND], [INCLUDES = `default-includes'])Check for the existence of each `AGGREGATE.MEMBER' of MEMBERSusing the previous macro. When MEMBER belongs to AGGREGATE,define `HAVE_AGGREGATE_MEMBER' (in all capitals, with spaces anddots replaced by underscores). If ACTION-IF-FOUND is given, it isexecuted for each of the found members. If ACTION-IF-NOT-FOUND isgiven, it is executed for each of the members that could not befound.This macro uses M4 lists:AC_CHECK_MEMBERS([struct stat.st_rdev, struct stat.st_blksize])File: autoconf.info, Node: Types, Next: Compilers and Preprocessors, Prev: Structures, Up: Existing Tests5.9 Types=========The following macros check for C types, either builtin or typedefs. Ifthere is no macro specifically defined to check for a type you need, andyou don't need to check for any special properties of it, then you canuse a general type-check macro.* Menu:* Particular Types:: Special handling to find certain types* Generic Types:: How to find other typesFile: autoconf.info, Node: Particular Types, Next: Generic Types, Up: Types5.9.1 Particular Type Checks----------------------------These macros check for particular C types in `sys/types.h', `stdlib.h',`stdint.h', `inttypes.h' and others, if they exist.The Gnulib `stdint' module is an alternate way to define many ofthese symbols; it is useful if you prefer your code to assume aC99-or-better environment. *Note Gnulib::.-- Macro: AC_TYPE_GETGROUPSDefine `GETGROUPS_T' to be whichever of `gid_t' or `int' is thebase type of the array argument to `getgroups'.-- Macro: AC_TYPE_INT8_TIf `stdint.h' or `inttypes.h' defines the type `int8_t', define`HAVE_INT8_T'. Otherwise, define `int8_t' to a signed integertype that is exactly 8 bits wide and that uses two's complementrepresentation, if such a type exists.-- Macro: AC_TYPE_INT16_TThis is like `AC_TYPE_INT8_T', except for 16-bit integers.-- Macro: AC_TYPE_INT32_TThis is like `AC_TYPE_INT8_T', except for 32-bit integers.-- Macro: AC_TYPE_INT64_TThis is like `AC_TYPE_INT8_T', except for 64-bit integers.-- Macro: AC_TYPE_INTMAX_TIf `stdint.h' or `inttypes.h' defines the type `intmax_t', define`HAVE_INTMAX_T'. Otherwise, define `intmax_t' to the widestsigned integer type.-- Macro: AC_TYPE_INTPTR_TIf `stdint.h' or `inttypes.h' defines the type `intptr_t', define`HAVE_INTPTR_T'. Otherwise, define `intptr_t' to a signed integertype wide enough to hold a pointer, if such a type exists.-- Macro: AC_TYPE_LONG_DOUBLEIf the C compiler supports a working `long double' type, define`HAVE_LONG_DOUBLE'. The `long double' type might have the samerange and precision as `double'.-- Macro: AC_TYPE_LONG_DOUBLE_WIDERIf the C compiler supports a working `long double' type with morerange or precision than the `double' type, define`HAVE_LONG_DOUBLE_WIDER'.-- Macro: AC_TYPE_LONG_LONG_INTIf the C compiler supports a working `long long int' type, define`HAVE_LONG_LONG_INT'.-- Macro: AC_TYPE_MBSTATE_TDefine `HAVE_MBSTATE_T' if `<wchar.h>' declares the `mbstate_t'type. Also, define `mbstate_t' to be a type if `<wchar.h>' doesnot declare it.-- Macro: AC_TYPE_MODE_TDefine `mode_t' to a suitable type, if standard headers do notdefine it.-- Macro: AC_TYPE_OFF_TDefine `off_t' to a suitable type, if standard headers do notdefine it.-- Macro: AC_TYPE_PID_TDefine `pid_t' to a suitable type, if standard headers do notdefine it.-- Macro: AC_TYPE_SIGNALIf `signal.h' declares `signal' as returning a pointer to afunction returning `void', define `RETSIGTYPE' to be `void';otherwise, define it to be `int'.Define signal handlers as returning type `RETSIGTYPE':RETSIGTYPEhup_handler (){...}-- Macro: AC_TYPE_SIZE_TDefine `size_t' to a suitable type, if standard headers do notdefine it.-- Macro: AC_TYPE_SSIZE_TDefine `ssize_t' to a suitable type, if standard headers do notdefine it.-- Macro: AC_TYPE_UID_TDefine `uid_t' and `gid_t' to suitable types, if standard headersdo not define them.-- Macro: AC_TYPE_UINT8_TIf `stdint.h' or `inttypes.h' defines the type `uint8_t', define`HAVE_UINT8_T'. Otherwise, define `uint8_t' to an unsignedinteger type that is exactly 8 bits wide, if such a type exists.-- Macro: AC_TYPE_UINT16_TThis is like `AC_TYPE_UINT8_T', except for 16-bit unsignedintegers.-- Macro: AC_TYPE_UINT32_TThis is like `AC_TYPE_UINT8_T', except for 32-bit unsignedintegers.-- Macro: AC_TYPE_UINT64_TThis is like `AC_TYPE_UINT8_T', except for 64-bit unsignedintegers.-- Macro: AC_TYPE_UINTMAX_TIf `stdint.h' or `inttypes.h' defines the type `uintmax_t', define`HAVE_UINTMAX_T'. Otherwise, define `uintmax_t' to the widestunsigned integer type.-- Macro: AC_TYPE_UINTPTR_TIf `stdint.h' or `inttypes.h' defines the type `uintptr_t', define`HAVE_UINTPTR_T'. Otherwise, define `uintptr_t' to an unsignedinteger type wide enough to hold a pointer, if such a type exists.-- Macro: AC_TYPE_UNSIGNED_LONG_LONG_INTIf the C compiler supports a working `unsigned long long int' type,define `HAVE_UNSIGNED_LONG_LONG_INT'.File: autoconf.info, Node: Generic Types, Prev: Particular Types, Up: Types5.9.2 Generic Type Checks-------------------------These macros are used to check for types not covered by the "particular"test macros.-- Macro: AC_CHECK_TYPE (TYPE, [ACTION-IF-FOUND],[ACTION-IF-NOT-FOUND], [INCLUDES = `default-includes'])Check whether TYPE is defined. It may be a compiler builtin typeor defined by the INCLUDES (*note Default Includes::).-- Macro: AC_CHECK_TYPES (TYPES, [ACTION-IF-FOUND],[ACTION-IF-NOT-FOUND], [INCLUDES = `default-includes'])For each TYPE of the TYPES that is defined, define `HAVE_TYPE' (inall capitals). If no INCLUDES are specified, the default includesare used (*note Default Includes::). If ACTION-IF-FOUND is given,it is additional shell code to execute when one of the types isfound. If ACTION-IF-NOT-FOUND is given, it is executed when oneof the types is not found.This macro uses M4 lists:AC_CHECK_TYPES([ptrdiff_t])AC_CHECK_TYPES([unsigned long long int, uintmax_t])Autoconf, up to 2.13, used to provide to another version of`AC_CHECK_TYPE', broken by design. In order to keep backwardcompatibility, a simple heuristics, quite safe but not totally, isimplemented. In case of doubt, read the documentation of the former`AC_CHECK_TYPE', see *Note Obsolete Macros::.File: autoconf.info, Node: Compilers and Preprocessors, Next: System Services, Prev: Types, Up: Existing Tests5.10 Compilers and Preprocessors================================All the tests for compilers (`AC_PROG_CC', `AC_PROG_CXX',`AC_PROG_F77') define the output variable `EXEEXT' based on the outputof the compiler, typically to the empty string if Posix and `.exe' if aDOS variant.They also define the output variable `OBJEXT' based on the output ofthe compiler, after `.c' files have been excluded, typically to `o' ifPosix, `obj' if a DOS variant.If the compiler being used does not produce executables, the testsfail. If the executables can't be run, and cross-compilation is notenabled, they fail too. *Note Manual Configuration::, for more onsupport for cross compiling.* Menu:* Specific Compiler Characteristics:: Some portability issues* Generic Compiler Characteristics:: Language independent tests and features* C Compiler:: Checking its characteristics* C++ Compiler:: Likewise* Objective C Compiler:: Likewise* Erlang Compiler and Interpreter:: Likewise* Fortran Compiler:: LikewiseFile: autoconf.info, Node: Specific Compiler Characteristics, Next: Generic Compiler Characteristics, Up: Compilers and Preprocessors5.10.1 Specific Compiler Characteristics----------------------------------------Some compilers exhibit different behaviors.Static/Dynamic ExpressionsAutoconf relies on a trick to extract one bit of information fromthe C compiler: using negative array sizes. For instance thefollowing excerpt of a C source demonstrates how to test whether`int' objects are 4 bytes wide:static int test_array[sizeof (int) == 4 ? 1 : -1];To our knowledge, there is a single compiler that does not supportthis trick: the HP C compilers (the real ones, not only the"bundled") on HP-UX 11.00. They incorrectly reject the aboveprogram with the diagnostic "Variable-length arrays cannot havestatic storage." This bug comes from HP compilers' mishandling of`sizeof (int)', not from the `? 1 : -1', and Autoconf works aroundthis problem by casting `sizeof (int)' to `long int' beforecomparing it.File: autoconf.info, Node: Generic Compiler Characteristics, Next: C Compiler, Prev: Specific Compiler Characteristics, Up: Compilers and Preprocessors5.10.2 Generic Compiler Characteristics----------------------------------------- Macro: AC_CHECK_SIZEOF (TYPE, [UNUSED], [INCLUDES =`default-includes'])Define `SIZEOF_TYPE' (*note Standard Symbols::) to be the size inbytes of TYPE. If `type' is unknown, it gets a size of 0. If noINCLUDES are specified, the default includes are used (*noteDefault Includes::).This macro now works even when cross-compiling. The UNUSEDargument was used when cross-compiling.For example, the callAC_CHECK_SIZEOF([int *])defines `SIZEOF_INT_P' to be 8 on DEC Alpha AXP systems.-- Macro: AC_CHECK_ALIGNOF (TYPE, [INCLUDES = `default-includes'])Define `ALIGNOF_TYPE' (*note Standard Symbols::) to be thealignment in bytes of TYPE. If `type' is unknown, it gets a sizeof 0. If no INCLUDES are specified, the default includes are used(*note Default Includes::).-- Macro: AC_COMPUTE_INT (VAR, EXPRESSION, [INCLUDES =`default-includes'], [ACTION-IF-FAILS])Store into the shell variable VAR the value of the integerEXPRESSION. The value should fit in an initializer in a Cvariable of type `signed long'. To support cross compilation (inwhich case, the macro only works on hosts that use twos-complementarithmetic), it should be possible to evaluate the expression atcompile-time. If no INCLUDES are specified, the default includesare used (*note Default Includes::).Execute ACTION-IF-FAILS if the value cannot be determinedcorrectly.-- Macro: AC_LANG_WERRORNormally Autoconf ignores warnings generated by the compiler,linker, and preprocessor. If this macro is used, warnings countas fatal errors for the current language. This macro is usefulwhen the results of configuration are used where warnings areunacceptable; for instance, if parts of a program are built withthe GCC `-Werror' option. If the whole program is built using`-Werror' it is often simpler to put `-Werror' in the compilerflags (`CFLAGS', etc.).File: autoconf.info, Node: C Compiler, Next: C++ Compiler, Prev: Generic Compiler Characteristics, Up: Compilers and Preprocessors5.10.3 C Compiler Characteristics---------------------------------The following macros provide ways to find and exercise a C Compiler.There are a few constructs that ought to be avoided, but do not deservebeing checked for, since they can easily be worked around.Don't use lines containing solitary backslashesThey tickle a bug in the HP-UX C compiler (checked on HP-UX 10.20,11.00, and 11i). When given the following source:#ifdef __STDC__/\* A comment with backslash-newlines in it. %{ %} *\\/char str[] = "\\" A string with backslash-newlines in it %{ %} \\"";char apostrophe = '\\\'\';#endifthe compiler incorrectly fails with the diagnostics"Non-terminating comment at end of file" and "Missing `#endif' atend of file." Removing the lines with solitary backslashes solvesthe problem.Don't compile several files at once if output matters to youSome compilers, such as HP's, report names of files being compiledwhen given more than one file operand. For instance:$ cc a.c b.ca.c:b.c:This can cause problems if you observe the output of the compilerto detect failures. Invoking `cc -c a.c && cc -c b.c && cc -o ca.o b.o' solves the issue.Don't rely on `#error' failingThe IRIX C compiler does not fail when #error is preprocessed; itsimply emits a diagnostic and continues, exiting successfully. So,instead of an error directive like `#error "Unsupported word size"'it is more portable to use an invalid directive like `#Unsupportedword size' in Autoconf tests. In ordinary source code, `#error' isOK, since installers with inadequate compilers like IRIX can simplyexamine these compilers' diagnostic output.Don't rely on correct `#line' supportOn Solaris, `c89' (at least Sun C 5.3 through 5.8) diagnoses`#line' directives whose line numbers are greater than 32767.Nothing in Posix makes this invalid. That is why Autoconf stoppedissuing `#line' directives.-- Macro: AC_PROG_CC ([COMPILER-SEARCH-LIST])Determine a C compiler to use. If `CC' is not already set in theenvironment, check for `gcc' and `cc', then for other C compilers.Set output variable `CC' to the name of the compiler found.This macro may, however, be invoked with an optional first argumentwhich, if specified, must be a blank-separated list of C compilersto search for. This just gives the user an opportunity to specifyan alternative search list for the C compiler. For example, ifyou didn't like the default order, then you could invoke`AC_PROG_CC' like this:AC_PROG_CC([gcc cl cc])If the C compiler does not handle function prototypes correctly bydefault, try to add an option to output variable `CC' to make itso. This macro tries various options that selectstandard-conformance modes on various systems.After calling this macro you can check whether the C compiler hasbeen set to accept ANSI C89 (ISO C90); if not, the shell variable`ac_cv_prog_cc_c89' is set to `no'. See also `AC_C_PROTOTYPES'below.If using the GNU C compiler, set shell variable `GCC' to `yes'.If output variable `CFLAGS' was not already set, set it to `-g-O2' for the GNU C compiler (`-O2' on systems where GCC does notaccept `-g'), or `-g' for other compilers.-- Macro: AC_PROG_CC_C_OIf the C compiler does not accept the `-c' and `-o' optionssimultaneously, define `NO_MINUS_C_MINUS_O'. This macro actuallytests both the compiler found by `AC_PROG_CC', and, if different,the first `cc' in the path. The test fails if one fails. Thismacro was created for GNU Make to choose the default C compilationrule.-- Macro: AC_PROG_CPPSet output variable `CPP' to a command that runs the Cpreprocessor. If `$CC -E' doesn't work, `/lib/cpp' is used. Itis only portable to run `CPP' on files with a `.c' extension.Some preprocessors don't indicate missing include files by theerror status. For such preprocessors an internal variable is setthat causes other macros to check the standard error from thepreprocessor and consider the test failed if any warnings havebeen reported. For most preprocessors, though, warnings do notcause include-file tests to fail unless `AC_PROG_CPP_WERROR' isalso specified.-- Macro: AC_PROG_CPP_WERRORThis acts like `AC_PROG_CPP', except it treats warnings from thepreprocessor as errors even if the preprocessor exit statusindicates success. This is useful for avoiding headers thatgenerate mandatory warnings, such as deprecation notices.The following macros check for C compiler or machine architecturefeatures. To check for characteristics not listed here, use`AC_COMPILE_IFELSE' (*note Running the Compiler::) or `AC_RUN_IFELSE'(*note Runtime::).-- Macro: AC_PROG_CC_STDCIf the C compiler cannot compile ISO Standard C (currently C99),try to add an option to output variable `CC' to make it work. Ifthe compiler does not support C99, fall back to supporting ANSIC89 (ISO C90).After calling this macro you can check whether the C compiler hasbeen set to accept Standard C; if not, the shell variable`ac_cv_prog_cc_stdc' is set to `no'.-- Macro: AC_PROG_CC_C89If the C compiler is not in ANSI C89 (ISO C90) mode by default,try to add an option to output variable `CC' to make it so. Thismacro tries various options that select ANSI C89 on some system oranother. It considers the compiler to be in ANSI C89 mode if ithandles function prototypes correctly.After calling this macro you can check whether the C compiler hasbeen set to accept ANSI C89; if not, the shell variable`ac_cv_prog_cc_c89' is set to `no'.This macro is called automatically by `AC_PROG_CC'.-- Macro: AC_PROG_CC_C99If the C compiler is not in C99 mode by default, try to add anoption to output variable `CC' to make it so. This macro triesvarious options that select C99 on some system or another. Itconsiders the compiler to be in C99 mode if it handles `_Bool',`//' comments, flexible array members, `inline', `long long int',mixed code and declarations, named initialization of structs,`restrict', `va_copy', varargs macros, variable declarations in`for' loops, and variable length arrays.After calling this macro you can check whether the C compiler hasbeen set to accept C99; if not, the shell variable`ac_cv_prog_cc_c99' is set to `no'.-- Macro: AC_C_BACKSLASH_ADefine `HAVE_C_BACKSLASH_A' to 1 if the C compiler understands`\a'.This macro is obsolescent, as current C compilers understand `\a'.New programs need not use this macro.-- Macro: AC_C_BIGENDIAN ([ACTION-IF-TRUE], [ACTION-IF-FALSE],[ACTION-IF-UNKNOWN])If words are stored with the most significant byte first (likeMotorola and SPARC CPUs), execute ACTION-IF-TRUE. If words arestored with the least significant byte first (like Intel and VAXCPUs), execute ACTION-IF-FALSE.This macro runs a test-case if endianness cannot be determinedfrom the system header files. When cross-compiling, the test-caseis not run but grep'ed for some magic values. ACTION-IF-UNKNOWNis executed if the latter case fails to determine the byte sex ofthe host system.The default for ACTION-IF-TRUE is to define `WORDS_BIGENDIAN'.The default for ACTION-IF-FALSE is to do nothing. And finally,the default for ACTION-IF-UNKNOWN is to abort configure and tellthe installer which variable he should preset to bypass this test.-- Macro: AC_C_CONSTIf the C compiler does not fully support the `const' keyword,define `const' to be empty. Some C compilers that do not define`__STDC__' do support `const'; some compilers that define`__STDC__' do not completely support `const'. Programs can simplyuse `const' as if every C compiler supported it; for those thatdon't, the makefile or configuration header file defines it asempty.Occasionally installers use a C++ compiler to compile C code,typically because they lack a C compiler. This causes problemswith `const', because C and C++ treat `const' differently. Forexample:const int foo;is valid in C but not in C++. These differences unfortunatelycannot be papered over by defining `const' to be empty.If `autoconf' detects this situation, it leaves `const' alone, asthis generally yields better results in practice. However, using aC++ compiler to compile C code is not recommended or supported, andinstallers who run into trouble in this area should get a Ccompiler like GCC to compile their C code.This macro is obsolescent, as current C compilers support `const'.New programs need not use this macro.-- Macro: AC_C_RESTRICTIf the C compiler recognizes the `restrict' keyword, don't doanything. If it recognizes only a variant spelling (`__restrict',`__restrict__', or `_Restrict'), then define `restrict' to that.Otherwise, define `restrict' to be empty. Thus, programs maysimply use `restrict' as if every C compiler supported it; forthose that do not, the makefile or configuration header defines itaway.Although support in C++ for the `restrict' keyword is notrequired, several C++ compilers do accept the keyword. This macroworks for them, too.-- Macro: AC_C_VOLATILEIf the C compiler does not understand the keyword `volatile',define `volatile' to be empty. Programs can simply use `volatile'as if every C compiler supported it; for those that do not, themakefile or configuration header defines it as empty.If the correctness of your program depends on the semantics of`volatile', simply defining it to be empty does, in a sense, breakyour code. However, given that the compiler does not support`volatile', you are at its mercy anyway. At least your programcompiles, when it wouldn't before. *Note Volatile Objects::, formore about `volatile'.In general, the `volatile' keyword is a standard C feature, so youmight expect that `volatile' is available only when `__STDC__' isdefined. However, Ultrix 4.3's native compiler does supportvolatile, but does not define `__STDC__'.This macro is obsolescent, as current C compilers support`volatile'. New programs need not use this macro.-- Macro: AC_C_INLINEIf the C compiler supports the keyword `inline', do nothing.Otherwise define `inline' to `__inline__' or `__inline' if itaccepts one of those, otherwise define `inline' to be empty.-- Macro: AC_C_CHAR_UNSIGNEDIf the C type `char' is unsigned, define `__CHAR_UNSIGNED__',unless the C compiler predefines it.-- Macro: AC_C_STRINGIZEIf the C preprocessor supports the stringizing operator, define`HAVE_STRINGIZE'. The stringizing operator is `#' and is found inmacros such as this:#define x(y) #yThis macro is obsolescent, as current C compilers support thestringizing operator. New programs need not use this macro.-- Macro: AC_C_FLEXIBLE_ARRAY_MEMBERIf the C compiler supports flexible array members, define`FLEXIBLE_ARRAY_MEMBER' to nothing; otherwise define it to 1.That way, a declaration like this:struct s{size_t n_vals;double val[FLEXIBLE_ARRAY_MEMBER];};will let applications use the "struct hack" even with compilersthat do not support flexible array members. To allocate and usesuch an object, you can use code like this:size_t i;size_t n = compute_value_count ();struct s *p =malloc (offsetof (struct s, val)+ n * sizeof (double));p->n_vals = n;for (i = 0; i < n; i++)p->val[i] = compute_value (i);-- Macro: AC_C_VARARRAYSIf the C compiler supports variable-length arrays, define`HAVE_C_VARRAYS'. A variable-length array is an array of automaticstorage duration whose length is determined at run time, when thearray is declared.-- Macro: AC_C_TYPEOFIf the C compiler supports GCC's `typeof' syntax either directly orthrough a different spelling of the keyword (e.g., `__typeof__'),define `HAVE_TYPEOF'. If the support is available only through adifferent spelling, define `typeof' to that spelling.-- Macro: AC_C_PROTOTYPESIf function prototypes are understood by the compiler (asdetermined by `AC_PROG_CC'), define `PROTOTYPES' and`__PROTOTYPES'. Defining `__PROTOTYPES' is for the benefit ofheader files that cannot use macros that infringe on user namespace.This macro is obsolescent, as current C compilers supportprototypes. New programs need not use this macro.-- Macro: AC_PROG_GCC_TRADITIONALAdd `-traditional' to output variable `CC' if using the GNU Ccompiler and `ioctl' does not work properly without`-traditional'. That usually happens when the fixed header fileshave not been installed on an old system.This macro is obsolescent, since current versions of the GNU Ccompiler fix the header files automatically when installed.File: autoconf.info, Node: C++ Compiler, Next: Objective C Compiler, Prev: C Compiler, Up: Compilers and Preprocessors5.10.4 C++ Compiler Characteristics------------------------------------- Macro: AC_PROG_CXX ([COMPILER-SEARCH-LIST])Determine a C++ compiler to use. Check whether the environmentvariable `CXX' or `CCC' (in that order) is set; if so, then setoutput variable `CXX' to its value.Otherwise, if the macro is invoked without an argument, thensearch for a C++ compiler under the likely names (first `g++' and`c++' then other names). If none of those checks succeed, then asa last resort set `CXX' to `g++'.This macro may, however, be invoked with an optional first argumentwhich, if specified, must be a blank-separated list of C++compilers to search for. This just gives the user an opportunityto specify an alternative search list for the C++ compiler. Forexample, if you didn't like the default order, then you couldinvoke `AC_PROG_CXX' like this:AC_PROG_CXX([gcc cl KCC CC cxx cc++ xlC aCC c++ g++])If using the GNU C++ compiler, set shell variable `GXX' to `yes'.If output variable `CXXFLAGS' was not already set, set it to `-g-O2' for the GNU C++ compiler (`-O2' on systems where G++ does notaccept `-g'), or `-g' for other compilers.-- Macro: AC_PROG_CXXCPPSet output variable `CXXCPP' to a command that runs the C++preprocessor. If `$CXX -E' doesn't work, `/lib/cpp' is used. Itis portable to run `CXXCPP' only on files with a `.c', `.C',`.cc', or `.cpp' extension.Some preprocessors don't indicate missing include files by theerror status. For such preprocessors an internal variable is setthat causes other macros to check the standard error from thepreprocessor and consider the test failed if any warnings havebeen reported. However, it is not known whether such brokenpreprocessors exist for C++.-- Macro: AC_PROG_CXX_C_OTest whether the C++ compiler accepts the options `-c' and `-o'simultaneously, and define `CXX_NO_MINUS_C_MINUS_O', if it doesnot.File: autoconf.info, Node: Objective C Compiler, Next: Erlang Compiler and Interpreter, Prev: C++ Compiler, Up: Compilers and Preprocessors5.10.5 Objective C Compiler Characteristics--------------------------------------------- Macro: AC_PROG_OBJC ([COMPILER-SEARCH-LIST])Determine an Objective C compiler to use. If `OBJC' is not alreadyset in the environment, check for Objective C compilers. Setoutput variable `OBJC' to the name of the compiler found.This macro may, however, be invoked with an optional first argumentwhich, if specified, must be a blank-separated list of Objective Ccompilers to search for. This just gives the user an opportunityto specify an alternative search list for the Objective Ccompiler. For example, if you didn't like the default order, thenyou could invoke `AC_PROG_OBJC' like this:AC_PROG_OBJC([gcc objcc objc])If using the GNU Objective C compiler, set shell variable `GOBJC'to `yes'. If output variable `OBJCFLAGS' was not already set, setit to `-g -O2' for the GNU Objective C compiler (`-O2' on systemswhere `gcc' does not accept `-g'), or `-g' for other compilers.-- Macro: AC_PROG_OBJCCPPSet output variable `OBJCCPP' to a command that runs the ObjectiveC preprocessor. If `$OBJC -E' doesn't work, `/lib/cpp' is used.File: autoconf.info, Node: Erlang Compiler and Interpreter, Next: Fortran Compiler, Prev: Objective C Compiler, Up: Compilers and Preprocessors5.10.6 Erlang Compiler and Interpreter Characteristics------------------------------------------------------Autoconf defines the following macros for determining paths to theessential Erlang/OTP programs:-- Macro: AC_ERLANG_PATH_ERLC ([VALUE-IF-NOT-FOUND], [PATH])Determine an Erlang compiler to use. If `ERLC' is not already setin the environment, check for `erlc'. Set output variable `ERLC'to the complete path of the compiler command found. In addition,if `ERLCFLAGS' is not set in the environment, set it to an emptyvalue.The two optional arguments have the same meaning as the two lastarguments of macro `AC_PROG_PATH' for looking for the `erlc'program. For example, to look for `erlc' only in the`/usr/lib/erlang/bin' directory:AC_ERLANG_PATH_ERLC([not found], [/usr/lib/erlang/bin])-- Macro: AC_ERLANG_NEED_ERLC ([PATH])A simplified variant of the `AC_ERLANG_PATH_ERLC' macro, thatprints an error message and exits the `configure' script if the`erlc' program is not found.-- Macro: AC_ERLANG_PATH_ERL ([VALUE-IF-NOT-FOUND], [PATH])Determine an Erlang interpreter to use. If `ERL' is not alreadyset in the environment, check for `erl'. Set output variable`ERL' to the complete path of the interpreter command found.The two optional arguments have the same meaning as the two lastarguments of macro `AC_PROG_PATH' for looking for the `erl'program. For example, to look for `erl' only in the`/usr/lib/erlang/bin' directory:AC_ERLANG_PATH_ERL([not found], [/usr/lib/erlang/bin])-- Macro: AC_ERLANG_NEED_ERL ([PATH])A simplified variant of the `AC_ERLANG_PATH_ERL' macro, thatprints an error message and exits the `configure' script if the`erl' program is not found.File: autoconf.info, Node: Fortran Compiler, Prev: Erlang Compiler and Interpreter, Up: Compilers and Preprocessors5.10.7 Fortran Compiler Characteristics---------------------------------------The Autoconf Fortran support is divided into two categories: legacyFortran 77 macros (`F77'), and modern Fortran macros (`FC'). Theformer are intended for traditional Fortran 77 code, and have outputvariables like `F77', `FFLAGS', and `FLIBS'. The latter are for newerprograms that can (or must) compile under the newer Fortran standards,and have output variables like `FC', `FCFLAGS', and `FCLIBS'.Except for two new macros `AC_FC_SRCEXT' and `AC_FC_FREEFORM' (seebelow), the `FC' and `F77' macros behave almost identically, and sothey are documented together in this section.-- Macro: AC_PROG_F77 ([COMPILER-SEARCH-LIST])Determine a Fortran 77 compiler to use. If `F77' is not alreadyset in the environment, then check for `g77' and `f77', and thensome other names. Set the output variable `F77' to the name ofthe compiler found.This macro may, however, be invoked with an optional first argumentwhich, if specified, must be a blank-separated list of Fortran 77compilers to search for. This just gives the user an opportunityto specify an alternative search list for the Fortran 77 compiler.For example, if you didn't like the default order, then you couldinvoke `AC_PROG_F77' like this:AC_PROG_F77([fl32 f77 fort77 xlf g77 f90 xlf90])If using `g77' (the GNU Fortran 77 compiler), then set the shellvariable `G77' to `yes'. If the output variable `FFLAGS' was notalready set in the environment, then set it to `-g -02' for `g77'(or `-O2' where `g77' does not accept `-g'). Otherwise, set`FFLAGS' to `-g' for all other Fortran 77 compilers.-- Macro: AC_PROG_FC ([COMPILER-SEARCH-LIST], [DIALECT])Determine a Fortran compiler to use. If `FC' is not already set inthe environment, then `dialect' is a hint to indicate what Fortrandialect to search for; the default is to search for the newestavailable dialect. Set the output variable `FC' to the name ofthe compiler found.By default, newer dialects are preferred over older dialects, butif `dialect' is specified then older dialects are preferredstarting with the specified dialect. `dialect' can currently beone of Fortran 77, Fortran 90, or Fortran 95. However, this isonly a hint of which compiler _name_ to prefer (e.g., `f90' or`f95'), and no attempt is made to guarantee that a particularlanguage standard is actually supported. Thus, it is preferablethat you avoid the `dialect' option, and use AC_PROG_FC only forcode compatible with the latest Fortran standard.This macro may, alternatively, be invoked with an optional firstargument which, if specified, must be a blank-separated list ofFortran compilers to search for, just as in `AC_PROG_F77'.If the output variable `FCFLAGS' was not already set in theenvironment, then set it to `-g -02' for GNU `g77' (or `-O2' where`g77' does not accept `-g'). Otherwise, set `FCFLAGS' to `-g' forall other Fortran compilers.-- Macro: AC_PROG_F77_C_O-- Macro: AC_PROG_FC_C_OTest whether the Fortran compiler accepts the options `-c' and`-o' simultaneously, and define `F77_NO_MINUS_C_MINUS_O' or`FC_NO_MINUS_C_MINUS_O', respectively, if it does not.The following macros check for Fortran compiler characteristics. Tocheck for characteristics not listed here, use `AC_COMPILE_IFELSE'(*note Running the Compiler::) or `AC_RUN_IFELSE' (*note Runtime::),making sure to first set the current language to Fortran 77 or Fortranvia `AC_LANG([Fortran 77])' or `AC_LANG(Fortran)' (*note LanguageChoice::).-- Macro: AC_F77_LIBRARY_LDFLAGS-- Macro: AC_FC_LIBRARY_LDFLAGSDetermine the linker flags (e.g., `-L' and `-l') for the "Fortranintrinsic and runtime libraries" that are required to successfullylink a Fortran program or shared library. The output variable`FLIBS' or `FCLIBS' is set to these flags (which should beincluded after `LIBS' when linking).This macro is intended to be used in those situations when it isnecessary to mix, e.g., C++ and Fortran source code in a singleprogram or shared library (*note Mixing Fortran 77 With C and C++:(automake)Mixing Fortran 77 With C and C++.).For example, if object files from a C++ and Fortran compiler mustbe linked together, then the C++ compiler/linker must be used forlinking (since special C++-ish things need to happen at link timelike calling global constructors, instantiating templates,enabling exception support, etc.).However, the Fortran intrinsic and runtime libraries must belinked in as well, but the C++ compiler/linker doesn't know bydefault how to add these Fortran 77 libraries. Hence, this macrowas created to determine these Fortran libraries.The macros `AC_F77_DUMMY_MAIN' and `AC_FC_DUMMY_MAIN' or`AC_F77_MAIN' and `AC_FC_MAIN' are probably also necessary to linkC/C++ with Fortran; see below.-- Macro: AC_F77_DUMMY_MAIN ([ACTION-IF-FOUND], [ACTION-IF-NOT-FOUND])-- Macro: AC_FC_DUMMY_MAIN ([ACTION-IF-FOUND], [ACTION-IF-NOT-FOUND])With many compilers, the Fortran libraries detected by`AC_F77_LIBRARY_LDFLAGS' or `AC_FC_LIBRARY_LDFLAGS' provide theirown `main' entry function that initializes things like FortranI/O, and which then calls a user-provided entry function named(say) `MAIN__' to run the user's program. The `AC_F77_DUMMY_MAIN'and `AC_FC_DUMMY_MAIN' or `AC_F77_MAIN' and `AC_FC_MAIN' macrosfigure out how to deal with this interaction.When using Fortran for purely numerical functions (no I/O, etc.)often one prefers to provide one's own `main' and skip the Fortranlibrary initializations. In this case, however, one may stillneed to provide a dummy `MAIN__' routine in order to preventlinking errors on some systems. `AC_F77_DUMMY_MAIN' or`AC_FC_DUMMY_MAIN' detects whether any such routine is _required_for linking, and what its name is; the shell variable`F77_DUMMY_MAIN' or `FC_DUMMY_MAIN' holds this name, `unknown'when no solution was found, and `none' when no such dummy main isneeded.By default, ACTION-IF-FOUND defines `F77_DUMMY_MAIN' or`FC_DUMMY_MAIN' to the name of this routine (e.g., `MAIN__') _if_it is required. ACTION-IF-NOT-FOUND defaults to exiting with anerror.In order to link with Fortran routines, the user's C/C++ programshould then include the following code to define the dummy main ifit is needed:#ifdef F77_DUMMY_MAIN# ifdef __cplusplusextern "C"# endifint F77_DUMMY_MAIN() { return 1; }#endif(Replace `F77' with `FC' for Fortran instead of Fortran 77.)Note that this macro is called automatically from `AC_F77_WRAPPERS'or `AC_FC_WRAPPERS'; there is generally no need to call itexplicitly unless one wants to change the default actions.-- Macro: AC_F77_MAIN-- Macro: AC_FC_MAINAs discussed above, many Fortran libraries allow you to provide anentry point called (say) `MAIN__' instead of the usual `main',which is then called by a `main' function in the Fortran librariesthat initializes things like Fortran I/O. The `AC_F77_MAIN' and`AC_FC_MAIN' macros detect whether it is _possible_ to utilizesuch an alternate main function, and defines `F77_MAIN' and`FC_MAIN' to the name of the function. (If no alternate mainfunction name is found, `F77_MAIN' and `FC_MAIN' are simplydefined to `main'.)Thus, when calling Fortran routines from C that perform thingslike I/O, one should use this macro and name the "main" function`F77_MAIN' or `FC_MAIN' instead of `main'.-- Macro: AC_F77_WRAPPERS-- Macro: AC_FC_WRAPPERSDefines C macros `F77_FUNC (name, NAME)', `FC_FUNC (name, NAME)',`F77_FUNC_(name, NAME)', and `FC_FUNC_(name, NAME)' to properlymangle the names of C/C++ identifiers, and identifiers withunderscores, respectively, so that they match the name-manglingscheme used by the Fortran compiler.Fortran is case-insensitive, and in order to achieve this theFortran compiler converts all identifiers into a canonical caseand format. To call a Fortran subroutine from C or to write a Cfunction that is callable from Fortran, the C program mustexplicitly use identifiers in the format expected by the Fortrancompiler. In order to do this, one simply wraps all C identifiersin one of the macros provided by `AC_F77_WRAPPERS' or`AC_FC_WRAPPERS'. For example, suppose you have the followingFortran 77 subroutine:subroutine foobar (x, y)double precision x, yy = 3.14159 * xreturnendYou would then declare its prototype in C or C++ as:#define FOOBAR_F77 F77_FUNC (foobar, FOOBAR)#ifdef __cplusplusextern "C" /* prevent C++ name mangling */#endifvoid FOOBAR_F77(double *x, double *y);Note that we pass both the lowercase and uppercase versions of thefunction name to `F77_FUNC' so that it can select the right one.Note also that all parameters to Fortran 77 routines are passed aspointers (*note Mixing Fortran 77 With C and C++: (automake)MixingFortran 77 With C and C++.).(Replace `F77' with `FC' for Fortran instead of Fortran 77.)Although Autoconf tries to be intelligent about detecting thename-mangling scheme of the Fortran compiler, there may be Fortrancompilers that it doesn't support yet. In this case, the abovecode generates a compile-time error, but some other behavior(e.g., disabling Fortran-related features) can be induced bychecking whether `F77_FUNC' or `FC_FUNC' is defined.Now, to call that routine from a C program, we would do somethinglike:{double x = 2.7183, y;FOOBAR_F77 (&x, &y);}If the Fortran identifier contains an underscore (e.g., `foo_bar'),you should use `F77_FUNC_' or `FC_FUNC_' instead of `F77_FUNC' or`FC_FUNC' (with the same arguments). This is because some Fortrancompilers mangle names differently if they contain an underscore.-- Macro: AC_F77_FUNC (NAME, [SHELLVAR])-- Macro: AC_FC_FUNC (NAME, [SHELLVAR])Given an identifier NAME, set the shell variable SHELLVAR to holdthe mangled version NAME according to the rules of the Fortranlinker (see also `AC_F77_WRAPPERS' or `AC_FC_WRAPPERS'). SHELLVARis optional; if it is not supplied, the shell variable is simplyNAME. The purpose of this macro is to give the caller a way toaccess the name-mangling information other than through the Cpreprocessor as above, for example, to call Fortran routines fromsome language other than C/C++.-- Macro: AC_FC_SRCEXT (EXT, [ACTION-IF-SUCCESS], [ACTION-IF-FAILURE])By default, the `FC' macros perform their tests using a `.f'extension for source-code files. Some compilers, however, onlyenable newer language features for appropriately named files,e.g., Fortran 90 features only for `.f90' files. On the otherhand, some other compilers expect all source files to end in `.f'and require special flags to support other file name extensions.The `AC_FC_SRCEXT' macro deals with both of these issues.The `AC_FC_SRCEXT' tries to get the `FC' compiler to accept filesending with the extension .EXT (i.e., EXT does _not_ contain thedot). If any special compiler flags are needed for this, itstores them in the output variable `FCFLAGS_'EXT. This extensionand these flags are then used for all subsequent `FC' tests (until`AC_FC_SRCEXT' is called again).For example, you would use `AC_FC_SRCEXT(f90)' to employ the`.f90' extension in future tests, and it would set a `FCFLAGS_f90'output variable with any extra flags that are needed to compilesuch files.The `FCFLAGS_'EXT can _not_ be simply absorbed into `FCFLAGS', fortwo reasons based on the limitations of some compilers. First,only one `FCFLAGS_'EXT can be used at a time, so files withdifferent extensions must be compiled separately. Second,`FCFLAGS_'EXT must appear _immediately_ before the source-codefile name when compiling. So, continuing the example above, youmight compile a `foo.f90' file in your makefile with the command:foo.o: foo.f90$(FC) -c $(FCFLAGS) $(FCFLAGS_f90) '$(srcdir)/foo.f90'If `AC_FC_SRCEXT' succeeds in compiling files with the EXTextension, it calls ACTION-IF-SUCCESS (defaults to nothing). Ifit fails, and cannot find a way to make the `FC' compiler acceptsuch files, it calls ACTION-IF-FAILURE (defaults to exiting with anerror message).-- Macro: AC_FC_FREEFORM ([ACTION-IF-SUCCESS], [ACTION-IF-FAILURE])The `AC_FC_FREEFORM' tries to ensure that the Fortran compiler(`$FC') allows free-format source code (as opposed to the olderfixed-format style from Fortran 77). If necessary, it may add someadditional flags to `FCFLAGS'.This macro is most important if you are using the default `.f'extension, since many compilers interpret this extension asindicating fixed-format source unless an additional flag issupplied. If you specify a different extension with`AC_FC_SRCEXT', such as `.f90' or `.f95', then `AC_FC_FREEFORM'ordinarily succeeds without modifying `FCFLAGS'.If `AC_FC_FREEFORM' succeeds in compiling free-form source, itcalls ACTION-IF-SUCCESS (defaults to nothing). If it fails, itcalls ACTION-IF-FAILURE (defaults to exiting with an errormessage).File: autoconf.info, Node: System Services, Next: Posix Variants, Prev: Compilers and Preprocessors, Up: Existing Tests5.11 System Services====================The following macros check for operating system services orcapabilities.-- Macro: AC_PATH_XTry to locate the X Window System include files and libraries. Ifthe user gave the command line options `--x-includes=DIR' and`--x-libraries=DIR', use those directories.If either or both were not given, get the missing values by running`xmkmf' (or an executable pointed to by the `XMKMF' environmentvariable) on a trivial `Imakefile' and examining the makefile thatit produces. Setting `XMKMF' to `false' disables this method.If this method fails to find the X Window System, `configure'looks for the files in several directories where they often reside.If either method is successful, set the shell variables`x_includes' and `x_libraries' to their locations, unless they arein directories the compiler searches by default.If both methods fail, or the user gave the command line option`--without-x', set the shell variable `no_x' to `yes'; otherwiseset it to the empty string.-- Macro: AC_PATH_XTRAAn enhanced version of `AC_PATH_X'. It adds the C compiler flagsthat X needs to output variable `X_CFLAGS', and the X linker flagsto `X_LIBS'. Define `X_DISPLAY_MISSING' if X is not available.This macro also checks for special libraries that some systemsneed in order to compile X programs. It adds any that the systemneeds to output variable `X_EXTRA_LIBS'. And it checks forspecial X11R6 libraries that need to be linked with before`-lX11', and adds any found to the output variable `X_PRE_LIBS'.-- Macro: AC_SYS_INTERPRETERCheck whether the system supports starting scripts with a line ofthe form `#!/bin/sh' to select the interpreter to use for thescript. After running this macro, shell code in `configure.ac'can check the shell variable `interpval'; it is set to `yes' ifthe system supports `#!', `no' if not.-- Macro: AC_SYS_LARGEFILEArrange for large-file support(http://www.unix-systems.org/version2/whatsnew/lfs20mar.html). Onsome hosts, one must use special compiler options to buildprograms that can access large files. Append any such options tothe output variable `CC'. Define `_FILE_OFFSET_BITS' and`_LARGE_FILES' if necessary.Large-file support can be disabled by configuring with the`--disable-largefile' option.If you use this macro, check that your program works even when`off_t' is wider than `long int', since this is common whenlarge-file support is enabled. For example, it is not correct toprint an arbitrary `off_t' value `X' with `printf ("%ld", (longint) X)'.The LFS introduced the `fseeko' and `ftello' functions to replacetheir C counterparts `fseek' and `ftell' that do not use `off_t'.Take care to use `AC_FUNC_FSEEKO' to make their prototypesavailable when using them and large-file support is enabled.-- Macro: AC_SYS_LONG_FILE_NAMESIf the system supports file names longer than 14 characters, define`HAVE_LONG_FILE_NAMES'.-- Macro: AC_SYS_POSIX_TERMIOSCheck to see if the Posix termios headers and functions areavailable on the system. If so, set the shell variable`ac_cv_sys_posix_termios' to `yes'. If not, set the variable to`no'.File: autoconf.info, Node: Posix Variants, Next: Erlang Libraries, Prev: System Services, Up: Existing Tests5.12 Posix Variants===================The following macros check for certain operating systems that needspecial treatment for some programs, due to exceptional oddities intheir header files or libraries. These macros are warts; they will bereplaced by a more systematic approach, based on the functions they makeavailable or the environments they provide.-- Macro: AC_AIXIf on AIX, define `_ALL_SOURCE'. Allows the use of some BSDfunctions. Should be called before any macros that run the Ccompiler.-- Macro: AC_GNU_SOURCEIf using the GNU C library, define `_GNU_SOURCE'. Allows the useof some GNU functions. Should be called before any macros thatrun the C compiler.-- Macro: AC_ISC_POSIXFor INTERACTIVE Systems Corporation Unix, add `-lcposix' to outputvariable `LIBS' if necessary for Posix facilities. Call thisafter `AC_PROG_CC' and before any other macros that use Posixinterfaces.This macro is obsolescent, as INTERACTIVE Unix is obsolete, and Sundropped support for it on 2006-07-23. New programs need not usethis macro.-- Macro: AC_MINIXIf on Minix, define `_MINIX' and `_POSIX_SOURCE' and define`_POSIX_1_SOURCE' to be 2. This allows the use of Posixfacilities. Should be called before any macros that run the Ccompiler.-- Macro: AC_USE_SYSTEM_EXTENSIONSIf possible, enable extensions to Posix on hosts that normallydisable the extensions, typically due to standards-conformancenamespace issues. This may involve defining `__EXTENSIONS__' and`_POSIX_PTHREAD_SEMANTICS', which are macros used by Solaris. Italso defines `_TANDEM_SOURCE' for the HP NonStop platform. Thismacro also has the combined effects of `AC_GNU_SOURCE', `AC_AIX',and `AC_MINIX'.File: autoconf.info, Node: Erlang Libraries, Prev: Posix Variants, Up: Existing Tests5.13 Erlang Libraries=====================The following macros check for an installation of Erlang/OTP, and forthe presence of certain Erlang libraries. All those macros require theconfiguration of an Erlang interpreter and an Erlang compiler (*noteErlang Compiler and Interpreter::).-- Macro: AC_ERLANG_SUBST_ROOT_DIRSet the output variable `ERLANG_ROOT_DIR' to the path to the basedirectory in which Erlang/OTP is installed (as returned byErlang's `code:root_dir/0' function). The result of this test iscached if caching is enabled when running `configure'.-- Macro: AC_ERLANG_SUBST_LIB_DIRSet the output variable `ERLANG_LIB_DIR' to the path of the librarydirectory of Erlang/OTP (as returned by Erlang's `code:lib_dir/0'function), which subdirectories each contain an installedErlang/OTP library. The result of this test is cached if cachingis enabled when running `configure'.-- Macro: AC_ERLANG_CHECK_LIB (LIBRARY, [ACTION-IF-FOUND],[ACTION-IF-NOT-FOUND])Test whether the Erlang/OTP library LIBRARY is installed bycalling Erlang's `code:lib_dir/1' function. The result of thistest is cached if caching is enabled when running `configure'.ACTION-IF-FOUND is a list of shell commands to run if the libraryis installed; ACTION-IF-NOT-FOUND is a list of shell commands torun if it is not. Additionally, if the library is installed, theoutput variable `ERLANG_LIB_DIR_LIBRARY' is set to the path to thelibrary installation directory, and the output variable`ERLANG_LIB_VER_LIBRARY' is set to the version number that is partof the subdirectory name, if it is in the standard form(`LIBRARY-VERSION'). If the directory name does not have aversion part, `ERLANG_LIB_VER_LIBRARY' is set to the empty string.If the library is not installed, `ERLANG_LIB_DIR_LIBRARY' and`ERLANG_LIB_VER_LIBRARY' are set to `"not found"'. For example,to check if library `stdlib' is installed:AC_ERLANG_CHECK_LIB([stdlib],[echo "stdlib version \"$ERLANG_LIB_VER_stdlib\""echo "is installed in \"$ERLANG_LIB_DIR_stdlib\""],[AC_MSG_ERROR([stdlib was not found!])])In addition to the above macros, which test installed Erlanglibraries, the following macros determine the paths to the directoriesinto which newly built Erlang libraries are to be installed:-- Macro: AC_ERLANG_SUBST_INSTALL_LIB_DIRSet the `ERLANG_INSTALL_LIB_DIR' output variable to the directoryinto which every built Erlang library should be installed in aseparate subdirectory. If this variable is not set in theenvironment when `configure' runs, its default value is`$ERLANG_LIB_DIR', which value is set by the`AC_ERLANG_SUBST_LIB_DIR' macro.-- Macro: AC_ERLANG_SUBST_INSTALL_LIB_SUBDIR (LIBRARY, VERSION)Set the `ERLANG_INSTALL_LIB_DIR_LIBRARY' output variable to thedirectory into which the built Erlang library LIBRARY versionVERSION should be installed. If this variable is not set in theenvironment when `configure' runs, its default value is`$ERLANG_INSTALL_LIB_DIR/LIBRARY-VERSION', the value of the`ERLANG_INSTALL_LIB_DIR' variable being set by the`AC_ERLANG_SUBST_INSTALL_LIB_DIR' macro.File: autoconf.info, Node: Writing Tests, Next: Results, Prev: Existing Tests, Up: Top6 Writing Tests***************If the existing feature tests don't do something you need, you have towrite new ones. These macros are the building blocks. They provideways for other macros to check whether various kinds of features areavailable and report the results.This chapter contains some suggestions and some of the reasons whythe existing tests are written the way they are. You can also learn alot about how to write Autoconf tests by looking at the existing ones.If something goes wrong in one or more of the Autoconf tests, thisinformation can help you understand the assumptions behind them, whichmight help you figure out how to best solve the problem.These macros check the output of the compiler system of the currentlanguage (*note Language Choice::). They do not cache the results oftheir tests for future use (*note Caching Results::), because they don'tknow enough about the information they are checking for to generate acache variable name. They also do not print any messages, for the samereason. The checks for particular kinds of features call these macrosand do cache their results and print messages about what they'rechecking for.When you write a feature test that could be applicable to more thanone software package, the best thing to do is encapsulate it in a newmacro. *Note Writing Autoconf Macros::, for how to do that.* Menu:* Language Choice:: Selecting which language to use for testing* Writing Test Programs:: Forging source files for compilers* Running the Preprocessor:: Detecting preprocessor symbols* Running the Compiler:: Detecting language or header features* Running the Linker:: Detecting library features* Runtime:: Testing for runtime features* Systemology:: A zoology of operating systems* Multiple Cases:: Tests for several possible valuesFile: autoconf.info, Node: Language Choice, Next: Writing Test Programs, Up: Writing Tests6.1 Language Choice===================Autoconf-generated `configure' scripts check for the C compiler and itsfeatures by default. Packages that use other programming languages(maybe more than one, e.g., C and C++) need to test features of thecompilers for the respective languages. The following macros determinewhich programming language is used in the subsequent tests in`configure.ac'.-- Macro: AC_LANG (LANGUAGE)Do compilation tests using the compiler, preprocessor, and fileextensions for the specified LANGUAGE.Supported languages are:`C'Do compilation tests using `CC' and `CPP' and use extension`.c' for test programs. Use compilation flags: `CPPFLAGS'with `CPP', and both `CPPFLAGS' and `CFLAGS' with `CC'.`C++'Do compilation tests using `CXX' and `CXXCPP' and useextension `.C' for test programs. Use compilation flags:`CPPFLAGS' with `CXXPP', and both `CPPFLAGS' and `CXXFLAGS'with `CXX'.`Fortran 77'Do compilation tests using `F77' and use extension `.f' fortest programs. Use compilation flags: `FFLAGS'.`Fortran'Do compilation tests using `FC' and use extension `.f' (orwhatever has been set by `AC_FC_SRCEXT') for test programs.Use compilation flags: `FCFLAGS'.`Erlang'Compile and execute tests using `ERLC' and `ERL' and useextension `.erl' for test Erlang modules. Use compilationflags: `ERLCFLAGS'.`Objective C'Do compilation tests using `OBJC' and `OBJCCPP' and useextension `.m' for test programs. Use compilation flags:`CPPFLAGS' with `OBJCPP', and both `CPPFLAGS' and `OBJCFLAGS'with `OBJC'.-- Macro: AC_LANG_PUSH (LANGUAGE)Remember the current language (as set by `AC_LANG') on a stack, andthen select the LANGUAGE. Use this macro and `AC_LANG_POP' inmacros that need to temporarily switch to a particular language.-- Macro: AC_LANG_POP ([LANGUAGE])Select the language that is saved on the top of the stack, as setby `AC_LANG_PUSH', and remove it from the stack.If given, LANGUAGE specifies the language we just _quit_. It is agood idea to specify it when it's known (which should be thecase...), since Autoconf detects inconsistencies.AC_LANG_PUSH([Fortran 77])# Perform some tests on Fortran 77.# ...AC_LANG_POP([Fortran 77])-- Macro: AC_LANG_ASSERT (LANGUAGE)Check statically that the current language is LANGUAGE. Youshould use this in your language specific macros to avoid thatthey be called with an inappropriate language.This macro runs only at `autoconf' time, and incurs no cost at`configure' time. Sadly enough and because Autoconf is a twolayer language (1), the macros `AC_LANG_PUSH' and `AC_LANG_POP'cannot be "optimizing", therefore as much as possible you ought toavoid using them to wrap your code, rather, require from the userto run the macro with a correct current language, and check itwith `AC_LANG_ASSERT'. And anyway, that may help the userunderstand she is running a Fortran macro while expecting a resultabout her Fortran 77 compiler...-- Macro: AC_REQUIRE_CPPEnsure that whichever preprocessor would currently be used fortests has been found. Calls `AC_REQUIRE' (*note PrerequisiteMacros::) with an argument of either `AC_PROG_CPP' or`AC_PROG_CXXCPP', depending on which language is current.---------- Footnotes ----------(1) Because M4 is not aware of Sh code, especially conditionals,some optimizations that look nice statically may produce incorrectresults at runtime.File: autoconf.info, Node: Writing Test Programs, Next: Running the Preprocessor, Prev: Language Choice, Up: Writing Tests6.2 Writing Test Programs=========================Autoconf tests follow a common scheme: feed some program with someinput, and most of the time, feed a compiler with some source file.This section is dedicated to these source samples.* Menu:* Guidelines:: General rules for writing test programs* Test Functions:: Avoiding pitfalls in test programs* Generating Sources:: Source program boilerplateFile: autoconf.info, Node: Guidelines, Next: Test Functions, Up: Writing Test Programs6.2.1 Guidelines for Test Programs----------------------------------The most important rule to follow when writing testing samples is:_Look for realism._This motto means that testing samples must be written with the samestrictness as real programs are written. In particular, you shouldavoid "shortcuts" and simplifications.Don't just play with the preprocessor if you want to prepare acompilation. For instance, using `cpp' to check whether a header isfunctional might let your `configure' accept a header which causes some_compiler_ error. Do not hesitate to check a header with other headersincluded before, especially required headers.Make sure the symbols you use are properly defined, i.e., refrain forsimply declaring a function yourself instead of including the properheader.Test programs should not write to standard output. They should exitwith status 0 if the test succeeds, and with status 1 otherwise, sothat success can be distinguished easily from a core dump or otherfailure; segmentation violations and other failures produce a nonzeroexit status. Unless you arrange for `exit' to be declared, testprograms should `return', not `exit', from `main', because on manysystems `exit' is not declared by default.Test programs can use `#if' or `#ifdef' to check the values ofpreprocessor macros defined by tests that have already run. Forexample, if you call `AC_HEADER_STDBOOL', then later on in`configure.ac' you can have a test program that includes `stdbool.h'conditionally:#ifdef HAVE_STDBOOL_H# include <stdbool.h>#endifBoth `#if HAVE_STDBOOL_H' and `#ifdef HAVE_STDBOOL_H' will work withany standard C compiler. Some developers prefer `#if' because it iseasier to read, while others prefer `#ifdef' because it avoidsdiagnostics with picky compilers like GCC with the `-Wundef' option.If a test program needs to use or create a data file, give it a namethat starts with `conftest', such as `conftest.data'. The `configure'script cleans up by running `rm -f -r conftest*' after running testprograms and if the script is interrupted.File: autoconf.info, Node: Test Functions, Next: Generating Sources, Prev: Guidelines, Up: Writing Test Programs6.2.2 Test Functions--------------------These days it's safe to assume support for function prototypes(introduced in C89).Functions that test programs declare should also be conditionalizedfor C++, which requires `extern "C"' prototypes. Make sure to notinclude any header files containing clashing prototypes.#ifdef __cplusplusextern "C"#endifvoid *valloc (size_t);If a test program calls a function with invalid parameters (just tosee whether it exists), organize the program to ensure that it neverinvokes that function. You can do this by calling it in anotherfunction that is never invoked. You can't do it by putting it after acall to `exit', because GCC version 2 knows that `exit' never returnsand optimizes out any code that follows it in the same block.If you include any header files, be sure to call the functionsrelevant to them with the correct number of arguments, even if they arejust 0, to avoid compilation errors due to prototypes. GCC version 2has internal prototypes for several functions that it automaticallyinlines; for example, `memcpy'. To avoid errors when checking forthem, either pass them the correct number of arguments or redeclare themwith a different return type (such as `char').File: autoconf.info, Node: Generating Sources, Prev: Test Functions, Up: Writing Test Programs6.2.3 Generating Sources------------------------Autoconf provides a set of macros that can be used to generate testsource files. They are written to be language generic, i.e., theyactually depend on the current language (*note Language Choice::) to"format" the output properly.-- Macro: AC_LANG_CONFTEST (SOURCE)Save the SOURCE text in the current test source file:`conftest.EXTENSION' where the EXTENSION depends on the currentlanguage.Note that the SOURCE is evaluated exactly once, like regularAutoconf macro arguments, and therefore (i) you may pass a macroinvocation, (ii) if not, be sure to double quote if needed.-- Macro: AC_LANG_SOURCE (SOURCE)Expands into the SOURCE, with the definition of all the`AC_DEFINE' performed so far.For instance executing (observe the double quotation!):AC_INIT([Hello], [1.0], [bug-hello@example.org])AC_DEFINE([HELLO_WORLD], ["Hello, World\n"],[Greetings string.])AC_LANG(C)AC_LANG_CONFTEST([AC_LANG_SOURCE([[const char hw[] = "Hello, World\n";]])])gcc -E -dD -o - conftest.cresults in:...# 1 "conftest.c"#define PACKAGE_NAME "Hello"#define PACKAGE_TARNAME "hello"#define PACKAGE_VERSION "1.0"#define PACKAGE_STRING "Hello 1.0"#define PACKAGE_BUGREPORT "bug-hello@example.org"#define HELLO_WORLD "Hello, World\n"const char hw[] = "Hello, World\n";When the test language is Fortran or Erlang, the `AC_DEFINE'definitions are not automatically translated into constants in thesource code by this macro.-- Macro: AC_LANG_PROGRAM (PROLOGUE, BODY)Expands into a source file which consists of the PROLOGUE, andthen BODY as body of the main function (e.g., `main' in C). Sinceit uses `AC_LANG_SOURCE', the features of the latter are available.For instance:AC_INIT([Hello], [1.0], [bug-hello@example.org])AC_DEFINE([HELLO_WORLD], ["Hello, World\n"],[Greetings string.])AC_LANG_CONFTEST([AC_LANG_PROGRAM([[const char hw[] = "Hello, World\n";]],[[fputs (hw, stdout);]])])gcc -E -dD -o - conftest.cresults in:...# 1 "conftest.c"#define PACKAGE_NAME "Hello"#define PACKAGE_TARNAME "hello"#define PACKAGE_VERSION "1.0"#define PACKAGE_STRING "Hello 1.0"#define PACKAGE_BUGREPORT "bug-hello@example.org"#define HELLO_WORLD "Hello, World\n"const char hw[] = "Hello, World\n";intmain (){fputs (hw, stdout);;return 0;}In Erlang tests, the created source file is that of an Erlang modulecalled `conftest' (`conftest.erl'). This module defines and exports atleast one `start/0' function, which is called to perform the test. ThePROLOGUE is optional code that is inserted between the module header andthe `start/0' function definition. BODY is the body of the `start/0'function without the final period (*note Runtime::, about constraintson this function's behavior).For instance:AC_INIT([Hello], [1.0], [bug-hello@example.org])AC_LANG(Erlang)AC_LANG_CONFTEST([AC_LANG_PROGRAM([[-define(HELLO_WORLD, "Hello, world!").]],[[io:format("~s~n", [?HELLO_WORLD])]])])cat conftest.erlresults in:-module(conftest).-export([start/0]).-define(HELLO_WORLD, "Hello, world!").start() ->io:format("~s~n", [?HELLO_WORLD]).-- Macro: AC_LANG_CALL (PROLOGUE, FUNCTION)Expands into a source file which consists of the PROLOGUE, andthen a call to the FUNCTION as body of the main function (e.g.,`main' in C). Since it uses `AC_LANG_PROGRAM', the feature of thelatter are available.This function will probably be replaced in the future by a versionwhich would enable specifying the arguments. The use of thismacro is not encouraged, as it violates strongly the typing system.This macro cannot be used for Erlang tests.-- Macro: AC_LANG_FUNC_LINK_TRY (FUNCTION)Expands into a source file which uses the FUNCTION in the body ofthe main function (e.g., `main' in C). Since it uses`AC_LANG_PROGRAM', the features of the latter are available.As `AC_LANG_CALL', this macro is documented only for completeness.It is considered to be severely broken, and in the future will beremoved in favor of actual function calls (with properly typedarguments).This macro cannot be used for Erlang tests.File: autoconf.info, Node: Running the Preprocessor, Next: Running the Compiler, Prev: Writing Test Programs, Up: Writing Tests6.3 Running the Preprocessor============================Sometimes one might need to run the preprocessor on some source file._Usually it is a bad idea_, as you typically need to _compile_ yourproject, not merely run the preprocessor on it; therefore you certainlywant to run the compiler, not the preprocessor. Resist the temptationof following the easiest path.Nevertheless, if you need to run the preprocessor, then use`AC_PREPROC_IFELSE'.The macros described in this section cannot be used for tests inErlang or Fortran, since those languages require no preprocessor.-- Macro: AC_PREPROC_IFELSE (INPUT, [ACTION-IF-TRUE],[ACTION-IF-FALSE])Run the preprocessor of the current language (*note LanguageChoice::) on the INPUT, run the shell commands ACTION-IF-TRUE onsuccess, ACTION-IF-FALSE otherwise. The INPUT can be made by`AC_LANG_PROGRAM' and friends.This macro uses `CPPFLAGS', but not `CFLAGS', because `-g', `-O',etc. are not valid options to many C preprocessors.It is customary to report unexpected failures with`AC_MSG_FAILURE'.For instance:AC_INIT([Hello], [1.0], [bug-hello@example.org])AC_DEFINE([HELLO_WORLD], ["Hello, World\n"],[Greetings string.])AC_PREPROC_IFELSE([AC_LANG_PROGRAM([[const char hw[] = "Hello, World\n";]],[[fputs (hw, stdout);]])],[AC_MSG_RESULT([OK])],[AC_MSG_FAILURE([unexpected preprocessor failure])])results in:checking for gcc... gccchecking for C compiler default output file name... a.outchecking whether the C compiler works... yeschecking whether we are cross compiling... nochecking for suffix of executables...checking for suffix of object files... ochecking whether we are using the GNU C compiler... yeschecking whether gcc accepts -g... yeschecking for gcc option to accept ISO C89... none neededchecking how to run the C preprocessor... gcc -EOKThe macro `AC_TRY_CPP' (*note Obsolete Macros::) used to play therole of `AC_PREPROC_IFELSE', but double quotes its argument, making itimpossible to use it to elaborate sources. You are encouraged to getrid of your old use of the macro `AC_TRY_CPP' in favor of`AC_PREPROC_IFELSE', but, in the first place, are you sure you need torun the _preprocessor_ and not the compiler?-- Macro: AC_EGREP_HEADER (PATTERN, HEADER-FILE, ACTION-IF-FOUND,[ACTION-IF-NOT-FOUND])If the output of running the preprocessor on the system header fileHEADER-FILE matches the extended regular expression PATTERN,execute shell commands ACTION-IF-FOUND, otherwise executeACTION-IF-NOT-FOUND.-- Macro: AC_EGREP_CPP (PATTERN, PROGRAM, [ACTION-IF-FOUND],[ACTION-IF-NOT-FOUND])PROGRAM is the text of a C or C++ program, on which shellvariable, back quote, and backslash substitutions are performed.If the output of running the preprocessor on PROGRAM matches theextended regular expression PATTERN, execute shell commandsACTION-IF-FOUND, otherwise execute ACTION-IF-NOT-FOUND.File: autoconf.info, Node: Running the Compiler, Next: Running the Linker, Prev: Running the Preprocessor, Up: Writing Tests6.4 Running the Compiler========================To check for a syntax feature of the current language's (*note LanguageChoice::) compiler, such as whether it recognizes a certain keyword, orsimply to try some library feature, use `AC_COMPILE_IFELSE' to try tocompile a small program that uses that feature.-- Macro: AC_COMPILE_IFELSE (INPUT, [ACTION-IF-TRUE],[ACTION-IF-FALSE])Run the compiler and compilation flags of the current language(*note Language Choice::) on the INPUT, run the shell commandsACTION-IF-TRUE on success, ACTION-IF-FALSE otherwise. The INPUTcan be made by `AC_LANG_PROGRAM' and friends.It is customary to report unexpected failures with`AC_MSG_FAILURE'. This macro does not try to link; use`AC_LINK_IFELSE' if you need to do that (*note Running theLinker::).For tests in Erlang, the INPUT must be the source code of a modulenamed `conftest'. `AC_COMPILE_IFELSE' generates a `conftest.beam' filethat can be interpreted by the Erlang virtual machine (`ERL'). It isrecommended to use `AC_LANG_PROGRAM' to specify the test program, toensure that the Erlang module has the right name.File: autoconf.info, Node: Running the Linker, Next: Runtime, Prev: Running the Compiler, Up: Writing Tests6.5 Running the Linker======================To check for a library, a function, or a global variable, Autoconf`configure' scripts try to compile and link a small program that usesit. This is unlike Metaconfig, which by default uses `nm' or `ar' onthe C library to try to figure out which functions are available.Trying to link with the function is usually a more reliable approachbecause it avoids dealing with the variations in the options and outputformats of `nm' and `ar' and in the location of the standard libraries.It also allows configuring for cross-compilation or checking afunction's runtime behavior if needed. On the other hand, it can beslower than scanning the libraries once, but accuracy is more importantthan speed.`AC_LINK_IFELSE' is used to compile test programs to test forfunctions and global variables. It is also used by `AC_CHECK_LIB' tocheck for libraries (*note Libraries::), by adding the library beingchecked for to `LIBS' temporarily and trying to link a small program.-- Macro: AC_LINK_IFELSE (INPUT, [ACTION-IF-TRUE], [ACTION-IF-FALSE])Run the compiler (and compilation flags) and the linker of thecurrent language (*note Language Choice::) on the INPUT, run theshell commands ACTION-IF-TRUE on success, ACTION-IF-FALSEotherwise. The INPUT can be made by `AC_LANG_PROGRAM' and friends.`LDFLAGS' and `LIBS' are used for linking, in addition to thecurrent compilation flags.It is customary to report unexpected failures with`AC_MSG_FAILURE'. This macro does not try to execute the program;use `AC_RUN_IFELSE' if you need to do that (*note Runtime::).The `AC_LINK_IFELSE' macro cannot be used for Erlang tests, sinceErlang programs are interpreted and do not require linking.File: autoconf.info, Node: Runtime, Next: Systemology, Prev: Running the Linker, Up: Writing Tests6.6 Checking Runtime Behavior=============================Sometimes you need to find out how a system performs at runtime, suchas whether a given function has a certain capability or bug. If youcan, make such checks when your program runs instead of when it isconfigured. You can check for things like the machine's endianness whenyour program initializes itself.If you really need to test for a runtime behavior while configuring,you can write a test program to determine the result, and compile andrun it using `AC_RUN_IFELSE'. Avoid running test programs if possible,because this prevents people from configuring your package forcross-compiling.-- Macro: AC_RUN_IFELSE (INPUT, [ACTION-IF-TRUE], [ACTION-IF-FALSE],[ACTION-IF-CROSS-COMPILING])If PROGRAM compiles and links successfully and returns an exitstatus of 0 when executed, run shell commands ACTION-IF-TRUE.Otherwise, run shell commands ACTION-IF-FALSE.The INPUT can be made by `AC_LANG_PROGRAM' and friends. `LDFLAGS'and `LIBS' are used for linking, in addition to the compilationflags of the current language (*note Language Choice::).If the compiler being used does not produce executables that runon the system where `configure' is being run, then the testprogram is not run. If the optional shell commandsACTION-IF-CROSS-COMPILING are given, they are run instead.Otherwise, `configure' prints an error message and exits.In the ACTION-IF-FALSE section, the failing exit status isavailable in the shell variable `$?'. This exit status might bethat of a failed compilation, or it might be that of a failedprogram execution.It is customary to report unexpected failures with`AC_MSG_FAILURE'.Try to provide a pessimistic default value to use whencross-compiling makes runtime tests impossible. You do this by passingthe optional last argument to `AC_RUN_IFELSE'. `autoconf' prints awarning message when creating `configure' each time it encounters acall to `AC_RUN_IFELSE' with no ACTION-IF-CROSS-COMPILING argumentgiven. You may ignore the warning, though users cannot configure yourpackage for cross-compiling. A few of the macros distributed withAutoconf produce this warning message.To configure for cross-compiling you can also choose a value forthose parameters based on the canonical system name (*note ManualConfiguration::). Alternatively, set up a test results cache file withthe correct values for the host system (*note Caching Results::).To provide a default for calls of `AC_RUN_IFELSE' that are embeddedin other macros, including a few of the ones that come with Autoconf,you can test whether the shell variable `cross_compiling' is set to`yes', and then use an alternate method to get the results instead ofcalling the macros.A C or C++ runtime test should be portable. *Note Portable C andC++::.Erlang tests must exit themselves the Erlang VM by calling the`halt/1' function: the given status code is used to determine thesuccess of the test (status is `0') or its failure (status is differentthan `0'), as explained above. It must be noted that data outputthrough the standard output (e.g., using `io:format/2') may betruncated when halting the VM. Therefore, if a test must outputconfiguration information, it is recommended to create and to outputdata into the temporary file named `conftest.out', using the functionsof module `file'. The `conftest.out' file is automatically deleted bythe `AC_RUN_IFELSE' macro. For instance, a simplified implementationof Autoconf's `AC_ERLANG_SUBST_LIB_DIR' macro is:AC_INIT([LibdirTest], [1.0], [bug-libdirtest@example.org])AC_ERLANG_NEED_ERLAC_LANG(Erlang)AC_RUN_IFELSE([AC_LANG_PROGRAM([], [dnlfile:write_file("conftest.out", code:lib_dir()),halt(0)])],[echo "code:lib_dir() returned: `cat conftest.out`"],[AC_MSG_FAILURE([test Erlang program execution failed])])File: autoconf.info, Node: Systemology, Next: Multiple Cases, Prev: Runtime, Up: Writing Tests6.7 Systemology===============This section aims at presenting some systems and pointers todocumentation. It may help you addressing particular problems reportedby users.Posix-conforming systems (http://www.opengroup.org/susv3) arederived from the Unix operating system(http://www.bell-labs.com/history/unix/).The Rosetta Stone for Unix (http://bhami.com/rosetta.html) containsa table correlating the features of various Posix-conforming systems.Unix History (http://www.levenez.com/unix/) is a simplified diagram ofhow many Unix systems were derived from each other.The Heirloom Project (http://heirloom.sourceforge.net/) providessome variants of traditional implementations of Unix utilities.DarwinDarwin is also known as Mac OS X. Beware that the file system_can_ be case-preserving, but case insensitive. This can causenasty problems, since for instance the installation attempt for apackage having an `INSTALL' file can result in `make install'report that nothing was to be done!That's all dependent on whether the file system is a UFS (casesensitive) or HFS+ (case preserving). By default Apple wants youto install the OS on HFS+. Unfortunately, there are some pieces ofsoftware which really need to be built on UFS. We may want torebuild Darwin to have both UFS and HFS+ available (and put the/local/build tree on the UFS).QNX 4.25QNX is a realtime operating system running on Intel architecturemeant to be scalable from the small embedded systems to the hundredprocessor super-computer. It claims to be Posix certified. Moreinformation is available on the QNX home page(http://www.qnx.com/).Tru64Documentation of several versions of Tru64(http://h30097.www3.hp.com/docs/) is available in differentformats.Unix version 7Officially this was called the "Seventh Edition" of "the UNIXtime-sharing system" but we use the more-common name "Unix version7". Documentation is available in the Unix Seventh Edition Manual(http://plan9.bell-labs.com/7thEdMan/). Previous versions of Unixare called "Unix version 6", etc., but they were not as widelyused.File: autoconf.info, Node: Multiple Cases, Prev: Systemology, Up: Writing Tests6.8 Multiple Cases==================Some operations are accomplished in several possible ways, depending onthe OS variant. Checking for them essentially requires a "casestatement". Autoconf does not directly provide one; however, it iseasy to simulate by using a shell variable to keep track of whether away to perform the operation has been found yet.Here is an example that uses the shell variable `fstype' to keeptrack of whether the remaining cases need to be checked.AC_MSG_CHECKING([how to get file system type])fstype=no# The order of these tests is important.AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[#include <sys/statvfs.h>#include <sys/fstyp.h>]])],[AC_DEFINE([FSTYPE_STATVFS], [1],[Define if statvfs exists.])fstype=SVR4])if test $fstype = no; thenAC_COMPILE_IFELSE([AC_LANG_PROGRAM([[#include <sys/statfs.h>#include <sys/fstyp.h>]])],[AC_DEFINE([FSTYPE_USG_STATFS], [1],[Define if USG statfs.])fstype=SVR3])fiif test $fstype = no; thenAC_COMPILE_IFELSE([AC_LANG_PROGRAM([[#include <sys/statfs.h>#include <sys/vmount.h>]])]),[AC_DEFINE([FSTYPE_AIX_STATFS], [1],[Define if AIX statfs.])fstype=AIX])fi# (more cases omitted here)AC_MSG_RESULT([$fstype])File: autoconf.info, Node: Results, Next: Programming in M4, Prev: Writing Tests, Up: Top7 Results of Tests******************Once `configure' has determined whether a feature exists, what can itdo to record that information? There are four sorts of things it cando: define a C preprocessor symbol, set a variable in the output files,save the result in a cache file for future `configure' runs, and printa message letting the user know the result of the test.* Menu:* Defining Symbols:: Defining C preprocessor symbols* Setting Output Variables:: Replacing variables in output files* Special Chars in Variables:: Characters to beware of in variables* Caching Results:: Speeding up subsequent `configure' runs* Printing Messages:: Notifying `configure' usersFile: autoconf.info, Node: Defining Symbols, Next: Setting Output Variables, Up: Results7.1 Defining C Preprocessor Symbols===================================A common action to take in response to a feature test is to define a Cpreprocessor symbol indicating the results of the test. That is done bycalling `AC_DEFINE' or `AC_DEFINE_UNQUOTED'.By default, `AC_OUTPUT' places the symbols defined by these macrosinto the output variable `DEFS', which contains an option`-DSYMBOL=VALUE' for each symbol defined. Unlike in Autoconf version1, there is no variable `DEFS' defined while `configure' is running.To check whether Autoconf macros have already defined a certain Cpreprocessor symbol, test the value of the appropriate cache variable,as in this example:AC_CHECK_FUNC([vprintf], [AC_DEFINE([HAVE_VPRINTF], [1],[Define if vprintf exists.])])if test "$ac_cv_func_vprintf" != yes; thenAC_CHECK_FUNC([_doprnt], [AC_DEFINE([HAVE_DOPRNT], [1],[Define if _doprnt exists.])])fiIf `AC_CONFIG_HEADERS' has been called, then instead of creating`DEFS', `AC_OUTPUT' creates a header file by substituting the correctvalues into `#define' statements in a template file. *NoteConfiguration Headers::, for more information about this kind of output.-- Macro: AC_DEFINE (VARIABLE, VALUE, [DESCRIPTION])-- Macro: AC_DEFINE (VARIABLE)Define the C preprocessor variable VARIABLE to VALUE (verbatim).VALUE should not contain literal newlines, and if you are notusing `AC_CONFIG_HEADERS' it should not contain any `#'characters, as `make' tends to eat them. To use a shell variable,use `AC_DEFINE_UNQUOTED' instead. DESCRIPTION is only useful ifyou are using `AC_CONFIG_HEADERS'. In this case, DESCRIPTION isput into the generated `config.h.in' as the comment before themacro define. The following example defines the C preprocessorvariable `EQUATION' to be the string constant `"$a > $b"':AC_DEFINE([EQUATION], ["$a > $b"],[Equation string.])If neither VALUE nor DESCRIPTION are given, then VALUE defaults to1 instead of to the empty string. This is for backwardscompatibility with older versions of Autoconf, but this usage isobsolescent and may be withdrawn in future versions of Autoconf.If the VARIABLE is a literal string, it is passed to`m4_pattern_allow' (*note Forbidden Patterns::).-- Macro: AC_DEFINE_UNQUOTED (VARIABLE, VALUE, [DESCRIPTION])-- Macro: AC_DEFINE_UNQUOTED (VARIABLE)Like `AC_DEFINE', but three shell expansions areperformed--once--on VARIABLE and VALUE: variable expansion (`$'),command substitution (``'), and backslash escaping (`\'). Singleand double quote characters in the value have no special meaning.Use this macro instead of `AC_DEFINE' when VARIABLE or VALUE is ashell variable. Examples:AC_DEFINE_UNQUOTED([config_machfile], ["$machfile"],[Configuration machine file.])AC_DEFINE_UNQUOTED([GETGROUPS_T], [$ac_cv_type_getgroups],[getgroups return type.])AC_DEFINE_UNQUOTED([$ac_tr_hdr], [1],[Translated header name.])Due to a syntactical bizarreness of the Bourne shell, do not usesemicolons to separate `AC_DEFINE' or `AC_DEFINE_UNQUOTED' calls fromother macro calls or shell code; that can cause syntax errors in theresulting `configure' script. Use either blanks or newlines. That is,do this:AC_CHECK_HEADER([elf.h],[AC_DEFINE([SVR4], [1], [System V Release 4]) LIBS="-lelf $LIBS"])or this:AC_CHECK_HEADER([elf.h],[AC_DEFINE([SVR4], [1], [System V Release 4])LIBS="-lelf $LIBS"])instead of this:AC_CHECK_HEADER([elf.h],[AC_DEFINE([SVR4], [1], [System V Release 4]); LIBS="-lelf $LIBS"])File: autoconf.info, Node: Setting Output Variables, Next: Special Chars in Variables, Prev: Defining Symbols, Up: Results7.2 Setting Output Variables============================Another way to record the results of tests is to set "outputvariables", which are shell variables whose values are substituted intofiles that `configure' outputs. The two macros below create new outputvariables. *Note Preset Output Variables::, for a list of outputvariables that are always available.-- Macro: AC_SUBST (VARIABLE, [VALUE])Create an output variable from a shell variable. Make `AC_OUTPUT'substitute the variable VARIABLE into output files (typically oneor more makefiles). This means that `AC_OUTPUT' replacesinstances of `@VARIABLE@' in input files with the value that theshell variable VARIABLE has when `AC_OUTPUT' is called. The valuecan contain newlines. The substituted value is not rescanned formore output variables; occurrences of `@VARIABLE@' in the valueare inserted literally into the output file. (The algorithm usesthe special marker `|#_!!_#|' internally, so the substituted valuecannot contain `|#_!!_#|'.)If VALUE is given, in addition assign it to VARIABLE.The string VARIABLE is passed to `m4_pattern_allow' (*noteForbidden Patterns::).-- Macro: AC_SUBST_FILE (VARIABLE)Another way to create an output variable from a shell variable.Make `AC_OUTPUT' insert (without substitutions) the contents ofthe file named by shell variable VARIABLE into output files. Thismeans that `AC_OUTPUT' replaces instances of `@VARIABLE@' inoutput files (such as `Makefile.in') with the contents of the filethat the shell variable VARIABLE names when `AC_OUTPUT' is called.Set the variable to `/dev/null' for cases that do not have a fileto insert. This substitution occurs only when the `@VARIABLE@' ison a line by itself, optionally surrounded by spaces and tabs. Thesubstitution replaces the whole line, including the spaces, tabs,and the terminating newline.This macro is useful for inserting makefile fragments containingspecial dependencies or other `make' directives for particular hostor target types into makefiles. For example, `configure.ac' couldcontain:AC_SUBST_FILE([host_frag])host_frag=$srcdir/conf/sun4.mhand then a `Makefile.in' could contain:@host_frag@The string VARIABLE is passed to `m4_pattern_allow' (*noteForbidden Patterns::).Running `configure' in varying environments can be extremelydangerous. If for instance the user runs `CC=bizarre-cc ./configure',then the cache, `config.h', and many other output files depend upon`bizarre-cc' being the C compiler. If for some reason the user runs`./configure' again, or if it is run via `./config.status --recheck',(*Note Automatic Remaking::, and *note config.status Invocation::),then the configuration can be inconsistent, composed of resultsdepending upon two different compilers.Environment variables that affect this situation, such as `CC'above, are called "precious variables", and can be declared as such by`AC_ARG_VAR'.-- Macro: AC_ARG_VAR (VARIABLE, DESCRIPTION)Declare VARIABLE is a precious variable, and include itsDESCRIPTION in the variable section of `./configure --help'.Being precious means that- VARIABLE is substituted via `AC_SUBST'.- The value of VARIABLE when `configure' was launched is savedin the cache, including if it was not specified on the commandline but via the environment. Indeed, while `configure' cannotice the definition of `CC' in `./configure CC=bizarre-cc',it is impossible to notice it in `CC=bizarre-cc ./configure',which, unfortunately, is what most users do.We emphasize that it is the _initial_ value of VARIABLE whichis saved, not that found during the execution of `configure'.Indeed, specifying `./configure FOO=foo' and letting`./configure' guess that `FOO' is `foo' can be two differentthings.- VARIABLE is checked for consistency between two `configure'runs. For instance:$ ./configure --silent --config-cache$ CC=cc ./configure --silent --config-cacheconfigure: error: `CC' was not set in the previous runconfigure: error: changes in the environment can compromise \the buildconfigure: error: run `make distclean' and/or \`rm config.cache' and start overand similarly if the variable is unset, or if its content ischanged.- VARIABLE is kept during automatic reconfiguration (*noteconfig.status Invocation::) as if it had been passed as acommand line argument, including when no cache is used:$ CC=/usr/bin/cc ./configure undeclared_var=raboof --silent$ ./config.status --recheckrunning CONFIG_SHELL=/bin/sh /bin/sh ./configure undeclared_var=raboof \CC=/usr/bin/cc --no-create --no-recursionFile: autoconf.info, Node: Special Chars in Variables, Next: Caching Results, Prev: Setting Output Variables, Up: Results7.3 Special Characters in Output Variables==========================================Many output variables are intended to be evaluated both by `make' andby the shell. Some characters are expanded differently in these twocontexts, so to avoid confusion these variables' values should notcontain any of the following characters:" # $ & ' ( ) * ; < > ? [ \ ^ ` |Also, these variables' values should neither contain newlines, norstart with `~', nor contain white space or `:' immediately followed by`~'. The values can contain nonempty sequences of white spacecharacters like tabs and spaces, but each such sequence mightarbitrarily be replaced by a single space during substitution.These restrictions apply both to the values that `configure'computes, and to the values set directly by the user. For example, thefollowing invocations of `configure' are problematic, since theyattempt to use special characters within `CPPFLAGS' and white spacewithin `$(srcdir)':CPPFLAGS='-DOUCH="&\"#$*?"' '../My Source/ouch-1.0/configure''../My Source/ouch-1.0/configure' CPPFLAGS='-DOUCH="&\"#$*?"'File: autoconf.info, Node: Caching Results, Next: Printing Messages, Prev: Special Chars in Variables, Up: Results7.4 Caching Results===================To avoid checking for the same features repeatedly in various`configure' scripts (or in repeated runs of one script), `configure'can optionally save the results of many checks in a "cache file" (*noteCache Files::). If a `configure' script runs with caching enabled andfinds a cache file, it reads the results of previous runs from thecache and avoids rerunning those checks. As a result, `configure' canthen run much faster than if it had to perform all of the checks everytime.-- Macro: AC_CACHE_VAL (CACHE-ID, COMMANDS-TO-SET-IT)Ensure that the results of the check identified by CACHE-ID areavailable. If the results of the check were in the cache filethat was read, and `configure' was not given the `--quiet' or`--silent' option, print a message saying that the result wascached; otherwise, run the shell commands COMMANDS-TO-SET-IT. Ifthe shell commands are run to determine the value, the value issaved in the cache file just before `configure' creates its outputfiles. *Note Cache Variable Names::, for how to choose the nameof the CACHE-ID variable.The COMMANDS-TO-SET-IT _must have no side effects_ except forsetting the variable CACHE-ID, see below.-- Macro: AC_CACHE_CHECK (MESSAGE, CACHE-ID, COMMANDS-TO-SET-IT)A wrapper for `AC_CACHE_VAL' that takes care of printing themessages. This macro provides a convenient shorthand for the mostcommon way to use these macros. It calls `AC_MSG_CHECKING' forMESSAGE, then `AC_CACHE_VAL' with the CACHE-ID and COMMANDSarguments, and `AC_MSG_RESULT' with CACHE-ID.The COMMANDS-TO-SET-IT _must have no side effects_ except forsetting the variable CACHE-ID, see below.It is common to find buggy macros using `AC_CACHE_VAL' or`AC_CACHE_CHECK', because people are tempted to call `AC_DEFINE' in theCOMMANDS-TO-SET-IT. Instead, the code that _follows_ the call to`AC_CACHE_VAL' should call `AC_DEFINE', by examining the value of thecache variable. For instance, the following macro is broken:AC_DEFUN([AC_SHELL_TRUE],[AC_CACHE_CHECK([whether true(1) works], [ac_cv_shell_true_works],[ac_cv_shell_true_works=no(true) 2>/dev/null && ac_cv_shell_true_works=yesif test "$ac_cv_shell_true_works" = yes; thenAC_DEFINE([TRUE_WORKS], [1],[Define if `true(1)' works properly.])fi])])This fails if the cache is enabled: the second time this macro is run,`TRUE_WORKS' _will not be defined_. The proper implementation is:AC_DEFUN([AC_SHELL_TRUE],[AC_CACHE_CHECK([whether true(1) works], [ac_cv_shell_true_works],[ac_cv_shell_true_works=no(true) 2>/dev/null && ac_cv_shell_true_works=yes])if test "$ac_cv_shell_true_works" = yes; thenAC_DEFINE([TRUE_WORKS], [1],[Define if `true(1)' works properly.])fi])Also, COMMANDS-TO-SET-IT should not print any messages, for examplewith `AC_MSG_CHECKING'; do that before calling `AC_CACHE_VAL', so themessages are printed regardless of whether the results of the check areretrieved from the cache or determined by running the shell commands.* Menu:* Cache Variable Names:: Shell variables used in caches* Cache Files:: Files `configure' uses for caching* Cache Checkpointing:: Loading and saving the cache fileFile: autoconf.info, Node: Cache Variable Names, Next: Cache Files, Up: Caching Results7.4.1 Cache Variable Names--------------------------The names of cache variables should have the following format:PACKAGE-PREFIX_cv_VALUE-TYPE_SPECIFIC-VALUE_[ADDITIONAL-OPTIONS]for example, `ac_cv_header_stat_broken' or`ac_cv_prog_gcc_traditional'. The parts of the variable name are:PACKAGE-PREFIXAn abbreviation for your package or organization; the same prefixyou begin local Autoconf macros with, except lowercase byconvention. For cache values used by the distributed Autoconfmacros, this value is `ac'.`_cv_'Indicates that this shell variable is a cache value. This string_must_ be present in the variable name, including the leadingunderscore.VALUE-TYPEA convention for classifying cache values, to produce a rationalnaming system. The values used in Autoconf are listed in *NoteMacro Names::.SPECIFIC-VALUEWhich member of the class of cache values this test applies to.For example, which function (`alloca'), program (`gcc'), or outputvariable (`INSTALL').ADDITIONAL-OPTIONSAny particular behavior of the specific member that this testapplies to. For example, `broken' or `set'. This part of thename may be omitted if it does not apply.The values assigned to cache variables may not contain newlines.Usually, their values are Boolean (`yes' or `no') or the names of filesor functions; so this is not an important restriction.File: autoconf.info, Node: Cache Files, Next: Cache Checkpointing, Prev: Cache Variable Names, Up: Caching Results7.4.2 Cache Files-----------------A cache file is a shell script that caches the results of configuretests run on one system so they can be shared between configure scriptsand configure runs. It is not useful on other systems. If its contentsare invalid for some reason, the user may delete or edit it.By default, `configure' uses no cache file, to avoid problems causedby accidental use of stale cache files.To enable caching, `configure' accepts `--config-cache' (or `-C') tocache results in the file `config.cache'. Alternatively,`--cache-file=FILE' specifies that FILE be the cache file. The cachefile is created if it does not exist already. When `configure' calls`configure' scripts in subdirectories, it uses the `--cache-file'argument so that they share the same cache. *Note Subdirectories::,for information on configuring subdirectories with the`AC_CONFIG_SUBDIRS' macro.`config.status' only pays attention to the cache file if it is giventhe `--recheck' option, which makes it rerun `configure'.It is wrong to try to distribute cache files for particular systemtypes. There is too much room for error in doing that, and too muchadministrative overhead in maintaining them. For any features thatcan't be guessed automatically, use the standard method of the canonicalsystem type and linking files (*note Manual Configuration::).The site initialization script can specify a site-wide cache file touse, instead of the usual per-program cache. In this case, the cachefile gradually accumulates information whenever someone runs a new`configure' script. (Running `configure' merges the new cache resultswith the existing cache file.) This may cause problems, however, ifthe system configuration (e.g., the installed libraries or compilers)changes and the stale cache file is not deleted.File: autoconf.info, Node: Cache Checkpointing, Prev: Cache Files, Up: Caching Results7.4.3 Cache Checkpointing-------------------------If your configure script, or a macro called from `configure.ac', happensto abort the configure process, it may be useful to checkpoint the cachea few times at key points using `AC_CACHE_SAVE'. Doing so reduces theamount of time it takes to rerun the configure script with (hopefully)the error that caused the previous abort corrected.-- Macro: AC_CACHE_LOADLoads values from existing cache file, or creates a new cache fileif a cache file is not found. Called automatically from `AC_INIT'.-- Macro: AC_CACHE_SAVEFlushes all cached values to the cache file. Called automaticallyfrom `AC_OUTPUT', but it can be quite useful to call`AC_CACHE_SAVE' at key points in `configure.ac'.For instance:... AC_INIT, etc. ...# Checks for programs.AC_PROG_CCAC_PROG_AWK... more program checks ...AC_CACHE_SAVE# Checks for libraries.AC_CHECK_LIB([nsl], [gethostbyname])AC_CHECK_LIB([socket], [connect])... more lib checks ...AC_CACHE_SAVE# Might abort...AM_PATH_GTK([1.0.2], [], [AC_MSG_ERROR([GTK not in path])])AM_PATH_GTKMM([0.9.5], [], [AC_MSG_ERROR([GTK not in path])])... AC_OUTPUT, etc. ...File: autoconf.info, Node: Printing Messages, Prev: Caching Results, Up: Results7.5 Printing Messages=====================`configure' scripts need to give users running them several kinds ofinformation. The following macros print messages in ways appropriatefor each kind. The arguments to all of them get enclosed in shelldouble quotes, so the shell performs variable and back-quotesubstitution on them.These macros are all wrappers around the `echo' shell command. Theydirect output to the appropriate file descriptor (*note File DescriptorMacros::). `configure' scripts should rarely need to run `echo'directly to print messages for the user. Using these macros makes iteasy to change how and when each kind of message is printed; suchchanges need only be made to the macro definitions and all the callerschange automatically.To diagnose static issues, i.e., when `autoconf' is run, see *NoteReporting Messages::.-- Macro: AC_MSG_CHECKING (FEATURE-DESCRIPTION)Notify the user that `configure' is checking for a particularfeature. This macro prints a message that starts with `checking 'and ends with `...' and no newline. It must be followed by a callto `AC_MSG_RESULT' to print the result of the check and thenewline. The FEATURE-DESCRIPTION should be something like`whether the Fortran compiler accepts C++ comments' or `for c89'.This macro prints nothing if `configure' is run with the `--quiet'or `--silent' option.-- Macro: AC_MSG_RESULT (RESULT-DESCRIPTION)Notify the user of the results of a check. RESULT-DESCRIPTION isalmost always the value of the cache variable for the check,typically `yes', `no', or a file name. This macro should follow acall to `AC_MSG_CHECKING', and the RESULT-DESCRIPTION should bethe completion of the message printed by the call to`AC_MSG_CHECKING'.This macro prints nothing if `configure' is run with the `--quiet'or `--silent' option.-- Macro: AC_MSG_NOTICE (MESSAGE)Deliver the MESSAGE to the user. It is useful mainly to print ageneral description of the overall purpose of a group of featurechecks, e.g.,AC_MSG_NOTICE([checking if stack overflow is detectable])This macro prints nothing if `configure' is run with the `--quiet'or `--silent' option.-- Macro: AC_MSG_ERROR (ERROR-DESCRIPTION, [EXIT-STATUS])Notify the user of an error that prevents `configure' fromcompleting. This macro prints an error message to the standarderror output and exits `configure' with EXIT-STATUS (1 by default).ERROR-DESCRIPTION should be something like `invalid value $HOMEfor \$HOME'.The ERROR-DESCRIPTION should start with a lower-case letter, and"cannot" is preferred to "can't".-- Macro: AC_MSG_FAILURE (ERROR-DESCRIPTION, [EXIT-STATUS])This `AC_MSG_ERROR' wrapper notifies the user of an error thatprevents `configure' from completing _and_ that additional detailsare provided in `config.log'. This is typically used whenabnormal results are found during a compilation.-- Macro: AC_MSG_WARN (PROBLEM-DESCRIPTION)Notify the `configure' user of a possible problem. This macroprints the message to the standard error output; `configure'continues running afterward, so macros that call `AC_MSG_WARN'should provide a default (back-up) behavior for the situationsthey warn about. PROBLEM-DESCRIPTION should be something like `ln-s seems to make hard links'.File: autoconf.info, Node: Programming in M4, Next: Writing Autoconf Macros, Prev: Results, Up: Top8 Programming in M4*******************Autoconf is written on top of two layers: "M4sugar", which providesconvenient macros for pure M4 programming, and "M4sh", which providesmacros dedicated to shell script generation.As of this version of Autoconf, these two layers are stillexperimental, and their interface might change in the future. As amatter of fact, _anything that is not documented must not be used_.* Menu:* M4 Quotation:: Protecting macros from unwanted expansion* Using autom4te:: The Autoconf executables backbone* Programming in M4sugar:: Convenient pure M4 macros* Programming in M4sh:: Common shell Constructs* File Descriptor Macros:: File descriptor macros for input and outputFile: autoconf.info, Node: M4 Quotation, Next: Using autom4te, Up: Programming in M48.1 M4 Quotation================The most common problem with existing macros is an improper quotation.This section, which users of Autoconf can skip, but which macro writers_must_ read, first justifies the quotation scheme that was chosen forAutoconf and then ends with a rule of thumb. Understanding the formerhelps one to follow the latter.* Menu:* Active Characters:: Characters that change the behavior of M4* One Macro Call:: Quotation and one macro call* Quotation and Nested Macros:: Macros calling macros* Changequote is Evil:: Worse than INTERCAL: M4 + changequote* Quadrigraphs:: Another way to escape special characters* Quotation Rule Of Thumb:: One parenthesis, one quoteFile: autoconf.info, Node: Active Characters, Next: One Macro Call, Up: M4 Quotation8.1.1 Active Characters-----------------------To fully understand where proper quotation is important, you first needto know what the special characters are in Autoconf: `#' introduces acomment inside which no macro expansion is performed, `,' separatesarguments, `[' and `]' are the quotes themselves, and finally `(' and`)' (which M4 tries to match by pairs).In order to understand the delicate case of macro calls, we firsthave to present some obvious failures. Below they are "obvious-ified",but when you find them in real life, they are usually in disguise.Comments, introduced by a hash and running up to the newline, areopaque tokens to the top level: active characters are turned off, andthere is no macro expansion:# define([def], ine)=># define([def], ine)Each time there can be a macro expansion, there is a quotationexpansion, i.e., one level of quotes is stripped:int tab[10];=>int tab10;[int tab[10];]=>int tab[10];Without this in mind, the reader might try hopelessly to use hermacro `array':define([array], [int tab[10];])array=>int tab10;[array]=>arrayHow can you correctly output the intended results(1)?---------- Footnotes ----------(1) Using `defn'.File: autoconf.info, Node: One Macro Call, Next: Quotation and Nested Macros, Prev: Active Characters, Up: M4 Quotation8.1.2 One Macro Call--------------------Let's proceed on the interaction between active characters and macroswith this small macro, which just returns its first argument:define([car], [$1])The two pairs of quotes above are not part of the arguments of`define'; rather, they are understood by the top level when it tries tofind the arguments of `define'. Therefore, assuming `car' is notalready defined, it is equivalent to write:define(car, $1)But, while it is acceptable for a `configure.ac' to avoid unnecessaryquotes, it is bad practice for Autoconf macros which must both be morerobust and also advocate perfect style.At the top level, there are only two possibilities: either you quoteor you don't:car(foo, bar, baz)=>foo[car(foo, bar, baz)]=>car(foo, bar, baz)Let's pay attention to the special characters:car(#)error-->EOF in argument listThe closing parenthesis is hidden in the comment; with a hypotheticalquoting, the top level understood it this way:car([#)]Proper quotation, of course, fixes the problem:car([#])=>#Here are more examples:car(foo, bar)=>foocar([foo, bar])=>foo, barcar((foo, bar))=>(foo, bar)car([(foo], [bar)])=>(foodefine([a], [b])=>car(a)=>bcar([a])=>bcar([[a]])=>acar([[[a]]])=>[a]With this in mind, we can explore the cases where macros invokemacros....File: autoconf.info, Node: Quotation and Nested Macros, Next: Changequote is Evil, Prev: One Macro Call, Up: M4 Quotation8.1.3 Quotation and Nested Macros---------------------------------The examples below use the following macros:define([car], [$1])define([active], [ACT, IVE])define([array], [int tab[10]])Each additional embedded macro call introduces other possibleinteresting quotations:car(active)=>ACTcar([active])=>ACT, IVEcar([[active]])=>activeIn the first case, the top level looks for the arguments of `car',and finds `active'. Because M4 evaluates its arguments before applyingthe macro, `active' is expanded, which results in:car(ACT, IVE)=>ACTIn the second case, the top level gives `active' as first and onlyargument of `car', which results in:active=>ACT, IVEi.e., the argument is evaluated _after_ the macro that invokes it. Inthe third case, `car' receives `[active]', which results in:[active]=>activeexactly as we already saw above.The example above, applied to a more realistic example, gives:car(int tab[10];)=>int tab10;car([int tab[10];])=>int tab10;car([[int tab[10];]])=>int tab[10];Huh? The first case is easily understood, but why is the second wrong,and the third right? To understand that, you must know that after M4expands a macro, the resulting text is immediately subjected to macroexpansion and quote removal. This means that the quote removal occurstwice--first before the argument is passed to the `car' macro, andsecond after the `car' macro expands to the first argument.As the author of the Autoconf macro `car', you then consider it tobe incorrect that your users have to double-quote the arguments of`car', so you "fix" your macro. Let's call it `qar' for quoted car:define([qar], [[$1]])and check that `qar' is properly fixed:qar([int tab[10];])=>int tab[10];Ahhh! That's much better.But note what you've done: now that the arguments are literalstrings, if the user wants to use the results of expansions asarguments, she has to use an _unquoted_ macro call:qar(active)=>ACTwhere she wanted to reproduce what she used to do with `car':car([active])=>ACT, IVEWorse yet: she wants to use a macro that produces a set of `cpp' macros:define([my_includes], [#include <stdio.h>])car([my_includes])=>#include <stdio.h>qar(my_includes)error-->EOF in argument listThis macro, `qar', because it double quotes its arguments, forcesits users to leave their macro calls unquoted, which is dangerous.Commas and other active symbols are interpreted by M4 before they aregiven to the macro, often not in the way the users expect. Also,because `qar' behaves differently from the other macros, it's anexception that should be avoided in Autoconf.File: autoconf.info, Node: Changequote is Evil, Next: Quadrigraphs, Prev: Quotation and Nested Macros, Up: M4 Quotation8.1.4 `changequote' is Evil---------------------------The temptation is often high to bypass proper quotation, in particularwhen it's late at night. Then, many experienced Autoconf hackersfinally surrender to the dark side of the force and use the ultimateweapon: `changequote'.The M4 builtin `changequote' belongs to a set of primitives thatallow one to adjust the syntax of the language to adjust it to one'sneeds. For instance, by default M4 uses ``' and `'' as quotes, but inthe context of shell programming (and actually of most programminglanguages), that's about the worst choice one can make: because ofstrings and back-quoted expressions in shell code (such as `'this'' and``that`'), because of literal characters in usual programming languages(as in `'0''), there are many unbalanced ``' and `''. Proper M4quotation then becomes a nightmare, if not impossible. In order tomake M4 useful in such a context, its designers have equipped it with`changequote', which makes it possible to choose another pair ofquotes. M4sugar, M4sh, Autoconf, and Autotest all have chosen to use`[' and `]'. Not especially because they are unlikely characters, but_because they are characters unlikely to be unbalanced_.There are other magic primitives, such as `changecom' to specifywhat syntactic forms are comments (it is common to see `changecom(<!--,-->)' when M4 is used to produce HTML pages), `changeword' and`changesyntax' to change other syntactic details (such as the characterto denote the Nth argument, `$' by default, the parenthesis aroundarguments, etc.).These primitives are really meant to make M4 more useful for specificdomains: they should be considered like command line options:`--quotes', `--comments', `--words', and `--syntax'. Nevertheless,they are implemented as M4 builtins, as it makes M4 libraries selfcontained (no need for additional options).There lies the problem....The problem is that it is then tempting to use them in the middle ofan M4 script, as opposed to its initialization. This, if not carefullythought out, can lead to disastrous effects: _you are changing thelanguage in the middle of the execution_. Changing and restoring thesyntax is often not enough: if you happened to invoke macros in between,these macros are lost, as the current syntax is probably not the onethey were implemented with.File: autoconf.info, Node: Quadrigraphs, Next: Quotation Rule Of Thumb, Prev: Changequote is Evil, Up: M4 Quotation8.1.5 Quadrigraphs------------------When writing an Autoconf macro you may occasionally need to generatespecial characters that are difficult to express with the standardAutoconf quoting rules. For example, you may need to output the regularexpression `[^[]', which matches any character other than `['. Thisexpression contains unbalanced brackets so it cannot be put easily intoan M4 macro.You can work around this problem by using one of the following"quadrigraphs":`@<:@'`['`@:>@'`]'`@S|@'`$'`@%:@'`#'`@&t@'Expands to nothing.Quadrigraphs are replaced at a late stage of the translation process,after `m4' is run, so they do not get in the way of M4 quoting. Forexample, the string `^@<:@', independently of its quotation, appears as`^[' in the output.The empty quadrigraph can be used:- to mark trailing spaces explicitlyTrailing spaces are smashed by `autom4te'. This is a feature.- to produce other quadrigraphsFor instance `@<@&t@:@' produces `@<:@'.- to escape _occurrences_ of forbidden patternsFor instance you might want to mention `AC_FOO' in a comment, whilestill being sure that `autom4te' still catches unexpanded `AC_*'.Then write `AC@&t@_FOO'.The name `@&t@' was suggested by Paul Eggert:I should give some credit to the `@&t@' pun. The `&' is my owninvention, but the `t' came from the source code of the ALGOL68Ccompiler, written by Steve Bourne (of Bourne shell fame), andwhich used `mt' to denote the empty string. In C, it would havelooked like something like:char const mt[] = "";but of course the source code was written in Algol 68.I don't know where he got `mt' from: it could have been his owninvention, and I suppose it could have been a common pun around theCambridge University computer lab at the time.File: autoconf.info, Node: Quotation Rule Of Thumb, Prev: Quadrigraphs, Up: M4 Quotation8.1.6 Quotation Rule Of Thumb-----------------------------To conclude, the quotation rule of thumb is:_One pair of quotes per pair of parentheses._Never over-quote, never under-quote, in particular in the definitionof macros. In the few places where the macros need to use brackets(usually in C program text or regular expressions), properly quote _thearguments_!It is common to read Autoconf programs with snippets like:AC_TRY_LINK(changequote(<<, >>)dnl<<#include <time.h>#ifndef tzname /* For SGI. */extern char *tzname[]; /* RS6000 and others reject char **tzname. */#endif>>,changequote([, ])dnl[atoi (*tzname);], ac_cv_var_tzname=yes, ac_cv_var_tzname=no)which is incredibly useless since `AC_TRY_LINK' is _already_ doublequoting, so you just need:AC_TRY_LINK([#include <time.h>#ifndef tzname /* For SGI. */extern char *tzname[]; /* RS6000 and others reject char **tzname. */#endif],[atoi (*tzname);],[ac_cv_var_tzname=yes],[ac_cv_var_tzname=no])The M4-fluent reader might note that these two examples are rigorouslyequivalent, since M4 swallows both the `changequote(<<, >>)' and `<<'`>>' when it "collects" the arguments: these quotes are not part of thearguments!Simplified, the example above is just doing this:changequote(<<, >>)dnl<<[]>>changequote([, ])dnlinstead of simply:[[]]With macros that do not double quote their arguments (which is therule), double-quote the (risky) literals:AC_LINK_IFELSE([AC_LANG_PROGRAM([[#include <time.h>#ifndef tzname /* For SGI. */extern char *tzname[]; /* RS6000 and others reject char **tzname. */#endif]],[atoi (*tzname);])],[ac_cv_var_tzname=yes],[ac_cv_var_tzname=no])Please note that the macro `AC_TRY_LINK' is obsolete, so you reallyshould be using `AC_LINK_IFELSE' instead.*Note Quadrigraphs::, for what to do if you run into a hopeless casewhere quoting does not suffice.When you create a `configure' script using newly written macros,examine it carefully to check whether you need to add more quotes inyour macros. If one or more words have disappeared in the M4 output,you need more quotes. When in doubt, quote.However, it's also possible to put on too many layers of quotes. Ifthis happens, the resulting `configure' script may contain unexpandedmacros. The `autoconf' program checks for this problem by looking forthe string `AC_' in `configure'. However, this heuristic does not workin general: for example, it does not catch overquoting in `AC_DEFINE'descriptions.File: autoconf.info, Node: Using autom4te, Next: Programming in M4sugar, Prev: M4 Quotation, Up: Programming in M48.2 Using `autom4te'====================The Autoconf suite, including M4sugar, M4sh, and Autotest, in additionto Autoconf per se, heavily rely on M4. All these different usesrevealed common needs factored into a layer over M4: `autom4te'(1).`autom4te' is a preprocessor that is like `m4'. It supports M4extensions designed for use in tools like Autoconf.* Menu:* autom4te Invocation:: A GNU M4 wrapper* Customizing autom4te:: Customizing the Autoconf package---------- Footnotes ----------(1) Yet another great name from Lars J. Aas.File: autoconf.info, Node: autom4te Invocation, Next: Customizing autom4te, Up: Using autom4te8.2.1 Invoking `autom4te'-------------------------The command line arguments are modeled after M4's:autom4te OPTIONS FILESwhere the FILES are directly passed to `m4'. By default, GNU M4 isfound during configuration, but the environment variable `M4' can beset to tell `autom4te' where to look. In addition to the regularexpansion, it handles the replacement of the quadrigraphs (*noteQuadrigraphs::), and of `__oline__', the current line in the output.It supports an extended syntax for the FILES:`FILE.m4f'This file is an M4 frozen file. Note that _all the previous filesare ignored_. See the option `--melt' for the rationale.`FILE?'If found in the library path, the FILE is included for expansion,otherwise it is ignored instead of triggering a failure.Of course, it supports the Autoconf common subset of options:`--help'`-h'Print a summary of the command line options and exit.`--version'`-V'Print the version number of Autoconf and exit.`--verbose'`-v'Report processing steps.`--debug'`-d'Don't remove the temporary files and be even more verbose.`--include=DIR'`-I DIR'Also look for input files in DIR. Multiple invocations accumulate.`--output=FILE'`-o FILE'Save output (script or trace) to FILE. The file `-' stands forthe standard output.As an extension of `m4', it includes the following options:`--warnings=CATEGORY'`-W CATEGORY'Report the warnings related to CATEGORY (which can actually be acomma separated list). *Note Reporting Messages::, macro`AC_DIAGNOSE', for a comprehensive list of categories. Specialvalues include:`all'report all the warnings`none'report none`error'treats warnings as errors`no-CATEGORY'disable warnings falling into CATEGORYWarnings about `syntax' are enabled by default, and the environmentvariable `WARNINGS', a comma separated list of categories, ishonored. `autom4te -W CATEGORY' actually behaves as if you hadrun:autom4te --warnings=syntax,$WARNINGS,CATEGORYFor example, if you want to disable defaults and `WARNINGS' of`autom4te', but enable the warnings about obsolete constructs, youwould use `-W none,obsolete'.`autom4te' displays a back trace for errors, but not for warnings;if you want them, just pass `-W error'.`--melt'`-M'Do not use frozen files. Any argument `FILE.m4f' is replaced by`FILE.m4'. This helps tracing the macros which are executed onlywhen the files are frozen, typically `m4_define'. For instance,running:autom4te --melt 1.m4 2.m4f 3.m4 4.m4f input.m4is roughly equivalent to running:m4 1.m4 2.m4 3.m4 4.m4 input.m4whileautom4te 1.m4 2.m4f 3.m4 4.m4f input.m4is equivalent to:m4 --reload-state=4.m4f input.m4`--freeze'`-f'Produce a frozen state file. `autom4te' freezing is stricter thanM4's: it must produce no warnings, and no output other than emptylines (a line with white space is _not_ empty) and comments(starting with `#'). Unlike `m4''s similarly-named option, thisoption takes no argument:autom4te 1.m4 2.m4 3.m4 --freeze --output=3.m4fcorresponds tom4 1.m4 2.m4 3.m4 --freeze-state=3.m4f`--mode=OCTAL-MODE'`-m OCTAL-MODE'Set the mode of the non-traces output to OCTAL-MODE; by default`0666'.As another additional feature over `m4', `autom4te' caches itsresults. GNU M4 is able to produce a regular output and traces at thesame time. Traces are heavily used in the GNU Build System:`autoheader' uses them to build `config.h.in', `autoreconf' todetermine what GNU Build System components are used, `automake' to"parse" `configure.ac' etc. To avoid recomputation, traces are cachedwhile performing regular expansion, and conversely. This cache is(actually, the caches are) stored in the directory `autom4te.cache'._It can safely be removed_ at any moment (especially if for some reason`autom4te' considers it is trashed).`--cache=DIRECTORY'`-C DIRECTORY'Specify the name of the directory where the result should becached. Passing an empty value disables caching. Be sure to passa relative file name, as for the time being, global caches are notsupported.`--no-cache'Don't cache the results.`--force'`-f'If a cache is used, consider it obsolete (but update it anyway).Because traces are so important to the GNU Build System, `autom4te'provides high level tracing features as compared to M4, and helpsexploiting the cache:`--trace=MACRO[:FORMAT]'`-t MACRO[:FORMAT]'Trace the invocations of MACRO according to the FORMAT. Multiple`--trace' arguments can be used to list several macros. Multiple`--trace' arguments for a single macro are not cumulative;instead, you should just make FORMAT as long as needed.The FORMAT is a regular string, with newlines if desired, andseveral special escape codes. It defaults to `$f:$l:$n:$%'. Itcan use the following special escapes:`$$'The character `$'.`$f'The file name from which MACRO is called.`$l'The line number from which MACRO is called.`$d'The depth of the MACRO call. This is an M4 technical detailthat you probably don't want to know about.`$n'The name of the MACRO.`$NUM'The NUMth argument of the call to MACRO.`$@'`$SEP@'`${SEPARATOR}@'All the arguments passed to MACRO, separated by the characterSEP or the string SEPARATOR (`,' by default). Each argumentis quoted, i.e., enclosed in a pair of square brackets.`$*'`$SEP*'`${SEPARATOR}*'As above, but the arguments are not quoted.`$%'`$SEP%'`${SEPARATOR}%'As above, but the arguments are not quoted, all new linecharacters in the arguments are smashed, and the defaultseparator is `:'.The escape `$%' produces single-line trace outputs (unlessyou put newlines in the `separator'), while `$@' and `$*' donot.*Note autoconf Invocation::, for examples of trace uses.`--preselect=MACRO'`-p MACRO'Cache the traces of MACRO, but do not enable traces. This isespecially important to save CPU cycles in the future. Forinstance, when invoked, `autoconf' preselects all the macros that`autoheader', `automake', `autoreconf', etc., trace, so thatrunning `m4' is not needed to trace them: the cache suffices.This results in a huge speed-up.Finally, `autom4te' introduces the concept of "Autom4te libraries".They consists in a powerful yet extremely simple feature: sets ofcombined command line arguments:`--language=LANGUAGE'`-l LANGUAGE'Use the LANGUAGE Autom4te library. Current languages include:`M4sugar'create M4sugar output.`M4sh'create M4sh executable shell scripts.`Autotest'create Autotest executable test suites.`Autoconf-without-aclocal-m4'create Autoconf executable configure scripts without reading`aclocal.m4'.`Autoconf'create Autoconf executable configure scripts. This languageinherits all the characteristics of`Autoconf-without-aclocal-m4' and additionally reads`aclocal.m4'.`--prepend-include=DIR'`-B DIR'Prepend directory DIR to the search path. This is used to includethe language-specific files before any third-party macros.As an example, if Autoconf is installed in its default location,`/usr/local', the command `autom4te -l m4sugar foo.m4' is strictlyequivalent to the command:autom4te --prepend-include /usr/local/share/autoconf \m4sugar/m4sugar.m4f --warnings syntax foo.m4Recursive expansion applies here: the command `autom4te -l m4sh foo.m4'is the same as `autom4te --language M4sugar m4sugar/m4sh.m4f foo.m4',i.e.:autom4te --prepend-include /usr/local/share/autoconf \m4sugar/m4sugar.m4f m4sugar/m4sh.m4f --mode 777 foo.m4The definition of the languages is stored in `autom4te.cfg'.File: autoconf.info, Node: Customizing autom4te, Prev: autom4te Invocation, Up: Using autom4te8.2.2 Customizing `autom4te'----------------------------One can customize `autom4te' via `~/.autom4te.cfg' (i.e., as found inthe user home directory), and `./.autom4te.cfg' (i.e., as found in thedirectory from which `autom4te' is run). The order is first reading`autom4te.cfg', then `~/.autom4te.cfg', then `./.autom4te.cfg', andfinally the command line arguments.In these text files, comments are introduced with `#', and emptylines are ignored. Customization is performed on a per-language basis,wrapped in between a `begin-language: "LANGUAGE"', `end-language:"LANGUAGE"' pair.Customizing a language stands for appending options (*note autom4teInvocation::) to the current definition of the language. Options, andmore generally arguments, are introduced by `args: ARGUMENTS'. You mayuse the traditional shell syntax to quote the ARGUMENTS.As an example, to disable Autoconf caches (`autom4te.cache')globally, include the following lines in `~/.autom4te.cfg':## ------------------ #### User Preferences. #### ------------------ ##begin-language: "Autoconf-without-aclocal-m4"args: --no-cacheend-language: "Autoconf-without-aclocal-m4"File: autoconf.info, Node: Programming in M4sugar, Next: Programming in M4sh, Prev: Using autom4te, Up: Programming in M48.3 Programming in M4sugar==========================M4 by itself provides only a small, but sufficient, set of all-purposemacros. M4sugar introduces additional generic macros. Its name wascoined by Lars J. Aas: "Readability And Greater Understanding Stands 4M4sugar".* Menu:* Redefined M4 Macros:: M4 builtins changed in M4sugar* Looping constructs:: Iteration in M4* Evaluation Macros:: More quotation and evaluation control* Text processing Macros:: String manipulation in M4* Forbidden Patterns:: Catching unexpanded macrosFile: autoconf.info, Node: Redefined M4 Macros, Next: Looping constructs, Up: Programming in M4sugar8.3.1 Redefined M4 Macros-------------------------With a few exceptions, all the M4 native macros are moved in the `m4_'pseudo-namespace, e.g., M4sugar renames `define' as `m4_define' etc.Some M4 macros are redefined, and are slightly incompatible withtheir native equivalent.-- Macro: dnlThis macro kept its original name: no `m4_dnl' is defined.-- Macro: m4_defn (MACRO)Unlike the M4 builtin, this macro fails if MACRO is not defined.See `m4_undefine'.-- Macro: m4_exit (EXIT-STATUS)This macro corresponds to `m4exit'.-- Macro: m4_if (COMMENT)-- Macro: m4_if (STRING-1, STRING-2, EQUAL, [NOT-EQUAL])-- Macro: m4_if (STRING-1, STRING-2, EQUAL, ...)This macro corresponds to `ifelse'.-- Macro: m4_include (FILE)-- Macro: m4_sinclude (FILE)Like the M4 builtins, but warn against multiple inclusions of FILE.-- Macro: m4_bpatsubst (STRING, REGEXP, [REPLACEMENT])This macro corresponds to `patsubst'. The name `m4_patsubst' iskept for future versions of M4sh, on top of GNU M4 which willprovide extended regular expression syntax via `epatsubst'.-- Macro: m4_popdef (MACRO)Unlike the M4 builtin, this macro fails if MACRO is not defined.See `m4_undefine'.-- Macro: m4_bregexp (STRING, REGEXP, [REPLACEMENT])This macro corresponds to `regexp'. The name `m4_regexp' is keptfor future versions of M4sh, on top of GNU M4 which will provideextended regular expression syntax via `eregexp'.-- Macro: m4_wrap (TEXT)This macro corresponds to `m4wrap'.Posix requires arguments of multiple `m4wrap' calls to bereprocessed at EOF in the same order as the original calls. GNUM4 versions through 1.4.x, however, reprocess them in reverseorder. Your code should not depend on the order.Also, Posix requires `m4wrap' to ignore its second and succeedingarguments, but GNU M4 versions through 1.4.x concatenate thearguments with intervening spaces. Your code should not pass morethan one argument.You are encouraged to end TEXT with `[]', to avoid unexpectedtoken pasting between consecutive invocations of `m4_wrap', as in:m4_define([foo], [bar])m4_define([foofoo], [OUCH])m4_wrap([foo])m4_wrap([foo])=>OUCH-- Macro: m4_undefine (MACRO)Unlike the M4 builtin, this macro fails if MACRO is not defined.Usem4_ifdef([MACRO], [m4_undefine([MACRO])])to recover the behavior of the builtin.-- Macro: m4_maketemp (TEMPLATE)-- Macro: m4_mkstemp (TEMPLATE)Posix requires `maketemp' to replace the trailing `X' charactersin TEMPLATE with the process id, without regards to the existenceof a file by that name, but this a security hole. When this waspointed out to the Posix folks, they agreed to invent a new macro`mkstemp' that always creates a uniquely named file, but not allversions of GNU M4 support the new macro. In M4sugar,`m4_maketemp' and `m4_mkstemp' are synonyms for each other, andboth have the secure semantics regardless of which macro theunderlying M4 provides.File: autoconf.info, Node: Looping constructs, Next: Evaluation Macros, Prev: Redefined M4 Macros, Up: Programming in M4sugar8.3.2 Looping constructs------------------------The following macros implement loops in M4.-- Macro: m4_for (VAR, FIRST, LAST, [STEP], EXPRESSION)Loop over the numeric values between FIRST and LAST includingbounds by increments of STEP. For each iteration, expandEXPRESSION with the numeric value assigned to VAR. If STEP isomitted, it defaults to `1' or `-1' depending on the order of thelimits. If given, STEP has to match this order.-- Macro: m4_foreach (VAR, LIST, EXPRESSION)Loop over the comma-separated M4 list LIST, assigning each valueto VAR, and expand EXPRESSION. The following example outputs twolines:m4_foreach([myvar], [[foo], [bar, baz]],[echo myvar])-- Macro: m4_foreach_w (VAR, LIST, EXPRESSION)Loop over the white-space-separated list LIST, assigning each valueto VAR, and expand EXPRESSION.The deprecated macro `AC_FOREACH' is an alias of `m4_foreach_w'.File: autoconf.info, Node: Evaluation Macros, Next: Text processing Macros, Prev: Looping constructs, Up: Programming in M4sugar8.3.3 Evaluation Macros-----------------------The following macros give some control over the order of the evaluationby adding or removing levels of quotes. They are meant for hard-core M4programmers.-- Macro: m4_dquote (ARG1, ...)Return the arguments as a quoted list of quoted arguments.-- Macro: m4_quote (ARG1, ...)Return the arguments as a single entity, i.e., wrap them into apair of quotes.The following example aims at emphasizing the difference between(i), not using these macros, (ii), using `m4_quote', and (iii), using`m4_dquote'.$ cat example.m4# Overquote, so that quotes are visible.m4_define([show], [$[]1 = [$1], $[]@ = [$@]])m4_define([mkargs], [1, 2, 3])m4_define([arg1], [[$1]])m4_divert(0)dnlshow(a, b)show(m4_quote(a, b))show(m4_dquote(a, b))arg1(mkargs)arg1([mkargs])arg1(m4_defn([mkargs]))arg1(m4_quote(mkargs))arg1(m4_dquote(mkargs))$ autom4te -l m4sugar example.m4$1 = a, $@ = [a],[b]$1 = a,b, $@ = [a,b]$1 = [a],[b], $@ = [[a],[b]]1mkargs1, 2, 31,2,3[1],[2],[3]File: autoconf.info, Node: Text processing Macros, Next: Forbidden Patterns, Prev: Evaluation Macros, Up: Programming in M4sugar8.3.4 Text processing Macros----------------------------The following macros may be used to manipulate strings in M4. They arenot intended for casual use.-- Macro: m4_re_escape (STRING)Backslash-escape all characters in STRING that are active inregexps.-- Macro: m4_tolower (STRING)-- Macro: m4_toupper (STRING)Return STRING with letters converted to upper or lower case,respectively.-- Macro: m4_split (STRING, [REGEXP])Split STRING into an M4 list of elements quoted by `[' and `]',while keeping white space at the beginning and at the end. IfREGEXP is given, use it instead of `[\t ]+' for splitting. IfSTRING is empty, the result is an empty list.-- Macro: m4_normalize (STRING)Remove leading and trailing spaces and tabs, sequences ofbackslash-then-newline, and replace multiple spaces and tabs with asingle space.-- Macro: m4_append (MACRO-NAME, STRING, [SEPARATOR])-- Macro: m4_append_uniq (MACRO-NAME, STRING, [SEPARATOR])Redefine MACRO-NAME to its former contents with SEPARATOR andSTRING added at the end. If MACRO-NAME was undefined before (butnot if it was defined but empty), then no SEPARATOR is added.`m4_append' can be used to grow strings, and `m4_append_uniq' togrow strings without duplicating substrings.File: autoconf.info, Node: Forbidden Patterns, Prev: Text processing Macros, Up: Programming in M4sugar8.3.5 Forbidden Patterns------------------------M4sugar provides a means to define suspicious patterns, patternsdescribing tokens which should not be found in the output. Forinstance, if an Autoconf `configure' script includes tokens such as`AC_DEFINE', or `dnl', then most probably something went wrong(typically a macro was not evaluated because of overquotation).M4sugar forbids all the tokens matching `^m4_' and `^dnl$'.-- Macro: m4_pattern_forbid (PATTERN)Declare that no token matching PATTERN must be found in the output.Comments are not checked; this can be a problem if, for instance,you have some macro left unexpanded after an `#include'. Noconsensus is currently found in the Autoconf community, as somepeople consider it should be valid to name macros in comments(which doesn't make sense to the author of this documentation, as`#'-comments should document the output, not the input, documentedby `dnl' comments).Of course, you might encounter exceptions to these generic rules, forinstance you might have to refer to `$m4_flags'.-- Macro: m4_pattern_allow (PATTERN)Any token matching PATTERN is allowed, including if it matches an`m4_pattern_forbid' pattern.File: autoconf.info, Node: Programming in M4sh, Next: File Descriptor Macros, Prev: Programming in M4sugar, Up: Programming in M48.4 Programming in M4sh=======================M4sh, pronounced "mash", is aiming at producing portable Bourne shellscripts. This name was coined by Lars J. Aas, who notes that,according to the Webster's Revised Unabridged Dictionary (1913):Mash \Mash\, n. [Akin to G. meisch, maisch, meische, maische,mash, wash, and prob. to AS. miscian to mix. See "Mix".]1. A mass of mixed ingredients reduced to a soft pulpy state bybeating or pressure....2. A mixture of meal or bran and water fed to animals.3. A mess; trouble. [Obs.] -Beau. & Fl.For the time being, it is not mature enough to be widely used.M4sh provides portable alternatives for some common shell constructsthat unfortunately are not portable in practice.-- Macro: AS_BOURNE_COMPATIBLESet up the shell to be more compatible with the Bourne shell asstandardized by Posix, if possible. This may involve settingenvironment variables, or setting options, or similarimplementation-specific actions.-- Macro: AS_CASE (WORD, [PATTERN1], [IF-MATCHED1], ..., [DEFAULT])Expand into a shell `case' statement, where WORD is matchedagainst one or more patterns. IF-MATCHED is run if thecorresponding pattern matched WORD, else DEFAULT is run.-- Macro: AS_DIRNAME (FILE-NAME)Output the directory portion of FILE-NAME. For example, if`$file' is `/one/two/three', the command`dir=`AS_DIRNAME(["$file"])`' sets `dir' to `/one/two'.-- Macro: AS_IF (TEST1, [RUN-IF-TRUE1], ..., [RUN-IF-FALSE])Run shell code TEST1. If TEST1 exits with a zero status then runshell code RUN-IF-TRUE1, else examine further tests. If no testexits with a zero status, run shell code RUN-IF-FALSE, withsimplifications if either RUN-IF-TRUE1 or RUN-IF-FALSE1 is empty.For example,AS_IF([test "$foo" = yes], [HANDLE_FOO([yes])],[test "$foo" != no], [HANDLE_FOO([maybe])],[echo foo not specified])ensures any required macros of `HANDLE_FOO' are expanded beforethe first test.-- Macro: AS_MKDIR_P (FILE-NAME)Make the directory FILE-NAME, including intervening directories asnecessary. This is equivalent to `mkdir -p FILE-NAME', exceptthat it is portable to older versions of `mkdir' that lack supportfor the `-p' option. Also, `AS_MKDIR_P' succeeds if FILE-NAME isa symbolic link to an existing directory, even though Posix isunclear whether `mkdir -p' should succeed in that case. Ifcreation of FILE-NAME fails, exit the script.Also see the `AC_PROG_MKDIR_P' macro (*note Particular Programs::).-- Macro: AS_SHELL_SANITIZEInitialize the shell suitably for `configure' scripts. This hasthe effect of `AS_BOURNE_COMPATIBLE', and sets some otherenvironment variables for predictable results from configurationtests. For example, it sets `LC_ALL' to change to the default Clocale. *Note Special Shell Variables::.-- Macro: AS_TR_CPP (EXPRESSION)Transform EXPRESSION into a valid right-hand side for a C`#define'. For example:# This outputs "#define HAVE_CHAR_P 1".type="char *"echo "#define AS_TR_CPP([HAVE_$type]) 1"-- Macro: AS_TR_SH (EXPRESSION)Transform EXPRESSION into a valid shell variable name. Forexample:# This outputs "Have it!".header="sys/some file.h"AS_TR_SH([HAVE_$header])=yesif test "$HAVE_sys_some_file_h" = yes; then echo "Have it!"; fi-- Macro: AS_SET_CATFILE (VAR, DIR, FILE)Set the shell variable VAR to DIR/FILE, but optimizing the commoncases (DIR or FILE is `.', FILE is absolute, etc.).File: autoconf.info, Node: File Descriptor Macros, Prev: Programming in M4sh, Up: Programming in M48.5 File Descriptor Macros==========================The following macros define file descriptors used to output messages(or input values) from `configure' scripts. For example:echo "$wombats found" >&AS_MESSAGE_LOG_FDecho 'Enter desired kangaroo count:' >&AS_MESSAGE_FDread kangaroos <&AS_ORIGINAL_STDIN_FD`However doing so is seldom needed, because Autoconf provides higherlevel macros as described below.-- Macro: AS_MESSAGE_FDThe file descriptor for `checking for...' messages and results.Normally this directs messages to the standard output, however when`configure' is run with the `-q' option, messages sent to`AS_MESSAGE_FD' are discarded.If you want to display some messages, consider using one of theprinting macros (*note Printing Messages::) instead. Copies ofmessages output via these macros are also recorded in `config.log'.-- Macro: AS_MESSAGE_LOG_FDThe file descriptor for messages logged to `config.log'. Macrosthat run tools, like `AC_COMPILE_IFELSE' (*note Running theCompiler::), redirect all output to this descriptor. You may wantto do so if you develop such a low-level macro.-- Macro: AS_ORIGINAL_STDIN_FDThe file descriptor for the original standard input.When `configure' runs, it may accidentally execute an interactivecommand that has the same name as the non-interactive meant to beused or checked. If the standard input was the terminal, suchinteractive programs would cause `configure' to stop, pending someuser input. Therefore `configure' redirects its standard inputfrom `/dev/null' during its initialization. This is not normallya problem, since `configure' normally does not need user input.In the extreme case where your `configure' script really needs toobtain some values from the original standard input, you can readthem explicitly from `AS_ORIGINAL_STDIN_FD'.File: autoconf.info, Node: Writing Autoconf Macros, Next: Portable Shell, Prev: Programming in M4, Up: Top9 Writing Autoconf Macros*************************When you write a feature test that could be applicable to more than onesoftware package, the best thing to do is encapsulate it in a new macro.Here are some instructions and guidelines for writing Autoconf macros.* Menu:* Macro Definitions:: Basic format of an Autoconf macro* Macro Names:: What to call your new macros* Reporting Messages:: Notifying `autoconf' users* Dependencies Between Macros:: What to do when macros depend on other macros* Obsoleting Macros:: Warning about old ways of doing things* Coding Style:: Writing Autoconf macros a` la AutoconfFile: autoconf.info, Node: Macro Definitions, Next: Macro Names, Up: Writing Autoconf Macros9.1 Macro Definitions=====================Autoconf macros are defined using the `AC_DEFUN' macro, which issimilar to the M4 builtin `m4_define' macro. In addition to defining amacro, `AC_DEFUN' adds to it some code that is used to constrain theorder in which macros are called (*note Prerequisite Macros::).An Autoconf macro definition looks like this:AC_DEFUN(MACRO-NAME, MACRO-BODY)You can refer to any arguments passed to the macro as `$1', `$2',etc. *Note How to define new macros: (m4.info)Definitions, for morecomplete information on writing M4 macros.Be sure to properly quote both the MACRO-BODY _and_ the MACRO-NAMEto avoid any problems if the macro happens to have been previouslydefined.Each macro should have a header comment that gives its prototype,and a brief description. When arguments have default values, displaythem in the prototype. For example:# AC_MSG_ERROR(ERROR, [EXIT-STATUS = 1])# --------------------------------------m4_define([AC_MSG_ERROR],[{ AS_MESSAGE([error: $1], [2])exit m4_default([$2], [1]); }])Comments about the macro should be left in the header comment. Mostother comments make their way into `configure', so just keep using `#'to introduce comments.If you have some special comments about pure M4 code, comments thatmake no sense in `configure' and in the header comment, then use thebuiltin `dnl': it causes M4 to discard the text through the nextnewline.Keep in mind that `dnl' is rarely needed to introduce comments;`dnl' is more useful to get rid of the newlines following macros thatproduce no output, such as `AC_REQUIRE'.File: autoconf.info, Node: Macro Names, Next: Reporting Messages, Prev: Macro Definitions, Up: Writing Autoconf Macros9.2 Macro Names===============All of the Autoconf macros have all-uppercase names starting with `AC_'to prevent them from accidentally conflicting with other text. Allshell variables that they use for internal purposes havemostly-lowercase names starting with `ac_'. To ensure that your macrosdon't conflict with present or future Autoconf macros, you shouldprefix your own macro names and any shell variables they use with someother sequence. Possibilities include your initials, or an abbreviationfor the name of your organization or software package.Most of the Autoconf macros' names follow a structured namingconvention that indicates the kind of feature check by the name. Themacro names consist of several words, separated by underscores, goingfrom most general to most specific. The names of their cache variablesuse the same convention (*note Cache Variable Names::, for moreinformation on them).The first word of the name after `AC_' usually tells the category ofthe feature being tested. Here are the categories used in Autoconf forspecific test macros, the kind of macro that you are more likely towrite. They are also used for cache variables, in all-lowercase. Usethem where applicable; where they're not, invent your own categories.`C'C language builtin features.`DECL'Declarations of C variables in header files.`FUNC'Functions in libraries.`GROUP'Posix group owners of files.`HEADER'Header files.`LIB'C libraries.`PATH'Absolute names of files, including programs.`PROG'The base names of programs.`MEMBER'Members of aggregates.`SYS'Operating system features.`TYPE'C builtin or declared types.`VAR'C variables in libraries.After the category comes the name of the particular feature beingtested. Any further words in the macro name indicate particular aspectsof the feature. For example, `AC_PROG_CC_STDC' checks whether the Ccompiler supports ISO Standard C.An internal macro should have a name that starts with an underscore;Autoconf internals should therefore start with `_AC_'. Additionally, amacro that is an internal subroutine of another macro should have aname that starts with an underscore and the name of that other macro,followed by one or more words saying what the internal macro does. Forexample, `AC_PATH_X' has internal macros `_AC_PATH_X_XMKMF' and`_AC_PATH_X_DIRECT'.File: autoconf.info, Node: Reporting Messages, Next: Dependencies Between Macros, Prev: Macro Names, Up: Writing Autoconf Macros9.3 Reporting Messages======================When macros statically diagnose abnormal situations, benign or fatal,they should report them using these macros. For dynamic issues, i.e.,when `configure' is run, see *Note Printing Messages::.-- Macro: AC_DIAGNOSE (CATEGORY, MESSAGE)Report MESSAGE as a warning (or as an error if requested by theuser) if warnings of the CATEGORY are turned on. You areencouraged to use standard categories, which currently include:`all'messages that don't fall into one of the followingcategories. Use of an empty CATEGORY is equivalent.`cross'related to cross compilation issues.`obsolete'use of an obsolete construct.`syntax'dubious syntactic constructs, incorrectly ordered macro calls.-- Macro: AC_WARNING (MESSAGE)Equivalent to `AC_DIAGNOSE([syntax], MESSAGE)', but you arestrongly encouraged to use a finer grained category.-- Macro: AC_FATAL (MESSAGE)Report a severe error MESSAGE, and have `autoconf' die.When the user runs `autoconf -W error', warnings from `AC_DIAGNOSE'and `AC_WARNING' are reported as error, see *Note autoconf Invocation::.File: autoconf.info, Node: Dependencies Between Macros, Next: Obsoleting Macros, Prev: Reporting Messages, Up: Writing Autoconf Macros9.4 Dependencies Between Macros===============================Some Autoconf macros depend on other macros having been called first inorder to work correctly. Autoconf provides a way to ensure that certainmacros are called if needed and a way to warn the user if macros arecalled in an order that might cause incorrect operation.* Menu:* Prerequisite Macros:: Ensuring required information* Suggested Ordering:: Warning about possible ordering problems* One-Shot Macros:: Ensuring a macro is called only onceFile: autoconf.info, Node: Prerequisite Macros, Next: Suggested Ordering, Up: Dependencies Between Macros9.4.1 Prerequisite Macros-------------------------A macro that you write might need to use values that have previouslybeen computed by other macros. For example, `AC_DECL_YYTEXT' examinesthe output of `flex' or `lex', so it depends on `AC_PROG_LEX' havingbeen called first to set the shell variable `LEX'.Rather than forcing the user of the macros to keep track of thedependencies between them, you can use the `AC_REQUIRE' macro to do itautomatically. `AC_REQUIRE' can ensure that a macro is only called ifit is needed, and only called once.-- Macro: AC_REQUIRE (MACRO-NAME)If the M4 macro MACRO-NAME has not already been called, call it(without any arguments). Make sure to quote MACRO-NAME withsquare brackets. MACRO-NAME must have been defined using`AC_DEFUN' or else contain a call to `AC_PROVIDE' to indicate thatit has been called.`AC_REQUIRE' must be used inside a macro defined by `AC_DEFUN'; itmust not be called from the top level.`AC_REQUIRE' is often misunderstood. It really implementsdependencies between macros in the sense that if one macro depends uponanother, the latter is expanded _before_ the body of the former. To bemore precise, the required macro is expanded before the outermostdefined macro in the current expansion stack. In particular,`AC_REQUIRE([FOO])' is not replaced with the body of `FOO'. Forinstance, this definition of macros:AC_DEFUN([TRAVOLTA],[test "$body_temperature_in_celsius" -gt "38" &&dance_floor=occupied])AC_DEFUN([NEWTON_JOHN],[test "$hair_style" = "curly" &&dance_floor=occupied])AC_DEFUN([RESERVE_DANCE_FLOOR],[if date | grep '^Sat.*pm' >/dev/null 2>&1; thenAC_REQUIRE([TRAVOLTA])AC_REQUIRE([NEWTON_JOHN])fi])with this `configure.ac'AC_INIT([Dance Manager], [1.0], [bug-dance@example.org])RESERVE_DANCE_FLOORif test "$dance_floor" = occupied; thenAC_MSG_ERROR([cannot pick up here, let's move])fidoes not leave you with a better chance to meet a kindred soul at othertimes than Saturday night since it expands into:test "$body_temperature_in_Celsius" -gt "38" &&dance_floor=occupiedtest "$hair_style" = "curly" &&dance_floor=occupiedfiif date | grep '^Sat.*pm' >/dev/null 2>&1; thenfiThis behavior was chosen on purpose: (i) it prevents messages inrequired macros from interrupting the messages in the requiring macros;(ii) it avoids bad surprises when shell conditionals are used, as in:if ...; thenAC_REQUIRE([SOME_CHECK])fi...SOME_CHECKThe helper macros `AS_IF' and `AS_CASE' may be used to enforceexpansion of required macros outside of shell conditional constructs.You are furthermore encouraged to put all `AC_REQUIRE' calls at thebeginning of a macro. You can use `dnl' to avoid the empty lines theyleave.File: autoconf.info, Node: Suggested Ordering, Next: One-Shot Macros, Prev: Prerequisite Macros, Up: Dependencies Between Macros9.4.2 Suggested Ordering------------------------Some macros should be run before another macro if both are called, butneither _requires_ that the other be called. For example, a macro thatchanges the behavior of the C compiler should be called before anymacros that run the C compiler. Many of these dependencies are noted inthe documentation.Autoconf provides the `AC_BEFORE' macro to warn users when macroswith this kind of dependency appear out of order in a `configure.ac'file. The warning occurs when creating `configure' from`configure.ac', not when running `configure'.For example, `AC_PROG_CPP' checks whether the C compiler can run theC preprocessor when given the `-E' option. It should therefore becalled after any macros that change which C compiler is being used,such as `AC_PROG_CC'. So `AC_PROG_CC' contains:AC_BEFORE([$0], [AC_PROG_CPP])dnlThis warns the user if a call to `AC_PROG_CPP' has already occurredwhen `AC_PROG_CC' is called.-- Macro: AC_BEFORE (THIS-MACRO-NAME, CALLED-MACRO-NAME)Make M4 print a warning message to the standard error output ifCALLED-MACRO-NAME has already been called. THIS-MACRO-NAME shouldbe the name of the macro that is calling `AC_BEFORE'. The macroCALLED-MACRO-NAME must have been defined using `AC_DEFUN' or elsecontain a call to `AC_PROVIDE' to indicate that it has been called.File: autoconf.info, Node: One-Shot Macros, Prev: Suggested Ordering, Up: Dependencies Between Macros9.4.3 One-Shot Macros---------------------Some macros should be called only once, either because calling themmultiple time is unsafe, or because it is bad style. For instanceAutoconf ensures that `AC_CANONICAL_BUILD' and cousins (*noteCanonicalizing::) are evaluated only once, because it makes no sense torun these expensive checks more than once. Such one-shot macros can bedefined using `AC_DEFUN_ONCE'.-- Macro: AC_DEFUN_ONCE (MACRO-NAME, MACRO-BODY)Declare macro MACRO-NAME like `AC_DEFUN' would (*note MacroDefinitions::), and emit a warning any time the macro is calledmore than once.Obviously it is not sensible to evaluate a macro defined by`AC_DEFUN_ONCE' in a macro defined by `AC_DEFUN'. Most of the time youwant to use `AC_REQUIRE' (*note Prerequisite Macros::).File: autoconf.info, Node: Obsoleting Macros, Next: Coding Style, Prev: Dependencies Between Macros, Up: Writing Autoconf Macros9.5 Obsoleting Macros=====================Configuration and portability technology has evolved over the years.Often better ways of solving a particular problem are developed, orad-hoc approaches are systematized. This process has occurred in manyparts of Autoconf. One result is that some of the macros are nowconsidered "obsolete"; they still work, but are no longer consideredthe best thing to do, hence they should be replaced with more modernmacros. Ideally, `autoupdate' should replace the old macro calls withtheir modern implementation.Autoconf provides a simple means to obsolete a macro.-- Macro: AU_DEFUN (OLD-MACRO, IMPLEMENTATION, [MESSAGE])Define OLD-MACRO as IMPLEMENTATION. The only difference with`AC_DEFUN' is that the user is warned that OLD-MACRO is nowobsolete.If she then uses `autoupdate', the call to OLD-MACRO is replacedby the modern IMPLEMENTATION. MESSAGE should include informationon what to do after running `autoupdate'; `autoupdate' prints itas a warning, and includes it in the updated `configure.ac' file.The details of this macro are hairy: if `autoconf' encounters an`AU_DEFUN'ed macro, all macros inside its second argument areexpanded as usual. However, when `autoupdate' is run, only M4 andM4sugar macros are expanded here, while all other macros aredisabled and appear literally in the updated `configure.ac'.-- Macro: AU_ALIAS (OLD-NAME, NEW-NAME)Used if the OLD-NAME is to be replaced by a call to NEW-MACRO withthe same parameters. This happens for example if the macro wasrenamed.File: autoconf.info, Node: Coding Style, Prev: Obsoleting Macros, Up: Writing Autoconf Macros9.6 Coding Style================The Autoconf macros follow a strict coding style. You are encouraged tofollow this style, especially if you intend to distribute your macro,either by contributing it to Autoconf itself, or via other means.The first requirement is to pay great attention to the quotation.For more details, see *Note Autoconf Language::, and *Note M4Quotation::.Do not try to invent new interfaces. It is likely that there is amacro in Autoconf that resembles the macro you are defining: try tostick to this existing interface (order of arguments, default values,etc.). We _are_ conscious that some of these interfaces are notperfect; nevertheless, when harmless, homogeneity should be preferredover creativity.Be careful about clashes both between M4 symbols and between shellvariables.If you stick to the suggested M4 naming scheme (*note Macro Names::),you are unlikely to generate conflicts. Nevertheless, when you need toset a special value, _avoid using a regular macro name_; rather, use an"impossible" name. For instance, up to version 2.13, the macro`AC_SUBST' used to remember what SYMBOL macros were already defined bysetting `AC_SUBST_SYMBOL', which is a regular macro name. But sincethere is a macro named `AC_SUBST_FILE', it was just impossible to`AC_SUBST(FILE)'! In this case, `AC_SUBST(SYMBOL)' or`_AC_SUBST(SYMBOL)' should have been used (yes, with the parentheses).No Autoconf macro should ever enter the user-variable name space;i.e., except for the variables that are the actual result of running themacro, all shell variables should start with `ac_'. In addition, smallmacros or any macro that is likely to be embedded in other macrosshould be careful not to use obvious names.Do not use `dnl' to introduce comments: most of the comments you arelikely to write are either header comments which are not output anyway,or comments that should make their way into `configure'. There areexceptional cases where you do want to comment special M4 constructs,in which case `dnl' is right, but keep in mind that it is unlikely.M4 ignores the leading blanks and newlines before each argument.Use this feature to indent in such a way that arguments are (more orless) aligned with the opening parenthesis of the macro being called.For instance, instead ofAC_CACHE_CHECK(for EMX OS/2 environment,ac_cv_emxos2,[AC_COMPILE_IFELSE([AC_LANG_PROGRAM(, [return __EMX__;])],[ac_cv_emxos2=yes], [ac_cv_emxos2=no])])writeAC_CACHE_CHECK([for EMX OS/2 environment], [ac_cv_emxos2],[AC_COMPILE_IFELSE([AC_LANG_PROGRAM([], [return __EMX__;])],[ac_cv_emxos2=yes],[ac_cv_emxos2=no])])or evenAC_CACHE_CHECK([for EMX OS/2 environment],[ac_cv_emxos2],[AC_COMPILE_IFELSE([AC_LANG_PROGRAM([],[return __EMX__;])],[ac_cv_emxos2=yes],[ac_cv_emxos2=no])])When using `AC_RUN_IFELSE' or any macro that cannot work whencross-compiling, provide a pessimistic value (typically `no').Feel free to use various tricks to prevent auxiliary tools, such assyntax-highlighting editors, from behaving improperly. For instance,instead of:m4_bpatsubst([$1], [$"])usem4_bpatsubst([$1], [$""])so that Emacsen do not open an endless "string" at the first quote.For the same reasons, avoid:test $[#] != 0and use:test $[@%:@] != 0Otherwise, the closing bracket would be hidden inside a `#'-comment,breaking the bracket-matching highlighting from Emacsen. Note thepreferred style to escape from M4: `$[1]', `$[@]', etc. Do not escapewhen it is unnecessary. Common examples of useless quotation are`[$]$1' (write `$$1'), `[$]var' (use `$var'), etc. If you addportability issues to the picture, you'll prefer `${1+"$[@]"}' to`"[$]@"', and you'll prefer do something better than hacking Autoconf`:-)'.When using `sed', don't use `-e' except for indenting purposes.With the `s' and `y' commands, the preferred separator is `/' unless`/' itself might appear in the pattern or replacement, in which caseyou should use `|', or optionally `,' if you know the pattern andreplacement cannot contain a file name. If none of these characterswill do, choose a printable character that cannot appear in the patternor replacement. Characters from the set `"#$&'()*;<=>?`|~' are goodchoices if the pattern or replacement might contain a file name, sincethey have special meaning to the shell and are less likely to occur infile names.*Note Macro Definitions::, for details on how to define a macro. Ifa macro doesn't use `AC_REQUIRE', is expected to never be the object ofan `AC_REQUIRE' directive, and macros required by other macros insidearguments do not need to be expanded before this macro, then use`m4_define'. In case of doubt, use `AC_DEFUN'. All the `AC_REQUIRE'statements should be at the beginning of the macro, and each statementshould be followed by `dnl'.You should not rely on the number of arguments: instead of checkingwhether an argument is missing, test that it is not empty. It providesboth a simpler and a more predictable interface to the user, and savesroom for further arguments.Unless the macro is short, try to leave the closing `])' at thebeginning of a line, followed by a comment that repeats the name of themacro being defined. This introduces an additional newline in`configure'; normally, that is not a problem, but if you want to removeit you can use `[]dnl' on the last line. You can similarly use `[]dnl'after a macro call to remove its newline. `[]dnl' is recommendedinstead of `dnl' to ensure that M4 does not interpret the `dnl' asbeing attached to the preceding text or macro output. For example,instead of:AC_DEFUN([AC_PATH_X],[AC_MSG_CHECKING([for X])AC_REQUIRE_CPP()# ...omitted...AC_MSG_RESULT([libraries $x_libraries, headers $x_includes])fi])you would write:AC_DEFUN([AC_PATH_X],[AC_REQUIRE_CPP()[]dnlAC_MSG_CHECKING([for X])# ...omitted...AC_MSG_RESULT([libraries $x_libraries, headers $x_includes])fi[]dnl])# AC_PATH_XIf the macro is long, try to split it into logical chunks.Typically, macros that check for a bug in a function and prepare its`AC_LIBOBJ' replacement should have an auxiliary macro to perform thissetup. Do not hesitate to introduce auxiliary macros to factor yourcode.In order to highlight the recommended coding style, here is a macrowritten the old way:dnl Check for EMX on OS/2.dnl _AC_EMXOS2AC_DEFUN(_AC_EMXOS2,[AC_CACHE_CHECK(for EMX OS/2 environment, ac_cv_emxos2,[AC_COMPILE_IFELSE([AC_LANG_PROGRAM(, return __EMX__;)],ac_cv_emxos2=yes, ac_cv_emxos2=no)])test "$ac_cv_emxos2" = yes && EMXOS2=yes])and the new way:# _AC_EMXOS2# ----------# Check for EMX on OS/2.m4_define([_AC_EMXOS2],[AC_CACHE_CHECK([for EMX OS/2 environment], [ac_cv_emxos2],[AC_COMPILE_IFELSE([AC_LANG_PROGRAM([], [return __EMX__;])],[ac_cv_emxos2=yes],[ac_cv_emxos2=no])])test "$ac_cv_emxos2" = yes && EMXOS2=yes[]dnl])# _AC_EMXOS2File: autoconf.info, Node: Portable Shell, Next: Portable Make, Prev: Writing Autoconf Macros, Up: Top10 Portable Shell Programming*****************************When writing your own checks, there are some shell-script programmingtechniques you should avoid in order to make your code portable. TheBourne shell and upward-compatible shells like the Korn shell and Bashhave evolved over the years, but to prevent trouble, do not takeadvantage of features that were added after Unix version 7, circa 1977(*note Systemology::).You should not use shell functions, aliases, negated characterclasses, or other features that are not found in all Bourne-compatibleshells; restrict yourself to the lowest common denominator. Even`unset' is not supported by all shells!Some ancient systems have quite small limits on the length of the`#!' line; for instance, 32 bytes (not including the newline) on SunOS4. A few ancient 4.2BSD based systems (such as Dynix circa 1984)required a single space between the `#!' and the `/'. However, theseancient systems are no longer of practical concern.The set of external programs you should run in a `configure' scriptis fairly small. *Note Utilities in Makefiles: (standards)Utilities inMakefiles, for the list. This restriction allows users to start outwith a fairly small set of programs and build the rest, avoiding toomany interdependencies between packages.Some of these external utilities have a portable subset of features;see *Note Limitations of Usual Tools::.There are other sources of documentation about shells. Thespecification for the Posix Shell Command Language(http://www.opengroup.org/susv3/utilities/xcu_chap02.html), though moregenerous than the restrictive shell subset described above, is fairlyportable nowadays. Also please see the Shell FAQs(http://www.faqs.org/faqs/unix-faq/shell/).* Menu:* Shellology:: A zoology of shells* Here-Documents:: Quirks and tricks* File Descriptors:: FDs and redirections* File System Conventions:: File names* Shell Substitutions:: Variable and command expansions* Assignments:: Varying side effects of assignments* Parentheses:: Parentheses in shell scripts* Slashes:: Slashes in shell scripts* Special Shell Variables:: Variables you should not change* Limitations of Builtins:: Portable use of not so portable /bin/sh* Limitations of Usual Tools:: Portable use of portable toolsFile: autoconf.info, Node: Shellology, Next: Here-Documents, Up: Portable Shell10.1 Shellology===============There are several families of shells, most prominently the Bourne familyand the C shell family which are deeply incompatible. If you want towrite portable shell scripts, avoid members of the C shell family. Thethe Shell difference FAQ(http://www.faqs.org/faqs/unix-faq/shell/shell-differences/) includes asmall history of Posix shells, and a comparison between several of them.Below we describe some of the members of the Bourne shell family.AshAsh is often used on GNU/Linux and BSD systems as a light-weightBourne-compatible shell. Ash 0.2 has some bugs that are fixed inthe 0.3.x series, but portable shell scripts should work aroundthem, since version 0.2 is still shipped with many GNU/Linuxdistributions.To be compatible with Ash 0.2:- don't use `$?' after expanding empty or unset variables, orat the start of an `eval':foo=false$fooecho "Do not use it: $?"falseeval 'echo "Do not use it: $?"'- don't use command substitution within variable expansion:cat ${FOO=`bar`}- beware that single builtin substitutions are not performed bya subshell, hence their effect applies to the current shell!*Note Shell Substitutions::, item "Command Substitution".BashTo detect whether you are running Bash, test whether`BASH_VERSION' is set. To require Posix compatibility, run `set-o posix'. *Note Bash Posix Mode: (bash)Bash POSIX Mode, fordetails.Bash 2.05 and laterVersions 2.05 and later of Bash use a different format for theoutput of the `set' builtin, designed to make evaluating itsoutput easier. However, this output is not compatible with earlierversions of Bash (or with many other shells, probably). So if youuse Bash 2.05 or higher to execute `configure', you'll need to useBash 2.05 for all other build tasks as well.KshThe Korn shell is compatible with the Bourne family and it mostlyconforms to Posix. It has two major variants commonly called`ksh88' and `ksh93', named after the years of initial release. Itis usually called `ksh', but is called `sh' on some hosts if youset your path appropriately.Solaris systems have three variants: `/usr/bin/ksh' is `ksh88'; itis standard on Solaris 2.0 and later. `/usr/xpg4/bin/sh' is aPosix-compliant variant of `ksh88'; it is standard on Solaris 9and later. `/usr/dt/bin/dtksh' is `ksh93'. Variants that are notstandard may be parts of optional packages. There is no extracharge for these packages, but they are not part of a minimal OSinstall and therefore some installations may not have it.Starting with Tru64 Version 4.0, the Korn shell `/usr/bin/ksh' isalso available as `/usr/bin/posix/sh'. If the environmentvariable `BIN_SH' is set to `xpg4', subsidiary invocations of thestandard shell conform to Posix.PdkshA public-domain clone of the Korn shell called `pdksh' is widelyavailable: it has most of the `ksh88' features along with a few ofits own. It usually sets `KSH_VERSION', except if invoked as`/bin/sh' on OpenBSD, and similarly to Bash you can require Posixcompatibility by running `set -o posix'. Unfortunately, with`pdksh' 5.2.14 (the latest stable version as of February 2006)Posix mode is buggy and causes `pdksh' to depart from Posix in atleast one respect:$ echo "`echo \"hello\"`"hello$ set -o posix$ echo "`echo \"hello\"`""hello"The last line of output contains spurious quotes. This is yetanother reason why portable shell code should not contain`"`...\"...\"...`"' constructs (*note Shell Substitutions::).ZshTo detect whether you are running `zsh', test whether`ZSH_VERSION' is set. By default `zsh' is _not_ compatible withthe Bourne shell: you must execute `emulate sh', and for `zsh'versions before 3.1.6-dev-18 you must also set `NULLCMD' to `:'.*Note Compatibility: (zsh)Compatibility, for details.The default Mac OS X `sh' was originally Zsh; it was changed toBash in Mac OS X 10.2.The following discussion between Russ Allbery and Robert Lipe isworth reading:Russ Allbery:The GNU assumption that `/bin/sh' is the one and only shell leadsto a permanent deadlock. Vendors don't want to break users'existing shell scripts, and there are some corner cases in theBourne shell that are not completely compatible with a Posixshell. Thus, vendors who have taken this route will _never_(OK..."never say never") replace the Bourne shell (as `/bin/sh')with a Posix shell.Robert Lipe:This is exactly the problem. While most (at least most SystemV's) do have a Bourne shell that accepts shell functions mostvendor `/bin/sh' programs are not the Posix shell.So while most modern systems do have a shell _somewhere_ thatmeets the Posix standard, the challenge is to find it.File: autoconf.info, Node: Here-Documents, Next: File Descriptors, Prev: Shellology, Up: Portable Shell10.2 Here-Documents===================Don't rely on `\' being preserved just because it has no specialmeaning together with the next symbol. In the native `sh' on OpenBSD2.7 `\"' expands to `"' in here-documents with unquoted delimiter. Asa general rule, if `\\' expands to `\' use `\\' to get `\'.With OpenBSD 2.7's `sh'$ cat <<EOF> \" \\> EOF" \and with Bash:bash-2.04$ cat <<EOF> \" \\> EOF\" \Some shells mishandle large here-documents: for example, Solaris 10`dtksh' and the UnixWare 7.1.1 Posix shell, which are derived from Kornshell version M-12/28/93d, mishandle braced variable expansion thatcrosses a 1024- or 4096-byte buffer boundary within a here-document.Only the part of the variable name after the boundary is used. Forexample, `${variable}' could be replaced by the expansion of `${ble}'.If the end of the variable name is aligned with the block boundary, theshell reports an error, as if you used `${}'. Instead of`${variable-default}', the shell may expand `${riable-default}', oreven `${fault}'. This bug can often be worked around by omitting thebraces: `$variable'. The bug was fixed in `ksh93g' (1998-04-30) but asof 2006 many operating systems were still shipping older versions withthe bug.Many older shells (including the Bourne shell) implementhere-documents inefficiently. In particular, some shells can beextremely inefficient when a single statement contains manyhere-documents. For instance if your `configure.ac' includes somethinglike:if <cross_compiling>; thenassume this and thatelsecheck thischeck thatcheck something else...on and on forever...fiA shell parses the whole `if'/`fi' construct, creating temporaryfiles for each here-document in it. Some shells create links for suchhere-documents on every `fork', so that the clean-up code they hadinstalled correctly removes them. It is creating the links that cantake the shell forever.Moving the tests out of the `if'/`fi', or creating multiple`if'/`fi' constructs, would improve the performance significantly.Anyway, this kind of construct is not exactly the typical use ofAutoconf. In fact, it's even not recommended, because M4 macros can'tlook into shell conditionals, so we may fail to expand a macro when itwas expanded before in a conditional path, and the condition turned outto be false at runtime, and we end up not executing the macro at all.File: autoconf.info, Node: File Descriptors, Next: File System Conventions, Prev: Here-Documents, Up: Portable Shell10.3 File Descriptors=====================Most shells, if not all (including Bash, Zsh, Ash), output traces onstderr, even for subshells. This might result in undesirable contentif you meant to capture the standard-error output of the inner command:$ ash -x -c '(eval "echo foo >&2") 2>stderr'$ cat stderr+ eval echo foo >&2+ echo foofoo$ bash -x -c '(eval "echo foo >&2") 2>stderr'$ cat stderr+ eval 'echo foo >&2'++ echo foofoo$ zsh -x -c '(eval "echo foo >&2") 2>stderr'# Traces on startup files deleted here.$ cat stderr+zsh:1> eval echo foo >&2+zsh:1> echo foofooOne workaround is to grep out uninteresting lines, hoping not to removegood ones.If you intend to redirect both standard error and standard output,redirect standard output first. This works better with HP-UX, sinceits shell mishandles tracing if standard error is redirected first:$ sh -x -c ': 2>err >out'+ :+ 2> err $ cat err1> outDon't try to redirect the standard error of a command substitution.It must be done _inside_ the command substitution. When running `: `cd/zorglub` 2>/dev/null' expect the error message to escape, while `: `cd/zorglub 2>/dev/null`' works properly.It is worth noting that Zsh (but not Ash nor Bash) makes it possiblein assignments though: `foo=`cd /zorglub` 2>/dev/null'.Don't redirect the same file descriptor several times, as you aredoomed to failure under Ultrix.ULTRIX V4.4 (Rev. 69) System #31: Thu Aug 10 19:42:23 GMT 1995UWS V4.4 (Rev. 11)$ eval 'echo matter >fullness' >voidillegal io$ eval '(echo matter >fullness)' >voidillegal io$ (eval '(echo matter >fullness)') >voidAmbiguous output redirect.In each case the expected result is of course `fullness' containing`matter' and `void' being empty.Don't rely on file descriptors 0, 1, and 2 remaining closed in asubsidiary program. If any of these descriptors is closed, theoperating system may open an unspecified file for the descriptor in thenew process image. Posix says this may be done only if the subsidiaryprogram is set-user-ID or set-group-ID, but HP-UX 11.23 does it even forordinary programs.Don't rely on open file descriptors being open in child processes.In `ksh', file descriptors above 2 which are opened using `exec N>file'are closed by a subsequent `exec' (such as that involved in thefork-and-exec which runs a program or script). Thus, using `sh', wehave:$ cat ./descrips#!/bin/sh -echo hello >&5$ exec 5>t$ ./descrips$ cat t$helloBut using ksh:$ exec 5>t$ ./descripshello$ cat t$Within the process which runs the `descrips' script, file descriptor 5is closed.DOS variants cannot rename or remove open files, such as in `mv foobar >foo' or `rm foo >foo', even though this is perfectly portableamong Posix hosts.A few ancient systems reserved some file descriptors. By convention,file descriptor 3 was opened to `/dev/tty' when you logged into EighthEdition (1985) through Tenth Edition Unix (1989). File descriptor 4had a special use on the Stardent/Kubota Titan (circa 1990), though wedon't now remember what it was. Both these systems are obsolete, soit's now safe to treat file descriptors 3 and 4 like any other filedescriptors.File: autoconf.info, Node: File System Conventions, Next: Shell Substitutions, Prev: File Descriptors, Up: Portable Shell10.4 File System Conventions============================Autoconf uses shell-script processing extensively, so the file namesthat it processes should not contain characters that are special to theshell. Special characters include space, tab, newline, NUL, and thefollowing:" # $ & ' ( ) * ; < = > ? [ \ ` |Also, file names should not begin with `~' or `-', and shouldcontain neither `-' immediately after `/' nor `~' immediately after`:'. On Posix-like platforms, directory names should not contain `:',as this runs afoul of `:' used as the path separator.These restrictions apply not only to the files that you distribute,but also to the absolute file names of your source, build, anddestination directories.On some Posix-like platforms, `!' and `^' are special too, so theyshould be avoided.Posix lets implementations treat leading `//' specially, butrequires leading `///' and beyond to be equivalent to `/'. Most Unixvariants treat `//' like `/'. However, some treat `//' as a"super-root" that can provide access to files that are not otherwisereachable from `/'. The super-root tradition began with ApolloDomain/OS, which died out long ago, but unfortunately Cygwin hasrevived it.While `autoconf' and friends are usually run on some Posix variety,they can be used on other systems, most notably DOS variants. Thisimpacts several assumptions regarding file names.For example, the following code:case $foo_dir in/*) # Absolute;;*)foo_dir=$dots$foo_dir ;;esacfails to properly detect absolute file names on those systems, becausethey can use a drivespec, and usually use a backslash as directoryseparator. If you want to be portable to DOS variants (at the price ofrejecting valid but oddball Posix file names like `a:\b'), you cancheck for absolute file names like this:case $foo_dir in[\\/]* | ?:[\\/]* ) # Absolute;;*)foo_dir=$dots$foo_dir ;;esacMake sure you quote the brackets if appropriate and keep the backslashas first character (*note Limitations of Builtins::).Also, because the colon is used as part of a drivespec, thesesystems don't use it as path separator. When creating or accessingpaths, you can use the `PATH_SEPARATOR' output variable instead.`configure' sets this to the appropriate value (`:' or `;') when itstarts up.File names need extra care as well. While DOS variants that arePosixy enough to run `autoconf' (such as DJGPP) are usually able tohandle long file names properly, there are still limitations that canseriously break packages. Several of these issues can be easilydetected by the doschk(ftp://ftp.gnu.org/gnu/non-gnu/doschk/doschk-1.1.tar.gz) package.A short overview follows; problems are marked with SFN/LFN toindicate where they apply: SFN means the issues are only relevant toplain DOS, not to DOS under Microsoft Windows variants, while LFNidentifies problems that exist even under Microsoft Windows variants.No multiple dots (SFN)DOS cannot handle multiple dots in file names. This is anespecially important thing to remember when building a portableconfigure script, as `autoconf' uses a .in suffix for templatefiles.This is perfectly OK on Posix variants:AC_CONFIG_HEADERS([config.h])AC_CONFIG_FILES([source.c foo.bar])AC_OUTPUTbut it causes problems on DOS, as it requires `config.h.in',`source.c.in' and `foo.bar.in'. To make your package more portableto DOS-based environments, you should use this instead:AC_CONFIG_HEADERS([config.h:config.hin])AC_CONFIG_FILES([source.c:source.cin foo.bar:foobar.in])AC_OUTPUTNo leading dot (SFN)DOS cannot handle file names that start with a dot. This isusually not important for `autoconf'.Case insensitivity (LFN)DOS is case insensitive, so you cannot, for example, have both afile called `INSTALL' and a directory called `install'. This alsoaffects `make'; if there's a file called `INSTALL' in thedirectory, `make install' does nothing (unless the `install'target is marked as PHONY).The 8+3 limit (SFN)Because the DOS file system only stores the first 8 characters ofthe file name and the first 3 of the extension, those must beunique. That means that `foobar-part1.c', `foobar-part2.c' and`foobar-prettybird.c' all resolve to the same file name(`FOOBAR-P.C'). The same goes for `foo.bar' and `foo.bartender'.The 8+3 limit is not usually a problem under Microsoft Windows, asit uses numeric tails in the short version of file names to makethem unique. However, a registry setting can turn this behavioroff. While this makes it possible to share file trees containinglong file names between SFN and LFN environments, it also meansthe above problem applies there as well.Invalid characters (LFN)Some characters are invalid in DOS file names, and should thereforebe avoided. In a LFN environment, these are `/', `\', `?', `*',`:', `<', `>', `|' and `"'. In a SFN environment, othercharacters are also invalid. These include `+', `,', `[' and `]'.Invalid names (LFN)Some DOS file names are reserved, and cause problems if you try touse files with those names. These names include `CON', `AUX',`COM1', `COM2', `COM3', `COM4', `LPT1', `LPT2', `LPT3', `NUL', and`PRN'. File names are case insensitive, so even names like`aux/config.guess' are disallowed.File: autoconf.info, Node: Shell Substitutions, Next: Assignments, Prev: File System Conventions, Up: Portable Shell10.5 Shell Substitutions========================Contrary to a persistent urban legend, the Bourne shell does notsystematically split variables and back-quoted expressions, inparticular on the right-hand side of assignments and in the argument of`case'. For instance, the following code:case "$given_srcdir" in.) top_srcdir="`echo "$dots" | sed 's,/$,,'`" ;;*) top_srcdir="$dots$given_srcdir" ;;esacis more readable when written as:case $given_srcdir in.) top_srcdir=`echo "$dots" | sed 's,/$,,'` ;;*) top_srcdir=$dots$given_srcdir ;;esacand in fact it is even _more_ portable: in the first case of the firstattempt, the computation of `top_srcdir' is not portable, since not allshells properly understand `"`..."..."...`"'. Worse yet, not allshells understand `"`...\"...\"...`"' the same way. There is just noportable way to use double-quoted strings inside double-quotedback-quoted expressions (pfew!).`$@'One of the most famous shell-portability issues is related to`"$@"'. When there are no positional arguments, Posix says that`"$@"' is supposed to be equivalent to nothing, but the originalUnix version 7 Bourne shell treated it as equivalent to `""'instead, and this behavior survives in later implementations likeDigital Unix 5.0.The traditional way to work around this portability problem is touse `${1+"$@"}'. Unfortunately this method does not work with Zsh(3.x and 4.x), which is used on Mac OS X. When emulating theBourne shell, Zsh performs word splitting on `${1+"$@"}':zsh $ emulate shzsh $ for i in "$@"; do echo $i; doneHello World!zsh $ for i in ${1+"$@"}; do echo $i; doneHelloWorld!Zsh handles plain `"$@"' properly, but we can't use plain `"$@"'because of the portability problems mentioned above. Oneworkaround relies on Zsh's "global aliases" to convert `${1+"$@"}'into `"$@"' by itself:test "${ZSH_VERSION+set}" = set && alias -g '${1+"$@"}'='"$@"'A more conservative workaround is to avoid `"$@"' if it ispossible that there may be no positional arguments. For example,instead of:cat conftest.c "$@"you can use this instead:case $# in0) cat conftest.c;;*) cat conftest.c "$@";;esacAutoconf macros often use the `set' command to update `$@', so ifyou are writing shell code intended for `configure' you should notassume that the value of `$@' persists for any length of time.`${10}'The 10th, 11th, ... positional parameters can be accessed onlyafter a `shift'. The 7th Edition shell reported an error if given`${10}', and Solaris 10 `/bin/sh' still acts that way:$ set 1 2 3 4 5 6 7 8 9 10$ echo ${10}bad substitution`${VAR:-VALUE}'Old BSD shells, including the Ultrix `sh', don't accept the colonfor any shell substitution, and complain and die.`${VAR=LITERAL}'Be sure to quote:: ${var='Some words'}otherwise some shells, such as on Digital Unix V 5.0, die becauseof a "bad substitution".Solaris `/bin/sh' has a frightening bug in its interpretation ofthis. Imagine you need set a variable to a string containing `}'.This `}' character confuses Solaris `/bin/sh' when the affectedvariable was already set. This bug can be exercised by running:$ unset foo$ foo=${foo='}'}$ echo $foo}$ foo=${foo='}' # no error; this hints to what the bug is$ echo $foo}$ foo=${foo='}'}$ echo $foo}}^ ugh!It seems that `}' is interpreted as matching `${', even though itis enclosed in single quotes. The problem doesn't happen usingdouble quotes.`${VAR=EXPANDED-VALUE}'On Ultrix, runningdefault="yu,yaa": ${var="$default"}sets VAR to `M-yM-uM-,M-yM-aM-a', i.e., the 8th bit of each charis set. You don't observe the phenomenon using a simple `echo$var' since apparently the shell resets the 8th bit when itexpands $var. Here are two means to make this shell confess itssins:$ cat -v <<EOF$varEOFand$ set | grep '^var=' | cat -vOne classic incarnation of this bug is:default="a b c": ${list="$default"}for c in $list; doecho $cdoneYou'll get `a b c' on a single line. Why? Because there are nospaces in `$list': there are `M- ', i.e., spaces with the 8th bitset, hence no IFS splitting is performed!!!One piece of good news is that Ultrix works fine with `:${list=$default}'; i.e., if you _don't_ quote. The bad news isthen that QNX 4.25 then sets LIST to the _last_ item of DEFAULT!The portable way out consists in using a double assignment, toswitch the 8th bit twice on Ultrix:list=${list="$default"}...but beware of the `}' bug from Solaris (see above). For safety,use:test "${var+set}" = set || var={VALUE}``COMMANDS`'Posix requires shells to trim all trailing newlines from commandoutput before substituting it, so assignments like `dir=`echo"$file" | tr a A`' do not work as expected if `$file' ends in anewline.While in general it makes no sense, do not substitute a singlebuiltin with side effects, because Ash 0.2, trying to optimize,does not fork a subshell to perform the command.For instance, if you wanted to check that `cd' is silent, do notuse `test -z "`cd /`"' because the following can happen:$ pwd/tmp$ test -z "`cd /`" && pwd/The result of `foo=`exit 1`' is left as an exercise to the reader.The MSYS shell leaves a stray byte in the expansion of adouble-quoted command substitution of a native program, if the endof the substution is not aligned with the end of the double quote.This may be worked around by inserting another pair of quotes:$ echo "`printf 'foo\r\n'` bar" > broken$ echo "`printf 'foo\r\n'`"" bar" | cmp - broken- broken differ: char 4, line 1`$(COMMANDS)'This construct is meant to replace ``COMMANDS`', and it has mostof the problems listed under ``COMMANDS`'.This construct can be nested while this is impossible to doportably with back quotes. Unfortunately it is not yetuniversally supported. Most notably, even recent releases ofSolaris don't support it:$ showrev -c /bin/sh | grep versionCommand version: SunOS 5.10 Generic 121004-01 Oct 2005$ echo $(echo blah)syntax error: `(' unexpectednor does IRIX 6.5's Bourne shell:$ uname -aIRIX firebird-image 6.5 07151432 IP22$ echo $(echo blah)$(echo blah)If you do use `$(COMMANDS)', make sure that the commands do notstart with a parenthesis, as that would cause confusion with adifferent notation `$((EXPRESSION))' that in modern shells is anarithmetic expression not a command. To avoid the confusion,insert a space between the two opening parentheses.Avoid COMMANDS that contain unbalanced parentheses inhere-documents, comments, or case statement patterns, as manyshells mishandle them. For example, Bash 3.1, `ksh88', `pdksh'5.2.14, and Zsh 4.2.6 all mishandle the following valid command:echo $(case x in x) echo hello;; esac)`^'Always quote `^', otherwise traditional shells such as `/bin/sh'on Solaris 10 treat this like `|'.File: autoconf.info, Node: Assignments, Next: Parentheses, Prev: Shell Substitutions, Up: Portable Shell10.6 Assignments================When setting several variables in a row, be aware that the order of theevaluation is undefined. For instance `foo=1 foo=2; echo $foo' gives`1' with Solaris `/bin/sh', but `2' with Bash. You must use `;' toenforce the order: `foo=1; foo=2; echo $foo'.Don't rely on the following to find `subdir/program':PATH=subdir$PATH_SEPARATOR$PATH programas this does not work with Zsh 3.0.6. Use something like this instead:(PATH=subdir$PATH_SEPARATOR$PATH; export PATH; exec program)Don't rely on the exit status of an assignment: Ash 0.2 does notchange the status and propagates that of the last statement:$ false || foo=bar; echo $?1$ false || foo=`:`; echo $?0and to make things even worse, QNX 4.25 just sets the exit status to 0in any case:$ foo=`exit 1`; echo $?0To assign default values, follow this algorithm:1. If the default value is a literal and does not contain any closingbrace, use:: ${var='my literal'}2. If the default value contains no closing brace, has to beexpanded, and the variable being initialized is not intended to beIFS-split (i.e., it's not a list), then use:: ${var="$default"}3. If the default value contains no closing brace, has to beexpanded, and the variable being initialized is intended to beIFS-split (i.e., it's a list), then use:var=${var="$default"}4. If the default value contains a closing brace, then use:test "${var+set}" = set || var="has a '}'"In most cases `var=${var="$default"}' is fine, but in case of doubt,just use the last form. *Note Shell Substitutions::, items`${VAR:-VALUE}' and `${VAR=VALUE}' for the rationale.File: autoconf.info, Node: Parentheses, Next: Slashes, Prev: Assignments, Up: Portable Shell10.7 Parentheses in Shell Scripts=================================Beware of two opening parentheses in a row, as some shellimplementations mishandle them. For example, `pdksh' 5.2.14 misparsesthe following code:if ((true) || false); thenecho okfiTo work around this problem, insert a space between the two openingparentheses. There is a similar problem and workaround with `$(('; see*Note Shell Substitutions::.Posix requires support for `case' patterns with opening parentheseslike this:case $file_name in(*.c) echo "C source code";;esacbut the `(' in this example is not portable to many older Bourne shellimplementations. It can be omitted safely.File: autoconf.info, Node: Slashes, Next: Special Shell Variables, Prev: Parentheses, Up: Portable Shell10.8 Slashes in Shell Scripts=============================Unpatched Tru64 5.1 `sh' omits the last slash of command-line argumentsthat contain two trailing slashes:$ echo / // /// //// .// //./ / // /// ./ //.$ x=//$ eval "echo \$x"/$ set -x$ echo abc | tr -t ab //+ echo abc+ tr -t ab //bcUnpatched Tru64 4.0 `sh' adds a slash after `"$var"' if the variableis empty and the second double-quote is followed by a word that beginsand ends with slash:$ sh -xc 'p=; echo "$p"/ouch/'p=+ echo //ouch///ouch/However, our understanding is that patches are available, so perhapsit's not worth worrying about working around these horrendous bugs.File: autoconf.info, Node: Special Shell Variables, Next: Limitations of Builtins, Prev: Slashes, Up: Portable Shell10.9 Special Shell Variables============================Some shell variables should not be used, since they can have a deepinfluence on the behavior of the shell. In order to recover a sanebehavior from the shell, some variables should be unset, but `unset' isnot portable (*note Limitations of Builtins::) and a fallback value isneeded.As a general rule, shell variable names containing a lower-caseletter are safe; you can define and use these variables withoutworrying about their effect on the underlying system, and withoutworrying about whether the shell changes them unexpectedly. (Theexception is the shell variable `status', as described below.)Here is a list of names that are known to cause trouble. This listis not exhaustive, but you should be safe if you avoid the name`status' and names containing only upper-case letters and underscores.`_'Many shells reserve `$_' for various purposes, e.g., the name ofthe last command executed.`BIN_SH'In Tru64, if `BIN_SH' is set to `xpg4', subsidiary invocations ofthe standard shell conform to Posix.`CDPATH'When this variable is set it specifies a list of directories tosearch when invoking `cd' with a relative file name that did notstart with `./' or `../'. Posix 1003.1-2001 says that if anonempty directory name from `CDPATH' is used successfully, `cd'prints the resulting absolute file name. Unfortunately thisoutput can break idioms like `abs=`cd src && pwd`' because `abs'receives the name twice. Also, many shells do not conform to thispart of Posix; for example, `zsh' prints the result only if adirectory name other than `.' was chosen from `CDPATH'.In practice the shells that have this problem also support`unset', so you can work around the problem as follows:(unset CDPATH) >/dev/null 2>&1 && unset CDPATHYou can also avoid output by ensuring that your directory name isabsolute or anchored at `./', as in `abs=`cd ./src && pwd`'.Autoconf-generated scripts automatically unset `CDPATH' ifpossible, so you need not worry about this problem in thosescripts.`DUALCASE'In the MKS shell, case statements and file name generation arecase-insensitive unless `DUALCASE' is nonzero. Autoconf-generatedscripts export this variable when they start up.`ENV'`MAIL'`MAILPATH'`PS1'`PS2'`PS4'These variables should not matter for shell scripts, since they aresupposed to affect only interactive shells. However, at least oneshell (the pre-3.0 UWIN Korn shell) gets confused about whether itis interactive, which means that (for example) a `PS1' with a sideeffect can unexpectedly modify `$?'. To work around this bug,Autoconf-generated scripts do something like this:(unset ENV) >/dev/null 2>&1 && unset ENV MAIL MAILPATHPS1='$ 'PS2='> 'PS4='+ '`IFS'Long ago, shell scripts inherited `IFS' from the environment, butthis caused many problems so modern shells ignore any environmentsettings for `IFS'.Don't set the first character of `IFS' to backslash. Indeed,Bourne shells use the first character (backslash) when joining thecomponents in `"$@"' and some shells then reinterpret (!) thebackslash escapes, so you can end up with backspace and otherstrange characters.The proper value for `IFS' (in regular code, not when performingsplits) is `<SPC><TAB><RET>'. The first character is especiallyimportant, as it is used to join the arguments in `$*'; however,note that traditional shells, but also bash-2.04, fail to adhereto this and join with a space anyway.`LANG'`LC_ALL'`LC_COLLATE'`LC_CTYPE'`LC_MESSAGES'`LC_MONETARY'`LC_NUMERIC'`LC_TIME'Autoconf-generated scripts normally set all these variables to `C'because so much configuration code assumes the C locale and Posixrequires that locale environment variables be set to `C' if the Clocale is desired. However, some older, nonstandard systems(notably SCO) break if locale environment variables are set to`C', so when running on these systems Autoconf-generated scriptsunset the variables instead.`LANGUAGE'`LANGUAGE' is not specified by Posix, but it is a GNU extensionthat overrides `LC_ALL' in some cases, so Autoconf-generatedscripts set it too.`LC_ADDRESS'`LC_IDENTIFICATION'`LC_MEASUREMENT'`LC_NAME'`LC_PAPER'`LC_TELEPHONE'These locale environment variables are GNU extensions. They aretreated like their Posix brethren (`LC_COLLATE', etc.) asdescribed above.`LINENO'Most modern shells provide the current line number in `LINENO'.Its value is the line number of the beginning of the currentcommand. Autoconf attempts to execute `configure' with a shellthat supports `LINENO'. If no such shell is available, itattempts to implement `LINENO' with a Sed prepass that replaceseach instance of the string `$LINENO' (not followed by analphanumeric character) with the line's number.You should not rely on `LINENO' within `eval', as the behaviordiffers in practice. Also, the possibility of the Sed prepassmeans that you should not rely on `$LINENO' when quoted, when inhere-documents, or when in long commands that cross lineboundaries. Subshells should be OK, though. In the followingexample, lines 1, 6, and 9 are portable, but the other instances of`LINENO' are not:$ cat linenoecho 1. $LINENOcat <<EOF3. $LINENO4. $LINENOEOF( echo 6. $LINENO )eval 'echo 7. $LINENO'echo 8. '$LINENO'echo 9. $LINENO '10.' $LINENO$ bash-2.05 lineno1. 13. 24. 26. 67. 18. $LINENO9. 910. 9$ zsh-3.0.6 lineno1. 13. 24. 26. 67. 78. $LINENO9. 910. 9$ pdksh-5.2.14 lineno1. 13. 24. 26. 67. 08. $LINENO9. 910. 9$ sed '=' <lineno |> sed '> N> s,$,-,> t loop> :loop> s,^\([0-9]*\)\(.*\)[$]LINENO\([^a-zA-Z0-9_]\),\1\2\1\3,> t loop> s,-$,,> s,^[0-9]*\n,,> ' |> sh1. 13. 34. 46. 67. 78. 89. 910. 10`NULLCMD'When executing the command `>foo', `zsh' executes `$NULLCMD >foo'unless it is operating in Bourne shell compatibility mode and the`zsh' version is newer than 3.1.6-dev-18. If you are using anolder `zsh' and forget to set `NULLCMD', your script might besuspended waiting for data on its standard input.`PATH_SEPARATOR'On DJGPP systems, the `PATH_SEPARATOR' environment variable can beset to either `:' or `;' to control the path separator Bash usesto set up certain environment variables (such as `PATH'). You canset this variable to `;' if you want `configure' to use `;' as aseparator; this might be useful if you plan to use non-Posixshells to execute files. *Note File System Conventions::, formore information about `PATH_SEPARATOR'.`PWD'Posix 1003.1-2001 requires that `cd' and `pwd' must update the`PWD' environment variable to point to the logical name of thecurrent directory, but traditional shells do not support this.This can cause confusion if one shell instance maintains `PWD' buta subsidiary and different shell does not know about `PWD' andexecutes `cd'; in this case `PWD' points to the wrong directory.Use ``pwd`' rather than `$PWD'.`RANDOM'Many shells provide `RANDOM', a variable that returns a differentinteger each time it is used. Most of the time, its value does notchange when it is not used, but on IRIX 6.5 the value changes allthe time. This can be observed by using `set'. It is commonpractice to use `$RANDOM' as part of a file name, but codeshouldn't rely on `$RANDOM' expanding to a nonempty string.`status'This variable is an alias to `$?' for `zsh' (at least 3.1.6),hence read-only. Do not use it.File: autoconf.info, Node: Limitations of Builtins, Next: Limitations of Usual Tools, Prev: Special Shell Variables, Up: Portable Shell10.10 Limitations of Shell Builtins===================================No, no, we are serious: some shells do have limitations! :)You should always keep in mind that any builtin or command maysupport options, and therefore differ in behavior with argumentsstarting with a dash. For instance, the innocent `echo "$word"' cangive unexpected results when `word' starts with a dash. It is oftenpossible to avoid this problem using `echo "x$word"', taking the `x'into account later in the pipe.`.'Use `.' only with regular files (use `test -f'). Bash 2.03, forinstance, chokes on `. /dev/null'. Also, remember that `.' uses`PATH' if its argument contains no slashes, so if you want to use`.' on a file `foo' in the current directory, you must use `../foo'.`!'The Unix version 7 shell did not support negating the exit statusof commands with `!', and this feature is still absent from someshells (e.g., Solaris `/bin/sh'). Shell code like this:if ! cmp file1 file2 >/dev/null 2>&1; thenecho files differ or troublefiis therefore not portable in practice. Typically it is easy torewrite such code, e.g.:cmp file1 file2 >/dev/null 2>&1 ||echo files differ or troubleMore generally, one can always rewrite `! COMMAND' as:if COMMAND; then (exit 1); else :; fi`break'The use of `break 2' etc. is safe.`case'You don't need to quote the argument; no splitting is performed.You don't need the final `;;', but you should use it.Because of a bug in its `fnmatch', Bash fails to properly handlebackslashes in character classes:bash-2.02$ case /tmp in [/\\]*) echo OK;; esacbash-2.02$This is extremely unfortunate, since you are likely to use thiscode to handle Posix or MS-DOS absolute file names. To workaround this bug, always put the backslash first:bash-2.02$ case '\TMP' in [\\/]*) echo OK;; esacOKbash-2.02$ case /tmp in [\\/]*) echo OK;; esacOKMany Bourne shells cannot handle closing brackets in characterclasses correctly.Some shells also have problems with backslash escaping in case youdo not want to match the backslash: both a backslash and theescaped character match this pattern. To work around this,specify the character class in a variable, so that quote removaldoes not apply afterwards, and the special characters don't haveto be backslash-escaped:$ case '\' in [\<]) echo OK;; esacOK$ scanset='[<]'; case '\' in $scanset) echo OK;; esac$Even with this, Solaris `ksh' matches a backslash if the setcontains any of the characters `|', `&', `(', or `)'.Conversely, Tru64 `ksh' (circa 2003) erroneously always matches aclosing parenthesis if not specified in a character class:$ case foo in *\)*) echo fail ;; esacfail$ case foo in *')'*) echo fail ;; esacfailSome shells, such as Ash 0.3.8, are confused by an empty`case'/`esac':ash-0.3.8 $ case foo in esac;error-->Syntax error: ";" unexpected (expecting ")")Many shells still do not support parenthesized cases, which is apity for those of us using tools that rely on balancedparentheses. For instance, Solaris `/bin/sh':$ case foo in (foo) echo foo;; esacerror-->syntax error: `(' unexpected`cd'Posix 1003.1-2001 requires that `cd' must support the `-L'("logical") and `-P' ("physical") options, with `-L' being thedefault. However, traditional shells do not support theseoptions, and their `cd' command has the `-P' behavior.Portable scripts should assume neither option is supported, andshould assume neither behavior is the default. This can be a bittricky, since the Posix default behavior means that, for example,`ls ..' and `cd ..' may refer to different directories if thecurrent logical directory is a symbolic link. It is safe to use`cd DIR' if DIR contains no `..' components. Also,Autoconf-generated scripts check for this problem when computingvariables like `ac_top_srcdir' (*note Configuration Actions::), soit is safe to `cd' to these variables.See *Note Special Shell Variables::, for portability problemsinvolving `cd' and the `CDPATH' environment variable. Also pleasesee the discussion of the `pwd' command.`echo'The simple `echo' is probably the most surprising source ofportability troubles. It is not possible to use `echo' portablyunless both options and escape sequences are omitted. Newapplications which are not aiming at portability should use`printf' instead of `echo'.Don't expect any option. *Note Preset Output Variables::, `ECHO_N'etc. for a means to simulate `-n'.Do not use backslashes in the arguments, as there is no consensuson their handling. For `echo '\n' | wc -l', the `sh' of Solarisoutputs 2, but Bash and Zsh (in `sh' emulation mode) output 1.The problem is truly `echo': all the shells understand `'\n'' asthe string composed of a backslash and an `n'.Because of these problems, do not pass a string containingarbitrary characters to `echo'. For example, `echo "$foo"' is safeif you know that FOO's value cannot contain backslashes and cannotstart with `-', but otherwise you should use a here-document likethis:cat <<EOF$fooEOF`eval'The `eval' command is useful in limited circumstances, e.g., usingcommands like `eval table_$key=\$value' and `evalvalue=table_$key' to simulate a hash table when the key is knownto be alphanumeric. However, `eval' is tricky to use on arbitraryarguments, even when it is implemented correctly.It is obviously unwise to use `eval $cmd' if the string value of`cmd' was derived from an untrustworthy source. But even if thestring value is valid, `eval $cmd' might not work as intended,since it causes field splitting and file name expansion to occurtwice, once for the `eval' and once for the command itself. It istherefore safer to use `eval "$cmd"'. For example, if CMD has thevalue `cat test?.c', `eval $cmd' might expand to the equivalent of`cat test;.c' if there happens to be a file named `test;.c' in thecurrent directory; and this in turn mistakenly attempts to invoke`cat' on the file `test' and then execute the command `.c'. Toavoid this problem, use `eval "$cmd"' rather than `eval $cmd'.However, suppose that you want to output the text of the evaluatedcommand just before executing it. Assuming the previous example,`echo "Executing: $cmd"' outputs `Executing: cat test?.c', butthis output doesn't show the user that `test;.c' is the actual nameof the copied file. Conversely, `eval "echo Executing: $cmd"'works on this example, but it fails with `cmd='cat foo >bar'',since it mistakenly replaces the contents of `bar' by the string`cat foo'. No simple, general, and portable solution to thisproblem is known.You should also be wary of common bugs in `eval' implementations.In some shell implementations (e.g., older `ash', OpenBSD 3.8`sh', `pdksh' v5.2.14 99/07/13.2, and `zsh' 4.2.5), the argumentsof `eval' are evaluated in a context where `$?' is 0, so theyexhibit behavior like this:$ false; eval 'echo $?'0The correct behavior here is to output a nonzero value, butportable scripts should not rely on this.You should not rely on `LINENO' within `eval'. *Note SpecialShell Variables::.`exit'The default value of `exit' is supposed to be `$?'; unfortunately,some shells, such as the DJGPP port of Bash 2.04, just perform`exit 0'.bash-2.04$ foo=`exit 1` || echo failfailbash-2.04$ foo=`(exit 1)` || echo failfailbash-2.04$ foo=`(exit 1); exit` || echo failbash-2.04$Using `exit $?' restores the expected behavior.Some shell scripts, such as those generated by `autoconf', use atrap to clean up before exiting. If the last shell command exitedwith nonzero status, the trap also exits with nonzero status sothat the invoker can tell that an error occurred.Unfortunately, in some shells, such as Solaris `/bin/sh', an exittrap ignores the `exit' command's argument. In these shells, atrap cannot determine whether it was invoked by plain `exit' or by`exit 1'. Instead of calling `exit' directly, use the`AC_MSG_ERROR' macro that has a workaround for this problem.`export'The builtin `export' dubs a shell variable "environment variable".Each update of exported variables corresponds to an update of theenvironment variables. Conversely, each environment variablereceived by the shell when it is launched should be imported as ashell variable marked as exported.Alas, many shells, such as Solaris `/bin/sh', IRIX 6.3, IRIX 5.2,AIX 4.1.5, and Digital Unix 4.0, forget to `export' theenvironment variables they receive. As a result, two variablescoexist: the environment variable and the shell variable. Thefollowing code demonstrates this failure:#!/bin/shecho $FOOFOO=barecho $FOOexec /bin/sh $0when run with `FOO=foo' in the environment, these shells printalternately `foo' and `bar', although they should print only `foo'and then a sequence of `bar's.Therefore you should `export' again each environment variable thatyou update.`false'Don't expect `false' to exit with status 1: in native Solaris`/bin/false' exits with status 255.`for'To loop over positional arguments, use:for argdoecho "$arg"doneYou may _not_ leave the `do' on the same line as `for', since someshells improperly grok:for arg; doecho "$arg"doneIf you want to explicitly refer to the positional arguments, giventhe `$@' bug (*note Shell Substitutions::), use:for arg in ${1+"$@"}; doecho "$arg"doneBut keep in mind that Zsh, even in Bourne shell emulation mode,performs word splitting on `${1+"$@"}'; see *Note ShellSubstitutions::, item `$@', for more.`if'Using `!' is not portable. Instead of:if ! cmp -s file file.new; thenmv file.new filefiuse:if cmp -s file file.new; then :; elsemv file.new filefiThere are shells that do not reset the exit status from an `if':$ if (exit 42); then true; fi; echo $?42whereas a proper shell should have printed `0'. This is especiallybad in makefiles since it produces false failures. This is whyproperly written makefiles, such as Automake's, have such hairyconstructs:if test -f "$file"; theninstall "$file" "$dest"else:fi`printf'A format string starting with a `-' can cause problems. Bash(e.g., 2.05b) interprets it as an options argument and gives anerror. And `--' to mark the end of options is not good in theNetBSD Almquist shell (e.g., 0.4.6) which takes that literally asthe format string. Putting the `-' in a `%c' or `%s' is probablythe easiest way to avoid doubt,printf %s -foo`read'Not all shells support `-r' (Solaris `/bin/sh' for example).`pwd'With modern shells, plain `pwd' outputs a "logical" directoryname, some of whose components may be symbolic links. Thesedirectory names are in contrast to "physical" directory names,whose components are all directories.Posix 1003.1-2001 requires that `pwd' must support the `-L'("logical") and `-P' ("physical") options, with `-L' being thedefault. However, traditional shells do not support theseoptions, and their `pwd' command has the `-P' behavior.Portable scripts should assume neither option is supported, andshould assume neither behavior is the default. Also, on many hosts`/bin/pwd' is equivalent to `pwd -P', but Posix does not requirethis behavior and portable scripts should not rely on it.Typically it's best to use plain `pwd'. On modern hosts thisoutputs logical directory names, which have the followingadvantages:* Logical names are what the user specified.* Physical names may not be portable from one installation hostto another due to network file system gymnastics.* On modern hosts `pwd -P' may fail due to lack of permissionsto some parent directory, but plain `pwd' cannot fail for thisreason.Also please see the discussion of the `cd' command.`set'With the FreeBSD 6.0 shell, the `set' command (without anyoptions) does not sort its output.The `set' builtin faces the usual problem with arguments startingwith a dash. Modern shells such as Bash or Zsh understand `--' tospecify the end of the options (any argument after `--' is aparameter, even `-x' for instance), but many traditional shells(e.g., Solaris 10 `/bin/sh') simply stop option processing as soonas a non-option argument is found. Therefore, use `dummy' orsimply `x' to end the option processing, and use `shift' to pop itout:set x $my_list; shiftAvoid `set -', e.g., `set - $my_list'. Posix no longer requiressupport for this command, and in traditional shells `set -$my_list' resets the `-v' and `-x' options, which makes scriptsharder to debug.Some nonstandard shells do not recognize more than one option(e.g., `set -e -x' assigns `-x' to the command line). It isbetter to combine them:set -exThe BSD shell has had several problems with the `-e' option,partly because BSD `make' traditionally used `-e' even though thiswas incompatible with Posix (*note Failure in Make Rules::).Older versions of the BSD shell (circa 1990) mishandled `&&',`||', `if', and `case' when `-e' was in effect, causing the shellto exit unexpectedly in some cases. This was particularly aproblem with makefiles, and led to circumlocutions like `sh -c'test -f file || touch file'', where the seemingly-unnecessary `sh-c '...'' wrapper works around the bug.Even relatively-recent versions of the BSD shell (e.g., OpenBSD3.4) wrongly exit with `-e' if a command within `&&' fails insidea compound statement. For example:#! /bin/shset -efoo=''test -n "$foo" && exit 1echo oneif :; thentest -n "$foo" && exit 1fiecho twodoes not print `two'. One workaround is to use `if test -n"$foo"; then exit 1; fi' rather than `test -n "$foo" && exit 1'.Another possibility is to warn BSD users not to use `sh -e'.`shift'Not only is `shift'ing a bad idea when there is nothing left toshift, but in addition it is not portable: the shell of MIPSRISC/OS 4.52 refuses to do it.Don't use `shift 2' etc.; it was not in the 7th Edition Bourneshell, and it is also absent in many pre-Posix shells.`source'This command is not portable, as Posix does not require it; use`.' instead.`test'The `test' program is the way to perform many file and stringtests. It is often invoked by the alternate name `[', but usingthat name in Autoconf code is asking for trouble since it is an M4quote character.If you need to make multiple checks using `test', combine them withthe shell operators `&&' and `||' instead of using the `test'operators `-a' and `-o'. On System V, the precedence of `-a' and`-o' is wrong relative to the unary operators; consequently, Posixdoes not specify them, so using them is nonportable. If youcombine `&&' and `||' in the same statement, keep in mind thatthey have equal precedence.It is safe to use `!' as a `test' operator. For example, `if test! -d foo; ...' is portable even though `if ! test -d foo; ...' isnot.`test' (files)To enable `configure' scripts to support cross-compilation, theyshouldn't do anything that tests features of the build systeminstead of the host system. But occasionally you may find itnecessary to check whether some arbitrary file exists. To do so,use `test -f' or `test -r'. Do not use `test -x', because 4.3BSDdoes not have it. Do not use `test -e' either, because Solaris`/bin/sh' lacks it. To test for symbolic links on systems thathave them, use `test -h' rather than `test -L'; either formconforms to Posix 1003.1-2001, but older shells like Solaris 8`/bin/sh' support only `-h'.`test' (strings)Avoid `test "STRING"', in particular if STRING might start with adash, since `test' might interpret its argument as an option(e.g., `STRING = "-n"').Contrary to a common belief, `test -n STRING' and `test -z STRING'*are* portable. Nevertheless many shells (such as Solaris, AIX3.2, UNICOS 10.0.0.6, Digital Unix 4, etc.) have bizarreprecedence and may be confused if STRING looks like an operator:$ test -n =test: argument expectedIf there are risks, use `test "xSTRING" = x' or `test "xSTRING" !=x' instead.It is common to find variations of the following idiom:test -n "`echo $ac_feature | sed 's/[-a-zA-Z0-9_]//g'`" &&ACTIONto take an action when a token matches a given pattern. Suchconstructs should always be avoided by using:echo "$ac_feature" | grep '[^-a-zA-Z0-9_]' >/dev/null 2>&1 &&ACTIONUse `case' where possible since it is faster, being a shellbuiltin:case $ac_feature in*[!-a-zA-Z0-9_]*) ACTION;;esacAlas, negated character classes are probably not portable,although no shell is known to not support the Posix syntax `[!...]'(when in interactive mode, `zsh' is confused by the `[!...]'syntax and looks for an event in its history because of `!').Many shells do not support the alternative syntax `[^...]'(Solaris, Digital Unix, etc.).One solution can be:expr "$ac_feature" : '.*[^-a-zA-Z0-9_]' >/dev/null &&ACTIONor better yetexpr "X$ac_feature" : '.*[^-a-zA-Z0-9_]' >/dev/null &&ACTION`expr "XFOO" : "XBAR"' is more robust than `echo "XFOO" | grep"^XBAR"', because it avoids problems when `FOO' containsbackslashes.`trap'It is safe to trap at least the signals 1, 2, 13, and 15. You canalso trap 0, i.e., have the `trap' run when the script ends(either via an explicit `exit', or the end of the script). Thetrap for 0 should be installed outside of a shell function, or AIX5.3 `/bin/sh' will invoke the trap at the end of this function.Posix says that `trap - 1 2 13 15' resets the traps for thespecified signals to their default values, but many common shells(e.g., Solaris `/bin/sh') misinterpret this and attempt to executea "command" named `-' when the specified conditions arise. Thereis no portable workaround, except for `trap - 0', for which `trap'' 0' is a portable substitute.Although Posix is not absolutely clear on this point, it is widelyadmitted that when entering the trap `$?' should be set to the exitstatus of the last command run before the trap. The ambiguity canbe summarized as: "when the trap is launched by an `exit', what isthe _last_ command run: that before `exit', or `exit' itself?"Bash considers `exit' to be the last command, while Zsh andSolaris `/bin/sh' consider that when the trap is run it is _still_in the `exit', hence it is the previous exit status that the trapreceives:$ cat trap.shtrap 'echo $?' 0(exit 42); exit 0$ zsh trap.sh42$ bash trap.sh0The portable solution is then simple: when you want to `exit 42',run `(exit 42); exit 42', the first `exit' being used to set theexit status to 42 for Zsh, and the second to trigger the trap andpass 42 as exit status for Bash.The shell in FreeBSD 4.0 has the following bug: `$?' is reset to 0by empty lines if the code is inside `trap'.$ trap 'falseecho $?' 0$ exit0Fortunately, this bug only affects `trap'.`true'Don't worry: as far as we know `true' is portable. Nevertheless,it's not always a builtin (e.g., Bash 1.x), and the portable shellcommunity tends to prefer using `:'. This has a funny sideeffect: when asked whether `false' is more portable than `true'Alexandre Oliva answered:In a sense, yes, because if it doesn't exist, the shell willproduce an exit status of failure, which is correct for`false', but not for `true'.`unset'In some nonconforming shells (e.g., Bash 2.05a), `unset FOO' failswhen `FOO' is not set. Also, Bash 2.01 mishandles `unset MAIL' insome cases and dumps core.A few ancient shells lack `unset' entirely. Nevertheless, becauseit is extremely useful to disable embarrassing variables such as`PS1', you can test for its existence and use it _provided_ yougive a neutralizing value when `unset' is not supported:# "|| exit" suppresses any "Segmentation fault" message.if ( (MAIL=60; unset MAIL) || exit) >/dev/null 2>&1; thenunset=unsetelseunset=falsefi$unset PS1 || PS1='$ '*Note Special Shell Variables::, for some neutralizing values.Also, see *Note Limitations of Builtins::, documentation of`export', for the case of environment variables.File: autoconf.info, Node: Limitations of Usual Tools, Prev: Limitations of Builtins, Up: Portable Shell10.11 Limitations of Usual Tools================================The small set of tools you can expect to find on any machine can stillinclude some limitations you should be aware of.AwkDon't leave white space before the opening parenthesis in a userfunction call. Posix does not allow this and GNU Awk rejects it:$ gawk 'function die () { print "Aaaaarg!" }BEGIN { die () }'gawk: cmd. line:2: BEGIN { die () }gawk: cmd. line:2: ^ parse error$ gawk 'function die () { print "Aaaaarg!" }BEGIN { die() }'Aaaaarg!If you want your program to be deterministic, don't depend on `for'on arrays:$ cat for.awkEND {arr["foo"] = 1arr["bar"] = 1for (i in arr)print i}$ gawk -f for.awk </dev/nullfoobar$ nawk -f for.awk </dev/nullbarfooSome Awk implementations, such as HP-UX 11.0's native one,mishandle anchors:$ echo xfoo | $AWK '/foo|^bar/ { print }'$ echo bar | $AWK '/foo|^bar/ { print }'bar$ echo xfoo | $AWK '/^bar|foo/ { print }'xfoo$ echo bar | $AWK '/^bar|foo/ { print }'barEither do not depend on such patterns (i.e., use `/^(.*foo|bar)/',or use a simple test to reject such implementations.AIX version 5.2 has an arbitrary limit of 399 on the length ofregular expressions and literal strings in an Awk program.Traditional Awk implementations derived from Unix version 7, suchas Solaris `/bin/awk', have many limitations and do not conform toPosix. Nowadays `AC_PROG_AWK' (*note Particular Programs::) findsyou an Awk that doesn't have these problems, but if for somereason you prefer not to use `AC_PROG_AWK' you may need to addressthem.Traditional Awk does not support multidimensional arrays oruser-defined functions.Traditional Awk does not support the `-v' option. You can useassignments after the program instead, e.g., `$AWK '{print v $1}'v=x'; however, don't forget that such assignments are notevaluated until they are encountered (e.g., after any `BEGIN'action).Traditional Awk does not support the keywords `delete' or `do'.Traditional Awk does not support the expressions `A?B:C', `!A',`A^B', or `A^=B'.Traditional Awk does not support the predefined `CONVFMT' variable.Traditional Awk supports only the predefined functions `exp',`int', `length', `log', `split', `sprintf', `sqrt', and `substr'.Traditional Awk `getline' is not at all compatible with Posix;avoid it.Traditional Awk `split' supports only two arguments.Traditional Awk has a limit of 99 fields in a record. You may beable to circumvent this problem by using `split'.`basename'Not all hosts have a working `basename'. You can use `expr'instead.`cat'Don't rely on any option.`cc'The command `cc -c foo.c' traditionally produces an object filenamed `foo.o'. Most compilers allow `-c' to be combined with `-o'to specify a different object file name, but Posix does notrequire this combination and a few compilers lack support for it.*Note C Compiler::, for how GNU Make tests for this feature with`AC_PROG_CC_C_O'.When a compilation such as `cc -o foo foo.c' fails, some compilers(such as CDS on Reliant Unix) leave a `foo.o'.HP-UX `cc' doesn't accept `.S' files to preprocess and assemble.`cc -c foo.S' appears to succeed, but in fact does nothing.The default executable, produced by `cc foo.c', can be* `a.out' -- usual Posix convention.* `b.out' -- i960 compilers (including `gcc').* `a.exe' -- DJGPP port of `gcc'.* `a_out.exe' -- GNV `cc' wrapper for DEC C on OpenVMS.* `foo.exe' -- various MS-DOS compilers.The C compiler's traditional name is `cc', but other names like`gcc' are common. Posix 1003.1-2001 specifies the name `c99', butolder Posix editions specified `c89' and anyway these standardnames are rarely used in practice. Typically the C compiler isinvoked from makefiles that use `$(CC)', so the value of the `CC'make variable selects the compiler name.`chmod'Avoid usages like `chmod -w file'; use `chmod a-w file' instead,for two reasons. First, plain `-w' does not necessarily make thefile unwritable, since it does not affect mode bits thatcorrespond to bits in the file mode creation mask. Second, Posixsays that the `-w' might be interpreted as animplementation-specific option, not as a mode; Posix suggestsusing `chmod -- -w file' to avoid this confusion, but unfortunately`--' does not work on some older hosts.`cmp'`cmp' performs a raw data comparison of two files, while `diff'compares two text files. Therefore, if you might compare DOSfiles, even if only checking whether two files are different, use`diff' to avoid spurious differences due to differences of newlineencoding.`cp'Avoid the `-r' option, since Posix 1003.1-2004 marks it asobsolescent and its behavior on special files isimplementation-defined. Use `-R' instead. On GNU hosts the twooptions are equivalent, but on Solaris hosts (for example) `cp -r'reads from pipes instead of replicating them.Some `cp' implementations (e.g., BSD/OS 4.2) do not allow trailingslashes at the end of nonexistent destination directories. Toavoid this problem, omit the trailing slashes. For example, use`cp -R source /tmp/newdir' rather than `cp -R source /tmp/newdir/'if `/tmp/newdir' does not exist.The ancient SunOS 4 `cp' does not support `-f', although its `mv'does.Traditionally, file timestamps had 1-second resolution, and `cp-p' copied the timestamps exactly. However, many modern filesystems have timestamps with 1-nanosecond resolution.Unfortunately, `cp -p' implementations truncate timestamps whencopying files, so this can result in the destination fileappearing to be older than the source. The exact amount oftruncation depends on the resolution of the system calls that `cp'uses; traditionally this was `utime', which has 1-secondresolution, but some newer `cp' implementations use `utimes',which has 1-microsecond resolution. These newer implementationsinclude GNU Core Utilities 5.0.91 or later, and Solaris 8 (sparc)patch 109933-02 or later. Unfortunately as of January 2006 thereis still no system call to set timestamps to the full nanosecondresolution.Bob Proulx notes that `cp -p' always _tries_ to copy ownerships.But whether it actually does copy ownerships or not is a systemdependent policy decision implemented by the kernel. If thekernel allows it then it happens. If the kernel does not allow itthen it does not happen. It is not something `cp' itself hascontrol over.In Unix System V any user can chown files to any other user, andSystem V also has a non-sticky `/tmp'. That probably derives fromthe heritage of System V in a business environment without hostileusers. BSD changed this to be a more secure model where only rootcan `chown' files and a sticky `/tmp' is used. That undoubtedlyderives from the heritage of BSD in a campus environment.GNU/Linux and Solaris by default follow BSD, but can be configuredto allow a System V style `chown'. On the other hand, HP-UXfollows System V, but can be configured to use the modern securitymodel and disallow `chown'. Since it is anadministrator-configurable parameter you can't use the name of thekernel as an indicator of the behavior.`date'Some versions of `date' do not recognize special `%' directives,and unfortunately, instead of complaining, they just pass themthrough, and exit with success:$ uname -aOSF1 medusa.sis.pasteur.fr V5.1 732 alpha$ date "+%s"%s`diff'Option `-u' is nonportable.Some implementations, such as Tru64's, fail when comparing to`/dev/null'. Use an empty file instead.`dirname'Not all hosts have a working `dirname', and you should instead use`AS_DIRNAME' (*note Programming in M4sh::). For example:dir=`dirname "$file"` # This is not portable.dir=`AS_DIRNAME(["$file"])` # This is more portable.`egrep'Posix 1003.1-2001 no longer requires `egrep', but many older hostsdo not yet support the Posix replacement `grep -E'. Also, sometraditional implementations do not work on long input lines. Towork around these problems, invoke `AC_PROG_EGREP' and then use`$EGREP'.Portable extended regular expressions should use `\' only to escapecharacters in the string `$()*+.?[\^{|'. For example, `\}' is notportable, even though it typically matches `}'.The empty alternative is not portable. Use `?' instead. Forinstance with Digital Unix v5.0:> printf "foo\n|foo\n" | $EGREP '^(|foo|bar)$'|foo> printf "bar\nbar|\n" | $EGREP '^(foo|bar|)$'bar|> printf "foo\nfoo|\n|bar\nbar\n" | $EGREP '^(foo||bar)$'foo|bar`$EGREP' also suffers the limitations of `grep'.`expr'No `expr' keyword starts with `X', so use `expr X"WORD" :'XREGEX'' to keep `expr' from misinterpreting WORD.Don't use `length', `substr', `match' and `index'.`expr' (`|')You can use `|'. Although Posix does require that `expr '''return the empty string, it does not specify the result when you`|' together the empty string (or zero) with the empty string. Forexample:expr '' \| ''Posix 1003.2-1992 returns the empty string for this case, buttraditional Unix returns `0' (Solaris is one such example). InPosix 1003.1-2001, the specification was changed to matchtraditional Unix's behavior (which is bizarre, but it's too lateto fix this). Please note that the same problem does arise whenthe empty string results from a computation, as in:expr bar : foo \| foo : barAvoid this portability problem by avoiding the empty string.`expr' (`:')Portable `expr' regular expressions should use `\' to escape onlycharacters in the string `$()*.0123456789[\^n{}'. For example,alternation, `\|', is common but Posix does not require itssupport, so it should be avoided in portable scripts. Similarly,`\+' and `\?' should be avoided.Portable `expr' regular expressions should not begin with `^'.Patterns are automatically anchored so leading `^' is not neededanyway.The Posix standard is ambiguous as to whether `expr 'a' : '\(b\)''outputs `0' or the empty string. In practice, it outputs theempty string on most platforms, but portable scripts should notassume this. For instance, the QNX 4.25 native `expr' returns `0'.One might think that a way to get a uniform behavior would be touse the empty string as a default value:expr a : '\(b\)' \| ''Unfortunately this behaves exactly as the original expression; seethe `expr' (`|') entry for more information.Ancient `expr' implementations (e.g., SunOS 4 `expr' and Solaris 8`/usr/ucb/expr') have a silly length limit that causes `expr' tofail if the matched substring is longer than 120 bytes. In thiscase, you might want to fall back on `echo|sed' if `expr' fails.Nowadays this is of practical importance only for the rareinstaller who mistakenly puts `/usr/ucb' before `/usr/bin' in`PATH'.On Mac OS X 10.4, `expr' mishandles the pattern `[^-]' in somecases. For example, the commandexpr Xpowerpc-apple-darwin8.1.0 : 'X[^-]*-[^-]*-\(.*\)'outputs `apple-darwin8.1.0' rather than the correct `darwin8.1.0'.This particular case can be worked around by substituting `[^--]'for `[^-]'.Don't leave, there is some more!The QNX 4.25 `expr', in addition of preferring `0' to the emptystring, has a funny behavior in its exit status: it's always 1when parentheses are used!$ val=`expr 'a' : 'a'`; echo "$?: $val"0: 1$ val=`expr 'a' : 'b'`; echo "$?: $val"1: 0$ val=`expr 'a' : '\(a\)'`; echo "?: $val"1: a$ val=`expr 'a' : '\(b\)'`; echo "?: $val"1: 0In practice this can be a big problem if you are ready to catchfailures of `expr' programs with some other method (such as using`sed'), since you may get twice the result. For instance$ expr 'a' : '\(a\)' || echo 'a' | sed 's/^\(a\)$/\1/'outputs `a' on most hosts, but `aa' on QNX 4.25. A simpleworkaround consists of testing `expr' and using a variable set to`expr' or to `false' according to the result.Tru64 `expr' incorrectly treats the result as a number, if it canbe interpreted that way:$ expr 00001 : '.*\(...\)'1`fgrep'Posix 1003.1-2001 no longer requires `fgrep', but many older hostsdo not yet support the Posix replacement `grep -F'. Also, sometraditional implementations do not work on long input lines. Towork around these problems, invoke `AC_PROG_FGREP' and then use`$FGREP'.`find'The option `-maxdepth' seems to be GNU specific. Tru64 v5.1,NetBSD 1.5 and Solaris `find' commands do not understand it.The replacement of `{}' is guaranteed only if the argument isexactly _{}_, not if it's only a part of an argument. Forinstance on DU, and HP-UX 10.20 and HP-UX 11:$ touch foo$ find . -name foo -exec echo "{}-{}" \;{}-{}while GNU `find' reports `./foo-./foo'.`grep'Portable scripts can rely on the `grep' options `-c', `-l', `-n',and `-v', but should avoid other options. For example, don't use`-w', as Posix does not require it and Irix 6.5.16m's `grep' doesnot support it. Also, portable scripts should not combine `-c'with `-l', as Posix does not allow this.Some of the options required by Posix are not portable in practice.Don't use `grep -q' to suppress output, because many `grep'implementations (e.g., Solaris) do not support `-q'. Don't use`grep -s' to suppress output either, because Posix says `-s' doesnot suppress output, only some error messages; also, the `-s'option of traditional `grep' behaved like `-q' does in most modernimplementations. Instead, redirect the standard output andstandard error (in case the file doesn't exist) of `grep' to`/dev/null'. Check the exit status of `grep' to determine whetherit found a match.Some traditional `grep' implementations do not work on long inputlines. On AIX the default `grep' silently truncates long lines onthe input before matching.Also, many implementations do not support multiple regexps with`-e': they either reject `-e' entirely (e.g., Solaris) or honoronly the last pattern (e.g., IRIX 6.5 and NeXT). To work aroundthese problems, invoke `AC_PROG_GREP' and then use `$GREP'.Another possible workaround for the multiple `-e' problem is toseparate the patterns by newlines, for example:grep 'foobar' in.txtexcept that this fails with traditional `grep' implementations andwith OpenBSD 3.8 `grep'.Traditional `grep' implementations (e.g., Solaris) do not supportthe `-E' or `-F' options. To work around these problems, invoke`AC_PROG_EGREP' and then use `$EGREP', and similarly for`AC_PROG_FGREP' and `$FGREP'. Even if you are willing to requiresupport for Posix `grep', your script should not use both `-E' and`-F', since Posix does not allow this combination.Portable `grep' regular expressions should use `\' only to escapecharacters in the string `$()*.0123456789[\^{}'. For example,alternation, `\|', is common but Posix does not require itssupport in basic regular expressions, so it should be avoided inportable scripts. Solaris `grep' does not support it. Similarly,`\+' and `\?' should be avoided.`join'Solaris 8 `join' has bugs when the second operand is standardinput, and when standard input is a pipe. For example, thefollowing shell script causes Solaris 8 `join' to loop forever:cat >file <<'EOF'1 x2 yEOFcat file | join file -Use `join - file' instead.`ln'Don't rely on `ln' having a `-f' option. Symbolic links are notavailable on old systems; use `$(LN_S)' as a portable substitute.For versions of the DJGPP before 2.04, `ln' emulates symbolic linksto executables by generating a stub that in turn calls the realprogram. This feature also works with nonexistent files like inthe Posix spec. So `ln -s file link' generates `link.exe', whichattempts to call `file.exe' if run. But this feature only worksfor executables, so `cp -p' is used instead for these systems.DJGPP versions 2.04 and later have full support for symbolic links.`ls'The portable options are `-acdilrtu'. Current practice is for`-l' to output both owner and group, even though ancient versionsof `ls' omitted the group.On ancient hosts, `ls foo' sent the diagnostic `foo not found' tostandard output if `foo' did not exist. Hence a shell commandlike `sources=`ls *.c 2>/dev/null`' did not always work, since itwas equivalent to `sources='*.c not found'' in the absence of `.c'files. This is no longer a practical problem, since current `ls'implementations send diagnostics to standard error.`mkdir'No `mkdir' option is portable to older systems. Instead of `mkdir-p FILE-NAME', you should use `AS_MKDIR_P(FILE-NAME)' (*noteProgramming in M4sh::) or `AC_PROG_MKDIR_P' (*note ParticularPrograms::).Combining the `-m' and `-p' options, as in `mkdir -m go-w -p DIR',often leads to trouble. FreeBSD `mkdir' incorrectly attempts tochange the permissions of DIR even if it already exists. HP-UX11.23 and IRIX 6.5 `mkdir' often assign the wrong permissions toany newly-created parents of DIR.Posix does not clearly specify whether `mkdir -p foo' shouldsucceed when `foo' is a symbolic link to an already-existingdirectory. The GNU Core Utilities 5.1.0 `mkdir' succeeds, butSolaris `mkdir' fails.Traditional `mkdir -p' implementations suffer from race conditions.For example, if you invoke `mkdir -p a/b' and `mkdir -p a/c' atthe same time, both processes might detect that `a' is missing,one might create `a', then the other might try to create `a' andfail with a `File exists' diagnostic. The GNU Core Utilities(`fileutils' version 4.1), FreeBSD 5.0, NetBSD 2.0.2, and OpenBSD2.4 are known to be race-free when two processes invoke `mkdir -p'simultaneously, but earlier versions are vulnerable. Solaris`mkdir' is still vulnerable as of Solaris 10, and othertraditional Unix systems are probably vulnerable too. Thispossible race is harmful in parallel builds when several Makerules call `mkdir -p' to construct directories. You may use`install-sh -d' as a safe replacement, provided this script isrecent enough; the copy shipped with Autoconf 2.60 and Automake1.10 is OK, but copies from older versions are vulnerable.`mktemp'Shell scripts can use temporary files safely with `mktemp', but itdoes not exist on all systems. A portable way to create a safetemporary file name is to create a temporary directory with mode700 and use a file inside this directory. Both methods preventattackers from gaining control, though `mktemp' is far less likelyto fail gratuitously under attack.Here is sample code to create a new temporary directory safely:# Create a temporary directory $tmp in $TMPDIR (default /tmp).# Use mktemp if possible; otherwise fall back on mkdir,# with $RANDOM to make collisions less likely.: ${TMPDIR=/tmp}{tmp=`(umask 077 && mktemp -d "$TMPDIR/fooXXXXXX") 2>/dev/null` &&test -n "$tmp" && test -d "$tmp"} || {tmp=$TMPDIR/foo$$-$RANDOM(umask 077 && mkdir "$tmp")} || exit $?`mv'The only portable options are `-f' and `-i'.Moving individual files between file systems is portable (it wasin Unix version 6), but it is not always atomic: when doing `mvnew existing', there's a critical section where neither the oldnor the new version of `existing' actually exists.On some systems moving files from `/tmp' can sometimes causeundesirable (but perfectly valid) warnings, even if you createdthese files. This is because `/tmp' belongs to a group thatordinary users are not members of, and files created in `/tmp'inherit the group of `/tmp'. When the file is copied, `mv' issuesa diagnostic without failing:$ touch /tmp/foo$ mv /tmp/foo .error-->mv: ./foo: set owner/group (was: 100/0): Operation not permitted$ echo $?0$ ls foofooThis annoying behavior conforms to Posix, unfortunately.Moving directories across mount points is not portable, use `cp'and `rm'.DOS variants cannot rename or remove open files, and do notsupport commands like `mv foo bar >foo', even though this isperfectly portable among Posix hosts.`od'In Mac OS X 10.3, `od' does not support the standard Posix options`-A', `-j', `-N', or `-t', or the XSI option `-s'. The onlysupported Posix option is `-v', and the only supported XSI optionsare those in `-bcdox'. The BSD `hexdump' program can be usedinstead.This problem no longer exists in Mac OS X 10.4.3.`rm'The `-f' and `-r' options are portable.It is not portable to invoke `rm' without operands. For example,on many systems `rm -f -r' (with no other arguments) silentlysucceeds without doing anything, but it fails with a diagnostic onNetBSD 2.0.2.A file might not be removed even if its parent directory iswritable and searchable. Many Posix hosts cannot remove a mountpoint, a named stream, a working directory, or a last link to afile that is being executed.DOS variants cannot rename or remove open files, and do notsupport commands like `rm foo >foo', even though this is perfectlyportable among Posix hosts.`sed'Patterns should not include the separator (unless escaped), evenas part of a character class. In conformance with Posix, the Cray`sed' rejects `s/[^/]*$//': use `s,[^/]*$,,'.Avoid empty patterns within parentheses (i.e., `\(\)'). Posix doesnot require support for empty patterns, and Unicos 9 `sed' rejectsthem.Unicos 9 `sed' loops endlessly on patterns like `.*\n.*'.Sed scripts should not use branch labels longer than 8 charactersand should not contain comments. HP-UX sed has a limit of 99commands (not counting `:' commands) and 48 labels, which can notbe circumvented by using more than one script file. It canexecute up to 19 reads with the `r' command per cycle. Solaris`/usr/ucb/sed' rejects usages that exceed an limit of about 6000bytes for the internal representation of commands.Avoid redundant `;', as some `sed' implementations, such as NetBSD1.4.2's, incorrectly try to interpret the second `;' as a command:$ echo a | sed 's/x/x/;;s/x/x/'sed: 1: "s/x/x/;;s/x/x/": invalid command code ;Input should not have unreasonably long lines, since some `sed'implementations have an input buffer limited to 4000 bytes.Portable `sed' regular expressions should use `\' only to escapecharacters in the string `$()*.0123456789[\^n{}'. For example,alternation, `\|', is common but Posix does not require itssupport, so it should be avoided in portable scripts. Solaris`sed' does not support alternation; e.g., `sed '/a\|b/d'' deletesonly lines that contain the literal string `a|b'. Similarly, `\+'and `\?' should be avoided.Anchors (`^' and `$') inside groups are not portable.Nested parenthesization in patterns (e.g., `\(\(a*\)b*)\)') isquite portable to current hosts, but was not supported by someancient `sed' implementations like SVR3.Some `sed' implementations, e.g., Solaris, restrict the specialrole of the asterisk to one-character regular expressions. Thismay lead to unexpected behavior:$ echo '1*23*4' | /usr/bin/sed 's/\(.\)*/x/g'x2x4$ echo '1*23*4' | /usr/xpg4/bin/sed 's/\(.\)*/x/g'xThe `-e' option is portable, so long as its argument does notbegin with `a', `c', or `i' (as this runs afoul of a Tru64 5.1bug). Some people prefer to use `-e':sed -e 'COMMAND-1' \-e 'COMMAND-2'as opposed to the equivalent:sed 'COMMAND-1COMMAND-2'The following usage is sometimes equivalent:sed 'COMMAND-1;COMMAND-2'but Posix says that this use of a semicolon has undefined effect ifCOMMAND-1's verb is `{', `a', `b', `c', `i', `r', `t', `w', `:',or `#', so you should use semicolon only with simple scripts thatdo not use these verbs.Commands inside { } brackets are further restricted. Posix saysthat they cannot be preceded by addresses, `!', or `;', and thateach command must be followed immediately by a newline, without anyintervening blanks or semicolons. The closing bracket must bealone on a line, other than white space preceding or following it.Contrary to yet another urban legend, you may portably use `&' inthe replacement part of the `s' command to mean "what wasmatched". All descendants of Unix version 7 `sed' (at least; wedon't have first hand experience with older `sed' implementations)have supported it.Posix requires that you must not have any white space between `!'and the following command. It is OK to have blanks between theaddress and the `!'. For instance, on Solaris:$ echo "foo" | sed -n '/bar/ ! p'error-->Unrecognized command: /bar/ ! p$ echo "foo" | sed -n '/bar/! p'error-->Unrecognized command: /bar/! p$ echo "foo" | sed -n '/bar/ !p'fooPosix also says that you should not combine `!' and `;'. If youuse `!', it is best to put it on a command that is delimited bynewlines rather than `;'.Also note that Posix requires that the `b', `t', `r', and `w'commands be followed by exactly one space before their argument.On the other hand, no white space is allowed between `:' and thesubsequent label name.If a sed script is specified on the command line and ends in an`a', `c', or `i' command, the last line of inserted text should befollowed by a newline. Otherwise some `sed' implementations(e.g., OpenBSD 3.9) do not append a newline to the inserted text.Many `sed' implementations (e.g., MacOS X 10.4, OpenBSD 3.9,Solaris 10 `/usr/ucb/sed') strip leading white space from the textof `a', `c', and `i' commands. Prepend a backslash to work aroundthis incompatibility with Posix:$ echo flushleft | sed 'a\> indented> 'flushleftindented$ echo foo | sed 'a\> \ indented> 'flushleftindented`sed' (`t')Some old systems have `sed' that "forget" to reset their `t' flagwhen starting a new cycle. For instance on MIPS RISC/OS, and onIRIX 5.3, if you run the following `sed' script (the line numbersare not actual part of the texts):s/keep me/kept/g # at end # bs/.*/deleted/g # c:end # dondelete me # 1delete me # 2keep me # 3delete me # 4you getdeleteddelete mekeptdeletedinstead ofdeleteddeletedkeptdeletedWhy? When processing line 1, (c) matches, therefore sets the `t'flag, and the output is produced. When processing line 2, the `t'flag is still set (this is the bug). Command (a) fails to match,but `sed' is not supposed to clear the `t' flag when asubstitution fails. Command (b) sees that the flag is set,therefore it clears it, and jumps to (d), hence you get `delete me'instead of `deleted'. When processing line (3), `t' is clear, (a)matches, so the flag is set, hence (b) clears the flags and jumps.Finally, since the flag is clear, line 4 is processed properly.There are two things one should remember about `t' in `sed'.Firstly, always remember that `t' jumps if _some_ substitutionsucceeded, not only the immediately preceding substitution.Therefore, always use a fake `t clear' followed by a `:clear' onthe next line, to reset the `t' flag where needed.Secondly, you cannot rely on `sed' to clear the flag at each newcycle.One portable implementation of the script above is:t clear:clears/keep me/kept/gt ends/.*/deleted/g:end`touch'If you specify the desired timestamp (e.g., with the `-r' option),`touch' typically uses the `utime' or `utimes' system call, whichcan result in the same kind of timestamp truncation problems that`cp -p' has.On ancient BSD systems, `touch' or any command that results in anempty file does not update the timestamps, so use a command like`echo' as a workaround. Also, GNU `touch' 3.16r (and presumablyall before that) fails to work on SunOS 4.1.3 when the empty fileis on an NFS-mounted 4.2 volume. However, these problems are nolonger of practical concern.File: autoconf.info, Node: Portable Make, Next: Portable C and C++, Prev: Portable Shell, Up: Top11 Portable Make Programming****************************Writing portable makefiles is an art. Since a makefile's commands areexecuted by the shell, you must consider the shell portability issuesalready mentioned. However, other issues are specific to `make' itself.* Menu:* $< in Ordinary Make Rules:: $< in ordinary rules* Failure in Make Rules:: Failing portably in rules* Special Chars in Names:: Special Characters in Macro Names* Backslash-Newline-Newline:: Empty last lines in macro definitions* Backslash-Newline Comments:: Spanning comments across line boundaries* Long Lines in Makefiles:: Line length limitations* Macros and Submakes:: `make macro=value' and submakes* The Make Macro MAKEFLAGS:: `$(MAKEFLAGS)' portability issues* The Make Macro SHELL:: `$(SHELL)' portability issues* Comments in Make Rules:: Other problems with Make comments* obj/ and Make:: Don't name a subdirectory `obj'* make -k Status:: Exit status of `make -k'* VPATH and Make:: `VPATH' woes* Single Suffix Rules:: Single suffix rules and separated dependencies* Timestamps and Make:: Subsecond timestamp resolutionFile: autoconf.info, Node: $< in Ordinary Make Rules, Next: Failure in Make Rules, Up: Portable Make11.1 `$<' in Ordinary Make Rules================================Posix says that the `$<' construct in makefiles can be used only ininference rules and in the `.DEFAULT' rule; its meaning in ordinaryrules is unspecified. Solaris `make' for instance replaces it with theempty string. OpenBSD (3.0 and later) `make' diagnoses these uses anderrors out.File: autoconf.info, Node: Failure in Make Rules, Next: Special Chars in Names, Prev: $< in Ordinary Make Rules, Up: Portable Make11.2 Failure in Make Rules==========================Since 1992 Posix has required that `make' must invoke each command withthe equivalent of a `sh -c' subshell. However, many `make'implementations, including BSD make through 2004, use `sh -e -c'instead, and the `-e' option causes the subshell to exit immediately ifa subsidiary simple-command fails. For example, the command `touch T;rm -f U' always attempts to remove `U' with Posix make, but incompatible`make' implementations skip the `rm' if the `touch' fails. One way towork around this is to reword the affected simple-commands so that theyalways succeed, e.g., `touch T || :; rm -f U'. However, even thisapproach can run into common bugs in BSD implementations of the `-e'option of `sh' and `set' (*note Limitations of Builtins::), so if youare worried about porting to buggy BSD shells it may be simpler tomigrate complicated `make' actions into separate scripts.File: autoconf.info, Node: Special Chars in Names, Next: Backslash-Newline-Newline, Prev: Failure in Make Rules, Up: Portable Make11.3 Special Characters in Make Macro Names===========================================Posix limits macro names to nonempty strings containing only ASCIIletters and digits, `.', and `_'. Many `make' implementations allow awider variety of characters, but portable makefiles should avoid them.It is portable to start a name with a special character, e.g.,`$(.FOO)'.Some ancient `make' implementations don't support leadingunderscores in macro names. An example is NEWS-OS 4.2R.$ cat Makefile_am_include = #_am_quote =all:; @echo this is test$ makeMake: Must be a separator on rules line 2. Stop.$ cat Makefile2am_include = #am_quote =all:; @echo this is test$ make -f Makefile2this is testHowever, this problem is no longer of practical concern.File: autoconf.info, Node: Backslash-Newline-Newline, Next: Backslash-Newline Comments, Prev: Special Chars in Names, Up: Portable Make11.4 Backslash-Newline-Newline in Make Macro Values===================================================On some versions of HP-UX, `make' reads multiple newlines following abackslash, continuing to the next non-empty line. For example,FOO = one \BAR = twotest:: FOO is "$(FOO)": BAR is "$(BAR)"shows `FOO' equal to `one BAR = two'. Other implementations sensiblylet a backslash continue only to the immediately following line.File: autoconf.info, Node: Backslash-Newline Comments, Next: Long Lines in Makefiles, Prev: Backslash-Newline-Newline, Up: Portable Make11.5 Backslash-Newline in Make Comments=======================================According to Posix, Make comments start with `#' and continue until anunescaped newline is reached.$ cat Makefile# A = foo \bar \bazall:@echo ok$ make # GNU makeokHowever this is not always the case. Some implementations discardeverything from `#' through the end of the line, ignoring any trailingbackslash.$ pmake # BSD make"Makefile", line 3: Need an operatorFatal errors encountered -- cannot continueTherefore, if you want to comment out a multi-line definition, prefixeach line with `#', not only the first.# A = foo \# bar \# bazFile: autoconf.info, Node: Long Lines in Makefiles, Next: Macros and Submakes, Prev: Backslash-Newline Comments, Up: Portable Make11.6 Long Lines in Makefiles============================Tru64 5.1's `make' has been reported to crash when given a makefilewith lines longer than around 20 kB. Earlier versions are reported toexit with `Line too long' diagnostics.File: autoconf.info, Node: Macros and Submakes, Next: The Make Macro MAKEFLAGS, Prev: Long Lines in Makefiles, Up: Portable Make11.7 `make macro=value' and Submakes====================================A command-line variable definition such as `foo=bar' overrides anydefinition of `foo' in a makefile. Some `make' implementations (suchas GNU `make') propagate this override to subsidiary invocations of`make'. Some other implementations do not pass the substitution alongto submakes.$ cat Makefilefoo = fooone:@echo $(foo)$(MAKE) twotwo:@echo $(foo)$ make foo=bar # GNU make 3.79.1barmake twomake[1]: Entering directory `/home/adl'barmake[1]: Leaving directory `/home/adl'$ pmake foo=bar # BSD makebarpmake twofooYou have a few possibilities if you do want the `foo=bar' overrideto propagate to submakes. One is to use the `-e' option, which causesall environment variables to have precedence over the makefile macrodefinitions, and declare foo as an environment variable:$ env foo=bar make -eThe `-e' option is propagated to submakes automatically, and sincethe environment is inherited between `make' invocations, the `foo'macro is overridden in submakes as expected.This syntax (`foo=bar make -e') is portable only when used outsideof a makefile, for instance from a script or from the command line.When run inside a `make' rule, GNU `make' 3.80 and prior versionsforget to propagate the `-e' option to submakes.Moreover, using `-e' could have unexpected side effects if yourenvironment contains some other macros usually defined by the makefile.(See also the note about `make -e' and `SHELL' below.)Another way to propagate overrides to submakes is to do it manually,from your makefile:foo = fooone:@echo $(foo)$(MAKE) foo=$(foo) twotwo:@echo $(foo)You need to foresee all macros that a user might want to override ifyou do that.File: autoconf.info, Node: The Make Macro MAKEFLAGS, Next: The Make Macro SHELL, Prev: Macros and Submakes, Up: Portable Make11.8 The Make Macro MAKEFLAGS=============================Posix requires `make' to use `MAKEFLAGS' to affect the current andrecursive invocations of make, but allows implementations severalformats for the variable. It is tricky to parse `$MAKEFLAGS' todetermine whether `-s' for silent execution or `-k' for continuedexecution are in effect. For example, you cannot assume that the firstspace-separated word in `$MAKEFLAGS' contains single-letter options,since in the Cygwin version of GNU `make' it is either `--unix' or`--win32' with the second word containing single-letter options.$ cat Makefileall:@echo MAKEFLAGS = $(MAKEFLAGS)$ makeMAKEFLAGS = --unix$ make -kMAKEFLAGS = --unix -kFile: autoconf.info, Node: The Make Macro SHELL, Next: Comments in Make Rules, Prev: The Make Macro MAKEFLAGS, Up: Portable Make11.9 The Make Macro `SHELL'===========================Posix-compliant `make' internally uses the `$(SHELL)' macro to spawnshell processes and execute Make rules. This is a builtin macrosupplied by `make', but it can be modified by a makefile or by acommand-line argument.Not all `make' implementations define this `SHELL' macro. Tru64`make' is an example; this implementation always uses `/bin/sh'. Soit's a good idea to always define `SHELL' in your makefiles. If youuse Autoconf, doSHELL = @SHELL@Do not force `SHELL = /bin/sh' because that is not correcteverywhere. For instance DJGPP lacks `/bin/sh', and when its GNU`make' port sees such a setting it enters a special emulation modewhere features like pipes and redirections are emulated on top of DOS's`command.com'. Unfortunately this emulation is incomplete; forinstance it does not handle command substitutions. On DJGPP `SHELL'should point to Bash.Posix-compliant `make' should never acquire the value of $(SHELL)from the environment, even when `make -e' is used (otherwise, thinkabout what would happen to your rules if `SHELL=/bin/tcsh').However not all `make' implementations have this exception. Forinstance it's not surprising that Tru64 `make' doesn't protect `SHELL',since it doesn't use it.$ cat MakefileSHELL = /bin/shFOO = fooall:@echo $(SHELL)@echo $(FOO)$ env SHELL=/bin/tcsh FOO=bar make -e # Tru64 Make/bin/tcshbar$ env SHELL=/bin/tcsh FOO=bar gmake -e # GNU make/bin/shbarFile: autoconf.info, Node: Comments in Make Rules, Next: obj/ and Make, Prev: The Make Macro SHELL, Up: Portable Make11.10 Comments in Make Rules============================Never put comments in a rule.Some `make' treat anything starting with a tab as a command for thecurrent rule, even if the tab is immediately followed by a `#'. The`make' from Tru64 Unix V5.1 is one of them. The following makefileruns `# foo' through the shell.all:# fooFile: autoconf.info, Node: obj/ and Make, Next: make -k Status, Prev: Comments in Make Rules, Up: Portable Make11.11 The `obj/' Subdirectory and Make======================================Never name one of your subdirectories `obj/' if you don't likesurprises.If an `obj/' directory exists, BSD `make' enters it before readingthe makefile. Hence the makefile in the current directory is not read.$ cat Makefileall:echo Hello$ cat obj/Makefileall:echo World$ make # GNU makeecho HelloHello$ pmake # BSD makeecho WorldWorldFile: autoconf.info, Node: make -k Status, Next: VPATH and Make, Prev: obj/ and Make, Up: Portable Make11.12 Exit Status of `make -k'==============================Do not rely on the exit status of `make -k'. Some implementationsreflect whether they encountered an error in their exit status; otherimplementations always succeed.$ cat Makefileall:false$ make -k; echo exit status: $? # GNU makefalsemake: *** [all] Error 1exit status: 2$ pmake -k; echo exit status: $? # BSD makefalse*** Error code 1 (continuing)exit status: 0File: autoconf.info, Node: VPATH and Make, Next: Single Suffix Rules, Prev: make -k Status, Up: Portable Make11.13 `VPATH' and Make======================Posix does not specify the semantics of `VPATH'. Typically, `make'supports `VPATH', but its implementation is not consistent.Autoconf and Automake support makefiles whose usages of `VPATH' areportable to recent-enough popular implementations of `make', but tokeep the resulting makefiles portable, a package's makefile prototypesmust take the following issues into account. These issues arecomplicated and are often poorly understood, and installers who use`VPATH' should expect to find many bugs in this area. If you use`VPATH', the simplest way to avoid these portability bugs is to stickwith GNU `make', since it is the most commonly-used `make' amongAutoconf users.Here are some known issues with some `VPATH' implementations.* Menu:* VPATH and Double-colon:: Problems with `::' on ancient hosts* $< in Explicit Rules:: `$<' does not work in ordinary rules* Automatic Rule Rewriting:: `VPATH' goes wild on Solaris* Tru64 Directory Magic:: `mkdir' goes wild on Tru64* Make Target Lookup:: More details about `VPATH' lookupFile: autoconf.info, Node: VPATH and Double-colon, Next: $< in Explicit Rules, Up: VPATH and Make11.13.1 `VPATH' and Double-colon Rules--------------------------------------With ancient versions of Sun `make', any assignment to `VPATH' causes`make' to execute only the first set of double-colon rules. However,this problem is no longer of practical concern.File: autoconf.info, Node: $< in Explicit Rules, Next: Automatic Rule Rewriting, Prev: VPATH and Double-colon, Up: VPATH and Make11.13.2 `$<' Not Supported in Explicit Rules--------------------------------------------Using `$<' in explicit rules is not portable. The prerequisite filemust be named explicitly in the rule. If you want to find theprerequisite via a `VPATH' search, you have to code the whole thingmanually. *Note Build Directories::.File: autoconf.info, Node: Automatic Rule Rewriting, Next: Tru64 Directory Magic, Prev: $< in Explicit Rules, Up: VPATH and Make11.13.3 Automatic Rule Rewriting--------------------------------Some `make' implementations, such as Solaris and Tru64, search forprerequisites in `VPATH' and then rewrite each occurrence as a plainword in the rule. For instance:# This isn't portable to GNU make.VPATH = ../pkg/srcf.c: if.ccp if.c f.cexecutes `cp ../pkg/src/if.c f.c' if `if.c' is found in `../pkg/src'.However, this rule leads to real problems in practice. For example,if the source directory contains an ordinary file named `test' that isused in a dependency, Solaris `make' rewrites commands like `if test -rfoo; ...' to `if ../pkg/src/test -r foo; ...', which is typicallyundesirable. To avoid this problem, portable makefiles should nevermention a source file whose name is that of a shell keyword like`until' or a shell command like `cat' or `gcc' or `test'.Because of these problems GNU `make' and many other `make'implementations do not rewrite commands, so portable makefiles shouldsearch `VPATH' manually. It is tempting to write this:# This isn't portable to Solaris make.VPATH = ../pkg/srcf.c: if.ccp `test -f if.c || echo $(VPATH)/`if.c f.cHowever, the "prerequisite rewriting" still applies here. So if `if.c'is in `../pkg/src', Solaris and Tru64 `make' executecp `test -f ../pkg/src/if.c || echo ../pkg/src/`if.c f.cwhich reduces tocp if.c f.cand thus fails. Oops.A simple workaround, and good practice anyway, is to use `$?' and`$@' when possible:VPATH = ../pkg/srcf.c: if.ccp $? $@but this does not generalize well to commands with multipleprerequisites. A more general workaround is to rewrite the rule so thatthe prerequisite `if.c' never appears as a plain word. For example,these three rules would be safe, assuming `if.c' is in `../pkg/src' andthe other files are in the working directory:VPATH = ../pkg/srcf.c: if.c f1.ccat `test -f ./if.c || echo $(VPATH)/`if.c f1.c >$@g.c: if.c g1.ccat `test -f 'if.c' || echo $(VPATH)/`if.c g1.c >$@h.c: if.c h1.ccat `test -f "if.c" || echo $(VPATH)/`if.c h1.c >$@Things get worse when your prerequisites are in a macro.VPATH = ../pkg/srcHEADERS = f.h g.h h.hinstall-HEADERS: $(HEADERS)for i in $(HEADERS); do \$(INSTALL) -m 644 \`test -f $$i || echo $(VPATH)/`$$i \$(DESTDIR)$(includedir)/$$i; \doneThe above `install-HEADERS' rule is not Solaris-proof because `for iin $(HEADERS);' is expanded to `for i in f.h g.h h.h;' where `f.h' and`g.h' are plain words and are hence subject to `VPATH' adjustments.If the three files are in `../pkg/src', the rule is run as:for i in ../pkg/src/f.h ../pkg/src/g.h h.h; do \install -m 644 \`test -f $i || echo ../pkg/src/`$i \/usr/local/include/$i; \donewhere the two first `install' calls fail. For instance, considerthe `f.h' installation:install -m 644 \`test -f ../pkg/src/f.h || \echo ../pkg/src/ \`../pkg/src/f.h \/usr/local/include/../pkg/src/f.h;It reduces to:install -m 644 \../pkg/src/f.h \/usr/local/include/../pkg/src/f.h;Note that the manual `VPATH' search did not cause any problems here;however this command installs `f.h' in an incorrect directory.Trying to quote `$(HEADERS)' in some way, as we did for `foo.c' afew makefiles ago, does not help:install-HEADERS: $(HEADERS)headers='$(HEADERS)'; \for i in $$headers; do \$(INSTALL) -m 644 \`test -f $$i || echo $(VPATH)/`$$i \$(DESTDIR)$(includedir)/$$i; \doneNow, `headers='$(HEADERS)'' macroexpands to:headers='f.h g.h h.h'but `g.h' is still a plain word. (As an aside, the idiom`headers='$(HEADERS)'; for i in $$headers;' is a good idea if`$(HEADERS)' can be empty, because some shells diagnose a syntax erroron `for i in;'.)One workaround is to strip this unwanted `../pkg/src/' prefixmanually:VPATH = ../pkg/srcHEADERS = f.h g.h h.hinstall-HEADERS: $(HEADERS)headers='$(HEADERS)'; \for i in $$headers; do \i=`expr "$$i" : '$(VPATH)/\(.*\)'`;$(INSTALL) -m 644 \`test -f $$i || echo $(VPATH)/`$$i \$(DESTDIR)$(includedir)/$$i; \doneAutomake does something similar. However the above hack works onlyif the files listed in `HEADERS' are in the current directory or asubdirectory; they should not be in an enclosing directory. If we had`HEADERS = ../f.h', the above fragment would fail in a VPATH build withTru64 `make'. The reason is that not only does Tru64 `make' rewritedependencies, but it also simplifies them. Hence `../f.h' becomes`../pkg/f.h' instead of `../pkg/src/../f.h'. This obviously defeatsany attempt to strip a leading `../pkg/src/' component.The following example makes the behavior of Tru64 `make' moreapparent.$ cat MakefileVPATH = suball: ../fooecho ../foo$ lsMakefile foo$ makeecho foofooDependency `../foo' was found in `sub/../foo', but Tru64 `make'simplified it as `foo'. (Note that the `sub/' directory does not evenexist, this just means that the simplification occurred before the filewas checked for.)For the record here is how SunOS 4 `make' behaves on this example.$ makemake: Fatal error: Don't know how to make target `../foo'$ mkdir sub$ makeecho sub/../foosub/../fooFile: autoconf.info, Node: Tru64 Directory Magic, Next: Make Target Lookup, Prev: Automatic Rule Rewriting, Up: VPATH and Make11.13.4 Tru64 `make' Creates Prerequisite Directories Magically---------------------------------------------------------------When a prerequisite is a subdirectory of `VPATH', Tru64 `make' createsit in the current directory.$ mkdir -p foo/bar build$ cd build$ cat >Makefile <<ENDVPATH = ..all: foo/barEND$ makemkdir foomkdir foo/barThis can yield unexpected results if a rule uses a manual `VPATH'search as presented before.VPATH = ..all : foo/barcommand `test -d foo/bar || echo ../`foo/barThe above `command' is run on the empty `foo/bar' directory that wascreated in the current directory.File: autoconf.info, Node: Make Target Lookup, Prev: Tru64 Directory Magic, Up: VPATH and Make11.13.5 Make Target Lookup--------------------------GNU `make' uses a complex algorithm to decide when it should use filesfound via a `VPATH' search. *Note How Directory Searches arePerformed: (make)Search Algorithm.If a target needs to be rebuilt, GNU `make' discards the file namefound during the `VPATH' search for this target, and builds the filelocally using the file name given in the makefile. If a target doesnot need to be rebuilt, GNU `make' uses the file name found during the`VPATH' search.Other `make' implementations, like NetBSD `make', are easier todescribe: the file name found during the `VPATH' search is used whetherthe target needs to be rebuilt or not. Therefore new files are createdlocally, but existing files are updated at their `VPATH' location.OpenBSD and FreeBSD `make', however, never perform a `VPATH' searchfor a dependency that has an explicit rule. This is extremely annoying.When attempting a `VPATH' build for an autoconfiscated package(e.g., `mkdir build && cd build && ../configure'), this means GNU`make' builds everything locally in the `build' directory, while BSD`make' builds new files locally and updates existing files in thesource directory.$ cat MakefileVPATH = ..all: foo.x bar.xfoo.x bar.x: newer.x@echo Building $@$ touch ../bar.x$ touch ../newer.x$ make # GNU makeBuilding foo.xBuilding bar.x$ pmake # NetBSD makeBuilding foo.xBuilding ../bar.x$ fmake # FreeBSD make, OpenBSD makeBuilding foo.xBuilding bar.x$ tmake # Tru64 makeBuilding foo.xBuilding bar.x$ touch ../bar.x$ make # GNU makeBuilding foo.x$ pmake # NetBSD makeBuilding foo.x$ fmake # FreeBSD make, OpenBSD makeBuilding foo.xBuilding bar.x$ tmake # Tru64 makeBuilding foo.xBuilding bar.xNote how NetBSD `make' updates `../bar.x' in its VPATH location, andhow FreeBSD, OpenBSD, and Tru64 `make' always update `bar.x', even when`../bar.x' is up to date.Another point worth mentioning is that once GNU `make' has decidedto ignore a `VPATH' file name (e.g., it ignored `../bar.x' in the aboveexample) it continues to ignore it when the target occurs as aprerequisite of another rule.The following example shows that GNU `make' does not look up `bar.x'in `VPATH' before performing the `.x.y' rule, because it ignored the`VPATH' result of `bar.x' while running the `bar.x: newer.x' rule.$ cat MakefileVPATH = ..all: bar.ybar.x: newer.x@echo Building $@.SUFFIXES: .x .y.x.y:cp $< $@$ touch ../bar.x$ touch ../newer.x$ make # GNU makeBuilding bar.xcp bar.x bar.ycp: cannot stat `bar.x': No such file or directorymake: *** [bar.y] Error 1$ pmake # NetBSD makeBuilding ../bar.xcp ../bar.x bar.y$ rm bar.y$ fmake # FreeBSD make, OpenBSD makeecho Building bar.xcp bar.x bar.ycp: cannot stat `bar.x': No such file or directory*** Error code 1$ tmake # Tru64 makeBuilding bar.xcp: bar.x: No such file or directory*** Exit 1Note that if you drop away the command from the `bar.x: newer.x'rule, GNU `make' magically starts to work: it knows that `bar.x' hasn'tbeen updated, therefore it doesn't discard the result from `VPATH'(`../bar.x') in succeeding uses. Tru64 also works, but FreeBSD andOpenBSD still don't.$ cat MakefileVPATH = ..all: bar.ybar.x: newer.x.SUFFIXES: .x .y.x.y:cp $< $@$ touch ../bar.x$ touch ../newer.x$ make # GNU makecp ../bar.x bar.y$ rm bar.y$ pmake # NetBSD makecp ../bar.x bar.y$ rm bar.y$ fmake # FreeBSD make, OpenBSD makecp bar.x bar.ycp: cannot stat `bar.x': No such file or directory*** Error code 1$ tmake # Tru64 makecp ../bar.x bar.yIt seems the sole solution that would please every `make'implementation is to never rely on `VPATH' searches for targets. Inother words, `VPATH' should be reserved to unbuilt sources.File: autoconf.info, Node: Single Suffix Rules, Next: Timestamps and Make, Prev: VPATH and Make, Up: Portable Make11.14 Single Suffix Rules and Separated Dependencies====================================================A "Single Suffix Rule" is basically a usual suffix (inference) rule(`.from.to:'), but which _destination_ suffix is empty (`.from:')."Separated dependencies" simply refers to listing the prerequisiteof a target, without defining a rule. Usually one can list on the onehand side, the rules, and on the other hand side, the dependencies.Solaris `make' does not support separated dependencies for targetsdefined by single suffix rules:$ cat Makefile.SUFFIXES: .infoo: foo.in.in:cp $< $@$ touch foo.in$ make$ lsMakefile foo.inwhile GNU Make does:$ gmakecp foo.in foo$ lsMakefile foo foo.inNote it works without the `foo: foo.in' dependency.$ cat Makefile.SUFFIXES: .in.in:cp $< $@$ make foocp foo.in fooand it works with double suffix inference rules:$ cat Makefilefoo.out: foo.in.SUFFIXES: .in .out.in.out:cp $< $@$ makecp foo.in foo.outAs a result, in such a case, you have to write target rules.File: autoconf.info, Node: Timestamps and Make, Prev: Single Suffix Rules, Up: Portable Make11.15 Timestamp Resolution and Make===================================Traditionally, file timestamps had 1-second resolution, and `make' usedthose timestamps to determine whether one file was newer than theother. However, many modern file systems have timestamps with1-nanosecond resolution. Some `make' implementations look at theentire timestamp; others ignore the fractional part, which can lead toincorrect results. Normally this is not a problem, but in some extremecases you may need to use tricks like `sleep 1' to work aroundtimestamp truncation bugs.Commands like `cp -p' and `touch -r' typically do not copy filetimestamps to their full resolutions (*note Limitations of UsualTools::). Hence you should be wary of rules like this:dest: srccp -p src destas `dest' often appears to be older than `src' after the timestampis truncated, and this can cause `make' to do needless rework the nexttime it is invoked. To work around this problem, you can use atimestamp file, e.g.:dest-stamp: srccp -p src destdate >dest-stampFile: autoconf.info, Node: Portable C and C++, Next: Manual Configuration, Prev: Portable Make, Up: Top12 Portable C and C++ Programming*********************************C and C++ programs often use low-level features of the underlyingsystem, and therefore are often more difficult to make portable to otherplatforms.Several standards have been developed to help make your programs moreportable. If you write programs with these standards in mind, you canhave greater confidence that your programs work on a wide variety ofsystems. *Note Language Standards Supported by GCC: (gcc)Standards,for a list of C-related standards. Many programs also assume the Posixstandard (http://www.opengroup.org/susv3).Some old code is written to be portable to K&R C, which predates anyC standard. K&R C compilers are no longer of practical interest,though, and the rest of section assumes at least C89, the first Cstandard.Program portability is a huge topic, and this section can onlybriefly introduce common pitfalls. *Note Portability between SystemTypes: (standards)System Portability, for more information.* Menu:* Varieties of Unportability:: How to make your programs unportable* Integer Overflow:: When integers get too large* Null Pointers:: Properties of null pointers* Buffer Overruns:: Subscript errors and the like* Volatile Objects:: `volatile' and signals* Floating Point Portability:: Portable floating-point arithmetic* Exiting Portably:: Exiting and the exit statusFile: autoconf.info, Node: Varieties of Unportability, Next: Integer Overflow, Up: Portable C and C++12.1 Varieties of Unportability===============================Autoconf tests and ordinary programs often need to test what is allowedon a system, and therefore they may need to deliberately exceed theboundaries of what the standards allow, if only to see whether anoptional feature is present. When you write such a program, you shouldkeep in mind the difference between constraints, unspecified behavior,and undefined behavior.In C, a "constraint" is a rule that the compiler must enforce. Anexample constraint is that C programs must not declare a bit-field withnegative width. Tests can therefore reliably assume that programs withnegative-width bit-fields are rejected by a compiler that conforms tothe standard."Unspecified behavior" is valid behavior, where the standard allowsmultiple possibilities. For example, the order of evaluation offunction arguments is unspecified. Some unspecified behavior is"implementation-defined", i.e., documented by the implementation, butsince Autoconf tests cannot read the documentation they cannotdistinguish between implementation-defined and other unspecifiedbehavior. It is common for Autoconf tests to probe implementations todetermine otherwise-unspecified behavior."Undefined behavior" is invalid behavior, where the standard allowsthe implementation to do anything it pleases. For example,dereferencing a null pointer leads to undefined behavior. If possible,test programs should avoid undefined behavior, since a program withundefined behavior might succeed on a test that should fail.The above rules apply to programs that are intended to conform to thestandard. However, strictly-conforming programs are quite rare, sincethe standards are so limiting. A major goal of Autoconf is to supportprograms that use implementation features not described by the standard,and it is fairly common for test programs to violate the above rules, ifthe programs work well enough in practice.File: autoconf.info, Node: Integer Overflow, Next: Null Pointers, Prev: Varieties of Unportability, Up: Portable C and C++12.2 Integer Overflow=====================In C, signed integer overflow leads to undefined behavior. However,many programs and Autoconf tests assume that signed integer overflowafter addition, subtraction, or multiplication silently wraps aroundmodulo a power of two, using two's complement arithmetic, so long asyou cast the resulting value to an integer type or store it into aninteger variable. Such programs are portable to the vast majority ofmodern platforms. However, signed integer division is not alwaysharmless: for example, on CPUs of the i386 family, dividing `INT_MIN'by `-1' yields a SIGFPE signal which by default terminates the program.Worse, taking the remainder of these two values typically yields thesame signal on these CPUs, even though the C standard requires `INT_MIN% -1' to yield zero because the expression does not overflow.GCC users might consider using the `-ftrapv' option if they areworried about porting their code to the rare platforms where signedinteger overflow does not wrap around after addition, subtraction, ormultiplication.Unsigned integer overflow reliably wraps around modulo the word size.This is guaranteed by the C standard and is portable in practice.File: autoconf.info, Node: Null Pointers, Next: Buffer Overruns, Prev: Integer Overflow, Up: Portable C and C++12.3 Properties of Null Pointers================================Most modern hosts reliably fail when you attempt to dereference a nullpointer.On almost all modern hosts, null pointers use an all-bits-zerointernal representation, so you can reliably use `memset' with 0 to setall the pointers in an array to null values.If `p' is a null pointer to an object type, the C expression `p + 0'always evaluates to `p' on modern hosts, even though the standard saysthat it has undefined behavior.File: autoconf.info, Node: Buffer Overruns, Next: Volatile Objects, Prev: Null Pointers, Up: Portable C and C++12.4 Buffer Overruns and Subscript Errors=========================================Buffer overruns and subscript errors are the most common dangerouserrors in C programs. They result in undefined behavior because storingoutside an array typically modifies storage that is used by some otherobject, and most modern systems lack runtime checks to catch theseerrors. Programs should not rely on buffer overruns being caught.There is one exception to the usual rule that a portable programcannot address outside an array. In C, it is valid to compute theaddress just past an object, e.g., `&a[N]' where `a' has `N' elements,so long as you do not dereference the resulting pointer. But it is notvalid to compute the address just before an object, e.g., `&a[-1]'; noris it valid to compute two past the end, e.g., `&a[N+1]'. On mostplatforms `&a[-1] < &a[0] && &a[N] < &a[N+1]', but this is not reliablein general, and it is usually easy enough to avoid the potentialportability problem, e.g., by allocating an extra unused array elementat the start or end.Valgrind (http://valgrind.org/) can catch many overruns. GCC usersmight also consider using the `-fmudflap' option to catch overruns.Buffer overruns are usually caused by off-by-one errors, but thereare more subtle ways to get them.Using `int' values to index into an array or compute array sizescauses problems on typical 64-bit hosts where an array index might be2^31 or larger. Index values of type `size_t' avoid this problem, butcannot be negative. Index values of type `ptrdiff_t' are signed, andare wide enough in practice.If you add or multiply two numbers to calculate an array size, e.g.,`malloc (x * sizeof y + z)', havoc ensues if the addition ormultiplication overflows.Many implementations of the `alloca' function silently misbehave andcan generate buffer overflows if given sizes that are too large. Thesize limits are implementation dependent, but are at least 4000 byteson all platforms that we know about.The standard functions `asctime', `asctime_r', `ctime', `ctime_r',and `gets' are prone to buffer overflows, and portable code should notuse them unless the inputs are known to be within certain limits. Thetime-related functions can overflow their buffers if given timestampsout of range (e.g., a year less than -999 or greater than 9999).Time-related buffer overflows cannot happen with recent-enough versionsof the GNU C library, but are possible with other implementations. The`gets' function is the worst, since it almost invariably overflows itsbuffer when presented with an input line larger than the buffer.File: autoconf.info, Node: Volatile Objects, Next: Floating Point Portability, Prev: Buffer Overruns, Up: Portable C and C++12.5 Volatile Objects=====================The keyword `volatile' is often misunderstood in portable code. Itsuse inhibits some memory-access optimizations, but programmers oftenwish that it had a different meaning than it actually does.`volatile' was designed for code that accesses special objects likememory-mapped device registers whose contents spontaneously change.Such code is inherently low-level, and it is difficult to specifyportably what `volatile' means in these cases. The C standard says,"What constitutes an access to an object that has volatile-qualifiedtype is implementation-defined," so in theory each implementation issupposed to fill in the gap by documenting what `volatile' means forthat implementation. In practice, though, this documentation isusually absent or incomplete.One area of confusion is the distinction between objects defined withvolatile types, and volatile lvalues. From the C standard's point ofview, an object defined with a volatile type has externally visiblebehavior. You can think of such objects as having little oscilloscopeprobes attached to them, so that the user can observe some properties ofaccesses to them, just as the user can observe data written to outputfiles. However, the standard does not make it clear whether users canobserve accesses by volatile lvalues to ordinary objects. For example:/* Declare and access a volatile object.Accesses to X are "visible" to users. */static int volatile x;x = 1;/* Access two ordinary objects via a volatile lvalue.It's not clear whether accesses to *P are "visible". */int y;int *z = malloc (sizeof (int));int volatile *p;p = &y;*p = 1;p = z;*p = 1;Programmers often wish that `volatile' meant "Perform the memoryaccess here and now, without merging several memory accesses, withoutchanging the memory word size, and without reordering." But the Cstandard does not require this. For objects defined with a volatiletype, accesses must be done before the next sequence point; butotherwise merging, reordering, and word-size change is allowed. Worse,it is not clear from the standard whether volatile lvalues provide moreguarantees in general than nonvolatile lvalues, if the underlyingobjects are ordinary.Even when accessing objects defined with a volatile type, the Cstandard allows only extremely limited signal handlers: the behavior isundefined if a signal handler reads any nonlocal object, or writes toany nonlocal object whose type is not `sig_atomic_t volatile', or callsany standard library function other than `abort', `signal', and (if C99)`_Exit'. Hence C compilers need not worry about a signal handlerdisturbing ordinary computation, unless the computation accesses a`sig_atomic_t volatile' lvalue that is not a local variable. (There isan obscure exception for accesses via a pointer to a volatilecharacter, since it may point into part of a `sig_atomic_t volatile'object.) Posix adds to the list of library functions callable from aportable signal handler, but otherwise is like the C standard in thisarea.Some C implementations allow memory-access optimizations within eachtranslation unit, such that actual behavior agrees with the behaviorrequired by the standard only when calling a function in some othertranslation unit, and a signal handler acts like it was called from adifferent translation unit. The C standard hints that in theseimplementations, objects referred to by signal handlers "would requireexplicit specification of `volatile' storage, as well as otherimplementation-defined restrictions." But unfortunately even for thisspecial case these other restrictions are often not documented well.*Note When is a Volatile Object Accessed?: (gcc)Volatiles, for somerestrictions imposed by GCC. *Note Defining Signal Handlers:(libc)Defining Handlers, for some restrictions imposed by the GNU Clibrary. Restrictions differ on other platforms.If possible, it is best to use a signal handler that fits within thelimits imposed by the C and Posix standards.If this is not practical, you can try the following rules of thumb.A signal handler should access only volatile lvalues, preferably lvaluesthat refer to objects defined with a volatile type, and should notassume that the accessed objects have an internally consistent state ifthey are larger than a machine word. Furthermore, installers shouldemploy compilers and compiler options that are commonly used forbuilding operating system kernels, because kernels often need more from`volatile' than the C Standard requires, and installers who compile anapplication in a similar environment can sometimes benefit from theextra constraints imposed by kernels on compilers. Admittedly we arehandwaving somewhat here, as there are few guarantees in this area; therules of thumb may help to fix some bugs but there is a good chancethat they will not fix them all.For `volatile', C++ has the same problems that C does.Multithreaded applications have even more problems with `volatile', butthey are beyond the scope of this section.The bottom line is that using `volatile' typically hurts performancebut should not hurt correctness. In some cases its use does helpcorrectness, but these cases are often so poorly understood that alltoo often adding `volatile' to a data structure merely alleviates somesymptoms of a bug while not fixing the bug in general.File: autoconf.info, Node: Floating Point Portability, Next: Exiting Portably, Prev: Volatile Objects, Up: Portable C and C++12.6 Floating Point Portability===============================Almost all modern systems use IEEE-754 floating point, and it is safe toassume IEEE-754 in most portable code these days. For more information,please see David Goldberg's classic paper What Every Computer ScientistShould Know About Floating-Point Arithmetic(http://www.validlab.com/goldberg/paper.pdf).File: autoconf.info, Node: Exiting Portably, Prev: Floating Point Portability, Up: Portable C and C++12.7 Exiting Portably=====================A C or C++ program can exit with status N by returning N from the`main' function. Portable programs are supposed to exit either withstatus 0 or `EXIT_SUCCESS' to succeed, or with status `EXIT_FAILURE' tofail, but in practice it is portable to fail by exiting with status 1,and test programs that assume Posix can fail by exiting with statusvalues from 1 through 255. Programs on SunOS 2.0 (1985) through 3.5.2(1988) incorrectly exited with zero status when `main' returnednonzero, but ancient systems like these are no longer of practicalconcern.A program can also exit with status N by passing N to the `exit'function, and a program can fail by calling the `abort' function. If aprogram is specialized to just some platforms, it can fail by callingfunctions specific to those platforms, e.g., `_exit' (Posix) and`_Exit' (C99). However, like other functions, an exit function shouldbe declared, typically by including a header. For example, if a Cprogram calls `exit', it should include `stdlib.h' either directly orvia the default includes (*note Default Includes::).A program can fail due to undefined behavior such as dereferencing anull pointer, but this is not recommended as undefined behavior allowsan implementation to do whatever it pleases and this includes exitingsuccessfully.File: autoconf.info, Node: Manual Configuration, Next: Site Configuration, Prev: Portable C and C++, Up: Top13 Manual Configuration***********************A few kinds of features can't be guessed automatically by running testprograms. For example, the details of the object-file format, orspecial options that need to be passed to the compiler or linker. Youcan check for such features using ad-hoc means, such as having`configure' check the output of the `uname' program, or looking forlibraries that are unique to particular systems. However, Autoconfprovides a uniform method for handling unguessable features.* Menu:* Specifying Names:: Specifying the system type* Canonicalizing:: Getting the canonical system type* Using System Type:: What to do with the system typeFile: autoconf.info, Node: Specifying Names, Next: Canonicalizing, Up: Manual Configuration13.1 Specifying the System Type===============================Like other GNU `configure' scripts, Autoconf-generated `configure'scripts can make decisions based on a canonical name for the systemtype, which has the form: `CPU-VENDOR-OS', where OS can be `SYSTEM' or`KERNEL-SYSTEM'`configure' can usually guess the canonical name for the type ofsystem it's running on. To do so it runs a script called`config.guess', which infers the name using the `uname' command orsymbols predefined by the C preprocessor.Alternately, the user can specify the system type with command linearguments to `configure'. Doing so is necessary when cross-compiling.In the most complex case of cross-compiling, three system types areinvolved. The options to specify them are:`--build=BUILD-TYPE'the type of system on which the package is being configured andcompiled. It defaults to the result of running `config.guess'.`--host=HOST-TYPE'the type of system on which the package runs. By default it is thesame as the build machine. Specifying it enables thecross-compilation mode.`--target=TARGET-TYPE'the type of system for which any compiler tools in the packageproduce code (rarely needed). By default, it is the same as host.If you mean to override the result of `config.guess', use `--build',not `--host', since the latter enables cross-compilation. Forhistorical reasons, passing `--host' also changes the build type.Therefore, whenever you specify `--host', be sure to specify `--build'too; this will be fixed in the future. So, to enter cross-compilationmode, use a command like this./configure --build=i686-pc-linux-gnu --host=m68k-coffNote that if you do not specify `--host', `configure' fails if it can'trun the code generated by the specified compiler. For example,configuring as follows fails:./configure CC=m68k-coff-gccIn the future, when cross-compiling Autoconf will _not_ accept tools(compilers, linkers, assemblers) whose name is not prefixed with thehost type. The only case when this may be useful is when you reallyare not cross-compiling, but only building for aleast-common-denominator architecture: an example is building for`i386-pc-linux-gnu' while running on an `i686-pc-linux-gnu'architecture. In this case, some particular pairs might be similarenough to let you get away with the system compilers, but in generalthe compiler might make bogus assumptions on the host: if you know whatyou are doing, please create symbolic links from the host compiler tothe build compiler.`configure' recognizes short aliases for many system types; forexample, `decstation' can be used instead of `mips-dec-ultrix4.2'.`configure' runs a script called `config.sub' to canonicalize systemtype aliases.This section deliberately omits the description of the obsoleteinterface; see *Note Hosts and Cross-Compilation::.File: autoconf.info, Node: Canonicalizing, Next: Using System Type, Prev: Specifying Names, Up: Manual Configuration13.2 Getting the Canonical System Type======================================The following macros make the system type available to `configure'scripts.The variables `build_alias', `host_alias', and `target_alias' arealways exactly the arguments of `--build', `--host', and `--target'; inparticular, they are left empty if the user did not use them, even ifthe corresponding `AC_CANONICAL' macro was run. Any configure scriptmay use these variables anywhere. These are the variables that shouldbe used when in interaction with the user.If you need to recognize some special environments based on theirsystem type, run the following macros to get canonical system names.These variables are not set before the macro call.If you use these macros, you must distribute `config.guess' and`config.sub' along with your source code. *Note Output::, forinformation about the `AC_CONFIG_AUX_DIR' macro which you can use tocontrol in which directory `configure' looks for those scripts.-- Macro: AC_CANONICAL_BUILDCompute the canonical build-system type variable, `build', and itsthree individual parts `build_cpu', `build_vendor', and `build_os'.If `--build' was specified, then `build' is the canonicalizationof `build_alias' by `config.sub', otherwise it is determined bythe shell script `config.guess'.-- Macro: AC_CANONICAL_HOSTCompute the canonical host-system type variable, `host', and itsthree individual parts `host_cpu', `host_vendor', and `host_os'.If `--host' was specified, then `host' is the canonicalization of`host_alias' by `config.sub', otherwise it defaults to `build'.-- Macro: AC_CANONICAL_TARGETCompute the canonical target-system type variable, `target', andits three individual parts `target_cpu', `target_vendor', and`target_os'.If `--target' was specified, then `target' is the canonicalizationof `target_alias' by `config.sub', otherwise it defaults to `host'.Note that there can be artifacts due to the backward compatibilitycode. See *Note Hosts and Cross-Compilation::, for more.File: autoconf.info, Node: Using System Type, Prev: Canonicalizing, Up: Manual Configuration13.3 Using the System Type==========================In `configure.ac' the system type is generally used by one or more`case' statements to select system-specifics. Shell wildcards can beused to match a group of system types.For example, an extra assembler code object file could be chosen,giving access to a CPU cycle counter register. `$(CYCLE_OBJ)' in thefollowing would be used in a makefile to add the object to a program orlibrary.case $host inalpha*-*-*) CYCLE_OBJ=rpcc.o ;;i?86-*-*) CYCLE_OBJ=rdtsc.o ;;*) CYCLE_OBJ= ;;esacAC_SUBST([CYCLE_OBJ])`AC_CONFIG_LINKS' (*note Configuration Links::) is another good wayto select variant source files, for example optimized code for someCPUs. The configured CPU type doesn't always indicate exact CPU types,so some runtime capability checks may be necessary too.case $host inalpha*-*-*) AC_CONFIG_LINKS([dither.c:alpha/dither.c]) ;;powerpc*-*-*) AC_CONFIG_LINKS([dither.c:powerpc/dither.c]) ;;*-*-*) AC_CONFIG_LINKS([dither.c:generic/dither.c]) ;;esacThe host system type can also be used to find cross-compilation toolswith `AC_CHECK_TOOL' (*note Generic Programs::).The above examples all show `$host', since this is where the code isgoing to run. Only rarely is it necessary to test `$build' (which iswhere the build is being done).Whenever you're tempted to use `$host' it's worth consideringwhether some sort of probe would be better. New system types come alongperiodically or previously missing features are added. Well-writtenprobes can adapt themselves to such things, but hard-coded lists ofnames can't. Here are some guidelines,* Availability of libraries and library functions should always bechecked by probing.* Variant behavior of system calls is best identified with runtimetests if possible, but bug workarounds or obscure difficultiesmight have to be driven from `$host'.* Assembler code is inevitably highly CPU-specific and is bestselected according to `$host_cpu'.* Assembler variations like underscore prefix on globals or ELFversus COFF type directives are however best determined byprobing, perhaps even examining the compiler output.`$target' is for use by a package creating a compiler or similar.For ordinary packages it's meaningless and should not be used. Itindicates what the created compiler should generate code for, if it cancross-compile. `$target' generally selects various hard-coded CPU andsystem conventions, since usually the compiler or tools underconstruction themselves determine how the target works.File: autoconf.info, Node: Site Configuration, Next: Running configure Scripts, Prev: Manual Configuration, Up: Top14 Site Configuration*********************`configure' scripts support several kinds of local configurationdecisions. There are ways for users to specify where external softwarepackages are, include or exclude optional features, install programsunder modified names, and set default values for `configure' options.* Menu:* Help Formatting:: Customizing `configure --help'* External Software:: Working with other optional software* Package Options:: Selecting optional features* Pretty Help Strings:: Formatting help string* Site Details:: Configuring site details* Transforming Names:: Changing program names when installing* Site Defaults:: Giving `configure' local defaultsFile: autoconf.info, Node: Help Formatting, Next: External Software, Up: Site Configuration14.1 Controlling Help Output============================Users consult `configure --help' to learn of configuration decisionsspecific to your package. By default, `configure' breaks this outputinto sections for each type of option; within each section, helpstrings appear in the order `configure.ac' defines them:Optional Features:...--enable-bar include barOptional Packages:...--with-foo use foo-- Macro: AC_PRESERVE_HELP_ORDERRequest an alternate `--help' format, in which options of alltypes appear together, in the order defined. Call this macrobefore any `AC_ARG_ENABLE' or `AC_ARG_WITH'.Optional Features and Packages:...--enable-bar include bar--with-foo use fooFile: autoconf.info, Node: External Software, Next: Package Options, Prev: Help Formatting, Up: Site Configuration14.2 Working With External Software===================================Some packages require, or can optionally use, other software packagesthat are already installed. The user can give `configure' command lineoptions to specify which such external software to use. The optionshave one of these forms:--with-PACKAGE[=ARG]--without-PACKAGEFor example, `--with-gnu-ld' means work with the GNU linker insteadof some other linker. `--with-x' means work with The X Window System.The user can give an argument by following the package name with `='and the argument. Giving an argument of `no' is for packages that areused by default; it says to _not_ use the package. An argument that isneither `yes' nor `no' could include a name or number of a version ofthe other package, to specify more precisely which other package thisprogram is supposed to work with. If no argument is given, it defaultsto `yes'. `--without-PACKAGE' is equivalent to `--with-PACKAGE=no'.`configure' scripts do not complain about `--with-PACKAGE' optionsthat they do not support. This behavior permits configuring a sourcetree containing multiple packages with a top-level `configure' scriptwhen the packages support different options, without spurious errormessages about options that some of the packages support. Anunfortunate side effect is that option spelling errors are notdiagnosed. No better approach to this problem has been suggested sofar.For each external software package that may be used, `configure.ac'should call `AC_ARG_WITH' to detect whether the `configure' user askedto use it. Whether each package is used or not by default, and whicharguments are valid, is up to you.-- Macro: AC_ARG_WITH (PACKAGE, HELP-STRING, [ACTION-IF-GIVEN],[ACTION-IF-NOT-GIVEN])If the user gave `configure' the option `--with-PACKAGE' or`--without-PACKAGE', run shell commands ACTION-IF-GIVEN. Ifneither option was given, run shell commands ACTION-IF-NOT-GIVEN.The name PACKAGE indicates another software package that thisprogram should work with. It should consist only of alphanumericcharacters, dashes, and dots.The option's argument is available to the shell commandsACTION-IF-GIVEN in the shell variable `withval', which is actuallyjust the value of the shell variable `with_PACKAGE', with anynon-alphanumeric characters changed into `_'. You may use thatvariable instead, if you wish.The argument HELP-STRING is a description of the option that lookslike this:--with-readline support fancy command line editingHELP-STRING may be more than one line long, if more detail isneeded. Just make sure the columns line up in `configure --help'.Avoid tabs in the help string. You'll need to enclose the helpstring in `[' and `]' in order to produce the leading blanks.You should format your HELP-STRING with the macro `AS_HELP_STRING'(*note Pretty Help Strings::).The following example shows how to use the `AC_ARG_WITH' macro ina common situation. You want to let the user decide whether toenable support for an external library (e.g., the readlinelibrary); if the user specified neither `--with-readline' nor`--without-readline', you want to enable support for readline onlyif the library is available on the system.AC_ARG_WITH([readline],[AS_HELP_STRING([--with-readline],[support fancy command line editing @<:@default=check@:>@])],[],[with_readline=check])LIBREADLINE=AS_IF([test "x$with_readline" != xno],[AC_CHECK_LIB([readline], [main],[AC_SUBST([LIBREADLINE], ["-lreadline -lncurses"])AC_DEFINE([HAVE_LIBREADLINE], [1],[Define if you have libreadline])],[if test "x$with_readline" != xcheck; thenAC_MSG_FAILURE([--with-readline was given, but test for readline failed])fi], -lncurses)])The next example shows how to use `AC_ARG_WITH' to give the userthe possibility to enable support for the readline library, incase it is still experimental and not well tested, and istherefore disabled by default.AC_ARG_WITH([readline],[AS_HELP_STRING([--with-readline],[enable experimental support for readline])],[],[with_readline=no])LIBREADLINE=AS_IF([test "x$with_readline" != xno],[AC_CHECK_LIB([readline], [main],[AC_SUBST([LIBREADLINE], ["-lreadline -lncurses"])AC_DEFINE([HAVE_LIBREADLINE], [1],[Define if you have libreadline])],[AC_MSG_FAILURE([--with-readline was given, but test for readline failed])],[-lncurses])])The last example shows how to use `AC_ARG_WITH' to give the userthe possibility to disable support for the readline library, giventhat it is an important feature and that it should be enabled bydefault.AC_ARG_WITH([readline],[AS_HELP_STRING([--without-readline],[disable support for readline])],[],[with_readline=yes])LIBREADLINE=AS_IF([test "x$with_readline" != xno],[AC_CHECK_LIB([readline], [main],[AC_SUBST([LIBREADLINE], ["-lreadline -lncurses"])AC_DEFINE([HAVE_LIBREADLINE], [1],[Define if you have libreadline])],[AC_MSG_FAILURE([readline test failed (--without-readline to disable)])],[-lncurses])])These three examples can be easily adapted to the case where`AC_ARG_ENABLE' should be preferred to `AC_ARG_WITH' (see *NotePackage Options::).-- Macro: AC_WITH (PACKAGE, ACTION-IF-GIVEN, [ACTION-IF-NOT-GIVEN])This is an obsolete version of `AC_ARG_WITH' that does not supportproviding a help string.File: autoconf.info, Node: Package Options, Next: Pretty Help Strings, Prev: External Software, Up: Site Configuration14.3 Choosing Package Options=============================If a software package has optional compile-time features, the user cangive `configure' command line options to specify whether to compilethem. The options have one of these forms:--enable-FEATURE[=ARG]--disable-FEATUREThese options allow users to choose which optional features to buildand install. `--enable-FEATURE' options should never make a featurebehave differently or cause one feature to replace another. Theyshould only cause parts of the program to be built rather than left out.The user can give an argument by following the feature name with `='and the argument. Giving an argument of `no' requests that the feature_not_ be made available. A feature with an argument looks like`--enable-debug=stabs'. If no argument is given, it defaults to `yes'.`--disable-FEATURE' is equivalent to `--enable-FEATURE=no'.`configure' scripts do not complain about `--enable-FEATURE' optionsthat they do not support. This behavior permits configuring a sourcetree containing multiple packages with a top-level `configure' scriptwhen the packages support different options, without spurious errormessages about options that some of the packages support. Anunfortunate side effect is that option spelling errors are notdiagnosed. No better approach to this problem has been suggested sofar.For each optional feature, `configure.ac' should call`AC_ARG_ENABLE' to detect whether the `configure' user asked to includeit. Whether each feature is included or not by default, and whicharguments are valid, is up to you.-- Macro: AC_ARG_ENABLE (FEATURE, HELP-STRING, [ACTION-IF-GIVEN],[ACTION-IF-NOT-GIVEN])If the user gave `configure' the option `--enable-FEATURE' or`--disable-FEATURE', run shell commands ACTION-IF-GIVEN. Ifneither option was given, run shell commands ACTION-IF-NOT-GIVEN.The name FEATURE indicates an optional user-level facility. Itshould consist only of alphanumeric characters, dashes, and dots.The option's argument is available to the shell commandsACTION-IF-GIVEN in the shell variable `enableval', which isactually just the value of the shell variable `enable_FEATURE',with any non-alphanumeric characters changed into `_'. You mayuse that variable instead, if you wish. The HELP-STRING argumentis like that of `AC_ARG_WITH' (*note External Software::).You should format your HELP-STRING with the macro `AS_HELP_STRING'(*note Pretty Help Strings::).See the examples suggested with the definition of `AC_ARG_WITH'(*note External Software::) to get an idea of possibleapplications of `AC_ARG_ENABLE'.-- Macro: AC_ENABLE (FEATURE, ACTION-IF-GIVEN, [ACTION-IF-NOT-GIVEN])This is an obsolete version of `AC_ARG_ENABLE' that does notsupport providing a help string.File: autoconf.info, Node: Pretty Help Strings, Next: Site Details, Prev: Package Options, Up: Site Configuration14.4 Making Your Help Strings Look Pretty=========================================Properly formatting the `help strings' which are used in `AC_ARG_WITH'(*note External Software::) and `AC_ARG_ENABLE' (*note PackageOptions::) can be challenging. Specifically, you want your own `helpstrings' to line up in the appropriate columns of `configure --help'just like the standard Autoconf `help strings' do. This is the purposeof the `AS_HELP_STRING' macro.-- Macro: AS_HELP_STRING (LEFT-HAND-SIDE, RIGHT-HAND-SIDE)Expands into an help string that looks pretty when the userexecutes `configure --help'. It is typically used in `AC_ARG_WITH'(*note External Software::) or `AC_ARG_ENABLE' (*note PackageOptions::). The following example makes this clearer.AC_ARG_WITH([foo],[AS_HELP_STRING([--with-foo],[use foo (default is no)])],[use_foo=$withval],[use_foo=no])The second argument of `AS_HELP_STRING' is not a literal, andshould not be double quoted. *Note Autoconf Language::, for amore detailed explanation. Then the last few lines of `configure--help' appear like this:--enable and --with options recognized:--with-foo use foo (default is no)The `AS_HELP_STRING' macro is particularly helpful when theLEFT-HAND-SIDE and/or RIGHT-HAND-SIDE are composed of macroarguments, as shown in the following example.AC_DEFUN([MY_ARG_WITH],[AC_ARG_WITH([$1],[AS_HELP_STRING([--with-$1], [use $1 (default is $2)])],[use_[]$1=$withval],[use_[]$1=$2])])File: autoconf.info, Node: Site Details, Next: Transforming Names, Prev: Pretty Help Strings, Up: Site Configuration14.5 Configuring Site Details=============================Some software packages require complex site-specific information. Someexamples are host names to use for certain services, company names, andemail addresses to contact. Since some configuration scripts generatedby Metaconfig ask for such information interactively, people sometimeswonder how to get that information in Autoconf-generated configurationscripts, which aren't interactive.Such site configuration information should be put in a file that isedited _only by users_, not by programs. The location of the file caneither be based on the `prefix' variable, or be a standard locationsuch as the user's home directory. It could even be specified by anenvironment variable. The programs should examine that file atruntime, rather than at compile time. Runtime configuration is moreconvenient for users and makes the configuration process simpler thangetting the information while configuring. *Note Variables forInstallation Directories: (standards)Directory Variables, for moreinformation on where to put data files.File: autoconf.info, Node: Transforming Names, Next: Site Defaults, Prev: Site Details, Up: Site Configuration14.6 Transforming Program Names When Installing===============================================Autoconf supports changing the names of programs when installing them.In order to use these transformations, `configure.ac' must call themacro `AC_ARG_PROGRAM'.-- Macro: AC_ARG_PROGRAMPlace in output variable `program_transform_name' a sequence of`sed' commands for changing the names of installed programs.If any of the options described below are given to `configure',program names are transformed accordingly. Otherwise, if`AC_CANONICAL_TARGET' has been called and a `--target' value isgiven, the target type followed by a dash is used as a prefix.Otherwise, no program name transformation is done.* Menu:* Transformation Options:: `configure' options to transform names* Transformation Examples:: Sample uses of transforming names* Transformation Rules:: Makefile uses of transforming namesFile: autoconf.info, Node: Transformation Options, Next: Transformation Examples, Up: Transforming Names14.6.1 Transformation Options-----------------------------You can specify name transformations by giving `configure' thesecommand line options:`--program-prefix=PREFIX'prepend PREFIX to the names;`--program-suffix=SUFFIX'append SUFFIX to the names;`--program-transform-name=EXPRESSION'perform `sed' substitution EXPRESSION on the names.File: autoconf.info, Node: Transformation Examples, Next: Transformation Rules, Prev: Transformation Options, Up: Transforming Names14.6.2 Transformation Examples------------------------------These transformations are useful with programs that can be part of across-compilation development environment. For example, across-assembler running on a Sun 4 configured with`--target=i960-vxworks' is normally installed as `i960-vxworks-as',rather than `as', which could be confused with a native Sun 4 assembler.You can force a program name to begin with `g', if you don't wantGNU programs installed on your system to shadow other programs with thesame name. For example, if you configure GNU `diff' with`--program-prefix=g', then when you run `make install' it is installedas `/usr/local/bin/gdiff'.As a more sophisticated example, you could use--program-transform-name='s/^/g/; s/^gg/g/; s/^gless/less/'to prepend `g' to most of the program names in a source tree,excepting those like `gdb' that already have one and those like `less'and `lesskey' that aren't GNU programs. (That is assuming that youhave a source tree containing those programs that is set up to use thisfeature.)One way to install multiple versions of some programs simultaneouslyis to append a version number to the name of one or both. For example,if you want to keep Autoconf version 1 around for awhile, you canconfigure Autoconf version 2 using `--program-suffix=2' to install theprograms as `/usr/local/bin/autoconf2', `/usr/local/bin/autoheader2',etc. Nevertheless, pay attention that only the binaries are renamed,therefore you'd have problems with the library files which mightoverlap.File: autoconf.info, Node: Transformation Rules, Prev: Transformation Examples, Up: Transforming Names14.6.3 Transformation Rules---------------------------Here is how to use the variable `program_transform_name' in a`Makefile.in':PROGRAMS = cp ls rmtransform = @program_transform_name@install:for p in $(PROGRAMS); do \$(INSTALL_PROGRAM) $$p $(DESTDIR)$(bindir)/`echo $$p | \sed '$(transform)'`; \doneuninstall:for p in $(PROGRAMS); do \rm -f $(DESTDIR)$(bindir)/`echo $$p | sed '$(transform)'`; \doneIt is guaranteed that `program_transform_name' is never empty, andthat there are no useless separators. Therefore you may safely embed`program_transform_name' within a sed program using `;':transform = @program_transform_name@transform_exe = s/$(EXEEXT)$$//;$(transform);s/$$/$(EXEEXT)/Whether to do the transformations on documentation files (Texinfo or`man') is a tricky question; there seems to be no perfect answer, dueto the several reasons for name transforming. Documentation is notusually particular to a specific architecture, and Texinfo files do notconflict with system documentation. But they might conflict withearlier versions of the same files, and `man' pages sometimes doconflict with system documentation. As a compromise, it is probablybest to do name transformations on `man' pages but not on Texinfomanuals.File: autoconf.info, Node: Site Defaults, Prev: Transforming Names, Up: Site Configuration14.7 Setting Site Defaults==========================Autoconf-generated `configure' scripts allow your site to providedefault values for some configuration values. You do this by creatingsite- and system-wide initialization files.If the environment variable `CONFIG_SITE' is set, `configure' usesits value as the name of a shell script to read. Otherwise, it readsthe shell script `PREFIX/share/config.site' if it exists, then`PREFIX/etc/config.site' if it exists. Thus, settings inmachine-specific files override those in machine-independent ones incase of conflict.Site files can be arbitrary shell scripts, but only certain kinds ofcode are really appropriate to be in them. Because `configure' readsany cache file after it has read any site files, a site file can definea default cache file to be shared between all Autoconf-generated`configure' scripts run on that system (*note Cache Files::). If youset a default cache file in a site file, it is a good idea to also setthe output variable `CC' in that site file, because the cache file isonly valid for a particular compiler, but many systems have severalavailable.You can examine or override the value set by a command line option to`configure' in a site file; options set shell variables that have thesame names as the options, with any dashes turned into underscores.The exceptions are that `--without-' and `--disable-' options are likegiving the corresponding `--with-' or `--enable-' option and the value`no'. Thus, `--cache-file=localcache' sets the variable `cache_file'to the value `localcache'; `--enable-warnings=no' or`--disable-warnings' sets the variable `enable_warnings' to the value`no'; `--prefix=/usr' sets the variable `prefix' to the value `/usr';etc.Site files are also good places to set default values for otheroutput variables, such as `CFLAGS', if you need to give them non-defaultvalues: anything you would normally do, repetitively, on the commandline. If you use non-default values for PREFIX or EXEC_PREFIX(wherever you locate the site file), you can set them in the site fileif you specify it with the `CONFIG_SITE' environment variable.You can set some cache values in the site file itself. Doing this isuseful if you are cross-compiling, where it is impossible to checkfeatures that require running a test program. You could "prime thecache" by setting those values correctly for that system in`PREFIX/etc/config.site'. To find out the names of the cache variablesyou need to set, look for shell variables with `_cv_' in their names inthe affected `configure' scripts, or in the Autoconf M4 source code forthose macros.The cache file is careful to not override any variables set in thesite files. Similarly, you should not override command-line options inthe site files. Your code should check that variables such as `prefix'and `cache_file' have their default values (as set near the top of`configure') before changing them.Here is a sample file `/usr/share/local/gnu/share/config.site'. Thecommand `configure --prefix=/usr/share/local/gnu' would read this file(if `CONFIG_SITE' is not set to a different file).# config.site for configure## Change some defaults.test "$prefix" = NONE && prefix=/usr/share/local/gnutest "$exec_prefix" = NONE && exec_prefix=/usr/local/gnutest "$sharedstatedir" = '$prefix/com' && sharedstatedir=/vartest "$localstatedir" = '$prefix/var' && localstatedir=/var# Give Autoconf 2.x generated configure scripts a shared default# cache file for feature test results, architecture-specific.if test "$cache_file" = /dev/null; thencache_file="$prefix/var/config.cache"# A cache file is only valid for one C compiler.CC=gccfiFile: autoconf.info, Node: Running configure Scripts, Next: config.status Invocation, Prev: Site Configuration, Up: Top15 Running `configure' Scripts******************************Below are instructions on how to configure a package that uses a`configure' script, suitable for inclusion as an `INSTALL' file in thepackage. A plain-text version of `INSTALL' which you may use comeswith Autoconf.* Menu:* Basic Installation:: Instructions for typical cases* Compilers and Options:: Selecting compilers and optimization* Multiple Architectures:: Compiling for multiple architectures at once* Installation Names:: Installing in different directories* Optional Features:: Selecting optional features* System Type:: Specifying the system type* Sharing Defaults:: Setting site-wide defaults for `configure'* Defining Variables:: Specifying the compiler etc.* configure Invocation:: Changing how `configure' runsFile: autoconf.info, Node: Basic Installation, Next: Compilers and Options, Up: Running configure Scripts15.1 Basic Installation=======================Briefly, the shell commands `./configure; make; make install' shouldconfigure, build, and install this package. The followingmore-detailed instructions are generic; see the `README' file forinstructions specific to this package.The `configure' shell script attempts to guess correct values forvarious system-dependent variables used during compilation. It usesthose values to create a `Makefile' in each directory of the package.It may also create one or more `.h' files containing system-dependentdefinitions. Finally, it creates a shell script `config.status' thatyou can run in the future to recreate the current configuration, and afile `config.log' containing compiler output (useful mainly fordebugging `configure').It can also use an optional file (typically called `config.cache'and enabled with `--cache-file=config.cache' or simply `-C') that savesthe results of its tests to speed up reconfiguring. Caching isdisabled by default to prevent problems with accidental use of stalecache files.If you need to do unusual things to compile the package, please tryto figure out how `configure' could check whether to do them, and maildiffs or instructions to the address given in the `README' so they canbe considered for the next release. If you are using the cache, and atsome point `config.cache' contains results you don't want to keep, youmay remove or edit it.The file `configure.ac' (or `configure.in') is used to create`configure' by a program called `autoconf'. You need `configure.ac' ifyou want to change it or regenerate `configure' using a newer versionof `autoconf'.The simplest way to compile this package is:1. `cd' to the directory containing the package's source code and type`./configure' to configure the package for your system.Running `configure' might take a while. While running, it printssome messages telling which features it is checking for.2. Type `make' to compile the package.3. Optionally, type `make check' to run any self-tests that come withthe package.4. Type `make install' to install the programs and any data files anddocumentation.5. You can remove the program binaries and object files from thesource code directory by typing `make clean'. To also remove thefiles that `configure' created (so you can compile the package fora different kind of computer), type `make distclean'. There isalso a `make maintainer-clean' target, but that is intended mainlyfor the package's developers. If you use it, you may have to getall sorts of other programs in order to regenerate files that camewith the distribution.File: autoconf.info, Node: Compilers and Options, Next: Multiple Architectures, Prev: Basic Installation, Up: Running configure Scripts15.2 Compilers and Options==========================Some systems require unusual options for compilation or linking that the`configure' script does not know about. Run `./configure --help' fordetails on some of the pertinent environment variables.You can give `configure' initial values for configuration parametersby setting variables in the command line or in the environment. Hereis an example:./configure CC=c99 CFLAGS=-g LIBS=-lposix*Note Defining Variables::, for more details.File: autoconf.info, Node: Multiple Architectures, Next: Installation Names, Prev: Compilers and Options, Up: Running configure Scripts15.3 Compiling For Multiple Architectures=========================================You can compile the package for more than one kind of computer at thesame time, by placing the object files for each architecture in theirown directory. To do this, you can use GNU `make'. `cd' to thedirectory where you want the object files and executables to go and runthe `configure' script. `configure' automatically checks for thesource code in the directory that `configure' is in and in `..'.With a non-GNU `make', it is safer to compile the package for onearchitecture at a time in the source code directory. After you haveinstalled the package for one architecture, use `make distclean' beforereconfiguring for another architecture.File: autoconf.info, Node: Installation Names, Next: Optional Features, Prev: Multiple Architectures, Up: Running configure Scripts15.4 Installation Names=======================By default, `make install' installs the package's commands under`/usr/local/bin', include files under `/usr/local/include', etc. Youcan specify an installation prefix other than `/usr/local' by giving`configure' the option `--prefix=PREFIX'.You can specify separate installation prefixes forarchitecture-specific files and architecture-independent files. If youpass the option `--exec-prefix=PREFIX' to `configure', the package usesPREFIX as the prefix for installing programs and libraries.Documentation and other data files still use the regular prefix.In addition, if you use an unusual directory layout you can giveoptions like `--bindir=DIR' to specify different values for particularkinds of files. Run `configure --help' for a list of the directoriesyou can set and what kinds of files go in them.If the package supports it, you can cause programs to be installedwith an extra prefix or suffix on their names by giving `configure' theoption `--program-prefix=PREFIX' or `--program-suffix=SUFFIX'.File: autoconf.info, Node: Optional Features, Next: System Type, Prev: Installation Names, Up: Running configure Scripts15.5 Optional Features======================Some packages pay attention to `--enable-FEATURE' options to`configure', where FEATURE indicates an optional part of the package.They may also pay attention to `--with-PACKAGE' options, where PACKAGEis something like `gnu-as' or `x' (for the X Window System). The`README' should mention any `--enable-' and `--with-' options that thepackage recognizes.For packages that use the X Window System, `configure' can usuallyfind the X include and library files automatically, but if it doesn't,you can use the `configure' options `--x-includes=DIR' and`--x-libraries=DIR' to specify their locations.File: autoconf.info, Node: System Type, Next: Sharing Defaults, Prev: Optional Features, Up: Running configure Scripts15.6 Specifying the System Type===============================There may be some features `configure' cannot figure out automatically,but needs to determine by the type of machine the package will run on.Usually, assuming the package is built to be run on the _same_architectures, `configure' can figure that out, but if it prints amessage saying it cannot guess the machine type, give it the`--build=TYPE' option. TYPE can either be a short name for the systemtype, such as `sun4', or a canonical name which has the form:CPU-COMPANY-SYSTEMwhere SYSTEM can have one of these forms:OS KERNEL-OSSee the file `config.sub' for the possible values of each field. If`config.sub' isn't included in this package, then this package doesn'tneed to know the machine type.If you are _building_ compiler tools for cross-compiling, you shoulduse the option `--target=TYPE' to select the type of system they willproduce code for.If you want to _use_ a cross compiler, that generates code for aplatform different from the build platform, you should specify the"host" platform (i.e., that on which the generated programs willeventually be run) with `--host=TYPE'.File: autoconf.info, Node: Sharing Defaults, Next: Defining Variables, Prev: System Type, Up: Running configure Scripts15.7 Sharing Defaults=====================If you want to set default values for `configure' scripts to share, youcan create a site shell script called `config.site' that gives defaultvalues for variables like `CC', `cache_file', and `prefix'.`configure' looks for `PREFIX/share/config.site' if it exists, then`PREFIX/etc/config.site' if it exists. Or, you can set the`CONFIG_SITE' environment variable to the location of the site script.A warning: not all `configure' scripts look for a site script.File: autoconf.info, Node: Defining Variables, Next: configure Invocation, Prev: Sharing Defaults, Up: Running configure Scripts15.8 Defining Variables=======================Variables not defined in a site shell script can be set in theenvironment passed to `configure'. However, some packages may runconfigure again during the build, and the customized values of thesevariables may be lost. In order to avoid this problem, you should setthem in the `configure' command line, using `VAR=value'. For example:./configure CC=/usr/local2/bin/gcccauses the specified `gcc' to be used as the C compiler (unless it isoverridden in the site shell script).Unfortunately, this technique does not work for `CONFIG_SHELL' due toan Autoconf bug. Until the bug is fixed you can use this workaround:CONFIG_SHELL=/bin/bash /bin/bash ./configure CONFIG_SHELL=/bin/bashFile: autoconf.info, Node: configure Invocation, Prev: Defining Variables, Up: Running configure Scripts15.9 `configure' Invocation===========================`configure' recognizes the following options to control how it operates.`--help'`-h'Print a summary of the options to `configure', and exit.`--version'`-V'Print the version of Autoconf used to generate the `configure'script, and exit.`--cache-file=FILE'Enable the cache: use and save the results of the tests in FILE,traditionally `config.cache'. FILE defaults to `/dev/null' todisable caching.`--config-cache'`-C'Alias for `--cache-file=config.cache'.`--quiet'`--silent'`-q'Do not print messages saying which checks are being made. Tosuppress all normal output, redirect it to `/dev/null' (any errormessages will still be shown).`--srcdir=DIR'Look for the package's source code in directory DIR. Usually`configure' can determine that directory automatically.`configure' also accepts some other, not widely useful, options. Run`configure --help' for more details.File: autoconf.info, Node: config.status Invocation, Next: Obsolete Constructs, Prev: Running configure Scripts, Up: Top16 Recreating a Configuration*****************************The `configure' script creates a file named `config.status', whichactually configures, "instantiates", the template files. It alsorecords the configuration options that were specified when the packagewas last configured in case reconfiguring is needed.Synopsis:./config.status OPTION... [FILE...]It configures the FILES; if none are specified, all the templatesare instantiated. The files must be specified without theirdependencies, as in./config.status foobarnot./config.status foobar:foo.in:bar.inThe supported options are:`--help'`-h'Print a summary of the command line options, the list of thetemplate files, and exit.`--version'`-V'Print the version number of Autoconf and the configurationsettings, and exit.`--silent'`--quiet'`-q'Do not print progress messages.`--debug'`-d'Don't remove the temporary files.`--file=FILE[:TEMPLATE]'Require that FILE be instantiated as if`AC_CONFIG_FILES(FILE:TEMPLATE)' was used. Both FILE and TEMPLATEmay be `-' in which case the standard output and/or standardinput, respectively, is used. If a TEMPLATE file name isrelative, it is first looked for in the build tree, and then inthe source tree. *Note Configuration Actions::, for more details.This option and the following ones provide one way for separatelydistributed packages to share the values computed by `configure'.Doing so can be useful if some of the packages need a superset ofthe features that one of them, perhaps a common library, does.These options allow a `config.status' file to create files otherthan the ones that its `configure.ac' specifies, so it can be usedfor a different package.`--header=FILE[:TEMPLATE]'Same as `--file' above, but with `AC_CONFIG_HEADERS'.`--recheck'Ask `config.status' to update itself and exit (no instantiation).This option is useful if you change `configure', so that theresults of some tests might be different from the previous run.The `--recheck' option reruns `configure' with the same argumentsyou used before, plus the `--no-create' option, which prevents`configure' from running `config.status' and creating `Makefile'and other files, and the `--no-recursion' option, which prevents`configure' from running other `configure' scripts insubdirectories. (This is so other Make rules can run`config.status' when it changes; *note Automatic Remaking::, foran example).`config.status' checks several optional environment variables thatcan alter its behavior:-- Variable: CONFIG_SHELLThe shell with which to run `configure' for the `--recheck'option. It must be Bourne-compatible. The default is a shell thatsupports `LINENO' if available, and `/bin/sh' otherwise. Invoking`configure' by hand bypasses this setting, so you may need to usea command like `CONFIG_SHELL=/bin/bash /bin/bash ./configure' toinsure that the same shell is used everywhere. The absolute nameof the shell should be passed.-- Variable: CONFIG_STATUSThe file name to use for the shell script that records theconfiguration. The default is `./config.status'. This variable isuseful when one package uses parts of another and the `configure'scripts shouldn't be merged because they are maintained separately.You can use `./config.status' in your makefiles. For example, inthe dependencies given above (*note Automatic Remaking::),`config.status' is run twice when `configure.ac' has changed. If thatbothers you, you can make each run only regenerate the files for thatrule:config.h: stamp-hstamp-h: config.h.in config.status./config.status config.hecho > stamp-hMakefile: Makefile.in config.status./config.status MakefileThe calling convention of `config.status' has changed; see *NoteObsolete config.status Use::, for details.File: autoconf.info, Node: Obsolete Constructs, Next: Using Autotest, Prev: config.status Invocation, Up: Top17 Obsolete Constructs**********************Autoconf changes, and throughout the years some constructs have beenobsoleted. Most of the changes involve the macros, but in some casesthe tools themselves, or even some concepts, are now consideredobsolete.You may completely skip this chapter if you are new to Autoconf. Itsintention is mainly to help maintainers updating their packages byunderstanding how to move to more modern constructs.* Menu:* Obsolete config.status Use:: Different calling convention* acconfig.h:: Additional entries in `config.h.in'* autoupdate Invocation:: Automatic update of `configure.ac'* Obsolete Macros:: Backward compatibility macros* Autoconf 1:: Tips for upgrading your files* Autoconf 2.13:: Some fresher tipsFile: autoconf.info, Node: Obsolete config.status Use, Next: acconfig.h, Up: Obsolete Constructs17.1 Obsolete `config.status' Invocation========================================`config.status' now supports arguments to specify the files toinstantiate; see *Note config.status Invocation::, for more details.Before, environment variables had to be used.-- Variable: CONFIG_COMMANDSThe tags of the commands to execute. The default is the argumentsgiven to `AC_OUTPUT' and `AC_CONFIG_COMMANDS' in `configure.ac'.-- Variable: CONFIG_FILESThe files in which to perform `@VARIABLE@' substitutions. Thedefault is the arguments given to `AC_OUTPUT' and`AC_CONFIG_FILES' in `configure.ac'.-- Variable: CONFIG_HEADERSThe files in which to substitute C `#define' statements. Thedefault is the arguments given to `AC_CONFIG_HEADERS'; if thatmacro was not called, `config.status' ignores this variable.-- Variable: CONFIG_LINKSThe symbolic links to establish. The default is the argumentsgiven to `AC_CONFIG_LINKS'; if that macro was not called,`config.status' ignores this variable.In *Note config.status Invocation::, using this old interface, theexample would be:config.h: stamp-hstamp-h: config.h.in config.statusCONFIG_COMMANDS= CONFIG_LINKS= CONFIG_FILES= \CONFIG_HEADERS=config.h ./config.statusecho > stamp-hMakefile: Makefile.in config.statusCONFIG_COMMANDS= CONFIG_LINKS= CONFIG_HEADERS= \CONFIG_FILES=Makefile ./config.status(If `configure.ac' does not call `AC_CONFIG_HEADERS', there is no needto set `CONFIG_HEADERS' in the `make' rules. Equally for`CONFIG_COMMANDS', etc.)File: autoconf.info, Node: acconfig.h, Next: autoupdate Invocation, Prev: Obsolete config.status Use, Up: Obsolete Constructs17.2 `acconfig.h'=================In order to produce `config.h.in', `autoheader' needs to build or tofind templates for each symbol. Modern releases of Autoconf use`AH_VERBATIM' and `AH_TEMPLATE' (*note Autoheader Macros::), but inolder releases a file, `acconfig.h', contained the list of neededtemplates. `autoheader' copied comments and `#define' and `#undef'statements from `acconfig.h' in the current directory, if present.This file used to be mandatory if you `AC_DEFINE' any additionalsymbols.Modern releases of Autoconf also provide `AH_TOP' and `AH_BOTTOM' ifyou need to prepend/append some information to `config.h.in'. Ancientversions of Autoconf had a similar feature: if `./acconfig.h' containsthe string `@TOP@', `autoheader' copies the lines before the linecontaining `@TOP@' into the top of the file that it generates.Similarly, if `./acconfig.h' contains the string `@BOTTOM@',`autoheader' copies the lines after that line to the end of the file itgenerates. Either or both of those strings may be omitted. An evenolder alternate way to produce the same effect in ancient versions ofAutoconf is to create the files `FILE.top' (typically `config.h.top')and/or `FILE.bot' in the current directory. If they exist,`autoheader' copies them to the beginning and end, respectively, of itsoutput.In former versions of Autoconf, the files used in preparing asoftware package for distribution were:configure.ac --. .------> autoconf* -----> configure+---+[aclocal.m4] --+ `---.[acsite.m4] ---' |+--> [autoheader*] -> [config.h.in][acconfig.h] ----. |+-----'[config.h.top] --+[config.h.bot] --'Using only the `AH_' macros, `configure.ac' should beself-contained, and should not depend upon `acconfig.h' etc.File: autoconf.info, Node: autoupdate Invocation, Next: Obsolete Macros, Prev: acconfig.h, Up: Obsolete Constructs17.3 Using `autoupdate' to Modernize `configure.ac'===================================================The `autoupdate' program updates a `configure.ac' file that callsAutoconf macros by their old names to use the current macro names. Inversion 2 of Autoconf, most of the macros were renamed to use a moreuniform and descriptive naming scheme. *Note Macro Names::, for adescription of the new scheme. Although the old names still work(*note Obsolete Macros::, for a list of the old macros and thecorresponding new names), you can make your `configure.ac' files morereadable and make it easier to use the current Autoconf documentationif you update them to use the new macro names.If given no arguments, `autoupdate' updates `configure.ac', backingup the original version with the suffix `~' (or the value of theenvironment variable `SIMPLE_BACKUP_SUFFIX', if that is set). If yougive `autoupdate' an argument, it reads that file instead of`configure.ac' and writes the updated file to the standard output.`autoupdate' accepts the following options:`--help'`-h'Print a summary of the command line options and exit.`--version'`-V'Print the version number of Autoconf and exit.`--verbose'`-v'Report processing steps.`--debug'`-d'Don't remove the temporary files.`--force'`-f'Force the update even if the file has not changed. Disregard thecache.`--include=DIR'`-I DIR'Also look for input files in DIR. Multiple invocations accumulate.Directories are browsed from last to first.File: autoconf.info, Node: Obsolete Macros, Next: Autoconf 1, Prev: autoupdate Invocation, Up: Obsolete Constructs17.4 Obsolete Macros====================Several macros are obsoleted in Autoconf, for various reasons (typicallythey failed to quote properly, couldn't be extended for more recentissues, etc.). They are still supported, but deprecated: their useshould be avoided.During the jump from Autoconf version 1 to version 2, most of themacros were renamed to use a more uniform and descriptive naming scheme,but their signature did not change. *Note Macro Names::, for adescription of the new naming scheme. Below, if there is just themapping from old names to new names for these macros, the reader isinvited to refer to the definition of the new macro for the signatureand the description.-- Macro: AC_ALLOCA`AC_FUNC_ALLOCA'-- Macro: AC_ARG_ARRAYremoved because of limited usefulness-- Macro: AC_C_CROSSThis macro is obsolete; it does nothing.-- Macro: AC_C_LONG_DOUBLEIf the C compiler supports a working `long double' type with morerange or precision than the `double' type, define`HAVE_LONG_DOUBLE'.You should use `AC_TYPE_LONG_DOUBLE' or`AC_TYPE_LONG_DOUBLE_WIDER' instead. *Note Particular Types::.-- Macro: AC_CANONICAL_SYSTEMDetermine the system type and set output variables to the names ofthe canonical system types. *Note Canonicalizing::, for detailsabout the variables this macro sets.The user is encouraged to use either `AC_CANONICAL_BUILD', or`AC_CANONICAL_HOST', or `AC_CANONICAL_TARGET', depending on theneeds. Using `AC_CANONICAL_TARGET' is enough to run the two othermacros.-- Macro: AC_CHAR_UNSIGNED`AC_C_CHAR_UNSIGNED'-- Macro: AC_CHECK_TYPE (TYPE, DEFAULT)Autoconf, up to 2.13, used to provide this version of`AC_CHECK_TYPE', deprecated because of its flaws. First, althoughit is a member of the `CHECK' clan, it does more than justchecking. Secondly, missing types are defined using `#define',not `typedef', and this can lead to problems in the case ofpointer types.This use of `AC_CHECK_TYPE' is obsolete and discouraged; see *NoteGeneric Types::, for the description of the current macro.If the type TYPE is not defined, define it to be the C (or C++)builtin type DEFAULT, e.g., `short int' or `unsigned int'.This macro is equivalent to:AC_CHECK_TYPE([TYPE], [],[AC_DEFINE_UNQUOTED([TYPE], [DEFAULT],[Define to `DEFAULT'if <sys/types.h> does not define.])])In order to keep backward compatibility, the two versions of`AC_CHECK_TYPE' are implemented, selected by a simple heuristics:1. If there are three or four arguments, the modern version isused.2. If the second argument appears to be a C or C++ type, then theobsolete version is used. This happens if the argument is aC or C++ _builtin_ type or a C identifier ending in `_t',optionally followed by one of `[(* ' and then by a string ofzero or more characters taken from the set `[]()* _a-zA-Z0-9'.3. If the second argument is spelled with the alphabet of validC and C++ types, the user is warned and the modern version isused.4. Otherwise, the modern version is used.You are encouraged either to use a valid builtin type, or to usethe equivalent modern code (see above), or better yet, to use`AC_CHECK_TYPES' together with#ifndef HAVE_LOFF_Ttypedef loff_t off_t;#endif-- Macro: AC_CHECKING (FEATURE-DESCRIPTION)Same as `AC_MSG_NOTICE([checking FEATURE-DESCRIPTION...]'.-- Macro: AC_COMPILE_CHECK (ECHO-TEXT, INCLUDES, FUNCTION-BODY,ACTION-IF-TRUE, [ACTION-IF-FALSE])This is an obsolete version of `AC_TRY_COMPILE' itself replaced by`AC_COMPILE_IFELSE' (*note Running the Compiler::), with theaddition that it prints `checking for ECHO-TEXT' to the standardoutput first, if ECHO-TEXT is non-empty. Use `AC_MSG_CHECKING'and `AC_MSG_RESULT' instead to print messages (*note PrintingMessages::).-- Macro: AC_CONST`AC_C_CONST'-- Macro: AC_CROSS_CHECKSame as `AC_C_CROSS', which is obsolete too, and does nothing`:-)'.-- Macro: AC_CYGWINCheck for the Cygwin environment in which case the shell variable`CYGWIN' is set to `yes'. Don't use this macro, the dignifiedmeans to check the nature of the host is using`AC_CANONICAL_HOST'. As a matter of fact this macro is defined as:AC_REQUIRE([AC_CANONICAL_HOST])[]dnlcase $host_os in*cygwin* ) CYGWIN=yes;;* ) CYGWIN=no;;esacBeware that the variable `CYGWIN' has a special meaning whenrunning Cygwin, and should not be changed. That's yet anotherreason not to use this macro.-- Macro: AC_DECL_SYS_SIGLISTSame as:AC_CHECK_DECLS([sys_siglist], [], [],[#include <signal.h>/* NetBSD declares sys_siglist in unistd.h. */#ifdef HAVE_UNISTD_H# include <unistd.h>#endif])-- Macro: AC_DECL_YYTEXTDoes nothing, now integrated in `AC_PROG_LEX'.-- Macro: AC_DIR_HEADERLike calling `AC_FUNC_CLOSEDIR_VOID' and`AC_HEADER_DIRENT', butdefines a different set of C preprocessor macros to indicate whichheader file is found:Header Old Symbol New Symbol`dirent.h' `DIRENT' `HAVE_DIRENT_H'`sys/ndir.h' `SYSNDIR' `HAVE_SYS_NDIR_H'`sys/dir.h' `SYSDIR' `HAVE_SYS_DIR_H'`ndir.h' `NDIR' `HAVE_NDIR_H'-- Macro: AC_DYNIX_SEQIf on DYNIX/ptx, add `-lseq' to output variable `LIBS'. Thismacro used to be defined asAC_CHECK_LIB([seq], [getmntent], [LIBS="-lseq $LIBS"])now it is just `AC_FUNC_GETMNTENT'.-- Macro: AC_EXEEXTDefined the output variable `EXEEXT' based on the output of thecompiler, which is now done automatically. Typically set to emptystring if Posix and `.exe' if a DOS variant.-- Macro: AC_EMXOS2Similar to `AC_CYGWIN' but checks for the EMX environment on OS/2and sets `EMXOS2'.-- Macro: AC_ERROR`AC_MSG_ERROR'-- Macro: AC_FIND_X`AC_PATH_X'-- Macro: AC_FIND_XTRA`AC_PATH_XTRA'-- Macro: AC_FOREACH`m4_foreach_w'-- Macro: AC_FUNC_CHECK`AC_CHECK_FUNC'-- Macro: AC_FUNC_WAIT3If `wait3' is found and fills in the contents of its third argument(a `struct rusage *'), which HP-UX does not do, define`HAVE_WAIT3'.These days portable programs should use `waitpid', not `wait3', as`wait3' has been removed from Posix.-- Macro: AC_GCC_TRADITIONAL`AC_PROG_GCC_TRADITIONAL'-- Macro: AC_GETGROUPS_T`AC_TYPE_GETGROUPS'-- Macro: AC_GETLOADAVG`AC_FUNC_GETLOADAVG'-- Macro: AC_HAVE_FUNCS`AC_CHECK_FUNCS'-- Macro: AC_HAVE_HEADERS`AC_CHECK_HEADERS'-- Macro: AC_HAVE_LIBRARY (LIBRARY, [ACTION-IF-FOUND],[ACTION-IF-NOT-FOUND], [OTHER-LIBRARIES])This macro is equivalent to calling `AC_CHECK_LIB' with a FUNCTIONargument of `main'. In addition, LIBRARY can be written as any of`foo', `-lfoo', or `libfoo.a'. In all of those cases, thecompiler is passed `-lfoo'. However, LIBRARY cannot be a shellvariable; it must be a literal name.-- Macro: AC_HAVE_POUNDBANG`AC_SYS_INTERPRETER' (different calling convention)-- Macro: AC_HEADER_CHECK`AC_CHECK_HEADER'-- Macro: AC_HEADER_EGREP`AC_EGREP_HEADER'-- Macro: AC_HELP_STRING`AS_HELP_STRING'-- Macro: AC_INIT (UNIQUE-FILE-IN-SOURCE-DIR)Formerly `AC_INIT' used to have a single argument, and wasequivalent to:AC_INITAC_CONFIG_SRCDIR(UNIQUE-FILE-IN-SOURCE-DIR)-- Macro: AC_INLINE`AC_C_INLINE'-- Macro: AC_INT_16_BITSIf the C type `int' is 16 bits wide, define `INT_16_BITS'. Use`AC_CHECK_SIZEOF(int)' instead.-- Macro: AC_IRIX_SUNIf on IRIX (Silicon Graphics Unix), add `-lsun' to output `LIBS'.If you were using it to get `getmntent', use `AC_FUNC_GETMNTENT'instead. If you used it for the NIS versions of the password andgroup functions, use `AC_CHECK_LIB(sun, getpwnam)'. Up toAutoconf 2.13, it used to beAC_CHECK_LIB([sun], [getmntent], [LIBS="-lsun $LIBS"])now it is defined asAC_FUNC_GETMNTENTAC_CHECK_LIB([sun], [getpwnam])-- Macro: AC_LANG_CSame as `AC_LANG([C])'.-- Macro: AC_LANG_CPLUSPLUSSame as `AC_LANG([C++])'.-- Macro: AC_LANG_FORTRAN77Same as `AC_LANG([Fortran 77])'.-- Macro: AC_LANG_RESTORESelect the LANGUAGE that is saved on the top of the stack, as setby `AC_LANG_SAVE', remove it from the stack, and call`AC_LANG(LANGUAGE)'.-- Macro: AC_LANG_SAVERemember the current language (as set by `AC_LANG') on a stack.The current language does not change. `AC_LANG_PUSH' is preferred.-- Macro: AC_LINK_FILES (SOURCE..., DEST...)This is an obsolete version of `AC_CONFIG_LINKS'. An updatedversion of:AC_LINK_FILES(config/$machine.h config/$obj_format.h,host.h object.h)is:AC_CONFIG_LINKS([host.h:config/$machine.hobject.h:config/$obj_format.h])-- Macro: AC_LN_S`AC_PROG_LN_S'-- Macro: AC_LONG_64_BITSDefine `LONG_64_BITS' if the C type `long int' is 64 bits wide.Use the generic macro `AC_CHECK_SIZEOF([long int])' instead.-- Macro: AC_LONG_DOUBLEIf the C compiler supports a working `long double' type with morerange or precision than the `double' type, define`HAVE_LONG_DOUBLE'.You should use `AC_TYPE_LONG_DOUBLE' or`AC_TYPE_LONG_DOUBLE_WIDER' instead. *Note Particular Types::.-- Macro: AC_LONG_FILE_NAMES`AC_SYS_LONG_FILE_NAMES'-- Macro: AC_MAJOR_HEADER`AC_HEADER_MAJOR'-- Macro: AC_MEMORY_HUsed to define `NEED_MEMORY_H' if the `mem' functions were definedin `memory.h'. Today it is equivalent to`AC_CHECK_HEADERS([memory.h])'. Adjust your code to depend upon`HAVE_MEMORY_H', not `NEED_MEMORY_H'; see *Note Standard Symbols::.-- Macro: AC_MINGW32Similar to `AC_CYGWIN' but checks for the MinGW compilerenvironment and sets `MINGW32'.-- Macro: AC_MINUS_C_MINUS_O`AC_PROG_CC_C_O'-- Macro: AC_MMAP`AC_FUNC_MMAP'-- Macro: AC_MODE_T`AC_TYPE_MODE_T'-- Macro: AC_OBJEXTDefined the output variable `OBJEXT' based on the output of thecompiler, after .c files have been excluded. Typically set to `o'if Posix, `obj' if a DOS variant. Now the compiler checkingmacros handle this automatically.-- Macro: AC_OBSOLETE (THIS-MACRO-NAME, [SUGGESTION])Make M4 print a message to the standard error output warning thatTHIS-MACRO-NAME is obsolete, and giving the file and line numberwhere it was called. THIS-MACRO-NAME should be the name of themacro that is calling `AC_OBSOLETE'. If SUGGESTION is given, itis printed at the end of the warning message; for example, it canbe a suggestion for what to use instead of THIS-MACRO-NAME.For instanceAC_OBSOLETE([$0], [; use AC_CHECK_HEADERS(unistd.h) instead])dnlYou are encouraged to use `AU_DEFUN' instead, since it gives betterservices to the user.-- Macro: AC_OFF_T`AC_TYPE_OFF_T'-- Macro: AC_OUTPUT ([FILE]..., [EXTRA-CMDS], [INIT-CMDS])The use of `AC_OUTPUT' with argument is deprecated. This obsoletedinterface is equivalent to:AC_CONFIG_FILES(FILE...)AC_CONFIG_COMMANDS([default],EXTRA-CMDS, INIT-CMDS)AC_OUTPUT-- Macro: AC_OUTPUT_COMMANDS (EXTRA-CMDS, [INIT-CMDS])Specify additional shell commands to run at the end of`config.status', and shell commands to initialize any variablesfrom `configure'. This macro may be called multiple times. It isobsolete, replaced by `AC_CONFIG_COMMANDS'.Here is an unrealistic example:fubar=27AC_OUTPUT_COMMANDS([echo this is extra $fubar, and so on.],[fubar=$fubar])AC_OUTPUT_COMMANDS([echo this is another, extra, bit],[echo init bit])Aside from the fact that `AC_CONFIG_COMMANDS' requires anadditional key, an important difference is that`AC_OUTPUT_COMMANDS' is quoting its arguments twice, unlike`AC_CONFIG_COMMANDS'. This means that `AC_CONFIG_COMMANDS' cansafely be given macro calls as arguments:AC_CONFIG_COMMANDS(foo, [my_FOO()])Conversely, where one level of quoting was enough for literalstrings with `AC_OUTPUT_COMMANDS', you need two with`AC_CONFIG_COMMANDS'. The following lines are equivalent:AC_OUTPUT_COMMANDS([echo "Square brackets: []"])AC_CONFIG_COMMANDS([default], [[echo "Square brackets: []"]])-- Macro: AC_PID_T`AC_TYPE_PID_T'-- Macro: AC_PREFIX`AC_PREFIX_PROGRAM'-- Macro: AC_PROGRAMS_CHECK`AC_CHECK_PROGS'-- Macro: AC_PROGRAMS_PATH`AC_PATH_PROGS'-- Macro: AC_PROGRAM_CHECK`AC_CHECK_PROG'-- Macro: AC_PROGRAM_EGREP`AC_EGREP_CPP'-- Macro: AC_PROGRAM_PATH`AC_PATH_PROG'-- Macro: AC_REMOTE_TAPEremoved because of limited usefulness-- Macro: AC_RESTARTABLE_SYSCALLS`AC_SYS_RESTARTABLE_SYSCALLS'-- Macro: AC_RETSIGTYPE`AC_TYPE_SIGNAL'-- Macro: AC_RSHremoved because of limited usefulness-- Macro: AC_SCO_INTLIf on SCO Unix, add `-lintl' to output variable `LIBS'. Thismacro used to do this:AC_CHECK_LIB([intl], [strftime], [LIBS="-lintl $LIBS"])Now it just calls `AC_FUNC_STRFTIME' instead.-- Macro: AC_SETVBUF_REVERSED`AC_FUNC_SETVBUF_REVERSED'-- Macro: AC_SET_MAKE`AC_PROG_MAKE_SET'-- Macro: AC_SIZEOF_TYPE`AC_CHECK_SIZEOF'-- Macro: AC_SIZE_T`AC_TYPE_SIZE_T'-- Macro: AC_STAT_MACROS_BROKEN`AC_HEADER_STAT'-- Macro: AC_STDC_HEADERS`AC_HEADER_STDC'-- Macro: AC_STRCOLL`AC_FUNC_STRCOLL'-- Macro: AC_ST_BLKSIZE`AC_CHECK_MEMBERS'-- Macro: AC_ST_BLOCKS`AC_STRUCT_ST_BLOCKS'-- Macro: AC_ST_RDEV`AC_CHECK_MEMBERS'-- Macro: AC_SYS_RESTARTABLE_SYSCALLSIf the system automatically restarts a system call that isinterrupted by a signal, define `HAVE_RESTARTABLE_SYSCALLS'. Thismacro does not check whether system calls are restarted ingeneral--it checks whether a signal handler installed with`signal' (but not `sigaction') causes system calls to berestarted. It does not check whether system calls can berestarted when interrupted by signals that have no handler.These days portable programs should use `sigaction' with`SA_RESTART' if they want restartable system calls. They shouldnot rely on `HAVE_RESTARTABLE_SYSCALLS', since nowadays whether asystem call is restartable is a dynamic issue, not aconfiguration-time issue.-- Macro: AC_SYS_SIGLIST_DECLARED`AC_DECL_SYS_SIGLIST'-- Macro: AC_TEST_CPP`AC_TRY_CPP', replaced by `AC_PREPROC_IFELSE'.-- Macro: AC_TEST_PROGRAM`AC_TRY_RUN', replaced by `AC_RUN_IFELSE'.-- Macro: AC_TIMEZONE`AC_STRUCT_TIMEZONE'-- Macro: AC_TIME_WITH_SYS_TIME`AC_HEADER_TIME'-- Macro: AC_TRY_COMPILE (INCLUDES, FUNCTION-BODY, [ACTION-IF-TRUE],[ACTION-IF-FALSE])Same as:AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[INCLUDES]],[[FUNCTION-BODY]])],[ACTION-IF-TRUE],[ACTION-IF-FALSE])*Note Running the Compiler::.This macro double quotes both INCLUDES and FUNCTION-BODY.For C and C++, INCLUDES is any `#include' statements needed by thecode in FUNCTION-BODY (INCLUDES is ignored if the currentlyselected language is Fortran or Fortran 77). The compiler andcompilation flags are determined by the current language (*noteLanguage Choice::).-- Macro: AC_TRY_CPP (INPUT, [ACTION-IF-TRUE], [ACTION-IF-FALSE])Same as:AC_PREPROC_IFELSE([AC_LANG_SOURCE([[INPUT]])],[ACTION-IF-TRUE],[ACTION-IF-FALSE])*Note Running the Preprocessor::.This macro double quotes the INPUT.-- Macro: AC_TRY_LINK (INCLUDES, FUNCTION-BODY, [ACTION-IF-TRUE],[ACTION-IF-FALSE])Same as:AC_LINK_IFELSE([AC_LANG_PROGRAM([[INCLUDES]],[[FUNCTION-BODY]])],[ACTION-IF-TRUE],[ACTION-IF-FALSE])*Note Running the Compiler::.This macro double quotes both INCLUDES and FUNCTION-BODY.Depending on the current language (*note Language Choice::),create a test program to see whether a function whose bodyconsists of FUNCTION-BODY can be compiled and linked. If the filecompiles and links successfully, run shell commandsACTION-IF-FOUND, otherwise run ACTION-IF-NOT-FOUND.This macro double quotes both INCLUDES and FUNCTION-BODY.For C and C++, INCLUDES is any `#include' statements needed by thecode in FUNCTION-BODY (INCLUDES is ignored if the currentlyselected language is Fortran or Fortran 77). The compiler andcompilation flags are determined by the current language (*noteLanguage Choice::), and in addition `LDFLAGS' and `LIBS' are usedfor linking.-- Macro: AC_TRY_LINK_FUNC (FUNCTION, [ACTION-IF-FOUND],[ACTION-IF-NOT-FOUND])This macro is equivalent to `AC_LINK_IFELSE([AC_LANG_CALL([],[FUNCTION])], [ACTION-IF-FOUND], [ACTION-IF-NOT-FOUND])'.-- Macro: AC_TRY_RUN (PROGRAM, [ACTION-IF-TRUE], [ACTION-IF-FALSE],[ACTION-IF-CROSS-COMPILING])Same as:AC_RUN_IFELSE([AC_LANG_SOURCE([[PROGRAM]])],[ACTION-IF-TRUE],[ACTION-IF-FALSE],[ACTION-IF-CROSS-COMPILING])*Note Runtime::.-- Macro: AC_UID_T`AC_TYPE_UID_T'-- Macro: AC_UNISTD_HSame as `AC_CHECK_HEADERS([unistd.h])'.-- Macro: AC_USGDefine `USG' if the BSD string functions are defined in`strings.h'. You should no longer depend upon `USG', but on`HAVE_STRING_H'; see *Note Standard Symbols::.-- Macro: AC_UTIME_NULL`AC_FUNC_UTIME_NULL'-- Macro: AC_VALIDATE_CACHED_SYSTEM_TUPLE ([CMD])If the cache file is inconsistent with the current host, target andbuild system types, it used to execute CMD or print a defaulterror message. This is now handled by default.-- Macro: AC_VERBOSE (RESULT-DESCRIPTION)`AC_MSG_RESULT'.-- Macro: AC_VFORK`AC_FUNC_VFORK'-- Macro: AC_VPRINTF`AC_FUNC_VPRINTF'-- Macro: AC_WAIT3`AC_FUNC_WAIT3'-- Macro: AC_WARN`AC_MSG_WARN'-- Macro: AC_WORDS_BIGENDIAN`AC_C_BIGENDIAN'-- Macro: AC_XENIX_DIRThis macro used to add `-lx' to output variable `LIBS' if onXenix. Also, if `dirent.h' is being checked for, added `-ldir' to`LIBS'. Now it is merely an alias of `AC_HEADER_DIRENT' instead,plus some code to detect whether running XENIX on which you shouldnot depend:AC_MSG_CHECKING([for Xenix])AC_EGREP_CPP([yes],[#if defined M_XENIX && !defined M_UNIXyes#endif],[AC_MSG_RESULT([yes]); XENIX=yes],[AC_MSG_RESULT([no]); XENIX=])-- Macro: AC_YYTEXT_POINTER`AC_DECL_YYTEXT'File: autoconf.info, Node: Autoconf 1, Next: Autoconf 2.13, Prev: Obsolete Macros, Up: Obsolete Constructs17.5 Upgrading From Version 1=============================Autoconf version 2 is mostly backward compatible with version 1.However, it introduces better ways to do some things, and doesn'tsupport some of the ugly things in version 1. So, depending on howsophisticated your `configure.ac' files are, you might have to do somemanual work in order to upgrade to version 2. This chapter points outsome problems to watch for when upgrading. Also, perhaps your`configure' scripts could benefit from some of the new features inversion 2; the changes are summarized in the file `NEWS' in theAutoconf distribution.* Menu:* Changed File Names:: Files you might rename* Changed Makefiles:: New things to put in `Makefile.in'* Changed Macros:: Macro calls you might replace* Changed Results:: Changes in how to check test results* Changed Macro Writing:: Better ways to write your own macrosFile: autoconf.info, Node: Changed File Names, Next: Changed Makefiles, Up: Autoconf 117.5.1 Changed File Names-------------------------If you have an `aclocal.m4' installed with Autoconf (as opposed to in aparticular package's source directory), you must rename it to`acsite.m4'. *Note autoconf Invocation::.If you distribute `install.sh' with your package, rename it to`install-sh' so `make' builtin rules don't inadvertently create a filecalled `install' from it. `AC_PROG_INSTALL' looks for the script underboth names, but it is best to use the new name.If you were using `config.h.top', `config.h.bot', or `acconfig.h',you still can, but you have less clutter if you use the `AH_' macros.*Note Autoheader Macros::.File: autoconf.info, Node: Changed Makefiles, Next: Changed Macros, Prev: Changed File Names, Up: Autoconf 117.5.2 Changed Makefiles------------------------Add `@CFLAGS@', `@CPPFLAGS@', and `@LDFLAGS@' in your `Makefile.in'files, so they can take advantage of the values of those variables inthe environment when `configure' is run. Doing this isn't necessary,but it's a convenience for users.Also add `@configure_input@' in a comment to each input file for`AC_OUTPUT', so that the output files contain a comment saying theywere produced by `configure'. Automatically selecting the rightcomment syntax for all the kinds of files that people call `AC_OUTPUT'on became too much work.Add `config.log' and `config.cache' to the list of files you removein `distclean' targets.If you have the following in `Makefile.in':prefix = /usr/localexec_prefix = $(prefix)you must change it to:prefix = @prefix@exec_prefix = @exec_prefix@The old behavior of replacing those variables without `@' charactersaround them has been removed.File: autoconf.info, Node: Changed Macros, Next: Changed Results, Prev: Changed Makefiles, Up: Autoconf 117.5.3 Changed Macros---------------------Many of the macros were renamed in Autoconf version 2. You can stilluse the old names, but the new ones are clearer, and it's easier to findthe documentation for them. *Note Obsolete Macros::, for a tableshowing the new names for the old macros. Use the `autoupdate' programto convert your `configure.ac' to using the new macro names. *Noteautoupdate Invocation::.Some macros have been superseded by similar ones that do the jobbetter, but are not call-compatible. If you get warnings about callingobsolete macros while running `autoconf', you may safely ignore them,but your `configure' script generally works better if you follow theadvice that is printed about what to replace the obsolete macros with.In particular, the mechanism for reporting the results of tests haschanged. If you were using `echo' or `AC_VERBOSE' (perhaps via`AC_COMPILE_CHECK'), your `configure' script's output looks better ifyou switch to `AC_MSG_CHECKING' and `AC_MSG_RESULT'. *Note PrintingMessages::. Those macros work best in conjunction with cachevariables. *Note Caching Results::.File: autoconf.info, Node: Changed Results, Next: Changed Macro Writing, Prev: Changed Macros, Up: Autoconf 117.5.4 Changed Results----------------------If you were checking the results of previous tests by examining theshell variable `DEFS', you need to switch to checking the values of thecache variables for those tests. `DEFS' no longer exists while`configure' is running; it is only created when generating outputfiles. This difference from version 1 is because properly quoting thecontents of that variable turned out to be too cumbersome andinefficient to do every time `AC_DEFINE' is called. *Note CacheVariable Names::.For example, here is a `configure.ac' fragment written for Autoconfversion 1:AC_HAVE_FUNCS(syslog)case "$DEFS" in*-DHAVE_SYSLOG*) ;;*) # syslog is not in the default libraries. See if it's in some other.saved_LIBS="$LIBS"for lib in bsd socket inet; doAC_CHECKING(for syslog in -l$lib)LIBS="-l$lib $saved_LIBS"AC_HAVE_FUNCS(syslog)case "$DEFS" in*-DHAVE_SYSLOG*) break ;;*) ;;esacLIBS="$saved_LIBS"done ;;esacHere is a way to write it for version 2:AC_CHECK_FUNCS([syslog])if test $ac_cv_func_syslog = no; then# syslog is not in the default libraries. See if it's in some other.for lib in bsd socket inet; doAC_CHECK_LIB([$lib], [syslog], [AC_DEFINE([HAVE_SYSLOG])LIBS="-l$lib $LIBS"; break])donefiIf you were working around bugs in `AC_DEFINE_UNQUOTED' by addingbackslashes before quotes, you need to remove them. It now workspredictably, and does not treat quotes (except back quotes) specially.*Note Setting Output Variables::.All of the Boolean shell variables set by Autoconf macros now use`yes' for the true value. Most of them use `no' for false, though forbackward compatibility some use the empty string instead. If you wererelying on a shell variable being set to something like 1 or `t' fortrue, you need to change your tests.File: autoconf.info, Node: Changed Macro Writing, Prev: Changed Results, Up: Autoconf 117.5.5 Changed Macro Writing----------------------------When defining your own macros, you should now use `AC_DEFUN' instead of`define'. `AC_DEFUN' automatically calls `AC_PROVIDE' and ensures thatmacros called via `AC_REQUIRE' do not interrupt other macros, toprevent nested `checking...' messages on the screen. There's no actualharm in continuing to use the older way, but it's less convenient andattractive. *Note Macro Definitions::.You probably looked at the macros that came with Autoconf as a guidefor how to do things. It would be a good idea to take a look at the newversions of them, as the style is somewhat improved and they takeadvantage of some new features.If you were doing tricky things with undocumented Autoconf internals(macros, variables, diversions), check whether you need to changeanything to account for changes that have been made. Perhaps you caneven use an officially supported technique in version 2 instead ofkludging. Or perhaps not.To speed up your locally written feature tests, add caching to them.See whether any of your tests are of general enough usefulness toencapsulate them into macros that you can share.File: autoconf.info, Node: Autoconf 2.13, Prev: Autoconf 1, Up: Obsolete Constructs17.6 Upgrading From Version 2.13================================The introduction of the previous section (*note Autoconf 1::) perfectlysuits this section....Autoconf version 2.50 is mostly backward compatible with version2.13. However, it introduces better ways to do some things, anddoesn't support some of the ugly things in version 2.13. So,depending on how sophisticated your `configure.ac' files are, youmight have to do some manual work in order to upgrade to version2.50. This chapter points out some problems to watch for whenupgrading. Also, perhaps your `configure' scripts could benefitfrom some of the new features in version 2.50; the changes aresummarized in the file `NEWS' in the Autoconf distribution.* Menu:* Changed Quotation:: Broken code which used to work* New Macros:: Interaction with foreign macros* Hosts and Cross-Compilation:: Bugward compatibility kludges* AC_LIBOBJ vs LIBOBJS:: LIBOBJS is a forbidden token* AC_FOO_IFELSE vs AC_TRY_FOO:: A more generic scheme for testing sourcesFile: autoconf.info, Node: Changed Quotation, Next: New Macros, Up: Autoconf 2.1317.6.1 Changed Quotation------------------------The most important changes are invisible to you: the implementation ofmost macros have completely changed. This allowed more factorization ofthe code, better error messages, a higher uniformity of the user'sinterface etc. Unfortunately, as a side effect, some construct whichused to (miraculously) work might break starting with Autoconf 2.50.The most common culprit is bad quotation.For instance, in the following example, the message is not properlyquoted:AC_INITAC_CHECK_HEADERS(foo.h, ,AC_MSG_ERROR(cannot find foo.h, bailing out))AC_OUTPUTAutoconf 2.13 simply ignores it:$ autoconf-2.13; ./configure --silentcreating cache ./config.cacheconfigure: error: cannot find foo.h$while Autoconf 2.50 produces a broken `configure':$ autoconf-2.50; ./configure --silentconfigure: error: cannot find foo.h./configure: exit: bad non-numeric arg `bailing'./configure: exit: bad non-numeric arg `bailing'$The message needs to be quoted, and the `AC_MSG_ERROR' invocationtoo!AC_INIT([Example], [1.0], [bug-example@example.org])AC_CHECK_HEADERS([foo.h], [],[AC_MSG_ERROR([cannot find foo.h, bailing out])])AC_OUTPUTMany many (and many more) Autoconf macros were lacking properquotation, including no less than... `AC_DEFUN' itself!$ cat configure.inAC_DEFUN([AC_PROG_INSTALL],[# My own much better version])AC_INITAC_PROG_INSTALLAC_OUTPUT$ autoconf-2.13autoconf: Undefined macros:***BUG in Autoconf--please report*** AC_FD_MSG***BUG in Autoconf--please report*** AC_EPIconfigure.in:1:AC_DEFUN([AC_PROG_INSTALL],configure.in:5:AC_PROG_INSTALL$ autoconf-2.50$File: autoconf.info, Node: New Macros, Next: Hosts and Cross-Compilation, Prev: Changed Quotation, Up: Autoconf 2.1317.6.2 New Macros-----------------While Autoconf was relatively dormant in the late 1990s, Automakeprovided Autoconf-like macros for a while. Starting with Autoconf 2.50in 2001, Autoconf provided versions of these macros, integrated in the`AC_' namespace, instead of `AM_'. But in order to ease the upgradingvia `autoupdate', bindings to such `AM_' macros are provided.Unfortunately older versions of Automake (e.g., Automake 1.4) didnot quote the names of these macros. Therefore, when `m4' findssomething like `AC_DEFUN(AM_TYPE_PTRDIFF_T, ...)' in `aclocal.m4',`AM_TYPE_PTRDIFF_T' is expanded, replaced with its Autoconf definition.Fortunately Autoconf catches pre-`AC_INIT' expansions, andcomplains, in its own words:$ cat configure.acAC_INIT([Example], [1.0], [bug-example@example.org])AM_TYPE_PTRDIFF_T$ aclocal-1.4$ autoconfaclocal.m4:17: error: m4_defn: undefined macro: _m4_divert_diversionaclocal.m4:17: the top levelautom4te: m4 failed with exit status: 1$Modern versions of Automake no longer define most of these macros,and properly quote the names of the remaining macros. If you must usean old Automake, do not depend upon macros from Automake as it issimply not its job to provide macros (but the one it requires itself):$ cat configure.acAC_INIT([Example], [1.0], [bug-example@example.org])AM_TYPE_PTRDIFF_T$ rm aclocal.m4$ autoupdateautoupdate: `configure.ac' is updated$ cat configure.acAC_INIT([Example], [1.0], [bug-example@example.org])AC_CHECK_TYPES([ptrdiff_t])$ aclocal-1.4$ autoconf$File: autoconf.info, Node: Hosts and Cross-Compilation, Next: AC_LIBOBJ vs LIBOBJS, Prev: New Macros, Up: Autoconf 2.1317.6.3 Hosts and Cross-Compilation----------------------------------Based on the experience of compiler writers, and after long publicdebates, many aspects of the cross-compilation chain have changed:- the relationship between the build, host, and target architecturetypes,- the command line interface for specifying them to `configure',- the variables defined in `configure',- the enabling of cross-compilation mode.The relationship between build, host, and target have been cleanedup: the chain of default is now simply: target defaults to host, host tobuild, and build to the result of `config.guess'. Nevertheless, inorder to ease the transition from 2.13 to 2.50, the followingtransition scheme is implemented. _Do not rely on it_, as it will becompletely disabled in a couple of releases (we cannot keep it, as itproves to cause more problems than it cures).They all default to the result of running `config.guess', unless youspecify either `--build' or `--host'. In this case, the defaultbecomes the system type you specified. If you specify both, andthey're different, `configure' enters cross compilation mode, so itdoesn't run any tests that require execution.Hint: if you mean to override the result of `config.guess', prefer`--build' over `--host'. In the future, `--host' will not override thename of the build system type. Whenever you specify `--host', be sureto specify `--build' too.For backward compatibility, `configure' accepts a system type as anoption by itself. Such an option overrides the defaults for build,host, and target system types. The following configure statementconfigures a cross toolchain that runs on NetBSD/alpha but generatescode for GNU Hurd/sparc, which is also the build platform../configure --host=alpha-netbsd sparc-gnuIn Autoconf 2.13 and before, the variables `build', `host', and`target' had a different semantics before and after the invocation of`AC_CANONICAL_BUILD' etc. Now, the argument of `--build' is strictlycopied into `build_alias', and is left empty otherwise. After the`AC_CANONICAL_BUILD', `build' is set to the canonicalized build type.To ease the transition, before, its contents is the same as that of`build_alias'. Do _not_ rely on this broken feature.For consistency with the backward compatibility scheme exposed above,when `--host' is specified but `--build' isn't, the build system isassumed to be the same as `--host', and `build_alias' is set to thatvalue. Eventually, this historically incorrect behavior will go away.The former scheme to enable cross-compilation proved to cause moreharm than good, in particular, it used to be triggered too easily,leaving regular end users puzzled in front of cryptic error messages.`configure' could even enter cross-compilation mode only because thecompiler was not functional. This is mainly because `configure' usedto try to detect cross-compilation, instead of waiting for an explicitflag from the user.Now, `configure' enters cross-compilation mode if and only if`--host' is passed.That's the short documentation. To ease the transition between 2.13and its successors, a more complicated scheme is implemented. _Do notrely on the following_, as it will be removed in the near future.If you specify `--host', but not `--build', when `configure'performs the first compiler test it tries to run an executable producedby the compiler. If the execution fails, it enters cross-compilationmode. This is fragile. Moreover, by the time the compiler test isperformed, it may be too late to modify the build-system type: othertests may have already been performed. Therefore, whenever you specify`--host', be sure to specify `--build' too../configure --build=i686-pc-linux-gnu --host=m68k-coffenters cross-compilation mode. The former interface, which consistedin setting the compiler to a cross-compiler without informing`configure' is obsolete. For instance, `configure' fails if it can'trun the code generated by the specified compiler if you configure asfollows:./configure CC=m68k-coff-gccFile: autoconf.info, Node: AC_LIBOBJ vs LIBOBJS, Next: AC_FOO_IFELSE vs AC_TRY_FOO, Prev: Hosts and Cross-Compilation, Up: Autoconf 2.1317.6.4 `AC_LIBOBJ' vs. `LIBOBJS'--------------------------------Up to Autoconf 2.13, the replacement of functions was triggered via thevariable `LIBOBJS'. Since Autoconf 2.50, the macro `AC_LIBOBJ' shouldbe used instead (*note Generic Functions::). Starting at Autoconf2.53, the use of `LIBOBJS' is an error.This change is mandated by the unification of the GNU Build Systemcomponents. In particular, the various fragile techniques used to parsea `configure.ac' are all replaced with the use of traces. As aconsequence, any action must be traceable, which obsoletes criticalvariable assignments. Fortunately, `LIBOBJS' was the only problem, andit can even be handled gracefully (read, "without your having to changesomething").There were two typical uses of `LIBOBJS': asking for a replacementfunction, and adjusting `LIBOBJS' for Automake and/or Libtool.As for function replacement, the fix is immediate: use `AC_LIBOBJ'.For instance:LIBOBJS="$LIBOBJS fnmatch.o"LIBOBJS="$LIBOBJS malloc.$ac_objext"should be replaced with:AC_LIBOBJ([fnmatch])AC_LIBOBJ([malloc])When used with Automake 1.10 or newer, a suitable value for`LIBOBJDIR' is set so that the `LIBOBJS' and `LTLIBOBJS' can bereferenced from any `Makefile.am'. Even without Automake, arrangingfor `LIBOBJDIR' to be set correctly enables referencing `LIBOBJS' and`LTLIBOBJS' in another directory. The `LIBOJBDIR' feature isexperimental.File: autoconf.info, Node: AC_FOO_IFELSE vs AC_TRY_FOO, Prev: AC_LIBOBJ vs LIBOBJS, Up: Autoconf 2.1317.6.5 `AC_FOO_IFELSE' vs. `AC_TRY_FOO'---------------------------------------Since Autoconf 2.50, internal codes uses `AC_PREPROC_IFELSE',`AC_COMPILE_IFELSE', `AC_LINK_IFELSE', and `AC_RUN_IFELSE' on one handand `AC_LANG_SOURCES', and `AC_LANG_PROGRAM' on the other hand insteadof the deprecated `AC_TRY_CPP', `AC_TRY_COMPILE', `AC_TRY_LINK', and`AC_TRY_RUN'. The motivations where:- a more consistent interface: `AC_TRY_COMPILE' etc. were doublequoting their arguments;- the combinatoric explosion is solved by decomposing on the onehand the generation of sources, and on the other hand executingthe program;- this scheme helps supporting more languages than plain C and C++.In addition to the change of syntax, the philosophy has changed too:while emphasis was put on speed at the expense of accuracy, today'sAutoconf promotes accuracy of the testing framework at, ahem..., theexpense of speed.As a perfect example of what is _not_ to be done, here is how tofind out whether a header file contains a particular declaration, suchas a typedef, a structure, a structure member, or a function. Use`AC_EGREP_HEADER' instead of running `grep' directly on the headerfile; on some systems the symbol might be defined in another headerfile that the file you are checking includes.As a (bad) example, here is how you should not check for Cpreprocessor symbols, either defined by header files or predefined bythe C preprocessor: using `AC_EGREP_CPP':AC_EGREP_CPP(yes,[#ifdef _AIXyes#endif], is_aix=yes, is_aix=no)The above example, properly written would (i) use `AC_LANG_PROGRAM',and (ii) run the compiler:AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[#ifndef _AIXerror: This isn't AIX!#endif]])],[is_aix=yes],[is_aix=no])File: autoconf.info, Node: Using Autotest, Next: FAQ, Prev: Obsolete Constructs, Up: Top18 Generating Test Suites with Autotest****************************************N.B.: This section describes an experimental feature which willbe part of Autoconf in a forthcoming release. Although we believeAutotest is stabilizing, this documentation describes an interface whichmight change in the future: do not depend upon Autotest withoutsubscribing to the Autoconf mailing lists.*It is paradoxical that portable projects depend on nonportable toolsto run their test suite. Autoconf by itself is the paragon of thisproblem: although it aims at perfectly portability, up to 2.13 its testsuite was using DejaGNU, a rich and complex testing framework, butwhich is far from being standard on Posix systems. Worse yet, it waslikely to be missing on the most fragile platforms, the very platformsthat are most likely to torture Autoconf and exhibit deficiencies.To circumvent this problem, many package maintainers have developedtheir own testing framework, based on simple shell scripts whose soleoutputs are exit status values describing whether the test succeeded.Most of these tests share common patterns, and this can result in lotsof duplicated code and tedious maintenance.Following exactly the same reasoning that yielded to the inception ofAutoconf, Autotest provides a test suite generation framework, based onM4 macros building a portable shell script. The suite itself isequipped with automatic logging and tracing facilities which greatlydiminish the interaction with bug reporters, and simple timing reports.Autoconf itself has been using Autotest for years, and we do attestthat it has considerably improved the strength of the test suite and thequality of bug reports. Other projects are known to use some generationof Autotest, such as Bison, Free Recode, Free Wdiff, GNU Tar, each ofthem with different needs, and this usage has validated Autotest as ageneral testing framework.Nonetheless, compared to DejaGNU, Autotest is inadequate forinteractive tool testing, which is probably its main limitation.* Menu:* Using an Autotest Test Suite:: Autotest and the user* Writing testsuite.at:: Autotest macros* testsuite Invocation:: Running `testsuite' scripts* Making testsuite Scripts:: Using autom4te to create `testsuite'File: autoconf.info, Node: Using an Autotest Test Suite, Next: Writing testsuite.at, Up: Using Autotest18.1 Using an Autotest Test Suite=================================* Menu:* testsuite Scripts:: The concepts of Autotest* Autotest Logs:: Their contentsFile: autoconf.info, Node: testsuite Scripts, Next: Autotest Logs, Up: Using an Autotest Test Suite18.1.1 `testsuite' Scripts--------------------------Generating testing or validation suites using Autotest is rather easy.The whole validation suite is held in a file to be processed through`autom4te', itself using GNU M4 under the scene, to produce astand-alone Bourne shell script which then gets distributed. Neither`autom4te' nor GNU M4 are needed at the installer's end.Each test of the validation suite should be part of some test group.A "test group" is a sequence of interwoven tests that ought to beexecuted together, usually because one test in the group creates datafiles than a later test in the same group needs to read. Complex testgroups make later debugging more tedious. It is much better to keeponly a few tests per test group. Ideally there is only one test pertest group.For all but the simplest packages, some file such as `testsuite.at'does not fully hold all test sources, as these are often easier tomaintain in separate files. Each of these separate files holds a singletest group, or a sequence of test groups all addressing some commonfunctionality in the package. In such cases, `testsuite.at' merelyinitializes the validation suite, and sometimes does elementary healthchecking, before listing include statements for all other test files.The special file `package.m4', containing the identification of thepackage, is automatically included if found.A convenient alternative consists in moving all the global issues(local Autotest macros, elementary health checking, and `AT_INIT'invocation) into the file `local.at', and making `testsuite.at' be asimple list of `m4_include' of sub test suites. In such case,generating the whole test suite or pieces of it is only a matter ofchoosing the `autom4te' command line arguments.The validation scripts that Autotest produces are by conventioncalled `testsuite'. When run, `testsuite' executes each test group inturn, producing only one summary line per test to say if thatparticular test succeeded or failed. At end of all tests, summarizingcounters get printed. One debugging directory is left for each testgroup which failed, if any: such directories are named`testsuite.dir/NN', where NN is the sequence number of the test group,and they include:* a debugging script named `run' which reruns the test in "debugmode" (*note testsuite Invocation::). The automatic generation ofdebugging scripts has the purpose of easing the chase for bugs.* all the files created with `AT_DATA'* a log of the run, named `testsuite.log'In the ideal situation, none of the tests fail, and consequently nodebugging directory is left behind for validation.It often happens in practice that individual tests in the validationsuite need to get information coming out of the configuration process.Some of this information, common for all validation suites, is providedthrough the file `atconfig', automatically created by`AC_CONFIG_TESTDIR'. For configuration informations which your testingenvironment specifically needs, you might prepare an optional filenamed `atlocal.in', instantiated by `AC_CONFIG_FILES'. Theconfiguration process produces `atconfig' and `atlocal' out of thesetwo input files, and these two produced files are automatically read bythe `testsuite' script.Here is a diagram showing the relationship between files.Files used in preparing a software package for distribution:[package.m4] -->.\subfile-1.at ->. [local.at] ---->+... \ \subfile-i.at ---->-- testsuite.at -->-- autom4te* -->testsuite... /subfile-n.at ->'Files used in configuring a software package:.--> atconfig/[atlocal.in] --> config.status* --<\`--> [atlocal]Files created during the test suite execution:atconfig -->. .--> testsuite.log\ />-- testsuite* --</ \[atlocal] ->' `--> [testsuite.dir]File: autoconf.info, Node: Autotest Logs, Prev: testsuite Scripts, Up: Using an Autotest Test Suite18.1.2 Autotest Logs--------------------When run, the test suite creates a log file named after itself, e.g., atest suite named `testsuite' creates `testsuite.log'. It contains alot of information, usually more than maintainers actually need, buttherefore most of the time it contains all that is needed:command line argumentsA bad but unfortunately widespread habit consists of settingenvironment variables before the command, such as in`CC=my-home-grown-cc ./testsuite'. The test suite does not knowthis change, hence (i) it cannot report it to you, and (ii) itcannot preserve the value of `CC' for subsequent runs. Autoconffaced exactly the same problem, and solved it by asking users topass the variable definitions as command line arguments. Autotestrequires this rule, too, but has no means to enforce it; the logthen contains a trace of the variables that were changed by theuser.`ChangeLog' excerptsThe topmost lines of all the `ChangeLog' files found in the sourcehierarchy. This is especially useful when bugs are reportedagainst development versions of the package, since the versionstring does not provide sufficient information to know the exactstate of the sources the user compiled. Of course, this relies onthe use of a `ChangeLog'.build machineRunning a test suite in a cross-compile environment is not an easytask, since it would mean having the test suite run on a machineBUILD, while running programs on a machine HOST. It is muchsimpler to run both the test suite and the programs on HOST, butthen, from the point of view of the test suite, there remains asingle environment, HOST = BUILD. The log contains relevantinformation on the state of the build machine, including someimportant environment variables.tested programsThe absolute file name and answers to `--version' of the testedprograms (see *Note Writing testsuite.at::, `AT_TESTED').configuration logThe contents of `config.log', as created by `configure', areappended. It contains the configuration flags and a detailedreport on the configuration itself.File: autoconf.info, Node: Writing testsuite.at, Next: testsuite Invocation, Prev: Using an Autotest Test Suite, Up: Using Autotest18.2 Writing `testsuite.at'===========================The `testsuite.at' is a Bourne shell script making use of specialAutotest M4 macros. It often contains a call to `AT_INIT' near itsbeginning followed by one call to `m4_include' per source file fortests. Each such included file, or the remainder of `testsuite.at' ifinclude files are not used, contain a sequence of test groups. Eachtest group begins with a call to `AT_SETUP', then an arbitrary numberof shell commands or calls to `AT_CHECK', and then completes with acall to `AT_CLEANUP'.-- Macro: AT_INIT ([NAME])Initialize Autotest. Giving a NAME to the test suite isencouraged if your package includes several test suites. In anycase, the test suite always displays the package name and version.It also inherits the package bug report address.-- Macro: AT_COPYRIGHT (COPYRIGHT-NOTICE)State that, in addition to the Free Software Foundation'scopyright on the Autotest macros, parts of your test suite arecovered by COPYRIGHT-NOTICE.The COPYRIGHT-NOTICE shows up in both the head of `testsuite' andin `testsuite --version'.-- Macro: AT_TESTED (EXECUTABLES)Log the file name and answer to `--version' of each program inspace-separated list EXECUTABLES. Several invocations registernew executables, in other words, don't fear registering one programseveral times.Autotest test suites rely on `PATH' to find the tested program.This avoids the need to generate absolute names of the various tools,and makes it possible to test installed programs. Therefore, knowingwhich programs are being exercised is crucial to understanding problemsin the test suite itself, or its occasional misuses. It is a good ideato also subscribe foreign programs you depend upon, to avoidincompatible diagnostics.-- Macro: AT_SETUP (TEST-GROUP-NAME)This macro starts a group of related tests, all to be executed inthe same subshell. It accepts a single argument, which holds afew words (no more than about 30 or 40 characters) quicklydescribing the purpose of the test group being started.-- Macro: AT_KEYWORDS (KEYWORDS)Associate the space-separated list of KEYWORDS to the enclosingtest group. This makes it possible to run "slices" of the testsuite. For instance, if some of your test groups exercise some`foo' feature, then using `AT_KEYWORDS(foo)' lets you run`./testsuite -k foo' to run exclusively these test groups. TheTITLE of the test group is automatically recorded to `AT_KEYWORDS'.Several invocations within a test group accumulate new keywords.In other words, don't fear registering the same keyword severaltimes in a test group.-- Macro: AT_CAPTURE_FILE (FILE)If the current test group fails, log the contents of FILE.Several identical calls within one test group have no additionaleffect.-- Macro: AT_XFAIL_IF (SHELL-CONDITION)Determine whether the test is expected to fail because it is aknown bug (for unsupported features, you should skip the test).SHELL-CONDITION is a shell expression such as a `test' command;you can instantiate this macro many times from within the sametest group, and one of the conditions is enough to turn the testinto an expected failure.-- Macro: AT_CLEANUPEnd the current test group.-- Macro: AT_DATA (FILE, CONTENTS)Initialize an input data FILE with given CONTENTS. Of course, theCONTENTS have to be properly quoted between square brackets toprotect against included commas or spurious M4 expansion. Thecontents ought to end with an end of line.-- Macro: AT_CHECK (COMMANDS, [STATUS = `0'], [STDOUT = `'], [STDERR =`'], [RUN-IF-FAIL], [RUN-IF-PASS])Execute a test by performing given shell COMMANDS. These commandsshould normally exit with STATUS, while producing expected STDOUTand STDERR contents. If COMMANDS exit with status 77, then thewhole test group is skipped. Otherwise, if this test fails, runshell commands RUN-IF-FAIL or, if this test passes, run shellcommands RUN-IF-PASS.The COMMANDS _must not_ redirect the standard output, nor thestandard error.If STATUS, or STDOUT, or STDERR is `ignore', then thecorresponding value is not checked.The special value `expout' for STDOUT means the expected output ofthe COMMANDS is the content of the file `expout'. If STDOUT is`stdout', then the standard output of the COMMANDS is availablefor further tests in the file `stdout'. Similarly for STDERR with`experr' and `stderr'.File: autoconf.info, Node: testsuite Invocation, Next: Making testsuite Scripts, Prev: Writing testsuite.at, Up: Using Autotest18.3 Running `testsuite' Scripts================================Autotest test suites support the following arguments:`--help'`-h'Display the list of options and exit successfully.`--version'`-V'Display the version of the test suite and exit successfully.`--clean'`-c'Remove all the files the test suite might have created and exit.Meant for `clean' Make targets.`--list'`-l'List all the tests (or only the selection), including theirpossible keywords.By default all tests are performed (or described with `--list') inthe default environment first silently, then verbosely, but theenvironment, set of tests, and verbosity level can be tuned:`VARIABLE=VALUE'Set the environment VARIABLE to VALUE. Use this rather than`FOO=foo ./testsuite' as debugging scripts would then run in adifferent environment.The variable `AUTOTEST_PATH' specifies the testing path to prependto `PATH'. Relative directory names (not starting with `/') areconsidered to be relative to the top level of the package beingbuilt. All directories are made absolute, first starting from thetop level _build_ tree, then from the _source_ tree. For instance`./testsuite AUTOTEST_PATH=tests:bin' for a `/src/foo-1.0' sourcepackage built in `/tmp/foo' results in`/tmp/foo/tests:/tmp/foo/bin' and then`/src/foo-1.0/tests:/src/foo-1.0/bin' being prepended to `PATH'.`NUMBER'`NUMBER-NUMBER'`NUMBER-'`-NUMBER'Add the corresponding test groups, with obvious semantics, to theselection.`--keywords=KEYWORDS'`-k KEYWORDS'Add to the selection the test groups with title or keywords(arguments to `AT_SETUP' or `AT_KEYWORDS') that match _all_keywords of the comma separated list KEYWORDS, case-insensitively.Use `!' immediately before the keyword to invert the selectionfor this keyword. By default, the keywords match whole words;enclose them in `.*' to also match parts of words.For example, running./testsuite -k 'autoupdate,.*FUNC.*'selects all tests tagged `autoupdate' _and_ with tags containing`FUNC' (as in `AC_CHECK_FUNC', `AC_FUNC_ALLOCA', etc.), while./testsuite -k '!autoupdate' -k '.*FUNC.*'selects all tests not tagged `autoupdate' _or_ with tagscontaining `FUNC'.`--errexit'`-e'If any test fails, immediately abort testing. It implies`--debug': post test group clean up, and top-level logging areinhibited. This option is meant for the full test suite, it isnot really useful for generated debugging scripts.`--verbose'`-v'Force more verbosity in the detailed output of what is being done.This is the default for debugging scripts.`--debug'`-d'Do not remove the files after a test group was performed --butthey are still removed _before_, therefore using this option issane when running several test groups. Create debugging scripts.Do not overwrite the top-level log (in order to preservesupposedly existing full log file). This is the default fordebugging scripts, but it can also be useful to debug thetestsuite itself.`--trace'`-x'Trigger shell tracing of the test groups.File: autoconf.info, Node: Making testsuite Scripts, Prev: testsuite Invocation, Up: Using Autotest18.4 Making `testsuite' Scripts===============================For putting Autotest into movement, you need some configuration andmakefile machinery. We recommend, at least if your package uses deep orshallow hierarchies, that you use `tests/' as the name of the directoryholding all your tests and their makefile. Here is a check list ofthings to do.- Make sure to create the file `package.m4', which defines theidentity of the package. It must define `AT_PACKAGE_STRING', thefull signature of the package, and `AT_PACKAGE_BUGREPORT', theaddress to which bug reports should be sent. For sake ofcompleteness, we suggest that you also define `AT_PACKAGE_NAME',`AT_PACKAGE_TARNAME', and `AT_PACKAGE_VERSION'. *NoteInitializing configure::, for a description of these variables. Wesuggest the following makefile excerpt:$(srcdir)/package.m4: $(top_srcdir)/configure.ac{ \echo '# Signature of the current package.'; \echo 'm4_define([AT_PACKAGE_NAME], [@PACKAGE_NAME@])'; \echo 'm4_define([AT_PACKAGE_TARNAME], [@PACKAGE_TARNAME@])'; \echo 'm4_define([AT_PACKAGE_VERSION], [@PACKAGE_VERSION@])'; \echo 'm4_define([AT_PACKAGE_STRING], [@PACKAGE_STRING@])'; \echo 'm4_define([AT_PACKAGE_BUGREPORT], [@PACKAGE_BUGREPORT@])'; \} >'$(srcdir)/package.m4'Be sure to distribute `package.m4' and to put it into the sourcehierarchy: the test suite ought to be shipped!- Invoke `AC_CONFIG_TESTDIR'.-- Macro: AC_CONFIG_TESTDIR (DIRECTORY, [TEST-PATH = `directory'])An Autotest test suite is to be configured in DIRECTORY. Thismacro requires the instantiation of `DIRECTORY/atconfig' from`DIRECTORY/atconfig.in', and sets the default `AUTOTEST_PATH'to TEST-PATH (*note testsuite Invocation::).- Still within `configure.ac', as appropriate, ensure that some`AC_CONFIG_FILES' command includes substitution for`tests/atlocal'.- The `tests/Makefile.in' should be modified so the validation inyour package is triggered by `make check'. An example is providedbelow.With Automake, here is a minimal example about how to link `makecheck' with a validation suite.EXTRA_DIST = testsuite.at $(TESTSUITE) atlocal.inTESTSUITE = $(srcdir)/testsuitecheck-local: atconfig atlocal $(TESTSUITE)$(SHELL) '$(TESTSUITE)' $(TESTSUITEFLAGS)installcheck-local: atconfig atlocal $(TESTSUITE)$(SHELL) '$(TESTSUITE)' AUTOTEST_PATH='$(bindir)' \$(TESTSUITEFLAGS)clean-local:test ! -f '$(TESTSUITE)' || \$(SHELL) '$(TESTSUITE)' --cleanAUTOTEST = $(AUTOM4TE) --language=autotest$(TESTSUITE): $(srcdir)/testsuite.at$(AUTOTEST) -I '$(srcdir)' -o $@.tmp $@.atmv $@.tmp $@You might want to list explicitly the dependencies, i.e., the list ofthe files `testsuite.at' includes.With strict Autoconf, you might need to add lines inspired from thefollowing:subdir = testsatconfig: $(top_builddir)/config.statuscd $(top_builddir) && \$(SHELL) ./config.status $(subdir)/$@atlocal: $(srcdir)/atlocal.in $(top_builddir)/config.statuscd $(top_builddir) && \$(SHELL) ./config.status $(subdir)/$@and manage to have `atconfig.in' and `$(EXTRA_DIST)' distributed.With all this in place, and if you have not initialized`TESTSUITEFLAGS' within your makefile, you can fine-tune test suiteexecution with this variable, for example:make check TESTSUITEFLAGS='-v -d -x 75 -k AC_PROG_CC CFLAGS=-g'File: autoconf.info, Node: FAQ, Next: History, Prev: Using Autotest, Up: Top19 Frequent Autoconf Questions, with answers********************************************Several questions about Autoconf come up occasionally. Here some ofthem are addressed.* Menu:* Distributing:: Distributing `configure' scripts* Why GNU M4:: Why not use the standard M4?* Bootstrapping:: Autoconf and GNU M4 require each other?* Why Not Imake:: Why GNU uses `configure' instead of Imake* Defining Directories:: Passing `datadir' to program* autom4te.cache:: What is it? Can I remove it?* Present But Cannot Be Compiled:: Compiler and Preprocessor DisagreeFile: autoconf.info, Node: Distributing, Next: Why GNU M4, Up: FAQ19.1 Distributing `configure' Scripts=====================================What are the restrictions on distributing `configure'scripts that Autoconf generates? How does that affect myprograms that use them?There are no restrictions on how the configuration scripts thatAutoconf produces may be distributed or used. In Autoconf version 1,they were covered by the GNU General Public License. We still encouragesoftware authors to distribute their work under terms like those of theGPL, but doing so is not required to use Autoconf.Of the other files that might be used with `configure',`config.h.in' is under whatever copyright you use for your`configure.ac'. `config.sub' and `config.guess' have an exception tothe GPL when they are used with an Autoconf-generated `configure'script, which permits you to distribute them under the same terms asthe rest of your package. `install-sh' is from the X Consortium and isnot copyrighted.File: autoconf.info, Node: Why GNU M4, Next: Bootstrapping, Prev: Distributing, Up: FAQ19.2 Why Require GNU M4?========================Why does Autoconf require GNU M4?Many M4 implementations have hard-coded limitations on the size andnumber of macros that Autoconf exceeds. They also lack several builtinmacros that it would be difficult to get along without in asophisticated application like Autoconf, including:m4_builtinm4_indirm4_bpatsubst__file____line__Autoconf requires version 1.4.7 or later of GNU M4.Since only software maintainers need to use Autoconf, and since GNUM4 is simple to configure and install, it seems reasonable to requireGNU M4 to be installed also. Many maintainers of GNU and other freesoftware already have most of the GNU utilities installed, since theyprefer them.File: autoconf.info, Node: Bootstrapping, Next: Why Not Imake, Prev: Why GNU M4, Up: FAQ19.3 How Can I Bootstrap?=========================If Autoconf requires GNU M4 and GNU M4 has an Autoconf`configure' script, how do I bootstrap? It seems like a chickenand egg problem!This is a misunderstanding. Although GNU M4 does come with a`configure' script produced by Autoconf, Autoconf is not required inorder to run the script and install GNU M4. Autoconf is only requiredif you want to change the M4 `configure' script, which few people haveto do (mainly its maintainer).File: autoconf.info, Node: Why Not Imake, Next: Defining Directories, Prev: Bootstrapping, Up: FAQ19.4 Why Not Imake?===================Why not use Imake instead of `configure' scripts?Several people have written addressing this question, so I includeadaptations of their explanations here.The following answer is based on one written by Richard Pixley:Autoconf generated scripts frequently work on machines that it hasnever been set up to handle before. That is, it does a good job ofinferring a configuration for a new system. Imake cannot do this.Imake uses a common database of host specific data. For X11, thismakes sense because the distribution is made as a collection oftools, by one central authority who has control over the database.GNU tools are not released this way. Each GNU tool has amaintainer; these maintainers are scattered across the world.Using a common database would be a maintenance nightmare.Autoconf may appear to be this kind of database, but in fact it isnot. Instead of listing host dependencies, it lists programrequirements.If you view the GNU suite as a collection of native tools, then theproblems are similar. But the GNU development tools can beconfigured as cross tools in almost any host+target permutation.All of these configurations can be installed concurrently. Theycan even be configured to share host independent files acrosshosts. Imake doesn't address these issues.Imake templates are a form of standardization. The GNU codingstandards address the same issues without necessarily imposing thesame restrictions.Here is some further explanation, written by Per Bothner:One of the advantages of Imake is that it easy to generate largemakefiles using the `#include' and macro mechanisms of `cpp'.However, `cpp' is not programmable: it has limited conditionalfacilities, and no looping. And `cpp' cannot inspect itsenvironment.All of these problems are solved by using `sh' instead of `cpp'.The shell is fully programmable, has macro substitution, canexecute (or source) other shell scripts, and can inspect itsenvironment.Paul Eggert elaborates more:With Autoconf, installers need not assume that Imake itself isalready installed and working well. This may not seem like muchof an advantage to people who are accustomed to Imake. But onmany hosts Imake is not installed or the default installation isnot working well, and requiring Imake to install a package hindersthe acceptance of that package on those hosts. For example, theImake template and configuration files might not be installedproperly on a host, or the Imake build procedure might wronglyassume that all source files are in one big directory tree, or theImake configuration might assume one compiler whereas the packageor the installer needs to use another, or there might be a versionmismatch between the Imake expected by the package and the Imakesupported by the host. These problems are much rarer withAutoconf, where each package comes with its own independentconfiguration processor.Also, Imake often suffers from unexpected interactions between`make' and the installer's C preprocessor. The fundamental problemhere is that the C preprocessor was designed to preprocess Cprograms, not makefiles. This is much less of a problem withAutoconf, which uses the general-purpose preprocessor M4, andwhere the package's author (rather than the installer) does thepreprocessing in a standard way.Finally, Mark Eichin notes:Imake isn't all that extensible, either. In order to add newfeatures to Imake, you need to provide your own project template,and duplicate most of the features of the existing one. Thismeans that for a sophisticated project, using the vendor-providedImake templates fails to provide any leverage--since they don'tcover anything that your own project needs (unless it is an X11program).On the other side, though:The one advantage that Imake has over `configure': `Imakefile'files tend to be much shorter (likewise, less redundant) than`Makefile.in' files. There is a fix to this, however--at leastfor the Kerberos V5 tree, we've modified things to call in common`post.in' and `pre.in' makefile fragments for the entire tree.This means that a lot of common things don't have to beduplicated, even though they normally are in `configure' setups.File: autoconf.info, Node: Defining Directories, Next: autom4te.cache, Prev: Why Not Imake, Up: FAQ19.5 How Do I `#define' Installation Directories?=================================================My program needs library files, installed in `datadir' andsimilar. If I useAC_DEFINE_UNQUOTED([DATADIR], [$datadir],[Define to the read-only architecture-independentdata directory.])I get#define DATADIR "${prefix}/share"As already explained, this behavior is on purpose, mandated by the GNUCoding Standards, see *Note Installation Directory Variables::. Thereare several means to achieve a similar goal:- Do not use `AC_DEFINE' but use your makefile to pass the actualvalue of `datadir' via compilation flags. *Note InstallationDirectory Variables::, for the details.- This solution can be simplified when compiling a program: you mayeither extend the `CPPFLAGS':CPPFLAGS = -DDATADIR='"$(datadir)"' @CPPFLAGS@or create a dedicated header file:DISTCLEANFILES = datadir.hdatadir.h: Makefileecho '#define DATADIR "$(datadir)"' >$@- Use `AC_DEFINE' but have `configure' compute the literal value of`datadir' and others. Many people have wrapped macros to automatethis task. For instance, the macro `AC_DEFINE_DIR' from theAutoconf Macro Archive (http://autoconf-archive.cryp.to/).This solution does not conform to the GNU Coding Standards.- Note that all the previous solutions hard wire the absolute name ofthese directories in the executables, which is not a goodproperty. You may try to compute the names relative to `prefix',and try to find `prefix' at runtime, this way your package isrelocatable. Some macros are already available to address thisissue: see `adl_COMPUTE_RELATIVE_PATHS' and`adl_COMPUTE_STANDARD_RELATIVE_PATHS' on the Autoconf MacroArchive (http://autoconf-archive.cryp.to/).File: autoconf.info, Node: autom4te.cache, Next: Present But Cannot Be Compiled, Prev: Defining Directories, Up: FAQ19.6 What is `autom4te.cache'?==============================What is this directory `autom4te.cache'? Can I safely remove it?In the GNU Build System, `configure.ac' plays a central role and isread by many tools: `autoconf' to create `configure', `autoheader' tocreate `config.h.in', `automake' to create `Makefile.in', `autoscan' tocheck the completeness of `configure.ac', `autoreconf' to check the GNUBuild System components that are used. To "read `configure.ac'"actually means to compile it with M4, which can be a long process forcomplex `configure.ac'.This is why all these tools, instead of running directly M4, invoke`autom4te' (*note autom4te Invocation::) which, while answering to aspecific demand, stores additional information in `autom4te.cache' forfuture runs. For instance, if you run `autoconf', behind the scenes,`autom4te' also stores information for the other tools, so that whenyou invoke `autoheader' or `automake' etc., reprocessing `configure.ac'is not needed. The speed up is frequently of 30%, and is increasingwith the size of `configure.ac'.But it is and remains being simply a cache: you can safely remove it.Can I permanently get rid of it?The creation of this cache can be disabled from `~/.autom4te.cfg',see *Note Customizing autom4te::, for more details. You should beaware that disabling the cache slows down the Autoconf test suite by40%. The more GNU Build System components are used, the more the cacheis useful; for instance running `autoreconf -f' on the Core Utilitiesis twice slower without the cache _although `--force' implies that thecache is not fully exploited_, and eight times slower than without`--force'.File: autoconf.info, Node: Present But Cannot Be Compiled, Prev: autom4te.cache, Up: FAQ19.7 Header Present But Cannot Be Compiled==========================================The most important guideline to bear in mind when checking for featuresis to mimic as much as possible the intended use. Unfortunately, oldversions of `AC_CHECK_HEADER' and `AC_CHECK_HEADERS' failed to followthis idea, and called the preprocessor, instead of the compiler, tocheck for headers. As a result, incompatibilities between headers wentunnoticed during configuration, and maintainers finally had to dealwith this issue elsewhere.As of Autoconf 2.56 both checks are performed, and `configure'complains loudly if the compiler and the preprocessor do not agree.For the time being the result used is that of the preprocessor, to givemaintainers time to adjust their `configure.ac', but in the future,only the compiler will be considered.Consider the following example:$ cat number.htypedef int number;$ cat pi.hconst number pi = 3;$ cat configure.acAC_INIT([Example], [1.0], [bug-example@example.org])AC_CHECK_HEADERS([pi.h])$ autoconf -Wall$ ./configurechecking for gcc... gccchecking for C compiler default output file name... a.outchecking whether the C compiler works... yeschecking whether we are cross compiling... nochecking for suffix of executables...checking for suffix of object files... ochecking whether we are using the GNU C compiler... yeschecking whether gcc accepts -g... yeschecking for gcc option to accept ISO C89... none neededchecking how to run the C preprocessor... gcc -Echecking for grep that handles long lines and -e... grepchecking for egrep... grep -Echecking for ANSI C header files... yeschecking for sys/types.h... yeschecking for sys/stat.h... yeschecking for stdlib.h... yeschecking for string.h... yeschecking for memory.h... yeschecking for strings.h... yeschecking for inttypes.h... yeschecking for stdint.h... yeschecking for unistd.h... yeschecking pi.h usability... nochecking pi.h presence... yesconfigure: WARNING: pi.h: present but cannot be compiledconfigure: WARNING: pi.h: check for missing prerequisite headers?configure: WARNING: pi.h: see the Autoconf documentationconfigure: WARNING: pi.h: section "Present But Cannot Be Compiled"configure: WARNING: pi.h: proceeding with the preprocessor's resultconfigure: WARNING: pi.h: in the future, the compiler will take precedenceconfigure: WARNING: ## -------------------------------------- ##configure: WARNING: ## Report this to bug-example@example.org ##configure: WARNING: ## -------------------------------------- ##checking for pi.h... yesThe proper way the handle this case is using the fourth argument (*noteGeneric Headers::):$ cat configure.acAC_INIT([Example], [1.0], [bug-example@example.org])AC_CHECK_HEADERS([number.h pi.h], [], [],[[#ifdef HAVE_NUMBER_H# include <number.h>#endif]])$ autoconf -Wall$ ./configurechecking for gcc... gccchecking for C compiler default output... a.outchecking whether the C compiler works... yeschecking whether we are cross compiling... nochecking for suffix of executables...checking for suffix of object files... ochecking whether we are using the GNU C compiler... yeschecking whether gcc accepts -g... yeschecking for gcc option to accept ANSI C... none neededchecking for number.h... yeschecking for pi.h... yesSee *Note Particular Headers::, for a list of headers with theirprerequisite.File: autoconf.info, Node: History, Next: Copying This Manual, Prev: FAQ, Up: Top20 History of Autoconf**********************You may be wondering, Why was Autoconf originally written? How did itget into its present form? (Why does it look like gorilla spit?) Ifyou're not wondering, then this chapter contains no information usefulto you, and you might as well skip it. If you _are_ wondering, thenlet there be light....* Menu:* Genesis:: Prehistory and naming of `configure'* Exodus:: The plagues of M4 and Perl* Leviticus:: The priestly code of portability arrives* Numbers:: Growth and contributors* Deuteronomy:: Approaching the promises of easy configurationFile: autoconf.info, Node: Genesis, Next: Exodus, Up: History20.1 Genesis============In June 1991 I was maintaining many of the GNU utilities for the FreeSoftware Foundation. As they were ported to more platforms and moreprograms were added, the number of `-D' options that users had toselect in the makefile (around 20) became burdensome. Especially forme--I had to test each new release on a bunch of different systems. SoI wrote a little shell script to guess some of the correct settings forthe fileutils package, and released it as part of fileutils 2.0. That`configure' script worked well enough that the next month I adapted it(by hand) to create similar `configure' scripts for several other GNUutilities packages. Brian Berliner also adapted one of my scripts forhis CVS revision control system.Later that summer, I learned that Richard Stallman and Richard Pixleywere developing similar scripts to use in the GNU compiler tools; so Iadapted my `configure' scripts to support their evolving interface:using the file name `Makefile.in' as the templates; adding `+srcdir',the first option (of many); and creating `config.status' files.File: autoconf.info, Node: Exodus, Next: Leviticus, Prev: Genesis, Up: History20.2 Exodus===========As I got feedback from users, I incorporated many improvements, usingEmacs to search and replace, cut and paste, similar changes in each ofthe scripts. As I adapted more GNU utilities packages to use`configure' scripts, updating them all by hand became impractical.Rich Murphey, the maintainer of the GNU graphics utilities, sent memail saying that the `configure' scripts were great, and asking if Ihad a tool for generating them that I could send him. No, I thought,but I should! So I started to work out how to generate them. And thejourney from the slavery of hand-written `configure' scripts to theabundance and ease of Autoconf began.Cygnus `configure', which was being developed at around that time,is table driven; it is meant to deal mainly with a discrete number ofsystem types with a small number of mainly unguessable features (such asdetails of the object file format). The automatic configuration systemthat Brian Fox had developed for Bash takes a similar approach. Forgeneral use, it seems to me a hopeless cause to try to maintain anup-to-date database of which features each variant of each operatingsystem has. It's easier and more reliable to check for most features onthe fly--especially on hybrid systems that people have hacked onlocally or that have patches from vendors installed.I considered using an architecture similar to that of Cygnus`configure', where there is a single `configure' script that readspieces of `configure.in' when run. But I didn't want to have todistribute all of the feature tests with every package, so I settled onhaving a different `configure' made from each `configure.in' by apreprocessor. That approach also offered more control and flexibility.I looked briefly into using the Metaconfig package, by Larry Wall,Harlan Stenn, and Raphael Manfredi, but I decided not to for severalreasons. The `Configure' scripts it produces are interactive, which Ifind quite inconvenient; I didn't like the ways it checked for somefeatures (such as library functions); I didn't know that it was stillbeing maintained, and the `Configure' scripts I had seen didn't work onmany modern systems (such as System V R4 and NeXT); it wasn't flexiblein what it could do in response to a feature's presence or absence; Ifound it confusing to learn; and it was too big and complex for myneeds (I didn't realize then how much Autoconf would eventually have togrow).I considered using Perl to generate my style of `configure' scripts,but decided that M4 was better suited to the job of simple textualsubstitutions: it gets in the way less, because output is implicit.Plus, everyone already has it. (Initially I didn't rely on the GNUextensions to M4.) Also, some of my friends at the University ofMaryland had recently been putting M4 front ends on several programs,including `tvtwm', and I was interested in trying out a new language.File: autoconf.info, Node: Leviticus, Next: Numbers, Prev: Exodus, Up: History20.3 Leviticus==============Since my `configure' scripts determine the system's capabilitiesautomatically, with no interactive user intervention, I decided to callthe program that generates them Autoconfig. But with a version numbertacked on, that name would be too long for old Unix file systems, so Ishortened it to Autoconf.In the fall of 1991 I called together a group of fellow questersafter the Holy Grail of portability (er, that is, alpha testers) togive me feedback as I encapsulated pieces of my handwritten scripts inM4 macros and continued to add features and improve the techniques usedin the checks. Prominent among the testers were Franc,ois Pinard, whocame up with the idea of making an Autoconf shell script to run M4 andcheck for unresolved macro calls; Richard Pixley, who suggested runningthe compiler instead of searching the file system to find include filesand symbols, for more accurate results; Karl Berry, who got Autoconf toconfigure TeX and added the macro index to the documentation; and IanLance Taylor, who added support for creating a C header file as analternative to putting `-D' options in a makefile, so he could useAutoconf for his UUCP package. The alpha testers cheerfully adjustedtheir files again and again as the names and calling conventions of theAutoconf macros changed from release to release. They all contributedmany specific checks, great ideas, and bug fixes.File: autoconf.info, Node: Numbers, Next: Deuteronomy, Prev: Leviticus, Up: History20.4 Numbers============In July 1992, after months of alpha testing, I released Autoconf 1.0,and converted many GNU packages to use it. I was surprised by howpositive the reaction to it was. More people started using it than Icould keep track of, including people working on software that wasn'tpart of the GNU Project (such as TCL, FSP, and Kerberos V5). Autoconfcontinued to improve rapidly, as many people using the `configure'scripts reported problems they encountered.Autoconf turned out to be a good torture test for M4 implementations.Unix M4 started to dump core because of the length of the macros thatAutoconf defined, and several bugs showed up in GNU M4 as well.Eventually, we realized that we needed to use some features that onlyGNU M4 has. 4.3BSD M4, in particular, has an impoverished set ofbuiltin macros; the System V version is better, but still doesn'tprovide everything we need.More development occurred as people put Autoconf under more stresses(and to uses I hadn't anticipated). Karl Berry added checks for X11.david zuhn contributed C++ support. Franc,ois Pinard made it diagnoseinvalid arguments. Jim Blandy bravely coerced it into configuring GNUEmacs, laying the groundwork for several later improvements. RolandMcGrath got it to configure the GNU C Library, wrote the `autoheader'script to automate the creation of C header file templates, and added a`--verbose' option to `configure'. Noah Friedman added the`--autoconf-dir' option and `AC_MACRODIR' environment variable. (Healso coined the term "autoconfiscate" to mean "adapt a software packageto use Autoconf".) Roland and Noah improved the quoting protection in`AC_DEFINE' and fixed many bugs, especially when I got sick of dealingwith portability problems from February through June, 1993.File: autoconf.info, Node: Deuteronomy, Prev: Numbers, Up: History20.5 Deuteronomy================A long wish list for major features had accumulated, and the effect ofseveral years of patching by various people had left some residualcruft. In April 1994, while working for Cygnus Support, I began a majorrevision of Autoconf. I added most of the features of the Cygnus`configure' that Autoconf had lacked, largely by adapting the relevantparts of Cygnus `configure' with the help of david zuhn and KenRaeburn. These features include support for using `config.sub',`config.guess', `--host', and `--target'; making links to files; andrunning `configure' scripts in subdirectories. Adding these featuresenabled Ken to convert GNU `as', and Rob Savoye to convert DejaGNU, tousing Autoconf.I added more features in response to other peoples' requests. Manypeople had asked for `configure' scripts to share the results of thechecks between runs, because (particularly when configuring a largesource tree, like Cygnus does) they were frustratingly slow. MikeHaertel suggested adding site-specific initialization scripts. Peopledistributing software that had to unpack on MS-DOS asked for a way tooverride the `.in' extension on the file names, which produced filenames like `config.h.in' containing two dots. Jim Avera did anextensive examination of the problems with quoting in `AC_DEFINE' and`AC_SUBST'; his insights led to significant improvements. RichardStallman asked that compiler output be sent to `config.log' instead of`/dev/null', to help people debug the Emacs `configure' script.I made some other changes because of my dissatisfaction with thequality of the program. I made the messages showing results of thechecks less ambiguous, always printing a result. I regularized thenames of the macros and cleaned up coding style inconsistencies. Iadded some auxiliary utilities that I had developed to help convertsource code packages to use Autoconf. With the help of Franc,oisPinard, I made the macros not interrupt each others' messages. (Thatfeature revealed some performance bottlenecks in GNU M4, which hehastily corrected!) I reorganized the documentation around problemspeople want to solve. And I began a test suite, because experience hadshown that Autoconf has a pronounced tendency to regress when we changeit.Again, several alpha testers gave invaluable feedback, especiallyFranc,ois Pinard, Jim Meyering, Karl Berry, Rob Savoye, Ken Raeburn,and Mark Eichin.Finally, version 2.0 was ready. And there was much rejoicing. (AndI have free time again. I think. Yeah, right.)File: autoconf.info, Node: Copying This Manual, Next: Indices, Prev: History, Up: TopAppendix A Copying This Manual******************************* Menu:* GNU Free Documentation License:: License for copying this manualFile: autoconf.info, Node: GNU Free Documentation License, Up: Copying This ManualA.1 GNU Free Documentation License==================================Version 1.2, November 2002Copyright (C) 2000,2001,2002 Free Software Foundation, Inc.51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USAEveryone is permitted to copy and distribute verbatim copiesof this license document, but changing it is not allowed.0. PREAMBLEThe purpose of this License is to make a manual, textbook, or otherfunctional and useful document "free" in the sense of freedom: toassure everyone the effective freedom to copy and redistribute it,with or without modifying it, either commercially ornoncommercially. Secondarily, this License preserves for theauthor and publisher a way to get credit for their work, while notbeing considered responsible for modifications made by others.This License is a kind of "copyleft", which means that derivativeworks of the document must themselves be free in the same sense.It complements the GNU General Public License, which is a copyleftlicense designed for free software.We have designed this License in order to use it for manuals forfree software, because free software needs free documentation: afree program should come with manuals providing the same freedomsthat the software does. But this License is not limited tosoftware manuals; it can be used for any textual work, regardlessof subject matter or whether it is published as a printed book.We recommend this License principally for works whose purpose isinstruction or reference.1. APPLICABILITY AND DEFINITIONSThis License applies to any manual or other work, in any medium,that contains a notice placed by the copyright holder saying itcan be distributed under the terms of this License. Such a noticegrants a world-wide, royalty-free license, unlimited in duration,to use that work under the conditions stated herein. The"Document", below, refers to any such manual or work. Any memberof the public is a licensee, and is addressed as "you". Youaccept the license if you copy, modify or distribute the work in away requiring permission under copyright law.A "Modified Version" of the Document means any work containing theDocument or a portion of it, either copied verbatim, or withmodifications and/or translated into another language.A "Secondary Section" is a named appendix or a front-matter sectionof the Document that deals exclusively with the relationship of thepublishers or authors of the Document to the Document's overallsubject (or to related matters) and contains nothing that couldfall directly within that overall subject. (Thus, if the Documentis in part a textbook of mathematics, a Secondary Section may notexplain any mathematics.) The relationship could be a matter ofhistorical connection with the subject or with related matters, orof legal, commercial, philosophical, ethical or political positionregarding them.The "Invariant Sections" are certain Secondary Sections whosetitles are designated, as being those of Invariant Sections, inthe notice that says that the Document is released under thisLicense. If a section does not fit the above definition ofSecondary then it is not allowed to be designated as Invariant.The Document may contain zero Invariant Sections. If the Documentdoes not identify any Invariant Sections then there are none.The "Cover Texts" are certain short passages of text that arelisted, as Front-Cover Texts or Back-Cover Texts, in the noticethat says that the Document is released under this License. AFront-Cover Text may be at most 5 words, and a Back-Cover Text maybe at most 25 words.A "Transparent" copy of the Document means a machine-readable copy,represented in a format whose specification is available to thegeneral public, that is suitable for revising the documentstraightforwardly with generic text editors or (for imagescomposed of pixels) generic paint programs or (for drawings) somewidely available drawing editor, and that is suitable for input totext formatters or for automatic translation to a variety offormats suitable for input to text formatters. A copy made in anotherwise Transparent file format whose markup, or absence ofmarkup, has been arranged to thwart or discourage subsequentmodification by readers is not Transparent. An image format isnot Transparent if used for any substantial amount of text. Acopy that is not "Transparent" is called "Opaque".Examples of suitable formats for Transparent copies include plainASCII without markup, Texinfo input format, LaTeX input format,SGML or XML using a publicly available DTD, andstandard-conforming simple HTML, PostScript or PDF designed forhuman modification. Examples of transparent image formats includePNG, XCF and JPG. Opaque formats include proprietary formats thatcan be read and edited only by proprietary word processors, SGML orXML for which the DTD and/or processing tools are not generallyavailable, and the machine-generated HTML, PostScript or PDFproduced by some word processors for output purposes only.The "Title Page" means, for a printed book, the title page itself,plus such following pages as are needed to hold, legibly, thematerial this License requires to appear in the title page. Forworks in formats which do not have any title page as such, "TitlePage" means the text near the most prominent appearance of thework's title, preceding the beginning of the body of the text.A section "Entitled XYZ" means a named subunit of the Documentwhose title either is precisely XYZ or contains XYZ in parenthesesfollowing text that translates XYZ in another language. (Here XYZstands for a specific section name mentioned below, such as"Acknowledgements", "Dedications", "Endorsements", or "History".)To "Preserve the Title" of such a section when you modify theDocument means that it remains a section "Entitled XYZ" accordingto this definition.The Document may include Warranty Disclaimers next to the noticewhich states that this License applies to the Document. TheseWarranty Disclaimers are considered to be included by reference inthis License, but only as regards disclaiming warranties: any otherimplication that these Warranty Disclaimers may have is void andhas no effect on the meaning of this License.2. VERBATIM COPYINGYou may copy and distribute the Document in any medium, eithercommercially or noncommercially, provided that this License, thecopyright notices, and the license notice saying this Licenseapplies to the Document are reproduced in all copies, and that youadd no other conditions whatsoever to those of this License. Youmay not use technical measures to obstruct or control the readingor further copying of the copies you make or distribute. However,you may accept compensation in exchange for copies. If youdistribute a large enough number of copies you must also followthe conditions in section 3.You may also lend copies, under the same conditions stated above,and you may publicly display copies.3. COPYING IN QUANTITYIf you publish printed copies (or copies in media that commonlyhave printed covers) of the Document, numbering more than 100, andthe Document's license notice requires Cover Texts, you mustenclose the copies in covers that carry, clearly and legibly, allthese Cover Texts: Front-Cover Texts on the front cover, andBack-Cover Texts on the back cover. Both covers must also clearlyand legibly identify you as the publisher of these copies. Thefront cover must present the full title with all words of thetitle equally prominent and visible. You may add other materialon the covers in addition. Copying with changes limited to thecovers, as long as they preserve the title of the Document andsatisfy these conditions, can be treated as verbatim copying inother respects.If the required texts for either cover are too voluminous to fitlegibly, you should put the first ones listed (as many as fitreasonably) on the actual cover, and continue the rest ontoadjacent pages.If you publish or distribute Opaque copies of the Documentnumbering more than 100, you must either include amachine-readable Transparent copy along with each Opaque copy, orstate in or with each Opaque copy a computer-network location fromwhich the general network-using public has access to downloadusing public-standard network protocols a complete Transparentcopy of the Document, free of added material. If you use thelatter option, you must take reasonably prudent steps, when youbegin distribution of Opaque copies in quantity, to ensure thatthis Transparent copy will remain thus accessible at the statedlocation until at least one year after the last time youdistribute an Opaque copy (directly or through your agents orretailers) of that edition to the public.It is requested, but not required, that you contact the authors ofthe Document well before redistributing any large number ofcopies, to give them a chance to provide you with an updatedversion of the Document.4. MODIFICATIONSYou may copy and distribute a Modified Version of the Documentunder the conditions of sections 2 and 3 above, provided that yourelease the Modified Version under precisely this License, withthe Modified Version filling the role of the Document, thuslicensing distribution and modification of the Modified Version towhoever possesses a copy of it. In addition, you must do thesethings in the Modified Version:A. Use in the Title Page (and on the covers, if any) a titledistinct from that of the Document, and from those ofprevious versions (which should, if there were any, be listedin the History section of the Document). You may use thesame title as a previous version if the original publisher ofthat version gives permission.B. List on the Title Page, as authors, one or more persons orentities responsible for authorship of the modifications inthe Modified Version, together with at least five of theprincipal authors of the Document (all of its principalauthors, if it has fewer than five), unless they release youfrom this requirement.C. State on the Title page the name of the publisher of theModified Version, as the publisher.D. Preserve all the copyright notices of the Document.E. Add an appropriate copyright notice for your modificationsadjacent to the other copyright notices.F. Include, immediately after the copyright notices, a licensenotice giving the public permission to use the ModifiedVersion under the terms of this License, in the form shown inthe Addendum below.G. Preserve in that license notice the full lists of InvariantSections and required Cover Texts given in the Document'slicense notice.H. Include an unaltered copy of this License.I. Preserve the section Entitled "History", Preserve its Title,and add to it an item stating at least the title, year, newauthors, and publisher of the Modified Version as given onthe Title Page. If there is no section Entitled "History" inthe Document, create one stating the title, year, authors,and publisher of the Document as given on its Title Page,then add an item describing the Modified Version as stated inthe previous sentence.J. Preserve the network location, if any, given in the Documentfor public access to a Transparent copy of the Document, andlikewise the network locations given in the Document forprevious versions it was based on. These may be placed inthe "History" section. You may omit a network location for awork that was published at least four years before theDocument itself, or if the original publisher of the versionit refers to gives permission.K. For any section Entitled "Acknowledgements" or "Dedications",Preserve the Title of the section, and preserve in thesection all the substance and tone of each of the contributoracknowledgements and/or dedications given therein.L. Preserve all the Invariant Sections of the Document,unaltered in their text and in their titles. Section numbersor the equivalent are not considered part of the sectiontitles.M. Delete any section Entitled "Endorsements". Such a sectionmay not be included in the Modified Version.N. Do not retitle any existing section to be Entitled"Endorsements" or to conflict in title with any InvariantSection.O. Preserve any Warranty Disclaimers.If the Modified Version includes new front-matter sections orappendices that qualify as Secondary Sections and contain nomaterial copied from the Document, you may at your optiondesignate some or all of these sections as invariant. To do this,add their titles to the list of Invariant Sections in the ModifiedVersion's license notice. These titles must be distinct from anyother section titles.You may add a section Entitled "Endorsements", provided it containsnothing but endorsements of your Modified Version by variousparties--for example, statements of peer review or that the texthas been approved by an organization as the authoritativedefinition of a standard.You may add a passage of up to five words as a Front-Cover Text,and a passage of up to 25 words as a Back-Cover Text, to the endof the list of Cover Texts in the Modified Version. Only onepassage of Front-Cover Text and one of Back-Cover Text may beadded by (or through arrangements made by) any one entity. If theDocument already includes a cover text for the same cover,previously added by you or by arrangement made by the same entityyou are acting on behalf of, you may not add another; but you mayreplace the old one, on explicit permission from the previouspublisher that added the old one.The author(s) and publisher(s) of the Document do not by thisLicense give permission to use their names for publicity for or toassert or imply endorsement of any Modified Version.5. COMBINING DOCUMENTSYou may combine the Document with other documents released underthis License, under the terms defined in section 4 above formodified versions, provided that you include in the combinationall of the Invariant Sections of all of the original documents,unmodified, and list them all as Invariant Sections of yourcombined work in its license notice, and that you preserve alltheir Warranty Disclaimers.The combined work need only contain one copy of this License, andmultiple identical Invariant Sections may be replaced with a singlecopy. If there are multiple Invariant Sections with the same namebut different contents, make the title of each such section uniqueby adding at the end of it, in parentheses, the name of theoriginal author or publisher of that section if known, or else aunique number. Make the same adjustment to the section titles inthe list of Invariant Sections in the license notice of thecombined work.In the combination, you must combine any sections Entitled"History" in the various original documents, forming one sectionEntitled "History"; likewise combine any sections Entitled"Acknowledgements", and any sections Entitled "Dedications". Youmust delete all sections Entitled "Endorsements."6. COLLECTIONS OF DOCUMENTSYou may make a collection consisting of the Document and otherdocuments released under this License, and replace the individualcopies of this License in the various documents with a single copythat is included in the collection, provided that you follow therules of this License for verbatim copying of each of thedocuments in all other respects.You may extract a single document from such a collection, anddistribute it individually under this License, provided you inserta copy of this License into the extracted document, and followthis License in all other respects regarding verbatim copying ofthat document.7. AGGREGATION WITH INDEPENDENT WORKSA compilation of the Document or its derivatives with otherseparate and independent documents or works, in or on a volume ofa storage or distribution medium, is called an "aggregate" if thecopyright resulting from the compilation is not used to limit thelegal rights of the compilation's users beyond what the individualworks permit. When the Document is included in an aggregate, thisLicense does not apply to the other works in the aggregate whichare not themselves derivative works of the Document.If the Cover Text requirement of section 3 is applicable to thesecopies of the Document, then if the Document is less than one halfof the entire aggregate, the Document's Cover Texts may be placedon covers that bracket the Document within the aggregate, or theelectronic equivalent of covers if the Document is in electronicform. Otherwise they must appear on printed covers that bracketthe whole aggregate.8. TRANSLATIONTranslation is considered a kind of modification, so you maydistribute translations of the Document under the terms of section4. Replacing Invariant Sections with translations requires specialpermission from their copyright holders, but you may includetranslations of some or all Invariant Sections in addition to theoriginal versions of these Invariant Sections. You may include atranslation of this License, and all the license notices in theDocument, and any Warranty Disclaimers, provided that you alsoinclude the original English version of this License and theoriginal versions of those notices and disclaimers. In case of adisagreement between the translation and the original version ofthis License or a notice or disclaimer, the original version willprevail.If a section in the Document is Entitled "Acknowledgements","Dedications", or "History", the requirement (section 4) toPreserve its Title (section 1) will typically require changing theactual title.9. TERMINATIONYou may not copy, modify, sublicense, or distribute the Documentexcept as expressly provided for under this License. Any otherattempt to copy, modify, sublicense or distribute the Document isvoid, and will automatically terminate your rights under thisLicense. However, parties who have received copies, or rights,from you under this License will not have their licensesterminated so long as such parties remain in full compliance.10. FUTURE REVISIONS OF THIS LICENSEThe Free Software Foundation may publish new, revised versions ofthe GNU Free Documentation License from time to time. Such newversions will be similar in spirit to the present version, but maydiffer in detail to address new problems or concerns. See`http://www.gnu.org/copyleft/'.Each version of the License is given a distinguishing versionnumber. If the Document specifies that a particular numberedversion of this License "or any later version" applies to it, youhave the option of following the terms and conditions either ofthat specified version or of any later version that has beenpublished (not as a draft) by the Free Software Foundation. Ifthe Document does not specify a version number of this License,you may choose any version ever published (not as a draft) by theFree Software Foundation.ADDENDUM: How to use this License for your documents====================================================To use this License in a document you have written, include a copy ofthe License in the document and put the following copyright and licensenotices just after the title page:Copyright (C) YEAR YOUR NAME.Permission is granted to copy, distribute and/or modify this documentunder the terms of the GNU Free Documentation License, Version 1.2or any later version published by the Free Software Foundation;with no Invariant Sections, no Front-Cover Texts, and no Back-CoverTexts. A copy of the license is included in the section entitled ``GNUFree Documentation License''.If you have Invariant Sections, Front-Cover Texts and Back-CoverTexts, replace the "with...Texts." line with this:with the Invariant Sections being LIST THEIR TITLES, withthe Front-Cover Texts being LIST, and with the Back-Cover Textsbeing LIST.If you have Invariant Sections without Cover Texts, or some othercombination of the three, merge those two alternatives to suit thesituation.If your document contains nontrivial examples of program code, werecommend releasing these examples in parallel under your choice offree software license, such as the GNU General Public License, topermit their use in free software.File: autoconf.info, Node: Indices, Prev: Copying This Manual, Up: TopAppendix B Indices******************* Menu:* Environment Variable Index:: Index of environment variables used* Output Variable Index:: Index of variables set in output files* Preprocessor Symbol Index:: Index of C preprocessor symbols defined* Autoconf Macro Index:: Index of Autoconf macros* M4 Macro Index:: Index of M4, M4sugar, and M4sh macros* Autotest Macro Index:: Index of Autotest macros* Program & Function Index:: Index of those with portability problems* Concept Index:: General indexFile: autoconf.info, Node: Environment Variable Index, Next: Output Variable Index, Up: IndicesB.1 Environment Variable Index==============================This is an alphabetical list of the environment variables that Autoconfchecks.