Published on

Introduction aux GNU/autotools.

Published in: Technology
  • Be the first to comment

No Downloads
Total Views
On Slideshare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide


  1. 1. AUTOTOOLS : beyond the theory, some practical usageAutotoolsAUTOTOOLS : beyond the theory, some practical usageThierry GAYET (EUROGICIEL)
  2. 2. PLAN1. Autotools introduction2. Mastering the build process3. Quick GNU/Make reminder4. The autotools process5. Using the autoscan tool6. The script7. Using libtool7. Using libtool8. The configure.{ac/in} template9. The template10.Using the library’s template11.Using the application’s template12.Many more usage ….13.Conclusion
  3. 3. Autotools introductionThe goal of this topic is to know how to well works with the autotools in a cross-compilation environement
  4. 4. History :Historically, a shell configure script transformed a into aMakefileAutoconf 1 (1992): autoconf transformed a into a configurefileThe autotools processAutoconf 2 (1994): added cross-compilation support, sub-directories,hidden results, more tests, …Automake (1994): automake transformed a into a MakefileLibtool (1996): changed the Automake behavior
  5. 5. Here is the full power of the autotools in action that make build easier:Autotools introduction
  6. 6. The Autotools are a set of scripts (automake, autoconf, aclocal, autoheader, libtools, … )that use M4 macros.Template make the component portable (not dependant from a specific build system)Lot of built-in rules needed for transformations(.c→.o, .c→.s, .o→binary, .c→.a, .c→.so, … )Developers only write basic templates ( and adapt to the cross-compilationTemplates make the makefiles independant of an architectureAutotools introduction6Templates make the makefiles independant of an architectureFinal makefile will be written as standard GNU/make.Lot of built-in features:• Launch the build: make• Clean the environment: make clean or make distclean• Install the build into the stagingdir: make DESTDIR=<PATH> install• Uninstall the build from the stagingdir make DESTDIR=<PATH> uninstall• Generate an archive of the current build: make dist• Many other useful targets…
  7. 7. Autotools introductionAutotools is a collection of OSS tools :GNU Automake is a tool for automatically generating ` files compliantwith the GNU Coding Standards. Autoconf is an extensible package of M4 macros that produce shell scripts to automatically configure software source code packages. Thesescripts can adapt the packages to many kinds of UNIX-like systems without manual user intervention. Autoconf creates a configuration script for apackage from a template file that lists the operating system features that the package can use, in the form of M4 macro calls.Producing configuration scripts using Autoconf requires GNU M4. You should install GNU M4 (at least version 1.4.6, although 1.4.13 or later isrecommended) before configuring Autoconf, so that Autoconfs configure script can find it. The configuration scripts produced by Autoconf are self-contained, so their users do not need to have Autoconf (or GNU M4). libtool is a generic library support script. Libtool hides the complexity of using shared libraries behind a consistent, portable interface. is a helper tool used when compiling applications and libraries. It helps you insert the correct compiler options on the command line so anapplication can use gcc -o test test.c `pkg-config --libs --cflags glib-2.0` for instance, rather than hard-coding values on where to find glib (or otherlibraries). It is language-agnostic, so it can be used for defining the location of documentation tools, for instance. M4 is an implementation of the traditional Unix macro processor. It is mostly SVR4 compatible although it has some extensions (for example,handling more than 9 positional parameters to macros). GNU M4 also has built-in functions for including files, running shell commands, doingarithmetic, etc.GNU M4 is a macro processor in the sense that it copies its input to the output expanding macros as it goes. Macros are either builtin or user-definedand can take any number of arguments. Besides just doing macro expansion, m4 has builtin functions for including named files, running UNIXcommands, doing integer arithmetic, manipulating text in various ways, recursion etc... m4 can be used either as a front-end to a compiler or as amacro processor in its own right. (a.k.a. buildconf) provides automatic build system preparation and is generally very useful to projects that use the GNU build system (i.e.the GNU autotools: autoconf, automake, and libtool). toolchain (GNU or other) that include binutils.
  8. 8. The GNU Binutils are a collection of binary tools. The main ones are:* ld - the GNU linker.* as - the GNU assembler.But they also include:* addr2line - Converts addresses into filenames and line numbers.* ar - A utility for creating, modifying and extracting from archives.* gprof - Displays profiling information.* nm - Lists symbols from object files.* objcopy - Copies and translates object files.Autotools introduction* objcopy - Copies and translates object files.* objdump - Displays information from object files.* ranlib - Generates an index to the contents of an archive.* readelf - Displays information from any ELF format object file.* size - Lists the section sizes of an object or archive file.* strings - Lists printable strings from files.* strip - Discards symbols.For a cross-compilation usage a prefix is added before the name of the binutils (sh4-linux-ar, sh4-linux-nm, sh4-linux-strip, .... )As well as for the makefile, autotools can be used for the cross-compiling but it can be also used forgenerating pdf, html, latex, … in other words, this is a mechanism for managing file transformationsincluding dependencies.
  9. 9. SDK (stagingdir) :Temporary rootfs dedicated tothe target archToolchain :• gcc• headers• host tools• …(Local rootfs) Intermediate installation :make DESTDIR=<STAGINGDIR> installUsed for compilation (headers) : -I<headerpath>Autotools introduction9For each embedded device, another separated SDK is required.Le stagindir peut inclure les hosttools pour n’avoir qu’une zone de dev.Configuration Mngt(SVN, GIT, CC, … )Used for compilation (headers) : -I<headerpath>and links (libraries) : -L<libpath> -l<libname>Real rootfs fortheembedded target RealembeddedtargetFirmwaresFlashingNFSBOOTFinal installation :make DESTDIR=<ROOTFSDIR> install
  10. 10. Focus on the staging_dir (aka SDK environment) :/usr /lib libraries (.a/.so/.la)pkgconfig/ pkg-configmetadata (.pc)STAGING_DIRAutotools introduction/include/<comp_namespace>/ header / public API (.h)STAGING_DIRPREFIX(eg: /usr, /local/usr)The staging directory is used as an intermediate filesystem for development purpose.All packages should install their build into (make DESTDIR=<STAGINGDIR> install).This is a reference between packages that need to compile and link with (in other wordsthat have depencencies with external packages).Example: ./configure--prefix=/usr …
  11. 11. /usr /lib/include/<comp_namespace>/pkgconfig/SDK/local/stagingInstallation de :- liba.a + + dans /usr/lib- liba.pc dans /usr/lib/pkgconfigDependency with A throughPKG_CHECK_MODULE(A)BInstallation de :- libb.a + + dans /usr/lib- libb.pc dans /usr/lib/pkgconfigExample dependenciesbewteen twocomponents A and BAutotools introduction# Environment settingSDK=/local/stagingPREFIX=/usr# Configuration./configure --prefix=$(PREFIX)# Compilingmake# Installationmake DESTDIR=$(SDK) install- liba.pc dans /usr/lib/pkgconfig- a.h dans /usr/include# Environment settingSDK=/local/stagingPKG_CONFIG_PATH=$(SDK)/lib/pkgconfigPREFIX=/usr# Configuration./configure --prefix=$(PREFIX)# Va récupérer B_CFLAGS: -I$(SDK)/$(PREFIX)/include# B_LDFLAGS: -L$(SDK)/$(PREFIX)/lib -la# Compilingmake# Installationmake DESTDIR=$(SDK) installAB- libb.pc dans /usr/lib/pkgconfig- b.h dans /usr/includeThe A package don’t have any dependencies except the libc.
  12. 12. xxx.pc.inFor each package a developper will ONLY have to managed some templates : +• provided by the developers• stored in repository ( CC UCM)config.cacheconfig.logautogen.shautoconfThe autotools process in detail :Autotools aclocal.m4configureconfig.h.inMakefile.inconfig.hMakefilexxx.pcautomakeautoheaderaclocalUSER VIEWDEV. VIEW
  13. 13. Initial preparation :./autogen.shConfiguration :./configure --prefix=/usrCompiling :Autotools introductionCompiling :makeInstallation :make DESTDIR=«stagingdir» install
  14. 14. Mastering the build processThe goal of this topic is to know how the build process works.
  15. 15. Mastering the build processThe GNU Compiler Collection (GCC) :is a compiler system produced by the GNU Projectis supporting various programming languagesis a key component of the GNU toolchainhas been adopted as the standard compiler by most other modern Unix-like computeroperating systems, including Linux, the BSD family and Mac OS Xhas been ported to a wide variety of processor architecturesis widely deployed as a tool in commercial, proprietary and closed source softwaredevelopment environmentsis also available for most embedded platforms, for example Symbian (called gcce), AMCCand Freescale Power Architecture-based chipsand Freescale Power Architecture-based chipscan target a wide variety of platforms, including videogame consoles such as the PlayStation2 and Dreamcast. Several companies make a business out of supplying and supporting GCCports to various platforms, and chip manufacturers today consider a GCC port almostessential to the success of an architecture.Originally named the GNU C Compiler, because it only handled the C programming language,GCC 1.0 was released in 1987, and the compiler was extended to compile C++ in December of thatyear. Front ends were later developed for Fortran, Pascal, Objective-C, Java, and Ada, among others.The Free Software Foundation (FSF) distributes GCC under the GNU General Public License(GNU GPL). GCC has played an important role in the growth of free software, as both a tool and anexample.
  16. 16. Summary :Dynamic library .soStatic library .aObjetcs .oMastering the build processSource code.c / .cppHeaders.hPreprocessinggcc -ELinkingldCompilinggcc -c.oOutputELFObjectAssemblingasgcc --verboseprovides lot of information for each step.
  17. 17. C preprocessing:• Lexical preprocessors.• Operate on the source text.• Prior to any parsing by performing simple substitution of tokenizedcharacter sequences.• Typically perform macro substitutions by inlining and templates, textualinclusion of other files, and conditional compilation or inclusion.Mastering the build processinclusion of other files, and conditional compilation or inclusion.• Take lines beginning with # as directivesThis is possible to stop the Compiler at this specific step. The stdout willgenerate the result of the C preprocessing. This command is equivalent to abuild command (compiling or link) with no output file expected:$ gcc -E file.c
  18. 18. Assembler :If the –S parameter is given to gcc, it stops after the compilation stage; it doesnot assemble. The output is in the form of an assembler code file for each non-assembler input file specified.By default, the assembler file name for a source file is made by replacing the suffix.c, .i, etc., with .sMastering the build processInput files that do not require compilation are ignored.Example for getting the assembly code of a .c source code:$ gcc -S file.c
  19. 19. Compiling : the compiler’s frontend :• Parses the source code through a lexical/semantic analyzer (such as GNU/flex) .• Builds an internal representation of the program.• In a first step it generates non-optimized intermediate code.• In a second step it generates optimized intermediate code (if required).• The intermediate code is adapted to the target architecture.Mastering the build processExample for generating an intermediate object:$ gcc -c file.c -o file.o$ file file.ofile.o: ELF 32-bit LSB relocatable, Intel 80386, version 1 (SYSV), not strippedGCC = GNU Compiler collectionGCCC JAVA Fortran PascalASM...
  20. 20. Linking : the compiler’s backend• Generates assembly code for the final output.• Generates ELF object (replace the old a.out one).• Uses ld through the gcc.• Can make:Binary: adds a main entry to the intermediate code.Dynamic library: if the -shared parameter has been given (cannot berunable except for the libc).Mastering the build processrunable except for the libc).Direct usage with the ld linker : $ ld -o mybinary /lib/crt0.o file.o –lccrt0 (or crt0.o, gcrt0.o, mcrt0.o) is a set of execution start-up routines (usually part ofthe C standard library) that are platform dependent, and is required in order to compileusing GCC and other GNU tools. crt stands for "C runtime".-e entryUse entry as the explicit symbol for beginning execution of the program, rather than thedefault entry point (main). If there is no symbol named entry, the linker will try to parseentry as a number, and use that as the entry address (the number will be interpreted inbase 10; you may use a leading 0x for base 16, or a leading 0 for base 8).
  21. 21. Mastering the build processGNU tools from the toolchain are set for an embedded usage :--sysroot=staging directoryUse dir as the logical root directory for headers and libraries. For example, if the compiler would normally search for headers in/usr/include and libraries in /usr/lib, it will instead search dir/usr/include and dir/usr/lib.If you use both this option and the -isysroot option, then the --sysroot option will apply to libraries, but the -isysroot option will apply toheader files.The GNU linker (beginning with version 2.16) has the necessary support for this option. If your linker does not support this option, theheader file aspect of --sysroot will still work, but the library aspect will not.Usually te environment is defined like this :Usually te environment is defined like this :export STAGING_DIR=<PATH TO THE STAGING DIRECTORY>export PREFIX=«i686-cm-linux-»export TOOLCHAIN_DIR=<PATH TO THE TOOLCHAIN>export CC=$(PREFIX)gcc --sysroot=$(STAGING_DIR)export LD=$(PREFIX)ls --sysroot=$(STAGING_DIR)export GCC=$(PREFIX)gcc --sysroot=$(STAGING_DIR)export CXX=$(PREFIX)gcc --sysroot=$(STAGING_DIR)export GDB="$(STAGING_DIR)/bin/$(PREFIX)gdb"export RANLIB="$(TOOLCHAIN_DIR)/bin/$(PREFIX)ranlib"export STRIP="$(TOOLCHAIN_DIR)/bin/$(PREFIX)strip"export OBJCOPY="$(TOOLCHAIN_DIR)/bin/$(PREFIX)objcopy"export AR="$(TOOLCHAIN_DIR)/bin/$(PREFIX)ar"export AS="$(TOOLCHAIN_DIR)/bin/$(PREFIX)as"export LD="$(TOOLCHAIN_DIR)/bin/$(PREFIX)ld"export NM="$(TOOLCHAIN_DIR)/bin/$(PREFIX)nm”etc …
  22. 22. BUILD PORCESS LABMastering the build processBUILD PORCESS LAB
  23. 23. Mastering the build processThe main goal of this lab is to know how is working theGNU/Using the helloworld.c source code try several parameters{--verbose/-E/-S}:gcc --verbosegcc -c helloworld.cgcc -c helloworld.c -o helloworld.ogcc -E helloworld.cgcc -S helloworld.c…
  24. 24. Quick GNU/make reminderThe goal of this topic is to know how works common GNU/make
  25. 25. Quick GNU/make reminderThe final files generated are gnu/make based.Most can be extend with gnu/make features that’s why this isimportant to know how makefiles are made.We will remain some basic makefile usage.
  26. 26. The make program gets its dependency "graph" from a text file called makefile orMakefile which resides in the same directory as the source files. Make checks themodification times of the files, and whenever a file becomes "newer" than somethingthat depends on it, (in other words, modified) it runs the compiler accordingly.Quick GNU/make reminder26Project1 is a target and the name of the final binary. Its dependencies are the threeobjects data.o, main.o and io.o. Each one have in teir turn their own dependencies thatmake will resolve one by one.If you edit io.c, it becomes "newer" than io.o, meaning that make must run gcc -c io.c tocreate a new io.o, then run gcc data.o main.o io.o -o project1 for project1.
  27. 27. Each dependency shown in the graph is circled with a corresponding color in theMakefile, and each uses the following format:target : source file(s)command (must be preceded by a tab)A target given in the Makefile is a file which will be created or updated when any of itssource files are modified. The command(s) given in the subsequent line(s) (which must bepreceded by a tab character) are executed in order to create the target file.Quick GNU/make reminder27For more information :
  28. 28. By default make will look for a “Makefile” file. We can specify another one through the –fparameter :$ make –f myMakefile will use myMakefile instead$ make –C /myProject will use the makefile present in /myProject directoryIf no Makefile is found, the make program will display:make: *** No targets specified and no makefile found. Stop.Make is compatible with native code and with cross-compilation. Adding specific rules forusing a toolchain is very easy:Quick GNU/make reminder28CC=$(PREFIX)-gcc.c.o:$(CC) –c $(CFLAG) –o $@ $<Make can get setting from environment variables or parameters:export TOOLCHAIN_BIN=<PATH_TOOLCHAIN>/binexport PREFIX=sh4-linuxormake ARCH=sh CROSS_COMPILE=sh4-linuxthen launch the “make” command.Command used for cross-compiling theGNU/Linux kernel.
  29. 29. In addition to those macros which you can create yourself, there are a few macros whichare used internally by the make program.Here are some of those, listed below:CC Contains the current C compiler. Defaults to gcc.CFLAGS Special options which are added to the built-in C rule.$@ Full name of the current target.$? A list of files for current dependency which are out-of-date.Quick GNU/make reminderYou can also manipulate the way these macros are evaluated, as follow, assuming that OBJS =data.o io.o main.o, using $(OBJS:.o=.c) within the Makefile substitutes .o at the end with .c, givingyou the following result: data.c io.c main.cFor debugging a Makefile : $ make -d$? A list of files for current dependency which are out-of-date.$< The source file of the current (single) dependency.LDFLAGS Special options which are added to the link.
  30. 30. Compilation and link:Uses “make” from the command line (it will call the default target such as “all”)Will look for the current Makefile or another file given with -f)Does not include lot of default rules and everything should be manually implementedInstallation:Uses “make install” for the command lineNot in standard … should be done by your ownThe install/cp command can be usedInput file.cSeveral targets used by gnu/makefile :Quick GNU/make reminder30The install/cp command can be usedCleaning:Uses “make clean” from the command lineRemove temporally and intermediate objects generateduring the build processArchive/delivery:Uses “make delivery” from the command lineNot in standard … should be also done by your ownThe tar.gz/tar.bz2/.7z/zip/... compression algorithms can be usedTransformationOutput file.c.o
  31. 31. With GNU/Makefiles :No target is buildin ; everything should be written from scratcheach time ;Doesn’t use generic templates for binaries, libraries, … ;Cross-compilation support should be manualy specified ;Pkg-config can be used (not by M4 macros) ;Can make ugly Makefile ;Quick GNU/make reminderCan make ugly Makefile ;Makefile are often more static than dynamicEverything done by gnu Makefile is automaticallynatively supported by the Autotools ☺☺☺☺ !Everything done by gnu Makefile is automaticallynatively supported by the Autotools ☺☺☺☺ !
  32. 32. Other make engine exists:o cmake ( qmake ( and so on…For more information about the GNU/make:Quick GNU/make reminderFor more information about the GNU/make:
  33. 33. GNU/MAKE LABQuick GNU/make reminderGNU/MAKE LAB
  34. 34. The main goal of the lab is to write a makefile with several targets:The project have three source code: data.c, main.c and io.cQuick GNU/make reminderThe make file should support the following targets:Compilation: make (aka make all)Cleaning old objects: make cleanCreate tarball: make distCreate an installer: make DESTDIR=«PATH» installCreate an uninstaller: make DESTDIR=«PATH» uninstall
  35. 35. So, if we check the several Makefiles written,no one will be identical,that’s mean there is no uniformisation/no standard.That what the autotools provide.So, if we check the several Makefiles written,no one will be identical,that’s mean there is no uniformisation/no standard.That what the autotools provide.Quick GNU/make reminder
  36. 36. The autotools processThe goal of this topic is to know how works the templates are written.
  37. 37. Developers, will work only on the<component>.pc.inOnly those files will be saved in the repository.The autotools processSTEP 0 : introspection with existing sourcecode. Will generate a configure.san (to berenamed into a 2 : this is what the end user will workwith:./configure …makemake installSTEP 1 : this is an intermediate step doneby the script. This should bedone each time the templates are updated.
  38. 38. ./ --prefix …make distmake or make –j7make htmlThis target generates adocumentation from thelatest public API (headers).This target generates atarball..Generates the final files (Makefile, config.h, … )The autotools processmake DESTDIR=<PATH> install make checkThis target launches the unitary tests using the Googletest/mock and provides junit.xml report per unit test.If gcov has been set, it will generate some informationthat will be analysed by lcov.--enable-test should be set to the configure scriptlatest public API (headers).This target generates the(cross)compilationand the link of the component.This target intalls the files generatedduring the build process.make DESTDIR=<PATH> uninstallThis target unintalls the files already installed by aprevious install process.
  39. 39. The autotools processworking with the autotools means for a developer to manage templates andpotfiles : used to define what should be build and howusing generic : used to define an autotools project. It can include<component>.*.in : used to associate some metadata(this is used by * used for managingdependencies or config files).Only those files have to be managed by the developers.No more files need to be stored in repository except if there are filled(README, LICENCE, … ).
  40. 40. The autotools processSTEP #1 : autogen.shThe is a generic script used to prepare an autotool project for end users.Its goal is to check the environment need for the autotools scripts and binaries.This script need to be launched each time a template have been modified.It will generate several files:o a configure script from the configure.aca form the Makefile.amo a form the Makefile.amo a if expectedRoadmap : ---|| ------> autoconfautoconfautoconfautoconf* -----> configureconfigureconfigureconfigure[aclocal.m4] --+--- || -----> autoheaderautoheaderautoheaderautoheader* --> [[[[]]]]|[acsite.m4] ------------------------------->
  41. 41. The autotools processSTEP #2 : configuration, compilation and installationThis is the end user view.This step must start by the launch of the configure script in order to generate a finalMakefile:./configure --prefix=/usr …Then, this is possible to use the several target from the Makefile:Targets Descriptionsmakemake –j7make allBuild programs, libraries, documentation, etc …make install Install what needs to be installed, copying the files from the packages tree to system-wide directories.make install-strip Same as make install, then strip debugging symbols. Some users like to trade space for useful bug reports...make uninstall The opposite of make install: erase the installed files. (This needs to be run from the same build tree that wasinstalled.)make clean Erase from the build tree the files built by make all.make distclean Additionally erase anything ./configure created.make check Run the test suite, if any.make installcheck Check the installed programs or libraries, if supported.make dist Recreate package-version.tar.gz from all the source files.and so on…
  42. 42. Global summary :STEP 0 : Reverse from the existent source code:your source files --> autoscanautoscanautoscanautoscan****--> [[[[configure.scanconfigure.scanconfigure.scanconfigure.scan]]]] --> configure.acconfigure.acconfigure.acconfigure.acSTEP 1 : preparing a software package ---|| ------> autoconfautoconfautoconfautoconf* -----> configureconfigureconfigureconfigure[aclocal.m4] --+--- || -----> autoheaderautoheaderautoheaderautoheader* --> [[[[]]]]|Make by the scriptThe autotools process|[acsite.m4] -------------------------------> Makefile.inMakefile.inMakefile.inMakefile.inSTEP 2 : configure/compile/install/… the package:.-------------> [config.cacheconfig.cacheconfig.cacheconfig.cache]]]]|configureconfigureconfigureconfigure* ----------------+-------------> [config.logconfig.logconfig.logconfig.log]||[[[[]]]] -- | ----> [[[[config.hconfig.hconfig.hconfig.h]]]] -----| v | ||------ config.statusconfig.statusconfig.statusconfig.status**** ---- | | --> makemakemakemake*| | | --- ----> MakefileMakefileMakefileMakefile ---| |[<comp> ]--- -----> [<[<[<[<comp.pccomp.pccomp.pccomp.pc>]>]>]>]Make by the configure script
  43. 43. We are seeing the existing files before to launch autoconf :$ cat configure.acAC_INITAC_CONFIG_FILES([Makefile])AC_OUTPUT$ cat Makefile.inprefix = @prefix@datadir = @datadir@We are launching the autoconf (or autoreconf):The autotools processThus, variables between areobases such as@prefix@ will be replace by the valuegiven to the configure script:$ autoconfWe are launching the configuration step:$ configure –prefix=/usr/localconfigure: creating ./config.statusconfig.status: creating Makefileconfig.status: seems to ignore the --datarootdir settingWe are consulting the files after the configuring step:$ cat Makefileprefix = /usr/localdatadir = ${prefix}/share@prefix@ /usr/local
  44. 44. The autotools processDebugging via autom4te:At times, it is desirable to see what was happening inside m4, to see why output was not matching expectations. However, post-processing done by autom4te means that directly using the m4 builtin m4_traceon is likely to interfere with operation. Also, frequentdiversion changes and the concept of forbidden tokens make it difficult to use m4_defn to generate inline comments in the final output.There are a couple of tools to help with this. One is the use of the --trace option provided by autom4te (as well as each of the programsthat wrap autom4te, such as autoconf), in order to inspect when a macro is called and with which arguments. For example, when thisparagraph was written, the autoconf version could be found by:$ autoconf$ autoconf --trace=AC_INIT:version is $2‘version is 2.63b.95-3963version is 2.63b.95-3963Another trick is to print out the expansion of various m4 expressions to standard error or to an independent file, with no further m4expansion, and without interfering with diversion changes or the post-processing done to standard output. m4_errprintn shows a givenexpression on standard error. For example, if you want to see the expansion of an autoconf primitive or of one of your autoconf macros,you can do it like this:$ cat <<EOF > configure.acAC_INITm4_errprintn([The definition of AC_DEFINE_UNQUOTED:])m4_errprintn(m4_defn([AC_DEFINE_UNQUOTED]))AC_OUTPUTEOF$ autoconferror-->The definition of AC_DEFINE_UNQUOTED:error-->_AC_DEFINE_Q([], $@)
  45. 45. Template #1: basic projectmakefile.amconfigure.acautogen.shTemplate for the projectTemplate for the MakefileGenerate the final filesThe autotools process45 06/17/10src/include/If you prefer to generate intermediate objects in a obj/ directory (or src/), you can move to the chosen directory). For information, all the intermediate objects aregenerated in the same directory than the template.Contains all the source codeContains all the headersThe is equivalent to the
  46. 46. Template #2 : project with subdirectoriesmakefile.amconfigure.acsrc/include/autogen.shTemplate for the projectMain template for the MakefileGenerate the final filesThe autotools processinclude/module1/module2/ Sub-template1 for theMakefilesrc/include/ Sub-template2 for theMakefileAnother project example with subdirectories.
  47. 47. • The essential files:The smallest project requires you provide only two files:CONFIGURE.AC : an input file to autoconf that provides the macro invocations and shell code fragmentsautoconf uses to build a configure script.MAKEFILE.AM: an input file to automake that specifies a projects build requirements: what needs to be built,and where it goes when installed.The GNU Autotools will generate the rest of the files needed to build the project.The autotools process• The Directory Structure:Before writing any code for a new project you need to decide on the directory structure the project will use ;The top-level directory is used for configuration files, such as, and other sundry files like ChangeLog,COPY (a copy of the project license) and README ;Any unique library should have its own subdirectory containing all headers and sources, a, and anyother library specific files ;The headers and sources for the main application should be in another subdirectory, typically called src ;Other directories can include: config for intermediate files, doc for the project documentation and test for theproject self-test suite ;The following steps will take you through creating and building the HelloWorld project. The top-level directory forHelloWorld is <tests/project>. You will find the projects headers and sources in the src subdirectory. There are threefiles:, helloworld.h and ;
  48. 48. Using an Autotools project at a glanceThen, using this Autotools project is simple:1. Generate the final files from the autotools templates: $ ./ configure(it also generate if used)2. Launch the configure script with parameters:$ ./configure -–prefix=/usr -–enable-debug3. Launch the compilation: $ make4. Install the files: $ make DESTDIR=${stagingdir} install5. Launch the unitary tests: $ make check6. Generate the documentation: $ make htmlAll the intermediate files have a .in extension ; they will be used as input by the configurescript for generating all the final files.Thus, by providing * files we are providing intermediate file ready for the updateprocess…
  49. 49. AUTOTOOLS LABThe autotools processAUTOTOOLS LAB
  50. 50. The goal of this lab if to use an hello world autotools project.Experiment the several steps :Preparation: ./autogen.shSee the files before and after.The autotools processConfiguration: ./configure –prefix=/usrRead the config.log that detail the configuration step ; this is a good wayto debug a configure script.Compilation: makeInstallation: make DESTDIR=pwd installDelivery: make dist
  51. 51. Using the autoscan toolThe goal of this topic is to know how to use the autoscan tool
  52. 52. Using the autoscan toolSTEP #0 : autoscanThe easiest way to create a (mostly) complete file is to run theautoscan utility, which is part of the autoconf package.This utility examines the contents of a project directory and generates the basis fora file (which autoscan names configure.scan) using existing makefilesand source files.The autoscan utility examines the project directory hierarchy and creates two filescalled configure.scan and autoscan.log.called configure.scan and autoscan.log.The project may or may not already be instrumented for Autotools ; it doesn’t reallymatter, because autoscan is decidedly non-destructive. It will never alter anyexisting files in a project.your source files autoscanautoscanautoscanautoscan**** configure.scanconfigure.scanconfigure.scanconfigure.scan
  53. 53. After the launch of the autoscan tool, two files should appear in the current directory:autoscan.logconfigure.scan should be renamed into a file afterwardAs we see, the contents of the generated configure.scan is similar to our hand-craftedtemplate:# -*- Autoconf -*-# Process this file with autoconf to produce a configure script.First example with an empty directory:Using the autoscan toolAC_PREREQ(2.56)AC_INIT(FULL-PACKAGE-NAME, VERSION, BUG-REPORT-ADDRESS)# Checks for programs.# Checks for libraries.# Checks for header files.# Checks for typedefs, structures, and compiler characteristics.# Checks for library functions.AC_OUTPUTAs the name autoscan implies, you can guess that it can do other things as well, not onlycreate empty templates.
  54. 54. Second example with two existing files in the project:A header sleep.h :#include <stdio.h>#include <unistd.h> /* Needed for sleep() */A source code sleep.c :#include "sleep.h"#define SECONDS_TO_SLEEP 3intUsing the autoscan toolintmain(){unsigned int sleep_left = 0;/* sleep() for SECONDS_TO_SLEEP seconds, then print a message. */sleep(SECONDS_TO_SLEEP);printf("I woke up after %d seconds.n", SECONDS_TO_SLEEP);return 0;}
  55. 55. # -*- Autoconf -*-# Process this file with autoconf to produce a configure script.AC_PREREQ(2.56)AC_INIT(FULL-PACKAGE-NAME, VERSION, BUG-REPORT-ADDRESS)AC_CONFIG_SRCDIR([sleep.c]) some file that is in the packages source directory.AC_CONFIG_HEADER([config.h]) containing C preprocessor #define statements.# Checks for programs.AC_PROG_CC determine the C compiler to use.# Checks for libraries.That will automaticaly generate the following configure.scan script:Using the autoscan tool# Checks for libraries.# Checks for header files.AC_CHECK_HEADERS([unistd.h]) check for existing header file(s) (in our case only one, unistd.h).# Checks for typedefs, structures, and compiler characteristics.# Checks for library functions.AC_OUTPUTTo get a very basic, but working input file to autoconf, rename configure.scan mv configure.scan configure.acThen update the AC_INIT macro, and add the AC_COPYRIGHT macro.
  56. 56. AUTOSCAN LABUsing the autoscan toolAUTOSCAN LAB
  57. 57. Using the autoscan toolThe main goal for this lab is to go into a directory where isexisting source code ;Launch the autoscan command: ./autoscanView the configure.scan generated.
  58. 58. The scriptThe goal of this topic is to know how works the script
  59. 59. The scriptThe script is used for converting all the templates (,, …) infinal files (Makefile, configure, …) needed for a common Autotools usage.Thus, The script (a.k.a. buildconf) provides automatic build system preparation and isgenerally very useful to projects that use the GNU build system (i.e. the GNU Autotools: autoconf,automake, and libtool). It is a POSIX shell script that is used for preparing a build system forcompilation, verifying versions, ensuring necessary functionality, and overcoming many commonbuild preparation issues.Official web site : web site : : BSDLatest stable release : 23.12.2009 script is standalone, its usage is mainly limited to a call in the autotools directory :$ ./autogen.shAnother way is to use the following command: autoreconf -i –force(This is what the script do in background)
  60. 60. The scriptfirst, we need to generate the required output files from the two input files and First we need tocollect all the macro invocations in that Autoconf will need to build the configure script. This is done with thefollowing command:$ aclocalThis generates the file aclocal.m4 and adds it to the current directory. Next, run autoconf:$ autoconfAfter running autoconf you will find the configure script in the current directory. Its important to run aclocal first becauseBefore the autoconf script some bootstrap command was used:After running autoconf you will find the configure script in the current directory. Its important to run aclocal first becauseautomake relies on the contents on and aclocal.m4.There are a few files that the GNU standard says must be present in the top-level directory, and if not found Automake willreport an error. Enter the following command to create these files:$ touch AUTHORS NEWS README ChangeLogNow we can run automake to create The –add-missing argument copies some boilerplate files from yourAutomake installation into the current directory.$ automake --add-missingBy now, the contents of the directory should be looking a lot like the top-level directory of a GNU package you may haveinstalled before:aclocal.m4 autom4te.cache depcomp install-sh mkinstalldirs README AUTHORSChangeLog configure COPYING INSTALL missing NEWS src
  61. 61. The scriptWhat the really do :It tranforms the template into intermediate files:Original file Final (if expected)Those files will complete the other files (, in order to beready for the configure script.Note : is by far the preferred naming for autoconf >= 2.50 is what was used by autoconf ⇐ 2.13 and was kept for *cough*backward compatibility *cough*…
  62. 62. The scriptLong name ShortnameDescription Default--help -h Help on usage No--verbose -v Verbose progress output No--quiet -q Quiet suppressed progress output Yes--download -d Download the latest config.guess from gnulib No--version Only perform GNU Build System version checks NoParameters used to control the script :There is two controversal parameters with the --quiet and --verbose that can be set in the same$ ./ –versionPreparing the toe build system...please waitFound GNU Autoconf version 2.67Found GNU Automake version 1.11.1Found GNU Libtool version build preparation script by Christopher Sean Morrison+ config.guess download patch by Sebastian Pipping (2008-12-03)revised 3-clause BSD-style license, copyright (c) 2005-2009script version 20090301, ISO/IEC 9945 POSIX shell script---Version requested. No preparation or configuration will be performed.Check of the autotools components version:There is two controversal parameters with the --quiet and --verbose that can be set in the sametime!! Indeed, the script will follow the last one provided at the launch.Identical as :./autoconf --version./automake –version./libtool --version
  63. 63. The script$ ./ –helpUsage: ./ [-h|--help] [-v|--verbose] [-q|--quiet] [-d|--download] [--version]--help Help on usage--verbose Verbose progress output--quiet Quiet suppressed progress output--download Download the latest config.guess from gnulib--version Only perform GNU Build System version checksDescription: This script will validate that minimum versions of theGNU Build System tools are installed and then run autoreconf for usage can be obtain with the command line:GNU Build System tools are installed and then run autoreconf for you.Should autoreconf fail, manual preparation steps will be runpotentially accounting for several common preparation issues. TheAUTORECONF, AUTOCONF, AUTOMAKE, LIBTOOLIZE, ACLOCAL,AUTOHEADER,PROJECT, & CONFIGURE environment variables and corresponding _OPTIONSvariables (e.g. AUTORECONF_OPTIONS) may be used to override thedefault automatic detection build preparation script by Christopher Sean Morrison+ config.guess download patch by Sebastian Pipping (2008-12-03)revised 3-clause BSD-style license, copyright (c) 2005-2009script version 20090301, ISO/IEC 9945 POSIX shell script---Help was requested. No preparation or configuration will be performed.
  64. 64. The script$ ./autogen.shPreparing the toe build system...please waitFound GNU Autoconf version 2.67Found GNU Automake version 1.11.1Found GNU Libtool version 2.2.6bAutomatically preparing build ... doneThe toe build system is now prepared. To build here, run:./configuremakeSilent launch (default):$ ./ –verboseVerbose output enabledFound a configure template: ./configure.acPreparing the toe build system...please waitChecking autoreconf version: autoreconf --versionChecking autoconf version: autoconf --versionFound GNU Autoconf version 2.67Checking if 2.67.0 is greater than 2.52.0Checking automake version: automake --versionFound GNU Automake version 1.11.1Checking if 1.11.1 is greater than 1.6.0Checking libtoolize version: libtoolize --versionFound GNU Libtool version 2.2.6bChecking if 2.2.6 is greater than 1.4.2Checking aclocal version: aclocal --versionChecking autoheader version: autoheader --versionChecking whether to only output version informationBacking up COPYING in /home/gayetth/workspace/TOEcp -p COPYING COPYING.25605.protect_from_automake.backupBacking up INSTALL in /home/gayetth/workspace/TOEcp -p INSTALL INSTALL.25605.protect_from_automake.backupFound an autom4te.cache directory, deleting itrm -rf autom4te.cache Verbose launchmake rm -rf autom4te.cachemv -f "./config.guess" "./config.guess.backup"mv -f "./config.sub" "./config.sub.backup"mv -f "./" "./"Automatically preparing build ... autoreconf -i -flibtoolize: putting auxiliary files in `..libtoolize: copying file `./config.guesslibtoolize: copying file `./config.sublibtoolize: copying file `./install-shlibtoolize: copying file `./ltmain.shlibtoolize: Consider adding `AC_CONFIG_MACRO_DIR([m4]) to andlibtoolize: rerunning libtoolize, to keep the correct libtool macros in-tree.libtoolize: Consider adding `-I m4 to ACLOCAL_AMFLAGS in -f COPYING.25605.protect_from_automake.backupRestoring INSTALL from backup (automake -f likely clobbered it)rm -f INSTALLmv INSTALL.25605.protect_from_automake.backup INSTALLrm -f INSTALL.25605.protect_from_automake.backuprm -f "./config.guess.backup"rm -f "./config.sub.backup"rm -f "./"doneThe toe build system is now prepared. To build here, run:./configuremakerm -f "./config.guess.backup"rm -f "./config.sub.backup"rm -f "./"
  65. 65. The scriptName Type DescriptionAUTOCONF Boolean Enable/disable the autotconf launchAUTOCONF_VERSION String Specify a specific version for the autoconf packageAUTOCONF_OPTIONS String Specify the parameters to provide to the autoconf toolAUTORECONF Boolean Enable/disable the autotconf launchAUTORECONF_OPTIONS String Specify the parameters to provide to the autoreconf toolAUTOMAKE Boolean Enable/disable the automake launchAUTOMAKE_VERSION String Specify a specific version for the automake packageAUTOMAKE_OPTIONS String Specify the parameters to provide to the automake toolUseful variables used to control the script :To skip autoreconf and prepare manually: AUTORECONF=false ./autogen.shTo verbosely try running with an older (unsupported) autoconf: AUTOCONF_VERSION=2.50 ./ --verboseAUTOMAKE_OPTIONS String Specify the parameters to provide to the automake toolLIBTOOLIZE Boolean Enable/disable the libtoolize launchLIBTOOL_VERSION String Specify a specific version for the autoconf packageLIBTOOLIZE_OPTIONS String Specify the parameters to provide to the libtoolize toolACLOCAL Boolean Enable/disable the aclocal launchACLOCAL_OPTIONS String Specify the parameters to provide to the aclocal toolAUTOHEADER Boolean Enable/disable the autoheader launchAUTOHEADER_OPTIONS String Specify the parameters to provide to the autoheader toolCONFIG_GUESS_URL String URL where the latest config.guess file can be download
  66. 66. The scriptImpact on the autotools templates:If we take the decision to use the script instead of the single autoreconfcommand, this file is mandatorary to include in the tarball generated by the « makedist » command.EXTRA_DIST = $(top_builddir)/autogen.shThe script should be within the files of the project.The script should be within the files of the project.If this file is not added the tarball will miss this file and won’t be standalone!
  67. 67. The environmentPKGCONFIG LABPKGCONFIG LAB
  68. 68. The scriptTake an autotools project and check the differential beforeand after the launch of the script.Check with the autotools hierarchy poster provided.
  69. 69. Using libtoolThe goal of this topic is to know how to uses libtool
  70. 70. Using libtoolGNU Libtool simplifies your job by encapsulating both the platform-specific dependencies, and the user interface, ina single script. GNU Libtool is designed so that the complete functionality of each host type is available via a genericinterface, but nasty quirks are hidden from the programmer.GNU Libtools consistent interface is reassuring... users dont need to read obscure documentation in order to havetheir favorite source package build shared libraries. They just run your package configure script (or equivalent), andlibtool does all the dirty work.What libtool can do :
  71. 71. Using libtoolLibtool is a tool used:The following issues need to be addressed in any reusable shared library system, specifically libtool:The package installer should be able to control what sort of libraries are built.It can be tricky to run dynamically linked programs whose libraries have not yet been installed. LD_LIBRARY_PATH must be set properly (if it is supported), orprograms fail to run.The system must operate consistently even on hosts that dont support shared libraries.The commands required to build shared libraries may differ wildly from host to host. These need to be determined at configure time in a consistent way. It is notalways obvious with what prefix or suffix a shared library should be installed. This makes it difficult for Makefile rules, since they generally assume that file namesare the same from host to host.The system needs a simple library version number abstraction, so that shared libraries can be upgraded in place. The programmer should be informed how to designthe interfaces to the library to maximize binary compatibility. The install Makefile target should warn the package installer to set the proper environment variables(LD_LIBRARY_PATH or equivalent), or run ldconfig.Motivation for writing libtool :(LD_LIBRARY_PATH or equivalent), or run ldconfig.Since early 1995, several different GNU developers have recognized the importance of having shared library support for their packages. The primary motivation forsuch a change is to encourage modularity and reuse of code (both conceptually and physically) in GNU programs.Such a demand means that the way libraries are built in GNU packages needs to be general, to allow for any library type the package installer might want. Theproblem is compounded by the absence of a standard procedure for creating shared libraries on different platforms.The following sections outline the major issues facing shared library support in GNU, and how shared library support could be standardized with libtool.The following specifications were used in developing and evaluating this system:The system must be as elegant as possible.The system must be fully integrated with the GNU Autoconf and Automake utilities, so that it will be easy for GNU maintainers to use. However, the system must notrequire these tools, so that it can be used by non-GNU packages.Portability to other (non-GNU) architectures and tools is desirable.
  72. 72. Using libtoollibtool libtool mode=link CC=sh4-linux-gcc .libs/foo.o –o foobinlibtool mode=compile CC=sh4-linux-gcc –c foo.c -o .libs/foo.o$ libtool --mode=link gcc -g -O -o foo.o hello.o*** Warning: Linking the shared library against the*** non-libtool objects foo.o hello.o is not portable!ar cru .libs/libhello.aranlib .libs/libhello.a$ libtool --mode=compile gcc -g -O -c foo.cmkdir .libsgcc -g -O -c foo.c -fPIC -DPIC -o .libs/foo.ogcc -g -O -c foo.c -o foo.o >/dev/null 2>&1libtool mode=installSuffix used by libtool :Extension’s name Library BinaryObjects .lo (library object) .oIntermediate .la (library archive)ranlib .libs/libhello.acreating .libs && rm -f && ln -s ../$ libtool --mode=link gcc -g -O -o test test.o /usr/local/lib/ gcc -g -O -o.libs/test test.o -Wl,--rpath -Wl,/usr/local/lib /usr/local/lib/libhello.a -lm creating test$ libtool --mode=install cp /usr/local/lib/libhello.lacp /usr/local/lib/libhello.lacp .libs/libhello.a /usr/local/lib/libhello.aranlib /usr/local/lib/libhello.a
  73. 73. Using libtoolLibtool is a tool used: libtool [OPTION]... [MODE-ARG]...Parameters Description-n|--dry-run Dont create, modify, or delete any files, just show what commands would be executed by `libtool--mode=MODE Use MODE as the operation mode. By default, the operation mode is inferred from the MODE-ARGS--features Display basic configuration options. This provides a way for packages to determine whether sharedor static libraries will be built--finish Same as --mode=finish--debug Dump a trace of shell script execution to standard output. This produces a lot of output, so you maywish to pipe it to `less (or `more) or redirect to a file--config Display libtool configuration variables and exitMODE Descriptionclean Remove files from the build directorycompile Compile a source file into a `libtool objectexecute Automatically set the library path, then run a programfinish Complete the installation of libtool librariesinstall Install libraries or executableslink Create a library or an executableuninstall Remove libraries from an installed directoryListing of the several modes available:--quiet--silentDont print nformational messages.--tag=TAG Use configuration variables from tag TAG
  74. 74. Using libtoolTAGs available :Language name TAG nameC CCC++ CXXJava GCJFortran 77 F77Fortran FCWindows resource RCThe same tags can be overwritten in the autotool context (this often do in aThe same tags can be overwritten in the autotool context (this often do in across-compilation mode):CC=sh4-linux-gcc CXX=sh4-linux-g++ ./configure --prefix=/usr …
  75. 75. Using libtool$ libtool --mode=compile gcc -g -O -c foo.cgcc -g -O -c foo.c -o foo.oCompilation mode :Compilation flag Description-o Note that the -o option is now fully supported. It is emulated on the platforms that dont support it (bylocking and moving the objects), so it is really easy to use libtool, just with minor modifications to yourMakefiles.Typing for example: libtool --mode=compile gcc -c foo/x.c -o foo/x.lo will do what you expect.Note, however, that, if the compiler does not support -c and -o, it is impossible to compile foo/x.c withoutoverwriting an existing ./x.o.Therefore, if you do have a source file ./x.c, make sure you introduce dependencies in your Makefile tomake sure ./x.o (or ./x.lo) is re-created after any sub-directorys x.lo: x.o x.lo: foo/x.lo bar/x.lomake sure ./x.o (or ./x.lo) is re-created after any sub-directorys x.lo: x.o x.lo: foo/x.lo bar/x.loThis will also ensure that make wont try to use a temporarily corrupted x.o to create a program or library.It may cause needless recompilation on platforms that support -c and -o together, but its the only way tomake it safe for those that dont.-no-suppress If both PIC and non-PIC objects are being built, libtool will normally suppress the compiler output for thePIC object compilation to save showing very similar, if not identical duplicate output for each object. Ifthe -no-suppress option is given in compile mode, libtool will show the compiler output for both objects.-prefer-pic Libtool will try to build only PIC objects.-prefer-non-pic Libtool will try to build only non-PIC objects.-shared Even if Libtool was configured with --enable-static, the object file Libtool builds will not be suitable forstatic linking. Libtool will signal an error if it was configured with --disable-shared, or if the host does notsupport shared libraries-static Even if libtool was configured with --disable-static, the object file Libtool builds will be suitable for staticlinking-Wc,flag-Xcompiler flagPass a flag directly to the compiler. With -Wc,, multiple flags may be separated by commas, whereas -Xcompiler passes through commas unchanged
  76. 76. Using libtoolLink mode links together object files (including library objects) to form another library or to create an executable program.mode-args consist of a command using the C compiler to create an output file (with the -o flag) from several object files. The followingcomponents of mode-args are treated specially:Link mode :Compilation flag Description-all-static If output-file is a program, then do not link it against any shared libraries at all. If output-file is a library,then only create a static library. In general, this flag cannot be used together with ‘disable-static’-avoid-version Tries to avoid versioning for libraries and modules, i.e. no version information is stored and no symbolic linksare created. If the platform requires versioning, this option has no effect.-bindir Pass the absolute name of the directory for installing executable programs. libtool may use this value to installshared libraries there on systems that do not provide for any library hardcoding and use the directory of ashared libraries there on systems that do not provide for any library hardcoding and use the directory of aprogram and the PATH variable as library search path. This is typically used for DLLs on Windows or othersystems using the PE (Portable Executable) format. On other systems, -bindir is ignored. The default valueused is libdir/../bin for libraries installed to libdir. You should not use -bindir for modules.-dlopen file Same as -dlpreopen file, if native dlopening is not supported on the host platform or if the program is linkedwith -static, -static-libtool-libs, or -all-static. Otherwise, no effect. If file is self Libtool will make sure thatthe program can dlopen itself, either by enabling -export-dynamic or by falling back to -dlpreopen self.-dlpreopen file Link file into the output program, and add its symbols to the list of preloaded symbols. If file is self, thesymbols of the program itself will be added to preloaded symbol lists. If fileis force Libtool will make sure thata preloaded symbol list is always defined, regardless of whether its empty or not.-export-dynamic Allow symbols from output-file to be resolved with dlsym-export-symbols symfileTells the linker to export only the symbols listed in symfile. The symbol file should end in .sym and mustcontain the name of one symbol per line. This option has no effect on some platforms. By default all symbolsare exported.-export-symbols-regex regexame as -export-symbols, except that only symbols matching the regular expression regex are exported. Bydefault all symbols are exported.
  77. 77. Using libtoolCompilation flag Description-Llibdir Search libdir for required libraries that have already been installed-lname output-file requires the installed library libname. This option is required even when output-file is not anexecutable-module reates a library that can be dlopened. This option doesnt work for programs. Module names dont need to beprefixed with ‘lib’. In order to prevent name clashes, however, libname and name must not be used at thesame time in your package-no-fast-install Disable fast-install mode for the executable output-file. Useful if the program wont be necessarily installed-no-install Link an executable output-file that cant be installed and therefore doesnt need a wrapper script on systemsthat allow hardcoding of library paths. Useful if the program is only used in the build tree, e.g., for testing orLink mode (cont)that allow hardcoding of library paths. Useful if the program is only used in the build tree, e.g., for testing orgenerating other files.-no-undefined Declare that output-file does not depend on any other libraries. Some platforms cannot create shared librariesthat depend on other libraries-o output-file Create output-file from the specified objects and libraries.-objectlist file Use a list of object files found in file to specify objects.-precious-files-regex regexPrevents removal of files from the temporary output directory whose names match this regular expression.You might specify ‘.bbg?$’ to keep those files created with gcc -ftest-coverage for example.-release release Specify that the library was generated by release release of your package, so that users can easily tell whichversions are newer than others. Be warned that no two releases of your package will be binary compatible ifyou use this flag. If you want binary compatibility, use the -version-info flag instead-rpath libdir output-file is a library, it will eventually be installed in libdir. If output-file is a program, add libdir to therun-time path of the program. On platforms that dont support hardcoding library paths into executables andonly search PATH for shared libraries, such as when output-file is a Windows (or other PE platform) DLL,the .la control file will be installed in libdir, but see -bindir above for the eventual destination of the .dll orother library file itself.
  78. 78. Using libtoolCompilation flag Description-R libdir If output-file is a program, add libdir to its run-time path. If output-file is a library, add -Rlibdir toits dependency_libs, so that, whenever the library is linked into a program, libdir will be added to its run-timepath.-shared If output-file is a program, then link it against any uninstalled shared libtool libraries (this is the default behavior).If output-file is a library, then only create a shared library. In the later case, libtool will signal an error if it wasconfigured with --disable-shared, or if the host does not support shared libraries.-shrext suffix If output-file is a libtool library, replace the systems standard file name extension for shared librarieswith suffix (most systems use .so here). This option is helpful in certain cases where an application requires thatshared libraries (typically modules) have an extension other than the default one. Please note you must supply thefull file name extension including any leading dot.-static If output-file is a program, then do not link it against any uninstalled shared libtool libraries. If output-file is alibrary, then only create a static library.-static-libtool-libs If output-file is a program, then do not link it against any shared libtool libraries. If output-file is a library, thenonly create a static library.Link mode (cont)only create a static library.-version-info current[:revision[:age]]If output-file is a libtool library, use interface version information current, revision, and age to build it. Do not usethis flag to specify package release information, rather see the -release flag.-version-number major[:minor[:revision]]If output-file is a libtool library, compute interface version information so that the resulting library uses thespecified major, minor and revision numbers. This is designed to permit libtool to be used with existing projectswhere identical version numbers are already used across operating systems. New projects should use the -version-info flag instead.-weak libname if output-file is a libtool library, declare that it provides a weak libname interface. This is a hint to libtool thatthere is no need to append libname to the list of dependency libraries of output-file, because linkingagainst output-file already supplies the same interface-Wc,flag-Xcompiler flagPass a linker-specific flag directly to the compiler. With -Wc,, multiple flags may be separated by commas,whereas -Xcompiler passes through commas unchanged.-Wl,flag-Xlinker flag Pass a linker-specific flag directly to the linker-XCClinker flag Pass a link-specific flag to the compiler driver (CC) during linking.
  79. 79. If the output-file ends in .la, then a libtool library is created, which must be built only from libraryobjects (.lo files). The -rpath option is required. In the current implementation, libtool libraries maynot depend on other uninstalled libtool libraries.If the output-file ends in .a, then a standard library is created using ar and possibly ranlib.If output-file ends in .o or .lo, then a reloadable object file is created from the input files (generallyusing ‘ld -r’). This method is often called partial linking.Using libtoolLink mode (cont)Otherwise, an executable program is created.
  80. 80. Using libtoolExecution mode :Compilation flag DescriptionFor execute mode, the library path is automatically set, then a program is executed.The first of the mode-args is treated as a program name, with the rest as arguments to thatprogram.The following components of mode-args are treated specially:-dlopen file Add the directory containing file to the library pathThis mode sets the library path environment variable according to any -dlopen flagsIf any of the args are libtool executable wrappers, then they are translated into the name of theircorresponding uninstalled binary, and any of their required library directories are added to thelibrary path.
  81. 81. Using libtoolInstallation mode :In install mode, libtool interprets most of the elements of mode-args as an installation command beginning with cp, or a BSD-compatible installprogram.The following components of mode-args are treated specially:-inst-prefix-dir inst-prefix-dirWhen installing into a temporary staging area, rather than the final prefix, this argument is used to reflect the temporary path, in much thesame way automake uses DESTDIR. For instance, if prefix is /usr/local, but inst-prefix-dir is /tmp, then the object will be installed under/tmp/usr/local/. If the installed object is a libtool library, then the internal fields of that library will reflect only prefix, not inst-prefix-dir:# Directory that this library needs to be installed in:libdir=/usr/local/libnot# Directory that this library needs to be installed in:libdir=/tmp/usr/local/lib‘libdir=/tmp/usr/local/lib‘inst-prefix is also used to insure that if the installed object must be relinked upon installation, that it is relinked against the libraries in inst-prefix-dir/prefix, not prefix.In truth, this option is not really intended for use when calling libtool directly; it is automatically used when libtool --mode=install calls libtool --mode=relink. Libtool does this by analyzing the destination path given in the original libtool --mode=install command and comparing it to theexpected installation path established during libtool --mode=link.Thus, end-users need change nothing, and automake-style make install DESTDIR=/tmp will Just Work(tm) most of the time. For systems where fastinstallation can not be turned on, relinking may be needed. In this case, a ‘DESTDIR’ install will fail.Currently it is not generally possible to install into a temporary staging area that contains needed third-party libraries which are not yet visible at theirfinal location.The rest of the mode-args are interpreted as arguments to the cp or install command.The command is run, and any necessary unprivileged post-installation commands are also completed.
  82. 82. Using libtoolFinish mode :Compilation flag Description--dry-run Running this command may require superuser privileges, and the --dry-run option may be usefulFinish mode has two functions. One is to help system administrators install libtool libraries so thatthey can be located and linked into user programs.To invoke this functionality, pass the name of a library directory as mode-arg:The second is to facilitate transferring libtool libraries to a native compilation environment afterThe second is to facilitate transferring libtool libraries to a native compilation environment afterthey were built in a cross-compilation environment. Cross-compilation environments may rely onrecent libtool features, and running libtool in finish mode will make it easier to work with olderversions of libtool. This task is performed whenever the mode-arg is a .la file.
  83. 83. Using libtoolUninstall mode :Uninstall mode deletes installed libraries, executables and objects.The first mode-arg is the name of the program to use to delete files (typically /bin/rm).The remaining mode-args are either flags for the deletion program (beginning with a ‘-’), or thenames of files to delete.
  84. 84. Using libtoolClean mode :Clean mode deletes uninstalled libraries, executables, objects and libtools temporary files associatedwith them.The first mode-arg is the name of the program to use to delete files (typically /bin/rm).The remaining mode-args are either flags for the deletion program (beginning with a ‘-’), or thenames of files to delete.
  85. 85. Using libtoolLIBTOOL LABLIBTOOL LAB
  86. 86. Using libtoolThe goal of this lab is to understand what libtool is really working.Try to compile a helloworld.c source code by the two way:gcc –c helloworld.c –o helloworld.oLibtool --mode=compile gcc -c helloworld.cSame for the link step (should create a helloworld binary):gcc helloworld.o –o helloworldlibtool --mode=link gcc –o helloworld helloworld.o
  87. 87. The configure.{ac/in} templateThe goal of this topic is to know how to write a template.
  88. 88. The configure.{in/ac} templateA is the template of the configure script that will be used bythe end user.A is written using M4 macros while a configure script is ashell script.The main goal of a configure script is to lead the configuration of acomponent. The several flags provided to the configure script is like the IDcard of the build.card of the build.The teamplate is equal to the that is the oldnotation.Those script are executed like shell script at the runtime (no compiled).Can build libraries, binaries, … in the same files, by managingdependencies.
  89. 89. The configure.{in/ac} templateCheck for programsCheck for (dynamic/static) librariesCheck for header filesCheck for typedefsVersion managementInitialisationSeveral usual stepsused by the configurationscript.Check for structuresCheck for compiler characteristicsCheck for libraries functionsCheck for system servicesGenerate output filesThere is M4 macros for each step…script.
  90. 90. Variable name Descriptionsrcdir The name of the directory that contains the source code for that makefile.top_srcdir The name of the top-level source code directory for the package. In the top-level directory, this is the sameas srcdir.top_builddir The relative name of the top level of the current build tree. In the top-level directory, this is the sameas builddir.abs_builddir Absolute name of builddir.builddir Rigorously equal to ‘.’. Added for symmetry only.top_build_prefix The relative name of the top level of the current build tree with final slash if nonemtpy. This is the samePreset Output Variables :The configure.{in/ac} templateBeware about all directories, because they can be override by configure options: ./configure –prefix=/usr –srcdir=/tmp_srcdir …If so, top_builddir can be different to top_srcdir and bring link problems, so be carefull !!top_build_prefix The relative name of the top level of the current build tree with final slash if nonemtpy. This is the sameas top_builddir, except that it contains zero or more runs of ../, so it should not be appended with a slash forconcatenation. This helps for make implementations that otherwise do not treat ./file and file as equal in thetoplevel build directory.abs_srcdir Absolute name of srcdir.abs_top_srcdir Absolute name of top_srcdir.abs_top_builddir Absolute name of top_builddir.
  91. 91. The configure.{in/ac} templateVariable name DescriptionLDFLAGS Options for the linkerLIBS -l options to pass to the linker. The default value is empty, but some Autoconf macros may prepend extralibraries to this variable if those libraries are found and provide necessary functions. configure uses thisvariable when linking programs to test for C, C++.OBJCFLAGS Debugging and optimization options for the Objective C compiler. It acts like CFLAGS, but for Objective Cinstead of C.CXXFLAGS Debugging and optimization options for the C++ compiler. It acts like CFLAGS, but for C++ instead of C.DEFS -D options to pass to the C compiler. If AC_CONFIG_HEADERS is called, configure replaces ‘@DEFS@’Flags overriding : -D options to pass to the C compiler. If AC_CONFIG_HEADERS is called, configure replaces ‘@DEFS@’with -DHAVE_CONFIG_H instead. This variable is not defined while configure is performing its tests, onlywhen creating the output files.CFLAGS Debugging and optimization options for the C compiler. If it is not set in the environmentwhen configure runs, the default value is set when you call AC_PROG_CC (or empty if youdont).configure uses this variable when compiling or linking programs to test for C features.CPPFLAGS Preprocessor options for the C, C++, Objective C, and Objective C++ preprocessors and compilers. If it isnot set in the environment when configure runs, the default value is empty.configure uses this variablewhen preprocessing or compiling programs to test for C, C++, Objective C, and Objective C++ features.configure_input A comment saying that the file was generated automatically by configure and giving the name of theinput file. AC_OUTPUT adds a comment line containing this variable to the top of every makefile itcreates. For other files, you should reference this variable in a comment at the top of each input file.OBJCXXFLAGS Debugging and optimization options for the Objective C++ compiler. It acts like CXXFLAGS, but forObjective C++ instead of C++.
  92. 92. The configure.{in/ac} templateVariable’s name Description Variable associatedCC C compiler CFLAGSLD Linker LDFLAGSCXX C++ compiler CXXFLAGSTMPDIR Path used for compiling any source codeAR Tools used for creating static librariesTools overriding :NM Tool used for extraing sysmbolsetc..Examples:./configure –prefix=/usrCC=gcc CFLAGS=-O3 LIBS=“-lposix” …orCC=sh4-linux-gcc AR=sha-linux-g++ ./configure –prefix=/usr …
  93. 93. The configure.{in/ac} templateSpecial Characters in Output Variables :Many output variables are intended to be evaluated both by make and by the shell. Somecharacters are expanded differently in these two contexts, so to avoid confusion thesevariables values should not contain any of the following characters: " # $ & ( ) * ; < > ? [ ^ ` |Also, these variables values should neither contain newlines, nor start with ‘~’, nor containwhite space or ‘:’ immediately followed by ‘~’. The values can contain nonemptysequences of white space characters like tabs and spaces, but each such sequence mightsequences of white space characters 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 setdirectly by the user. For example, the following invocations of configure are problematic,since they attempt 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="&"#$*?"
  94. 94. The configure.{in/ac} templateMacros DefinitionAC_INITPerforms essential initialization for the generated configure script. It takesas an argument a filename from the source directory, to ensure that thesource directory has been specified correctly.AM_INIT_AUTOMAKEDoes all the standard initialization required by Automake and takes twoarguments, the package name and version number.INTI_REQUIRED_VERSION Specifies the minimum required Inti version, in this case 1.0.7.Some of the useful built-in M4 macros:PKG_CHECK_MODULESChecks for the specified version of the Inti library and if found places thenecessary include flags in $(INTI_CFLAGS) and the libraries to link with$(INTI_LIBS). If the correct version is not found configure will report an error.AC_PROG_CXX Checks for the C++ compiler and sets the variables CXX, GXX and CXXFLAGS.AC_OUTPUT Must be called at the end of to create the Makefiles.There are many others ; check the gnu/autoconf manual for moreInformation (
  95. 95. AC_PREREQ(2.59)AC_INIT([pyPackage], [myPackageVersion], [])AC_ARG_ENABLE( debug,AS_HELP_STRING([--enable-debug],[enable debugging support]),[enable_debug=$enableval],[enable_debug=no] )if test "$enable_debug" = "yes" ; thenCXXFLAGS="$CXXFLAGS -Wall -ggdb -O0"InitializationCheck for the debug modeExample of configure.{in/ac} template using some m4 macros :The configure.{in/ac} templateCXXFLAGS="$CXXFLAGS -Wall -ggdb -O0"AC_DEFINE(DEBUG, 1, [Define to enable debug build])elseCXXFLAGS="$CXXFLAGS -Wall -O2"fiPKG_CHECK_MODULES([DIRECTFB],[directfb],[have_libdirectfb=yes],[have_libdirectfb=no])if test "$have_libdirectfb" = no ; thenAC_MSG_ERROR([Missing directfb-1.4.1 library!!])fiAC_OUTPUT(Makefile) File to generate from the Makefile.amtemplateCheck for the libdirectfb library
  96. 96. dnl ---------------------------------------dnl Load m4 macrosdnl ---------------------------------------(…)Adding comments or disabling lines into the :1. Official comments that are important and should stay in the file using the dnl keyword :2. Lines that are temporaly/definitively disabling in the configure file :The configure.{in/ac} templateAC_CANONICAL_HOST#AC_CANONICAL_TARGETAC_SUBST(PACKAGE_VERSION)Line disabled!!
  97. 97. The configure.{in/ac} templatePrinting messages :Configure scripts need to give users running them several kinds of information. The following macros print messagesin ways appropriate for each kind. The arguments to all of them get enclosed in shell double quotes, so the shellperforms variable and back-quote substitution on them. These macros are all wrappers around the echo shell command.They direct output to the appropriate file descriptor:Macro: AC_MSG_CHECKING (feature-description)Notify the user that configure is checking for a particular feature. This macro prints a message that starts with‘checking ’ and ends with ‘...’ and no newline. It must be followed by a call to AC_MSG_RESULT to print the result ofthe check and the newline. The feature-descriptionshould be something like ‘whether the Fortran compiler acceptsC++ comments’ or ‘for c89’. This macro prints nothing if configure is run with the --quiet or --silent option. This isquite similar to a echo -n.quite similar to a echo -n.Macro: AC_MSG_RESULT (result-description)Notify the user of the results of a check. result-description is almost always the value of the cache variable for thecheck, typically ‘yes’, ‘no’, or a file name. This macro should follow a call to AC_MSG_CHECKING, and the result-description should be the completion of the message printed by the call to AC_MSG_CHECKING. This macro printsnothing if configure is run with the --quiet or --silent option. This is quite similar to an echo after an echo -n, so it willbe in the same line.Example:AC_MSG_CHECKING(“Checking something”)(…)Something tested here…The result is a boolean variable such as « bchkSomething »(…)AC_MSG_RESULT(bchkSomething)
  98. 98. The configure.{in/ac} templateMacros used for traces :Macro: AC_MSG_NOTICE (message)Deliver the message to the user. It is useful mainly to print a general description of the overall purpose of a groupof feature checks, e.g., AC_MSG_NOTICE([checking if stack overflow is detectable]). This macro prints nothingif configure is run with the --quiet or --silent option.Macro: AC_MSG_ERROR (error-description, [exit-status = ‘$?/1’])Notify the user of an error that prevents configure from completing. This macro prints an error message to thestandard error output and exits configure with exit-status (‘$?’ by default, except that ‘0’ is converted to ‘1’). error-standard error output and exits configure with exit-status (‘$?’ by default, except that ‘0’ is converted to ‘1’). error-description should be something like ‘invalid value $HOME for $HOME’. The error-description should start witha lower-case letter, and “cannot” is preferred to “cant”.Macro: AC_MSG_FAILURE (error-description, [exit-status])This AC_MSG_ERROR wrapper notifies the user of an error that prevents configure from completing and thatadditional details are provided in config.log. This is typically used when abnormal results are found during acompilation.Examples:AC_MSG_NOTICE(“this is just a message”)
  99. 99. Initialisation of the configure script (including the requirements) :The Autoconf language differs from many other computer languages because it treats actual code the same as plain text. Whereas in C,for instance, data and instructions have different syntactic status, in Autoconf 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 white space between the macro name and the open parenthesis.AC_INIT([hello], [1.0]) # goodArguments should be enclosed within the quote characters ‘[’ and ‘]’, and be separated by commas. Any leading blanks or newlines inarguments are ignored, unless they are quoted. You should always quote an argument that might contain a macro name, comma,parenthesis, or a leading blank or newline. This rule applies recursively for every macro call, including macros called from othermacros.The configure.{in/ac} templateAC_COPYRIGHT (copyright-notice)State that, in addition to the Free Software Foundations copyright on the Autoconf macros, parts of your configure are covered by thecopyright-notice. The copyright-notice shows up in both the head of configure and in ‘configure --version’.Some are mandatory :o AC_INIT([pyPackage], [myPackageVersion], []) initializes autoconf with informationabout your project, including the project name, version number, bug-reporting address, tarball name and the projecthomepage.o AC_PREREQ(2.59) specify the autoconf versionOthers are not :o AC_AUTOMAKE() adds several standard checks and initializes automake.• AM_INIT_AUTOMAKE([1.10 no-define])• AM_INIT_AUTOMAKE([1.10 no-define foreign]) specify that the component won’t use the GNU file (NEWSREADME AUTHORS ChangeLog).
  100. 100. The configure.{in/ac} templateAC_CONFIG_SRCDIR(unique-file-in-source-dir)unique-file-in-source-dir is some file that is in the packages source directory; configure checks for this files existence to make sure thatthe directory that it is told contains the source code in fact does. Occasionally people accidentally specify the wrong directory with --srcdir; this is a safety check. Packages that do manual configuration or use the install program might need to tell configure where to findsome other shell scripts by calling AC_CONFIG_AUX_DIR, though the default places it looks are correct for most cases.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 indirectory dir. These are auxiliary files used in 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 doesnot automatically require distributing the other auxiliary files. It checks for also, but that name is obsolete because some makehave a rule that creates install from it if there is no makefile. The auxiliary directory is commonly named build-aux. If you needPATH and source code definition :have a rule that creates install from it if there is no makefile. The auxiliary directory is commonly named build-aux. If you needportability to DOS variants, do not name the auxiliary directory aux.AC_REQUIRE_AUX_FILE(file)Declares that file is expected in the directory defined above. In Autoconf proper, this macro does nothing: its sole purpose is to be tracedby third-party tools to produce a list of expected auxiliary files. For instance it is called by macros like AC_PROG_INSTALL (seeParticular Programs) or AC_CANONICAL_BUILD (see Canonicalizing) to register the auxiliary files they need. Similarly, packages thatuse aclocal should declare where local macros can be found using AC_CONFIG_MACRO_DIR.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 likeautoreconf that trace macro calls. It should be called directly from so that tools that install macros for aclocal can find themacros declarations. Note that if you use aclocal from Automake to generate aclocal.m4, you must also set ACLOCAL_AMFLAGS = -Idir in your top-level Due to a limitation in the Autoconf implementation of autoreconf, these include directives currentlymust be set on a single line in, without any backslash-newlines.
  101. 101. The configure.{in/ac} templateChecking for specific headers:AC_CHECK_HEADERS([unistd.h])Then you could have code like the following in The conf.h created by configure defines ‘HAVE_UNISTD_H’ to 1, if andonly if the system has unistd.h./* Define as 1 if you have unistd.h. */ #undef HAVE_UNISTD_HThe format of the template file is stricter than what the C preprocessor is required to accept. A directive line should contain onlywhitespace, ‘#undef’, and ‘HAVE_UNISTD_H’. The use of ‘#define’ instead of ‘#undef’, or of comments on the same line as‘#undef’, is strongly discouraged. Each hook should only be listed once. Other preprocessor lines, such as ‘#ifdef’ or ‘#include’, arecopied verbatim from the template into the generated header.
  102. 102. The configure.{in/ac} templateDefault prefix :By default, configure sets the prefix for files it installs to /usr/local. The user of configure can select a different prefix using the --prefix and --exec-prefix options. There are two ways to change the default: when creating configure, and when running it. Some softwarepackages might want to install in a directory other than /usr/local by default. To accomplish that, use the AC_PREFIX_DEFAULT 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 the installation prefix from the location of a related program that they havealready installed. If you wish to do that, you can call AC_PREFIX_PROGRAM.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 waythe shell does. If program is found, set the prefix to the parent of the directory containing program, else default the prefix as describedthe shell does. If program is found, set the prefix to the parent of the directory containing program, else default the prefix as describedabove (/usr/local or AC_PREFIX_DEFAULT). For example, if program is gcc and the PATH contains /usr/local/gnu/bin/gcc, set theprefix to /usr/local/gnu.For example, if the AC_PREFIX_DEFAULT(/usr) is defined within a, it won’t be mandatory to specify the prefix at theconfigure launch.If not we should mantadory specify the prefix: ./configure --prefix=/usr
  103. 103. In order to prevent autotools re-generating configure script automatically this is possible tospecify that we are in maintainer mode :Sometimes due to the SCM not strictly remembering the timestamp of files the generated Makefile will think that itneeds to re-run "autoreconf -i" or equivalent to re-generate from, configure, etc.You need to look into maintainer mode - that should prevent the autoreconf step, which will fix the end-usersproblems.In order to proceed, the following line should be add to the configure.{in/ac} templateAM_MAINTAINER_MODEOr provide set the --enable-maintainer-mode parameter to the configure script :./configure --prefix=/usr --enable-maintainer-mode
  104. 104. Managing version numbers for dynamic libraries:Your library can have two numbers - the release number and the version number.The release number uses a scheme of your own devising. Generally it indicates how much functionality has been added sincethe last version, and how many bugs were fixed.The version number uses an established scheme to indicate what type of changes happened to your librarys interface. Thefollowing diagram can be found in many files:FOO_LIBRARY_RELEASE=2:1:3 FOO_LIBRARY_VERSION=3:0:0current : revision : ageThe configure.{in/ac} templatecurrent : revision : ageUse this version number in your file:lfoo_la_LDFLAGS= -version-info $(FOO_LIBRARY_VERSION) -release $(FOO_LIBRARY__RELEASE)If the config.h header is used, the version will be pushed into this file. In the other case, it will be providedinto the compilation line. For a library, the delivery will generate a dynamic library using the version ( using a symbolic link to the native dynamic library (eg: This is nice to also have abuildin function (eg: get_API_version) that can provide the PACKAGE_VERSION metadata.increment if interfaces have been added | | set tozero if interfaces have been removed | | or changedIncrement if source code has changed | set tozero if current is incrementedincrement if interfaces have been added,removed or changed
  105. 105. The configure.{in/ac} templateNumbers Definitioncurrent The number of the current interface exported by the library. A current value of `0, means that you arecalling the interface exported by this library interface 0.The version scheme used by Libtool tracks interfaces, where an interface is the set of exported entrypoints into the library.All Libtool libraries start with `-version-info set to `0:0:0 -- this will be the default version number ifyou dont explicitly set it on the Libtool link command line.The meaning of these numbers (from left to right) is as follows:calling the interface exported by this library interface 0.revision The implementation number of the most recent interface exported by this library. In this case,a revision value of `0 means that this is the first implementation of the interface.If the next release of this library exports the same interface, but has a different implementation (perhapssome bugs have been fixed), the revision number will be higher, but current number will be the same. Inthat case, when given a choice, the library with the highest revision will always be used by the runtimeloader.age The number of previous additional interfaces supported by this library. If age were `2, then this library canbe linked into executables which were built with a release of this library that exported the currentinterface number, current, or any of the previous two interfaces. By definition age must be less than orequal to current. At the outset, only the first ever interface is implemented, so age can only be `0.Beware, this can generate a warning if you want to generate a static library.
  106. 106. m4_define([gm_os_major_version], [1])m4_define([gm_os_minor_version], [0])m4_define([gm_os_micro_version], [0])m4_define([gm_os_version],[gm_os_major_version.gm_os_minor_version.gm_os_micro_version])AC_INIT([gm_os_posix],[gm_os_version],[])LT_CURRENT=0LT_REVISION=0LT_AGE=0AC_SUBST(LT_CURRENT)In few steps, we can manage a package’s version:The configure.{in/ac} template Configure.acAC_SUBST(LT_CURRENT)AC_SUBST(LT_REVISION)AC_SUBST(LT_AGE)GM_OS_MAJOR_VERSION=gm_os_major_versionGM_OS_MINOR_VERSION=gm_os_minor_versionGM_OS_MICRO_VERSION=gm_os_micro_versionGM_OS_VERSION=gm_os_major_version.gm_os_minor_version.gm_os_micro_versionAC_SUBST(GM_OS_MAJOR_VERSION)AC_SUBST(GM_OS_MINOR_VERSION)AC_SUBST(GM_OS_MICRO_VERSION)AC_SUBST(GM_OS_VERSION)AM_INIT_AUTOMAKE(AC_PACKAGE_NAME, AC_PACKAGE_VERSION)
  107. 107.  Makefile.amThe configure.{in/ac} templatelib_LTLIBRARIES = libtoe.lalibtoe_la_SOURCES = src/toe_assert.c src/toe_memory.c src/toe_thread.c src/toe_messageQueue.c inc/utlist.h inc/internal_api.h inc/internal_config.hlibtoe_la_CFLAGS = -I$(HEADER_DIR) Example of template that use the version: Makefile.amlibtoe_la_CFLAGS = -I$(HEADER_DIR) $(LIBCONFIG_CFLAGS) $(LIBLOG_CFLAGS) -DLOG_NAME=TOE -DLOG_MASK_PRIO=LOG_PRIO_ALLlibtoe_la_LDFLAGS = -version-info $(LT_CURRENT):$(LT_REVISION):$(LT_AGE) -lpthread -lrtlibtoe_la_LIBADD = $(LIBCONFIG_LIBS) $(LIBLOG_LIBS) $(EFENCE_LIBS)
  108. 108. Then we can check if the tools needed for the compilation exist as well as their version:Some are buildin m4 macro povided by the autoconf package :AC_C_CONSTAC_ISC_POSIXAC_HEADER_STDCAC_PROG_CCAC_PROG_CC_STDCAC_PROG_CXXChecking for the tools expected for the build:The configure.{in/ac} templateAC_PROG_CXXAC_PROG_CPPAC_PROG_LN_SAC_PROG_INSTALLAC_PROG_LIBTOOLAC_PROG_MAKE_SETOthers can be test manualy:AC_PATH_PROG([PKG_CONFIG], [pkg-config])if test -z "$PKG_CONFIG" ; thenAC_MSG_ERROR([pkg-config not found])fi
  109. 109. Checking for the dependencies (static/dynamic libraries) :For a complete automatic build process, it can be useful to get metadata from a library (version, name, cflags,ldflags, …. ). This is what pkg-config brings to the OSS community:Example: resolution of a dependancy:# libglib2.0 dependencyPKG_CHECK_MODULES([GLIB2],[glib-2.0],[have_libglib=yes],[have_libglib=no])if test "$have_libglib" = no ; thenAC_MSG_ERROR([Missing libglib-2.0 library])elseAC_SUBST(GLIB2_CFLAGS)The configure.{in/ac} templateAC_SUBST(GLIB2_CFLAGS)AC_SUBST(GLIB2_LIBS)fiThis will check the presence of the .pc file that contains the metdata (usually in /usr/local/lib/pkg-config):$ pkg-config –-exist libnameThe PKG_CONFIG_PATH should be set to the directory that contain the .pc files.Then the M4 macro will export both the CFLAGS and the CFLAGS :$ pkg-config –-cflags libname$ pkg-config –-libs libnameThis topic will be detail with the chapter related to pkg-config.
  110. 110. Managing subdirs using AC_CONFIG_SUBDIRS (dir ...)Make AC_OUTPUT run configure in each subdirectory dir in the given blank-or-newline-separated list. Each dir should be a literal, i.e.,please do not use:if test "x$package_foo_enabled" = xyes; thenmy_subdirs="$my_subdirs foo"fiAC_CONFIG_SUBDIRS([$my_subdirs])because this prevents ‘./configure --help=recursive’ from displaying the options of the package foo. Instead, you should write:if test "x$package_foo_enabled" = xyes; thenAC_CONFIG_SUBDIRS([foo])fiThe configure.{in/ac} templatefiIf a given dir is not found at configure run time, a warning is reported; if the subdirectory 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-Autoconf scriptConfigure, which cant be called through a configure wrapper since it would be the same file on case-insensitive file systems.Likewise, if a dir contains but no configure, the Cygnus configure script found by AC_CONFIG_AUX_DIR is used.
  111. 111. Some operations are accomplished in several possible ways, depending on the OS variant. Checking for them essentially requires a“case statement”. Autoconf does not directly provide one; however, it is easy to simulate by using a shell variable to keep track ofwhether a way to perform the operation has been found yet.Here is an example that uses the shell variable fstype to keep track of whether the remaining cases need to be checked. Note thatsince the value of fstype is under our control, we dont have to use the longer ‘test "x$fstype" = xno’.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])The configure.{in/ac} templatefstype=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])
  1. A particular slide catching your eye?

    Clipping is a handy way to collect important slides you want to go back to later.