2 \input texinfo @c -*-texinfo-*-
5 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
7 @c GNAT DOCUMENTATION o
11 @c Copyright (C) 1992-2014, Free Software Foundation, Inc. o
13 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
15 @setfilename gnat_ugn.info
18 Copyright @copyright{} 1995-2014 Free Software Foundation,
21 Permission is granted to copy, distribute and/or modify this document
22 under the terms of the GNU Free Documentation License, Version 1.3 or
23 any later version published by the Free Software Foundation; with no
24 Invariant Sections, with no Front-Cover Texts and with no Back-Cover
25 Texts. A copy of the license is included in the section entitled
26 ``GNU Free Documentation License''.
29 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
31 @c GNAT_UGN Style Guide
33 @c 1. Always put a @noindent on the line before the first paragraph
34 @c after any of these commands:
46 @c 2. DO NOT use @example. Use @smallexample instead.
47 @c a) DO NOT use highlighting commands (@b{}, @i{}) inside an @smallexample
48 @c context. These can interfere with the readability of the texi
49 @c source file. Instead, use one of the following annotated
50 @c @smallexample commands, and preprocess the texi file with the
51 @c ada2texi tool (which generates appropriate highlighting):
52 @c @smallexample @c ada
53 @c @smallexample @c adanocomment
54 @c @smallexample @c projectfile
55 @c b) The "@c ada" markup will result in boldface for reserved words
56 @c and italics for comments
57 @c c) The "@c adanocomment" markup will result only in boldface for
58 @c reserved words (comments are left alone)
59 @c d) The "@c projectfile" markup is like "@c ada" except that the set
60 @c of reserved words include the new reserved words for project files
62 @c 3. Each @chapter, @section, @subsection, @subsubsection, etc.
63 @c command must be preceded by two empty lines
65 @c 4. The @item command should be on a line of its own if it is in an
66 @c @itemize or @enumerate command.
68 @c 5. When talking about ALI files use "ALI" (all uppercase), not "Ali"
71 @c 6. DO NOT put trailing spaces at the end of a line. Such spaces will
72 @c cause the document build to fail.
74 @c 7. DO NOT use @cartouche for examples that are longer than around 10 lines.
75 @c This command inhibits page breaks, so long examples in a @cartouche can
76 @c lead to large, ugly patches of empty space on a page.
78 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
81 @c This flag is used where the text refers to conditions that exist when the
82 @c text was entered into the document but which may change over time.
83 @c Update the setting for the flag, and (if necessary) the text surrounding,
84 @c the references to the flag, on future doc revisions:
85 @c search for @value{NOW}.
94 @c The ARG is an optional argument. To be used for macro arguments in
95 @c their documentation (@defmac).
97 @r{[}@var{\varname\}@r{]}@c
99 @c Status as of November 2009:
100 @c Unfortunately texi2pdf and texi2html treat the trailing "@c"
101 @c differently, and faulty output is produced by one or the other
102 @c depending on whether the "@c" is present or absent.
103 @c As a result, the @ovar macro is not used, and all invocations
104 @c of the @ovar macro have been expanded inline.
107 @settitle @value{EDITION} User's Guide
108 @dircategory GNU Ada tools
110 * @value{EDITION} User's Guide: (gnat_ugn). @value{PLATFORM}
113 @include gcc-common.texi
115 @setchapternewpage odd
120 @title @value{EDITION} User's Guide
124 @subtitle GNAT, The GNU Ada Development Environment
129 @vskip 0pt plus 1filll
136 @node Top, About This Guide, (dir), (dir)
137 @top @value{EDITION} User's Guide
140 @value{EDITION} User's Guide @value{PLATFORM}
143 GNAT, The GNU Ada Development Environment@*
144 GCC version @value{version-GCC}@*
151 * Getting Started with GNAT::
152 * The GNAT Compilation Model::
153 * Compiling with gcc::
154 * Binding with gnatbind::
155 * Linking with gnatlink::
156 * The GNAT Make Program gnatmake::
157 * Improving Performance::
158 * Renaming Files with gnatchop::
159 * Configuration Pragmas::
160 * Handling Arbitrary File Naming Conventions with gnatname::
161 * GNAT Project Manager::
162 * Tools Supporting Project Files::
163 * The Cross-Referencing Tools gnatxref and gnatfind::
165 * The GNAT Pretty-Printer gnatpp::
166 * The Ada-to-XML converter gnat2xml::
167 * The GNAT Metrics Tool gnatmetric::
169 * File Name Krunching with gnatkr::
170 * Preprocessing with gnatprep::
171 * The GNAT Library Browser gnatls::
172 * Cleaning Up with gnatclean::
173 * GNAT and Libraries::
174 * Using the GNU make Utility::
175 * Memory Management Issues::
176 * Stack Related Facilities::
178 * Verifying Properties with gnatcheck::
179 * Creating Sample Bodies with gnatstub::
180 * Creating Unit Tests with gnattest::
182 * Performing Dimensionality Analysis in GNAT::
183 * Generating Ada Bindings for C and C++ headers::
184 * Other Utility Programs::
185 * Code Coverage and Profiling::
186 * Running and Debugging Ada Programs::
187 * Platform-Specific Information for the Run-Time Libraries::
188 * Example of Binder Output File::
189 * Elaboration Order Handling in GNAT::
190 * Overflow Check Handling in GNAT::
191 * Conditional Compilation::
193 * Writing Portable Fixed-Point Declarations::
194 * Compatibility and Porting Guide::
195 * Microsoft Windows Topics::
197 * GNU Free Documentation License::
202 @node About This Guide
203 @unnumbered About This Guide
206 This guide describes the use of @value{EDITION},
207 a compiler and software development
208 toolset for the full Ada programming language.
209 It documents the features of the compiler and tools, and explains
210 how to use them to build Ada applications.
212 @value{EDITION} implements Ada 95, Ada 2005 and Ada 2012, and it may also be
213 invoked in Ada 83 compatibility mode.
214 By default, @value{EDITION} assumes Ada 2012, but you can override with a
215 compiler switch (@pxref{Compiling Different Versions of Ada})
216 to explicitly specify the language version.
217 Throughout this manual, references to ``Ada'' without a year suffix
218 apply to all Ada 95/2005/2012 versions of the language.
221 For ease of exposition, ``@value{EDITION}'' will be referred to simply as
222 ``GNAT'' in the remainder of this document.
227 * What This Guide Contains::
228 * What You Should Know before Reading This Guide::
229 * Related Information::
233 @node What This Guide Contains
234 @unnumberedsec What This Guide Contains
237 This guide contains the following chapters:
241 @ref{Getting Started with GNAT}, describes how to get started compiling
242 and running Ada programs with the GNAT Ada programming environment.
244 @ref{The GNAT Compilation Model}, describes the compilation model used
248 @ref{Compiling with gcc}, describes how to compile
249 Ada programs with @command{gcc}, the Ada compiler.
252 @ref{Binding with gnatbind}, describes how to
253 perform binding of Ada programs with @code{gnatbind}, the GNAT binding
257 @ref{Linking with gnatlink},
258 describes @command{gnatlink}, a
259 program that provides for linking using the GNAT run-time library to
260 construct a program. @command{gnatlink} can also incorporate foreign language
261 object units into the executable.
264 @ref{The GNAT Make Program gnatmake}, describes @command{gnatmake}, a
265 utility that automatically determines the set of sources
266 needed by an Ada compilation unit, and executes the necessary compilations
270 @ref{Improving Performance}, shows various techniques for making your
271 Ada program run faster or take less space and describes the effect of
272 the compiler's optimization switch.
275 the @command{gnatelim} tool and
277 unused subprogram/data elimination.
280 @ref{Renaming Files with gnatchop}, describes
281 @code{gnatchop}, a utility that allows you to preprocess a file that
282 contains Ada source code, and split it into one or more new files, one
283 for each compilation unit.
286 @ref{Configuration Pragmas}, describes the configuration pragmas
290 @ref{Handling Arbitrary File Naming Conventions with gnatname},
291 shows how to override the default GNAT file naming conventions,
292 either for an individual unit or globally.
295 @ref{GNAT Project Manager}, describes how to use project files
296 to organize large projects.
299 @ref{The Cross-Referencing Tools gnatxref and gnatfind}, discusses
300 @code{gnatxref} and @code{gnatfind}, two tools that provide an easy
301 way to navigate through sources.
305 @ref{The GNAT Pretty-Printer gnatpp}, shows how to produce a reformatted
306 version of an Ada source file with control over casing, indentation,
307 comment placement, and other elements of program presentation style.
312 @ref{The Ada-to-XML converter gnat2xml}, shows how to convert Ada
313 source code into XML.
318 @ref{The GNAT Metrics Tool gnatmetric}, shows how to compute various
319 metrics for an Ada source file, such as the number of types and subprograms,
320 and assorted complexity measures.
324 @ref{File Name Krunching with gnatkr}, describes the @code{gnatkr}
325 file name krunching utility, used to handle shortened
326 file names on operating systems with a limit on the length of names.
329 @ref{Preprocessing with gnatprep}, describes @code{gnatprep}, a
330 preprocessor utility that allows a single source file to be used to
331 generate multiple or parameterized source files by means of macro
335 @ref{The GNAT Library Browser gnatls}, describes @code{gnatls}, a
336 utility that displays information about compiled units, including dependences
337 on the corresponding sources files, and consistency of compilations.
340 @ref{Cleaning Up with gnatclean}, describes @code{gnatclean}, a utility
341 to delete files that are produced by the compiler, binder and linker.
344 @ref{GNAT and Libraries}, describes the process of creating and using
345 Libraries with GNAT. It also describes how to recompile the GNAT run-time
349 @ref{Using the GNU make Utility}, describes some techniques for using
350 the GNAT toolset in Makefiles.
353 @ref{Memory Management Issues}, describes some useful predefined storage pools
354 and in particular the GNAT Debug Pool facility, which helps detect incorrect
357 It also describes @command{gnatmem}, a utility that monitors dynamic
358 allocation and deallocation and helps detect ``memory leaks''.
362 @ref{Stack Related Facilities}, describes some useful tools associated with
363 stack checking and analysis.
367 @ref{Verifying Properties with gnatcheck}, discusses @code{gnatcheck},
368 a utility that checks Ada code against a set of rules.
371 @ref{Creating Sample Bodies with gnatstub}, discusses @code{gnatstub},
372 a utility that generates empty but compilable bodies for library units.
377 @ref{Creating Unit Tests with gnattest}, discusses @code{gnattest},
378 a utility that generates unit testing templates for library units.
382 @ref{Performing Dimensionality Analysis in GNAT}, describes the Ada 2012
383 facilities used in GNAT to declare dimensioned objects, and to verify that
384 uses of these objects are consistent with their given physical dimensions
385 (so that meters cannot be assigned to kilograms, and so on).
388 @ref{Generating Ada Bindings for C and C++ headers}, describes how to
389 generate automatically Ada bindings from C and C++ headers.
392 @ref{Other Utility Programs}, discusses several other GNAT utilities,
393 including @code{gnathtml}.
396 @ref{Code Coverage and Profiling}, describes how to perform a structural
397 coverage and profile the execution of Ada programs.
400 @ref{Running and Debugging Ada Programs}, describes how to run and debug
405 @ref{Platform-Specific Information for the Run-Time Libraries},
406 describes the various run-time
407 libraries supported by GNAT on various platforms and explains how to
408 choose a particular library.
411 @ref{Example of Binder Output File}, shows the source code for the binder
412 output file for a sample program.
415 @ref{Elaboration Order Handling in GNAT}, describes how GNAT helps
416 you deal with elaboration order issues.
419 @ref{Overflow Check Handling in GNAT}, describes how GNAT helps
420 you deal with arithmetic overflow issues.
423 @ref{Conditional Compilation}, describes how to model conditional compilation,
424 both with Ada in general and with GNAT facilities in particular.
427 @ref{Inline Assembler}, shows how to use the inline assembly facility
431 @ref{Writing Portable Fixed-Point Declarations}, gives some guidance on
432 defining portable fixed-point types.
435 @ref{Compatibility and Porting Guide}, contains sections on compatibility
436 of GNAT with other Ada development environments (including Ada 83 systems),
437 to assist in porting code from those environments.
440 @ref{Microsoft Windows Topics}, presents information relevant to the
441 Microsoft Windows platform.
444 @ref{Mac OS Topics}, presents information relevant to Apple's OS X
448 @c *************************************************
449 @node What You Should Know before Reading This Guide
450 @c *************************************************
451 @unnumberedsec What You Should Know before Reading This Guide
453 @cindex Ada 95 Language Reference Manual
454 @cindex Ada 2005 Language Reference Manual
456 This guide assumes a basic familiarity with the Ada 95 language, as
457 described in the International Standard ANSI/ISO/IEC-8652:1995, January
459 It does not require knowledge of the new features introduced by Ada 2005,
460 (officially known as ISO/IEC 8652:1995 with Technical Corrigendum 1
462 Both reference manuals are included in the GNAT documentation
465 @node Related Information
466 @unnumberedsec Related Information
469 For further information about related tools, refer to the following
474 @xref{Top, GNAT Reference Manual, About This Guide, gnat_rm, GNAT
475 Reference Manual}, which contains all reference material for the GNAT
476 implementation of Ada.
479 @cite{Using the GNAT Programming Studio}, which describes the GPS
480 Integrated Development Environment.
483 @cite{GNAT Programming Studio Tutorial}, which introduces the
484 main GPS features through examples.
487 @cite{Ada 95 Reference Manual}, which contains reference
488 material for the Ada 95 programming language.
491 @cite{Ada 2005 Reference Manual}, which contains reference
492 material for the Ada 2005 programming language.
495 @xref{Top,, Debugging with GDB, gdb, Debugging with GDB},
496 for all details on the use of the GNU source-level debugger.
499 @xref{Top,, The extensible self-documenting text editor, emacs,
501 for full information on the extensible editor and programming
508 @unnumberedsec Conventions
510 @cindex Typographical conventions
513 Following are examples of the typographical and graphic conventions used
518 @code{Functions}, @command{utility program names}, @code{standard names},
522 @option{Option flags}
525 @file{File names}, @samp{button names}, and @samp{field names}.
528 @code{Variables}, @env{environment variables}, and @var{metasyntactic
535 @r{[}optional information or parameters@r{]}
538 Examples are described by text
540 and then shown this way.
545 Commands that are entered by the user are preceded in this manual by the
546 characters @w{``@code{$ }''} (dollar sign followed by space). If your system
547 uses this sequence as a prompt, then the commands will appear exactly as
548 you see them in the manual. If your system uses some other prompt, then
549 the command will appear with the @code{$} replaced by whatever prompt
550 character you are using.
552 Full file names are shown with the ``@code{/}'' character
553 as the directory separator; e.g., @file{parent-dir/subdir/myfile.adb}.
554 If you are using GNAT on a Windows platform, please note that
555 the ``@code{\}'' character should be used instead.
557 @c ****************************
558 @node Getting Started with GNAT
559 @chapter Getting Started with GNAT
562 This chapter describes some simple ways of using GNAT to build
563 executable Ada programs.
564 @ref{Running GNAT}, through @ref{Using the gnatmake Utility},
565 show how to use the command line environment.
566 @ref{Introduction to GPS}, provides a brief
567 introduction to the GNAT Programming Studio, a visually-oriented
568 Integrated Development Environment for GNAT.
569 GPS offers a graphical ``look and feel'', support for development in
570 other programming languages, comprehensive browsing features, and
571 many other capabilities.
572 For information on GPS please refer to
573 @cite{Using the GNAT Programming Studio}.
577 * Running a Simple Ada Program::
578 * Running a Program with Multiple Units::
579 * Using the gnatmake Utility::
580 * Introduction to GPS::
584 @section Running GNAT
587 Three steps are needed to create an executable file from an Ada source
592 The source file(s) must be compiled.
594 The file(s) must be bound using the GNAT binder.
596 All appropriate object files must be linked to produce an executable.
600 All three steps are most commonly handled by using the @command{gnatmake}
601 utility program that, given the name of the main program, automatically
602 performs the necessary compilation, binding and linking steps.
604 @node Running a Simple Ada Program
605 @section Running a Simple Ada Program
608 Any text editor may be used to prepare an Ada program.
610 used, the optional Ada mode may be helpful in laying out the program.)
612 program text is a normal text file. We will assume in our initial
613 example that you have used your editor to prepare the following
614 standard format text file:
618 @b{with} Ada.Text_IO; @b{use} Ada.Text_IO;
619 @b{procedure} Hello @b{is}
621 Put_Line ("Hello WORLD!");
627 This file should be named @file{hello.adb}.
628 With the normal default file naming conventions, GNAT requires
630 contain a single compilation unit whose file name is the
632 with periods replaced by hyphens; the
633 extension is @file{ads} for a
634 spec and @file{adb} for a body.
635 You can override this default file naming convention by use of the
636 special pragma @code{Source_File_Name} (@pxref{Using Other File Names}).
637 Alternatively, if you want to rename your files according to this default
638 convention, which is probably more convenient if you will be using GNAT
639 for all your compilations, then the @code{gnatchop} utility
640 can be used to generate correctly-named source files
641 (@pxref{Renaming Files with gnatchop}).
643 You can compile the program using the following command (@code{$} is used
644 as the command prompt in the examples in this document):
651 @command{gcc} is the command used to run the compiler. This compiler is
652 capable of compiling programs in several languages, including Ada and
653 C. It assumes that you have given it an Ada program if the file extension is
654 either @file{.ads} or @file{.adb}, and it will then call
655 the GNAT compiler to compile the specified file.
657 The @option{-c} switch is required. It tells @command{gcc} to only do a
658 compilation. (For C programs, @command{gcc} can also do linking, but this
659 capability is not used directly for Ada programs, so the @option{-c}
660 switch must always be present.)
662 This compile command generates a file
663 @file{hello.o}, which is the object
664 file corresponding to your Ada program. It also generates
665 an ``Ada Library Information'' file @file{hello.ali},
666 which contains additional information used to check
667 that an Ada program is consistent.
668 To build an executable file,
669 use @code{gnatbind} to bind the program
670 and @command{gnatlink} to link it. The
671 argument to both @code{gnatbind} and @command{gnatlink} is the name of the
672 @file{ALI} file, but the default extension of @file{.ali} can
673 be omitted. This means that in the most common case, the argument
674 is simply the name of the main program:
682 A simpler method of carrying out these steps is to use
684 a master program that invokes all the required
685 compilation, binding and linking tools in the correct order. In particular,
686 @command{gnatmake} automatically recompiles any sources that have been
687 modified since they were last compiled, or sources that depend
688 on such modified sources, so that ``version skew'' is avoided.
689 @cindex Version skew (avoided by @command{gnatmake})
696 The result is an executable program called @file{hello}, which can be
704 assuming that the current directory is on the search path
705 for executable programs.
708 and, if all has gone well, you will see
715 appear in response to this command.
717 @c ****************************************
718 @node Running a Program with Multiple Units
719 @section Running a Program with Multiple Units
722 Consider a slightly more complicated example that has three files: a
723 main program, and the spec and body of a package:
728 @b{package} Greetings @b{is}
730 @b{procedure} Goodbye;
733 @b{with} Ada.Text_IO; @b{use} Ada.Text_IO;
734 @b{package} @b{body} Greetings @b{is}
735 @b{procedure} Hello @b{is}
737 Put_Line ("Hello WORLD!");
740 @b{procedure} Goodbye @b{is}
742 Put_Line ("Goodbye WORLD!");
749 @b{procedure} Gmain @b{is}
759 Following the one-unit-per-file rule, place this program in the
760 following three separate files:
764 spec of package @code{Greetings}
767 body of package @code{Greetings}
774 To build an executable version of
775 this program, we could use four separate steps to compile, bind, and link
776 the program, as follows:
780 $ gcc -c greetings.adb
786 Note that there is no required order of compilation when using GNAT.
787 In particular it is perfectly fine to compile the main program first.
788 Also, it is not necessary to compile package specs in the case where
789 there is an accompanying body; you only need to compile the body. If you want
790 to submit these files to the compiler for semantic checking and not code
791 generation, then use the
792 @option{-gnatc} switch:
795 $ gcc -c greetings.ads -gnatc
799 Although the compilation can be done in separate steps as in the
800 above example, in practice it is almost always more convenient
801 to use the @command{gnatmake} tool. All you need to know in this case
802 is the name of the main program's source file. The effect of the above four
803 commands can be achieved with a single one:
810 In the next section we discuss the advantages of using @command{gnatmake} in
813 @c *****************************
814 @node Using the gnatmake Utility
815 @section Using the @command{gnatmake} Utility
818 If you work on a program by compiling single components at a time using
819 @command{gcc}, you typically keep track of the units you modify. In order to
820 build a consistent system, you compile not only these units, but also any
821 units that depend on the units you have modified.
822 For example, in the preceding case,
823 if you edit @file{gmain.adb}, you only need to recompile that file. But if
824 you edit @file{greetings.ads}, you must recompile both
825 @file{greetings.adb} and @file{gmain.adb}, because both files contain
826 units that depend on @file{greetings.ads}.
828 @code{gnatbind} will warn you if you forget one of these compilation
829 steps, so that it is impossible to generate an inconsistent program as a
830 result of forgetting to do a compilation. Nevertheless it is tedious and
831 error-prone to keep track of dependencies among units.
832 One approach to handle the dependency-bookkeeping is to use a
833 makefile. However, makefiles present maintenance problems of their own:
834 if the dependencies change as you change the program, you must make
835 sure that the makefile is kept up-to-date manually, which is also an
838 The @command{gnatmake} utility takes care of these details automatically.
839 Invoke it using either one of the following forms:
847 The argument is the name of the file containing the main program;
848 you may omit the extension. @command{gnatmake}
849 examines the environment, automatically recompiles any files that need
850 recompiling, and binds and links the resulting set of object files,
851 generating the executable file, @file{gmain}.
852 In a large program, it
853 can be extremely helpful to use @command{gnatmake}, because working out by hand
854 what needs to be recompiled can be difficult.
856 Note that @command{gnatmake}
857 takes into account all the Ada rules that
858 establish dependencies among units. These include dependencies that result
859 from inlining subprogram bodies, and from
860 generic instantiation. Unlike some other
861 Ada make tools, @command{gnatmake} does not rely on the dependencies that were
862 found by the compiler on a previous compilation, which may possibly
863 be wrong when sources change. @command{gnatmake} determines the exact set of
864 dependencies from scratch each time it is run.
867 @node Introduction to GPS
868 @section Introduction to GPS
869 @cindex GPS (GNAT Programming Studio)
870 @cindex GNAT Programming Studio (GPS)
872 Although the command line interface (@command{gnatmake}, etc.) alone
873 is sufficient, a graphical Interactive Development
874 Environment can make it easier for you to compose, navigate, and debug
875 programs. This section describes the main features of GPS
876 (``GNAT Programming Studio''), the GNAT graphical IDE.
877 You will see how to use GPS to build and debug an executable, and
878 you will also learn some of the basics of the GNAT ``project'' facility.
880 GPS enables you to do much more than is presented here;
881 e.g., you can produce a call graph, interface to a third-party
882 Version Control System, and inspect the generated assembly language
884 Indeed, GPS also supports languages other than Ada.
885 Such additional information, and an explanation of all of the GPS menu
886 items. may be found in the on-line help, which includes
887 a user's guide and a tutorial (these are also accessible from the GNAT
891 * Building a New Program with GPS::
892 * Simple Debugging with GPS::
895 @node Building a New Program with GPS
896 @subsection Building a New Program with GPS
898 GPS invokes the GNAT compilation tools using information
899 contained in a @emph{project} (also known as a @emph{project file}):
900 a collection of properties such
901 as source directories, identities of main subprograms, tool switches, etc.,
902 and their associated values.
903 See @ref{GNAT Project Manager} for details.
904 In order to run GPS, you will need to either create a new project
905 or else open an existing one.
907 This section will explain how you can use GPS to create a project,
908 to associate Ada source files with a project, and to build and run
912 @item @emph{Creating a project}
914 Invoke GPS, either from the command line or the platform's IDE.
915 After it starts, GPS will display a ``Welcome'' screen with three
920 @code{Start with default project in directory}
923 @code{Create new project with wizard}
926 @code{Open existing project}
930 Select @code{Create new project with wizard} and press @code{OK}.
931 A new window will appear. In the text box labeled with
932 @code{Enter the name of the project to create}, type @file{sample}
934 In the next box, browse to choose the directory in which you
935 would like to create the project file.
936 After selecting an appropriate directory, press @code{Forward}.
938 A window will appear with the title
939 @code{Version Control System Configuration}.
940 Simply press @code{Forward}.
942 A window will appear with the title
943 @code{Please select the source directories for this project}.
944 The directory that you specified for the project file will be selected
945 by default as the one to use for sources; simply press @code{Forward}.
947 A window will appear with the title
948 @code{Please select the build directory for this project}.
949 The directory that you specified for the project file will be selected
950 by default for object files and executables;
951 simply press @code{Forward}.
953 A window will appear with the title
954 @code{Please select the main units for this project}.
955 You will supply this information later, after creating the source file.
956 Simply press @code{Forward} for now.
958 A window will appear with the title
959 @code{Please select the switches to build the project}.
960 Press @code{Apply}. This will create a project file named
961 @file{sample.prj} in the directory that you had specified.
963 @item @emph{Creating and saving the source file}
965 After you create the new project, a GPS window will appear, which is
966 partitioned into two main sections:
970 A @emph{Workspace area}, initially greyed out, which you will use for
971 creating and editing source files
974 Directly below, a @emph{Messages area}, which initially displays a
976 (If the Messages area is not visible, drag its border upward to expand it.)
980 Select @code{File} on the menu bar, and then the @code{New} command.
981 The Workspace area will become white, and you can now
982 enter the source program explicitly.
983 Type the following text
987 @b{with} Ada.Text_IO; @b{use} Ada.Text_IO;
988 @b{procedure} Hello @b{is}
990 Put_Line("Hello from GPS!");
996 Select @code{File}, then @code{Save As}, and enter the source file name
998 The file will be saved in the same directory you specified as the
999 location of the default project file.
1001 @item @emph{Updating the project file}
1003 You need to add the new source file to the project.
1005 the @code{Project} menu and then @code{Edit project properties}.
1006 Click the @code{Main files} tab on the left, and then the
1008 Choose @file{hello.adb} from the list, and press @code{Open}.
1009 The project settings window will reflect this action.
1012 @item @emph{Building and running the program}
1014 In the main GPS window, now choose the @code{Build} menu, then @code{Make},
1015 and select @file{hello.adb}.
1016 The Messages window will display the resulting invocations of @command{gcc},
1017 @command{gnatbind}, and @command{gnatlink}
1018 (reflecting the default switch settings from the
1019 project file that you created) and then a ``successful compilation/build''
1022 To run the program, choose the @code{Build} menu, then @code{Run}, and
1023 select @command{hello}.
1024 An @emph{Arguments Selection} window will appear.
1025 There are no command line arguments, so just click @code{OK}.
1027 The Messages window will now display the program's output (the string
1028 @code{Hello from GPS}), and at the bottom of the GPS window a status
1029 update is displayed (@code{Run: hello}).
1030 Close the GPS window (or select @code{File}, then @code{Exit}) to
1031 terminate this GPS session.
1034 @node Simple Debugging with GPS
1035 @subsection Simple Debugging with GPS
1037 This section illustrates basic debugging techniques (setting breakpoints,
1038 examining/modifying variables, single stepping).
1041 @item @emph{Opening a project}
1043 Start GPS and select @code{Open existing project}; browse to
1044 specify the project file @file{sample.prj} that you had created in the
1047 @item @emph{Creating a source file}
1049 Select @code{File}, then @code{New}, and type in the following program:
1051 @smallexample @c ada
1053 @b{with} Ada.Text_IO; @b{use} Ada.Text_IO;
1054 @b{procedure} Example @b{is}
1055 Line : String (1..80);
1058 Put_Line("Type a line of text at each prompt; an empty line to exit");
1062 Put_Line (Line (1..N) );
1063 @b{exit} @b{when} N=0;
1070 Select @code{File}, then @code{Save as}, and enter the file name
1073 @item @emph{Updating the project file}
1075 Add @code{Example} as a new main unit for the project:
1078 Select @code{Project}, then @code{Edit Project Properties}.
1081 Select the @code{Main files} tab, click @code{Add}, then
1082 select the file @file{example.adb} from the list, and
1084 You will see the file name appear in the list of main units
1090 @item @emph{Building/running the executable}
1092 To build the executable
1093 select @code{Build}, then @code{Make}, and then choose @file{example.adb}.
1095 Run the program to see its effect (in the Messages area).
1096 Each line that you enter is displayed; an empty line will
1097 cause the loop to exit and the program to terminate.
1099 @item @emph{Debugging the program}
1101 Note that the @option{-g} switches to @command{gcc} and @command{gnatlink},
1102 which are required for debugging, are on by default when you create
1104 Thus unless you intentionally remove these settings, you will be able
1105 to debug any program that you develop using GPS.
1108 @item @emph{Initializing}
1110 Select @code{Debug}, then @code{Initialize}, then @file{example}
1112 @item @emph{Setting a breakpoint}
1114 After performing the initialization step, you will observe a small
1115 icon to the right of each line number.
1116 This serves as a toggle for breakpoints; clicking the icon will
1117 set a breakpoint at the corresponding line (the icon will change to
1118 a red circle with an ``x''), and clicking it again
1119 will remove the breakpoint / reset the icon.
1121 For purposes of this example, set a breakpoint at line 10 (the
1122 statement @code{Put_Line@ (Line@ (1..N));}
1124 @item @emph{Starting program execution}
1126 Select @code{Debug}, then @code{Run}. When the
1127 @code{Program Arguments} window appears, click @code{OK}.
1128 A console window will appear; enter some line of text,
1129 e.g.@: @code{abcde}, at the prompt.
1130 The program will pause execution when it gets to the
1131 breakpoint, and the corresponding line is highlighted.
1133 @item @emph{Examining a variable}
1135 Move the mouse over one of the occurrences of the variable @code{N}.
1136 You will see the value (5) displayed, in ``tool tip'' fashion.
1137 Right click on @code{N}, select @code{Debug}, then select @code{Display N}.
1138 You will see information about @code{N} appear in the @code{Debugger Data}
1139 pane, showing the value as 5.
1141 @item @emph{Assigning a new value to a variable}
1143 Right click on the @code{N} in the @code{Debugger Data} pane, and
1144 select @code{Set value of N}.
1145 When the input window appears, enter the value @code{4} and click
1147 This value does not automatically appear in the @code{Debugger Data}
1148 pane; to see it, right click again on the @code{N} in the
1149 @code{Debugger Data} pane and select @code{Update value}.
1150 The new value, 4, will appear in red.
1152 @item @emph{Single stepping}
1154 Select @code{Debug}, then @code{Next}.
1155 This will cause the next statement to be executed, in this case the
1156 call of @code{Put_Line} with the string slice.
1157 Notice in the console window that the displayed string is simply
1158 @code{abcd} and not @code{abcde} which you had entered.
1159 This is because the upper bound of the slice is now 4 rather than 5.
1161 @item @emph{Removing a breakpoint}
1163 Toggle the breakpoint icon at line 10.
1165 @item @emph{Resuming execution from a breakpoint}
1167 Select @code{Debug}, then @code{Continue}.
1168 The program will reach the next iteration of the loop, and
1169 wait for input after displaying the prompt.
1170 This time, just hit the @kbd{Enter} key.
1171 The value of @code{N} will be 0, and the program will terminate.
1172 The console window will disappear.
1176 @node The GNAT Compilation Model
1177 @chapter The GNAT Compilation Model
1178 @cindex GNAT compilation model
1179 @cindex Compilation model
1182 * Source Representation::
1183 * Foreign Language Representation::
1184 * File Naming Rules::
1185 * Using Other File Names::
1186 * Alternative File Naming Schemes::
1187 * Generating Object Files::
1188 * Source Dependencies::
1189 * The Ada Library Information Files::
1190 * Binding an Ada Program::
1191 * Mixed Language Programming::
1192 * Building Mixed Ada & C++ Programs::
1193 * Comparison between GNAT and C/C++ Compilation Models::
1194 * Comparison between GNAT and Conventional Ada Library Models::
1198 This chapter describes the compilation model used by GNAT. Although
1199 similar to that used by other languages, such as C and C++, this model
1200 is substantially different from the traditional Ada compilation models,
1201 which are based on a library. The model is initially described without
1202 reference to the library-based model. If you have not previously used an
1203 Ada compiler, you need only read the first part of this chapter. The
1204 last section describes and discusses the differences between the GNAT
1205 model and the traditional Ada compiler models. If you have used other
1206 Ada compilers, this section will help you to understand those
1207 differences, and the advantages of the GNAT model.
1209 @node Source Representation
1210 @section Source Representation
1214 Ada source programs are represented in standard text files, using
1215 Latin-1 coding. Latin-1 is an 8-bit code that includes the familiar
1216 7-bit ASCII set, plus additional characters used for
1217 representing foreign languages (@pxref{Foreign Language Representation}
1218 for support of non-USA character sets). The format effector characters
1219 are represented using their standard ASCII encodings, as follows:
1224 Vertical tab, @code{16#0B#}
1228 Horizontal tab, @code{16#09#}
1232 Carriage return, @code{16#0D#}
1236 Line feed, @code{16#0A#}
1240 Form feed, @code{16#0C#}
1244 Source files are in standard text file format. In addition, GNAT will
1245 recognize a wide variety of stream formats, in which the end of
1246 physical lines is marked by any of the following sequences:
1247 @code{LF}, @code{CR}, @code{CR-LF}, or @code{LF-CR}. This is useful
1248 in accommodating files that are imported from other operating systems.
1250 @cindex End of source file
1251 @cindex Source file, end
1253 The end of a source file is normally represented by the physical end of
1254 file. However, the control character @code{16#1A#} (@code{SUB}) is also
1255 recognized as signalling the end of the source file. Again, this is
1256 provided for compatibility with other operating systems where this
1257 code is used to represent the end of file.
1259 Each file contains a single Ada compilation unit, including any pragmas
1260 associated with the unit. For example, this means you must place a
1261 package declaration (a package @dfn{spec}) and the corresponding body in
1262 separate files. An Ada @dfn{compilation} (which is a sequence of
1263 compilation units) is represented using a sequence of files. Similarly,
1264 you will place each subunit or child unit in a separate file.
1266 @node Foreign Language Representation
1267 @section Foreign Language Representation
1270 GNAT supports the standard character sets defined in Ada as well as
1271 several other non-standard character sets for use in localized versions
1272 of the compiler (@pxref{Character Set Control}).
1275 * Other 8-Bit Codes::
1276 * Wide_Character Encodings::
1277 * Wide_Wide_Character Encodings::
1285 The basic character set is Latin-1. This character set is defined by ISO
1286 standard 8859, part 1. The lower half (character codes @code{16#00#}
1287 @dots{} @code{16#7F#)} is identical to standard ASCII coding, but the upper
1288 half is used to represent additional characters. These include extended letters
1289 used by European languages, such as French accents, the vowels with umlauts
1290 used in German, and the extra letter A-ring used in Swedish.
1292 @findex Ada.Characters.Latin_1
1293 For a complete list of Latin-1 codes and their encodings, see the source
1294 file of library unit @code{Ada.Characters.Latin_1} in file
1295 @file{a-chlat1.ads}.
1296 You may use any of these extended characters freely in character or
1297 string literals. In addition, the extended characters that represent
1298 letters can be used in identifiers.
1300 @node Other 8-Bit Codes
1301 @subsection Other 8-Bit Codes
1304 GNAT also supports several other 8-bit coding schemes:
1307 @item ISO 8859-2 (Latin-2)
1310 Latin-2 letters allowed in identifiers, with uppercase and lowercase
1313 @item ISO 8859-3 (Latin-3)
1316 Latin-3 letters allowed in identifiers, with uppercase and lowercase
1319 @item ISO 8859-4 (Latin-4)
1322 Latin-4 letters allowed in identifiers, with uppercase and lowercase
1325 @item ISO 8859-5 (Cyrillic)
1328 ISO 8859-5 letters (Cyrillic) allowed in identifiers, with uppercase and
1329 lowercase equivalence.
1331 @item ISO 8859-15 (Latin-9)
1334 ISO 8859-15 (Latin-9) letters allowed in identifiers, with uppercase and
1335 lowercase equivalence
1337 @item IBM PC (code page 437)
1338 @cindex code page 437
1339 This code page is the normal default for PCs in the U.S. It corresponds
1340 to the original IBM PC character set. This set has some, but not all, of
1341 the extended Latin-1 letters, but these letters do not have the same
1342 encoding as Latin-1. In this mode, these letters are allowed in
1343 identifiers with uppercase and lowercase equivalence.
1345 @item IBM PC (code page 850)
1346 @cindex code page 850
1347 This code page is a modification of 437 extended to include all the
1348 Latin-1 letters, but still not with the usual Latin-1 encoding. In this
1349 mode, all these letters are allowed in identifiers with uppercase and
1350 lowercase equivalence.
1352 @item Full Upper 8-bit
1353 Any character in the range 80-FF allowed in identifiers, and all are
1354 considered distinct. In other words, there are no uppercase and lowercase
1355 equivalences in this range. This is useful in conjunction with
1356 certain encoding schemes used for some foreign character sets (e.g.,
1357 the typical method of representing Chinese characters on the PC).
1360 No upper-half characters in the range 80-FF are allowed in identifiers.
1361 This gives Ada 83 compatibility for identifier names.
1365 For precise data on the encodings permitted, and the uppercase and lowercase
1366 equivalences that are recognized, see the file @file{csets.adb} in
1367 the GNAT compiler sources. You will need to obtain a full source release
1368 of GNAT to obtain this file.
1370 @node Wide_Character Encodings
1371 @subsection Wide_Character Encodings
1374 GNAT allows wide character codes to appear in character and string
1375 literals, and also optionally in identifiers, by means of the following
1376 possible encoding schemes:
1381 In this encoding, a wide character is represented by the following five
1389 Where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal
1390 characters (using uppercase letters) of the wide character code. For
1391 example, ESC A345 is used to represent the wide character with code
1393 This scheme is compatible with use of the full Wide_Character set.
1395 @item Upper-Half Coding
1396 @cindex Upper-Half Coding
1397 The wide character with encoding @code{16#abcd#} where the upper bit is on
1398 (in other words, ``a'' is in the range 8-F) is represented as two bytes,
1399 @code{16#ab#} and @code{16#cd#}. The second byte cannot be a format control
1400 character, but is not required to be in the upper half. This method can
1401 be also used for shift-JIS or EUC, where the internal coding matches the
1404 @item Shift JIS Coding
1405 @cindex Shift JIS Coding
1406 A wide character is represented by a two-character sequence,
1408 @code{16#cd#}, with the restrictions described for upper-half encoding as
1409 described above. The internal character code is the corresponding JIS
1410 character according to the standard algorithm for Shift-JIS
1411 conversion. Only characters defined in the JIS code set table can be
1412 used with this encoding method.
1416 A wide character is represented by a two-character sequence
1418 @code{16#cd#}, with both characters being in the upper half. The internal
1419 character code is the corresponding JIS character according to the EUC
1420 encoding algorithm. Only characters defined in the JIS code set table
1421 can be used with this encoding method.
1424 A wide character is represented using
1425 UCS Transformation Format 8 (UTF-8) as defined in Annex R of ISO
1426 10646-1/Am.2. Depending on the character value, the representation
1427 is a one, two, or three byte sequence:
1432 16#0000#-16#007f#: 2#0@var{xxxxxxx}#
1433 16#0080#-16#07ff#: 2#110@var{xxxxx}# 2#10@var{xxxxxx}#
1434 16#0800#-16#ffff#: 2#1110@var{xxxx}# 2#10@var{xxxxxx}# 2#10@var{xxxxxx}#
1439 where the @var{xxx} bits correspond to the left-padded bits of the
1440 16-bit character value. Note that all lower half ASCII characters
1441 are represented as ASCII bytes and all upper half characters and
1442 other wide characters are represented as sequences of upper-half
1443 (The full UTF-8 scheme allows for encoding 31-bit characters as
1444 6-byte sequences, and in the following section on wide wide
1445 characters, the use of these sequences is documented).
1447 @item Brackets Coding
1448 In this encoding, a wide character is represented by the following eight
1456 Where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal
1457 characters (using uppercase letters) of the wide character code. For
1458 example, [``A345''] is used to represent the wide character with code
1459 @code{16#A345#}. It is also possible (though not required) to use the
1460 Brackets coding for upper half characters. For example, the code
1461 @code{16#A3#} can be represented as @code{[``A3'']}.
1463 This scheme is compatible with use of the full Wide_Character set,
1464 and is also the method used for wide character encoding in some standard
1465 ACATS (Ada Conformity Assessment Test Suite) test suite distributions.
1470 Note: Some of these coding schemes do not permit the full use of the
1471 Ada character set. For example, neither Shift JIS, nor EUC allow the
1472 use of the upper half of the Latin-1 set.
1474 @node Wide_Wide_Character Encodings
1475 @subsection Wide_Wide_Character Encodings
1478 GNAT allows wide wide character codes to appear in character and string
1479 literals, and also optionally in identifiers, by means of the following
1480 possible encoding schemes:
1485 A wide character is represented using
1486 UCS Transformation Format 8 (UTF-8) as defined in Annex R of ISO
1487 10646-1/Am.2. Depending on the character value, the representation
1488 of character codes with values greater than 16#FFFF# is a
1489 is a four, five, or six byte sequence:
1495 16#01_0000#-16#10_FFFF#: 11110xxx 10xxxxxx 10xxxxxx
1497 16#0020_0000#-16#03FF_FFFF#: 111110xx 10xxxxxx 10xxxxxx
1499 16#0400_0000#-16#7FFF_FFFF#: 1111110x 10xxxxxx 10xxxxxx
1500 10xxxxxx 10xxxxxx 10xxxxxx
1504 where the @var{xxx} bits correspond to the left-padded bits of the
1505 32-bit character value.
1507 @item Brackets Coding
1508 In this encoding, a wide wide character is represented by the following ten or
1509 twelve byte character sequence:
1513 [ " a b c d e f g h " ]
1517 Where @code{a-h} are the six or eight hexadecimal
1518 characters (using uppercase letters) of the wide wide character code. For
1519 example, ["1F4567"] is used to represent the wide wide character with code
1520 @code{16#001F_4567#}.
1522 This scheme is compatible with use of the full Wide_Wide_Character set,
1523 and is also the method used for wide wide character encoding in some standard
1524 ACATS (Ada Conformity Assessment Test Suite) test suite distributions.
1528 @node File Naming Rules
1529 @section File Naming Rules
1532 The default file name is determined by the name of the unit that the
1533 file contains. The name is formed by taking the full expanded name of
1534 the unit and replacing the separating dots with hyphens and using
1535 lowercase for all letters.
1537 An exception arises if the file name generated by the above rules starts
1538 with one of the characters
1539 @samp{a}, @samp{g}, @samp{i}, or @samp{s},
1540 and the second character is a
1541 minus. In this case, the character tilde is used in place
1542 of the minus. The reason for this special rule is to avoid clashes with
1543 the standard names for child units of the packages System, Ada,
1544 Interfaces, and GNAT, which use the prefixes
1545 @samp{s-}, @samp{a-}, @samp{i-}, and @samp{g-},
1548 The file extension is @file{.ads} for a spec and
1549 @file{.adb} for a body. The following list shows some
1550 examples of these rules.
1557 @item arith_functions.ads
1558 Arith_Functions (package spec)
1559 @item arith_functions.adb
1560 Arith_Functions (package body)
1562 Func.Spec (child package spec)
1564 Func.Spec (child package body)
1566 Sub (subunit of Main)
1568 A.Bad (child package body)
1572 Following these rules can result in excessively long
1573 file names if corresponding
1574 unit names are long (for example, if child units or subunits are
1575 heavily nested). An option is available to shorten such long file names
1576 (called file name ``krunching''). This may be particularly useful when
1577 programs being developed with GNAT are to be used on operating systems
1578 with limited file name lengths. @xref{Using gnatkr}.
1580 Of course, no file shortening algorithm can guarantee uniqueness over
1581 all possible unit names; if file name krunching is used, it is your
1582 responsibility to ensure no name clashes occur. Alternatively you
1583 can specify the exact file names that you want used, as described
1584 in the next section. Finally, if your Ada programs are migrating from a
1585 compiler with a different naming convention, you can use the gnatchop
1586 utility to produce source files that follow the GNAT naming conventions.
1587 (For details @pxref{Renaming Files with gnatchop}.)
1589 Note: in the case of @code{Windows NT/XP} or @code{OpenVMS} operating
1590 systems, case is not significant. So for example on @code{Windows XP}
1591 if the canonical name is @code{main-sub.adb}, you can use the file name
1592 @code{Main-Sub.adb} instead. However, case is significant for other
1593 operating systems, so for example, if you want to use other than
1594 canonically cased file names on a Unix system, you need to follow
1595 the procedures described in the next section.
1597 @node Using Other File Names
1598 @section Using Other File Names
1602 In the previous section, we have described the default rules used by
1603 GNAT to determine the file name in which a given unit resides. It is
1604 often convenient to follow these default rules, and if you follow them,
1605 the compiler knows without being explicitly told where to find all
1608 However, in some cases, particularly when a program is imported from
1609 another Ada compiler environment, it may be more convenient for the
1610 programmer to specify which file names contain which units. GNAT allows
1611 arbitrary file names to be used by means of the Source_File_Name pragma.
1612 The form of this pragma is as shown in the following examples:
1613 @cindex Source_File_Name pragma
1615 @smallexample @c ada
1617 @b{pragma} Source_File_Name (My_Utilities.Stacks,
1618 Spec_File_Name => "myutilst_a.ada");
1619 @b{pragma} Source_File_name (My_Utilities.Stacks,
1620 Body_File_Name => "myutilst.ada");
1625 As shown in this example, the first argument for the pragma is the unit
1626 name (in this example a child unit). The second argument has the form
1627 of a named association. The identifier
1628 indicates whether the file name is for a spec or a body;
1629 the file name itself is given by a string literal.
1631 The source file name pragma is a configuration pragma, which means that
1632 normally it will be placed in the @file{gnat.adc}
1633 file used to hold configuration
1634 pragmas that apply to a complete compilation environment.
1635 For more details on how the @file{gnat.adc} file is created and used
1636 see @ref{Handling of Configuration Pragmas}.
1637 @cindex @file{gnat.adc}
1639 GNAT allows completely arbitrary file names to be specified using the
1640 source file name pragma. However, if the file name specified has an
1641 extension other than @file{.ads} or @file{.adb} it is necessary to use
1642 a special syntax when compiling the file. The name in this case must be
1643 preceded by the special sequence @option{-x} followed by a space and the name
1644 of the language, here @code{ada}, as in:
1647 $ gcc -c -x ada peculiar_file_name.sim
1651 @command{gnatmake} handles non-standard file names in the usual manner (the
1652 non-standard file name for the main program is simply used as the
1653 argument to gnatmake). Note that if the extension is also non-standard,
1654 then it must be included in the @command{gnatmake} command, it may not
1657 @node Alternative File Naming Schemes
1658 @section Alternative File Naming Schemes
1659 @cindex File naming schemes, alternative
1662 In the previous section, we described the use of the @code{Source_File_Name}
1663 pragma to allow arbitrary names to be assigned to individual source files.
1664 However, this approach requires one pragma for each file, and especially in
1665 large systems can result in very long @file{gnat.adc} files, and also create
1666 a maintenance problem.
1668 GNAT also provides a facility for specifying systematic file naming schemes
1669 other than the standard default naming scheme previously described. An
1670 alternative scheme for naming is specified by the use of
1671 @code{Source_File_Name} pragmas having the following format:
1672 @cindex Source_File_Name pragma
1674 @smallexample @c ada
1675 @b{pragma} Source_File_Name (
1676 Spec_File_Name => FILE_NAME_PATTERN
1677 @r{[},Casing => CASING_SPEC@r{]}
1678 @r{[},Dot_Replacement => STRING_LITERAL@r{]});
1680 @b{pragma} Source_File_Name (
1681 Body_File_Name => FILE_NAME_PATTERN
1682 @r{[},Casing => CASING_SPEC@r{]}
1683 @r{[},Dot_Replacement => STRING_LITERAL@r{]});
1685 @b{pragma} Source_File_Name (
1686 Subunit_File_Name => FILE_NAME_PATTERN
1687 @r{[},Casing => CASING_SPEC@r{]}
1688 @r{[},Dot_Replacement => STRING_LITERAL@r{]});
1690 FILE_NAME_PATTERN ::= STRING_LITERAL
1691 CASING_SPEC ::= Lowercase | Uppercase | Mixedcase
1695 The @code{FILE_NAME_PATTERN} string shows how the file name is constructed.
1696 It contains a single asterisk character, and the unit name is substituted
1697 systematically for this asterisk. The optional parameter
1698 @code{Casing} indicates
1699 whether the unit name is to be all upper-case letters, all lower-case letters,
1700 or mixed-case. If no
1701 @code{Casing} parameter is used, then the default is all
1704 The optional @code{Dot_Replacement} string is used to replace any periods
1705 that occur in subunit or child unit names. If no @code{Dot_Replacement}
1706 argument is used then separating dots appear unchanged in the resulting
1708 Although the above syntax indicates that the
1709 @code{Casing} argument must appear
1710 before the @code{Dot_Replacement} argument, but it
1711 is also permissible to write these arguments in the opposite order.
1713 As indicated, it is possible to specify different naming schemes for
1714 bodies, specs, and subunits. Quite often the rule for subunits is the
1715 same as the rule for bodies, in which case, there is no need to give
1716 a separate @code{Subunit_File_Name} rule, and in this case the
1717 @code{Body_File_name} rule is used for subunits as well.
1719 The separate rule for subunits can also be used to implement the rather
1720 unusual case of a compilation environment (e.g.@: a single directory) which
1721 contains a subunit and a child unit with the same unit name. Although
1722 both units cannot appear in the same partition, the Ada Reference Manual
1723 allows (but does not require) the possibility of the two units coexisting
1724 in the same environment.
1726 The file name translation works in the following steps:
1731 If there is a specific @code{Source_File_Name} pragma for the given unit,
1732 then this is always used, and any general pattern rules are ignored.
1735 If there is a pattern type @code{Source_File_Name} pragma that applies to
1736 the unit, then the resulting file name will be used if the file exists. If
1737 more than one pattern matches, the latest one will be tried first, and the
1738 first attempt resulting in a reference to a file that exists will be used.
1741 If no pattern type @code{Source_File_Name} pragma that applies to the unit
1742 for which the corresponding file exists, then the standard GNAT default
1743 naming rules are used.
1748 As an example of the use of this mechanism, consider a commonly used scheme
1749 in which file names are all lower case, with separating periods copied
1750 unchanged to the resulting file name, and specs end with @file{.1.ada}, and
1751 bodies end with @file{.2.ada}. GNAT will follow this scheme if the following
1754 @smallexample @c ada
1755 @b{pragma} Source_File_Name
1756 (Spec_File_Name => "*.1.ada");
1757 @b{pragma} Source_File_Name
1758 (Body_File_Name => "*.2.ada");
1762 The default GNAT scheme is actually implemented by providing the following
1763 default pragmas internally:
1765 @smallexample @c ada
1766 @b{pragma} Source_File_Name
1767 (Spec_File_Name => "*.ads", Dot_Replacement => "-");
1768 @b{pragma} Source_File_Name
1769 (Body_File_Name => "*.adb", Dot_Replacement => "-");
1773 Our final example implements a scheme typically used with one of the
1774 Ada 83 compilers, where the separator character for subunits was ``__''
1775 (two underscores), specs were identified by adding @file{_.ADA}, bodies
1776 by adding @file{.ADA}, and subunits by
1777 adding @file{.SEP}. All file names were
1778 upper case. Child units were not present of course since this was an
1779 Ada 83 compiler, but it seems reasonable to extend this scheme to use
1780 the same double underscore separator for child units.
1782 @smallexample @c ada
1783 @b{pragma} Source_File_Name
1784 (Spec_File_Name => "*_.ADA",
1785 Dot_Replacement => "__",
1786 Casing = Uppercase);
1787 @b{pragma} Source_File_Name
1788 (Body_File_Name => "*.ADA",
1789 Dot_Replacement => "__",
1790 Casing = Uppercase);
1791 @b{pragma} Source_File_Name
1792 (Subunit_File_Name => "*.SEP",
1793 Dot_Replacement => "__",
1794 Casing = Uppercase);
1797 @node Generating Object Files
1798 @section Generating Object Files
1801 An Ada program consists of a set of source files, and the first step in
1802 compiling the program is to generate the corresponding object files.
1803 These are generated by compiling a subset of these source files.
1804 The files you need to compile are the following:
1808 If a package spec has no body, compile the package spec to produce the
1809 object file for the package.
1812 If a package has both a spec and a body, compile the body to produce the
1813 object file for the package. The source file for the package spec need
1814 not be compiled in this case because there is only one object file, which
1815 contains the code for both the spec and body of the package.
1818 For a subprogram, compile the subprogram body to produce the object file
1819 for the subprogram. The spec, if one is present, is as usual in a
1820 separate file, and need not be compiled.
1824 In the case of subunits, only compile the parent unit. A single object
1825 file is generated for the entire subunit tree, which includes all the
1829 Compile child units independently of their parent units
1830 (though, of course, the spec of all the ancestor unit must be present in order
1831 to compile a child unit).
1835 Compile generic units in the same manner as any other units. The object
1836 files in this case are small dummy files that contain at most the
1837 flag used for elaboration checking. This is because GNAT always handles generic
1838 instantiation by means of macro expansion. However, it is still necessary to
1839 compile generic units, for dependency checking and elaboration purposes.
1843 The preceding rules describe the set of files that must be compiled to
1844 generate the object files for a program. Each object file has the same
1845 name as the corresponding source file, except that the extension is
1848 You may wish to compile other files for the purpose of checking their
1849 syntactic and semantic correctness. For example, in the case where a
1850 package has a separate spec and body, you would not normally compile the
1851 spec. However, it is convenient in practice to compile the spec to make
1852 sure it is error-free before compiling clients of this spec, because such
1853 compilations will fail if there is an error in the spec.
1855 GNAT provides an option for compiling such files purely for the
1856 purposes of checking correctness; such compilations are not required as
1857 part of the process of building a program. To compile a file in this
1858 checking mode, use the @option{-gnatc} switch.
1860 @node Source Dependencies
1861 @section Source Dependencies
1864 A given object file clearly depends on the source file which is compiled
1865 to produce it. Here we are using @dfn{depends} in the sense of a typical
1866 @code{make} utility; in other words, an object file depends on a source
1867 file if changes to the source file require the object file to be
1869 In addition to this basic dependency, a given object may depend on
1870 additional source files as follows:
1874 If a file being compiled @code{with}'s a unit @var{X}, the object file
1875 depends on the file containing the spec of unit @var{X}. This includes
1876 files that are @code{with}'ed implicitly either because they are parents
1877 of @code{with}'ed child units or they are run-time units required by the
1878 language constructs used in a particular unit.
1881 If a file being compiled instantiates a library level generic unit, the
1882 object file depends on both the spec and body files for this generic
1886 If a file being compiled instantiates a generic unit defined within a
1887 package, the object file depends on the body file for the package as
1888 well as the spec file.
1892 @cindex @option{-gnatn} switch
1893 If a file being compiled contains a call to a subprogram for which
1894 pragma @code{Inline} applies and inlining is activated with the
1895 @option{-gnatn} switch, the object file depends on the file containing the
1896 body of this subprogram as well as on the file containing the spec. Note
1897 that for inlining to actually occur as a result of the use of this switch,
1898 it is necessary to compile in optimizing mode.
1900 @cindex @option{-gnatN} switch
1901 The use of @option{-gnatN} activates inlining optimization
1902 that is performed by the front end of the compiler. This inlining does
1903 not require that the code generation be optimized. Like @option{-gnatn},
1904 the use of this switch generates additional dependencies.
1906 When using a gcc-based back end (in practice this means using any version
1907 of GNAT other than the JGNAT, .NET or GNAAMP versions), then the use of
1908 @option{-gnatN} is deprecated, and the use of @option{-gnatn} is preferred.
1909 Historically front end inlining was more extensive than the gcc back end
1910 inlining, but that is no longer the case.
1913 If an object file @file{O} depends on the proper body of a subunit through
1914 inlining or instantiation, it depends on the parent unit of the subunit.
1915 This means that any modification of the parent unit or one of its subunits
1916 affects the compilation of @file{O}.
1919 The object file for a parent unit depends on all its subunit body files.
1922 The previous two rules meant that for purposes of computing dependencies and
1923 recompilation, a body and all its subunits are treated as an indivisible whole.
1926 These rules are applied transitively: if unit @code{A} @code{with}'s
1927 unit @code{B}, whose elaboration calls an inlined procedure in package
1928 @code{C}, the object file for unit @code{A} will depend on the body of
1929 @code{C}, in file @file{c.adb}.
1931 The set of dependent files described by these rules includes all the
1932 files on which the unit is semantically dependent, as dictated by the
1933 Ada language standard. However, it is a superset of what the
1934 standard describes, because it includes generic, inline, and subunit
1937 An object file must be recreated by recompiling the corresponding source
1938 file if any of the source files on which it depends are modified. For
1939 example, if the @code{make} utility is used to control compilation,
1940 the rule for an Ada object file must mention all the source files on
1941 which the object file depends, according to the above definition.
1942 The determination of the necessary
1943 recompilations is done automatically when one uses @command{gnatmake}.
1946 @node The Ada Library Information Files
1947 @section The Ada Library Information Files
1948 @cindex Ada Library Information files
1949 @cindex @file{ALI} files
1952 Each compilation actually generates two output files. The first of these
1953 is the normal object file that has a @file{.o} extension. The second is a
1954 text file containing full dependency information. It has the same
1955 name as the source file, but an @file{.ali} extension.
1956 This file is known as the Ada Library Information (@file{ALI}) file.
1957 The following information is contained in the @file{ALI} file.
1961 Version information (indicates which version of GNAT was used to compile
1962 the unit(s) in question)
1965 Main program information (including priority and time slice settings,
1966 as well as the wide character encoding used during compilation).
1969 List of arguments used in the @command{gcc} command for the compilation
1972 Attributes of the unit, including configuration pragmas used, an indication
1973 of whether the compilation was successful, exception model used etc.
1976 A list of relevant restrictions applying to the unit (used for consistency)
1980 Categorization information (e.g.@: use of pragma @code{Pure}).
1983 Information on all @code{with}'ed units, including presence of
1984 @code{Elaborate} or @code{Elaborate_All} pragmas.
1987 Information from any @code{Linker_Options} pragmas used in the unit
1990 Information on the use of @code{Body_Version} or @code{Version}
1991 attributes in the unit.
1994 Dependency information. This is a list of files, together with
1995 time stamp and checksum information. These are files on which
1996 the unit depends in the sense that recompilation is required
1997 if any of these units are modified.
2000 Cross-reference data. Contains information on all entities referenced
2001 in the unit. Used by tools like @code{gnatxref} and @code{gnatfind} to
2002 provide cross-reference information.
2007 For a full detailed description of the format of the @file{ALI} file,
2008 see the source of the body of unit @code{Lib.Writ}, contained in file
2009 @file{lib-writ.adb} in the GNAT compiler sources.
2011 @node Binding an Ada Program
2012 @section Binding an Ada Program
2015 When using languages such as C and C++, once the source files have been
2016 compiled the only remaining step in building an executable program
2017 is linking the object modules together. This means that it is possible to
2018 link an inconsistent version of a program, in which two units have
2019 included different versions of the same header.
2021 The rules of Ada do not permit such an inconsistent program to be built.
2022 For example, if two clients have different versions of the same package,
2023 it is illegal to build a program containing these two clients.
2024 These rules are enforced by the GNAT binder, which also determines an
2025 elaboration order consistent with the Ada rules.
2027 The GNAT binder is run after all the object files for a program have
2028 been created. It is given the name of the main program unit, and from
2029 this it determines the set of units required by the program, by reading the
2030 corresponding ALI files. It generates error messages if the program is
2031 inconsistent or if no valid order of elaboration exists.
2033 If no errors are detected, the binder produces a main program, in Ada by
2034 default, that contains calls to the elaboration procedures of those
2035 compilation unit that require them, followed by
2036 a call to the main program. This Ada program is compiled to generate the
2037 object file for the main program. The name of
2038 the Ada file is @file{b~@var{xxx}.adb} (with the corresponding spec
2039 @file{b~@var{xxx}.ads}) where @var{xxx} is the name of the
2042 Finally, the linker is used to build the resulting executable program,
2043 using the object from the main program from the bind step as well as the
2044 object files for the Ada units of the program.
2046 @node Mixed Language Programming
2047 @section Mixed Language Programming
2048 @cindex Mixed Language Programming
2051 This section describes how to develop a mixed-language program,
2052 specifically one that comprises units in both Ada and C.
2055 * Interfacing to C::
2056 * Calling Conventions::
2059 @node Interfacing to C
2060 @subsection Interfacing to C
2062 Interfacing Ada with a foreign language such as C involves using
2063 compiler directives to import and/or export entity definitions in each
2064 language---using @code{extern} statements in C, for instance, and the
2065 @code{Import}, @code{Export}, and @code{Convention} pragmas in Ada.
2066 A full treatment of these topics is provided in Appendix B, section 1
2067 of the Ada Reference Manual.
2069 There are two ways to build a program using GNAT that contains some Ada
2070 sources and some foreign language sources, depending on whether or not
2071 the main subprogram is written in Ada. Here is a source example with
2072 the main subprogram in Ada:
2078 void print_num (int num)
2080 printf ("num is %d.\n", num);
2086 /* num_from_Ada is declared in my_main.adb */
2087 extern int num_from_Ada;
2091 return num_from_Ada;
2095 @smallexample @c ada
2097 procedure My_Main is
2099 -- Declare then export an Integer entity called num_from_Ada
2100 My_Num : Integer := 10;
2101 pragma Export (C, My_Num, "num_from_Ada");
2103 -- Declare an Ada function spec for Get_Num, then use
2104 -- C function get_num for the implementation.
2105 function Get_Num return Integer;
2106 pragma Import (C, Get_Num, "get_num");
2108 -- Declare an Ada procedure spec for Print_Num, then use
2109 -- C function print_num for the implementation.
2110 procedure Print_Num (Num : Integer);
2111 pragma Import (C, Print_Num, "print_num";
2114 Print_Num (Get_Num);
2120 To build this example, first compile the foreign language files to
2121 generate object files:
2128 Then, compile the Ada units to produce a set of object files and ALI
2131 gnatmake -c my_main.adb
2135 Run the Ada binder on the Ada main program:
2137 gnatbind my_main.ali
2141 Link the Ada main program, the Ada objects and the other language
2144 gnatlink my_main.ali file1.o file2.o
2148 The last three steps can be grouped in a single command:
2150 gnatmake my_main.adb -largs file1.o file2.o
2153 @cindex Binder output file
2155 If the main program is in a language other than Ada, then you may have
2156 more than one entry point into the Ada subsystem. You must use a special
2157 binder option to generate callable routines that initialize and
2158 finalize the Ada units (@pxref{Binding with Non-Ada Main Programs}).
2159 Calls to the initialization and finalization routines must be inserted
2160 in the main program, or some other appropriate point in the code. The
2161 call to initialize the Ada units must occur before the first Ada
2162 subprogram is called, and the call to finalize the Ada units must occur
2163 after the last Ada subprogram returns. The binder will place the
2164 initialization and finalization subprograms into the
2165 @file{b~@var{xxx}.adb} file where they can be accessed by your C
2166 sources. To illustrate, we have the following example:
2170 extern void adainit (void);
2171 extern void adafinal (void);
2172 extern int add (int, int);
2173 extern int sub (int, int);
2175 int main (int argc, char *argv[])
2181 /* Should print "21 + 7 = 28" */
2182 printf ("%d + %d = %d\n", a, b, add (a, b));
2183 /* Should print "21 - 7 = 14" */
2184 printf ("%d - %d = %d\n", a, b, sub (a, b));
2190 @smallexample @c ada
2193 function Add (A, B : Integer) return Integer;
2194 pragma Export (C, Add, "add");
2198 package body Unit1 is
2199 function Add (A, B : Integer) return Integer is
2207 function Sub (A, B : Integer) return Integer;
2208 pragma Export (C, Sub, "sub");
2212 package body Unit2 is
2213 function Sub (A, B : Integer) return Integer is
2222 The build procedure for this application is similar to the last
2223 example's. First, compile the foreign language files to generate object
2230 Next, compile the Ada units to produce a set of object files and ALI
2233 gnatmake -c unit1.adb
2234 gnatmake -c unit2.adb
2238 Run the Ada binder on every generated ALI file. Make sure to use the
2239 @option{-n} option to specify a foreign main program:
2241 gnatbind -n unit1.ali unit2.ali
2245 Link the Ada main program, the Ada objects and the foreign language
2246 objects. You need only list the last ALI file here:
2248 gnatlink unit2.ali main.o -o exec_file
2251 This procedure yields a binary executable called @file{exec_file}.
2255 Depending on the circumstances (for example when your non-Ada main object
2256 does not provide symbol @code{main}), you may also need to instruct the
2257 GNAT linker not to include the standard startup objects by passing the
2258 @option{-nostartfiles} switch to @command{gnatlink}.
2260 @node Calling Conventions
2261 @subsection Calling Conventions
2262 @cindex Foreign Languages
2263 @cindex Calling Conventions
2264 GNAT follows standard calling sequence conventions and will thus interface
2265 to any other language that also follows these conventions. The following
2266 Convention identifiers are recognized by GNAT:
2269 @cindex Interfacing to Ada
2270 @cindex Other Ada compilers
2271 @cindex Convention Ada
2273 This indicates that the standard Ada calling sequence will be
2274 used and all Ada data items may be passed without any limitations in the
2275 case where GNAT is used to generate both the caller and callee. It is also
2276 possible to mix GNAT generated code and code generated by another Ada
2277 compiler. In this case, the data types should be restricted to simple
2278 cases, including primitive types. Whether complex data types can be passed
2279 depends on the situation. Probably it is safe to pass simple arrays, such
2280 as arrays of integers or floats. Records may or may not work, depending
2281 on whether both compilers lay them out identically. Complex structures
2282 involving variant records, access parameters, tasks, or protected types,
2283 are unlikely to be able to be passed.
2285 Note that in the case of GNAT running
2286 on a platform that supports HP Ada 83, a higher degree of compatibility
2287 can be guaranteed, and in particular records are laid out in an identical
2288 manner in the two compilers. Note also that if output from two different
2289 compilers is mixed, the program is responsible for dealing with elaboration
2290 issues. Probably the safest approach is to write the main program in the
2291 version of Ada other than GNAT, so that it takes care of its own elaboration
2292 requirements, and then call the GNAT-generated adainit procedure to ensure
2293 elaboration of the GNAT components. Consult the documentation of the other
2294 Ada compiler for further details on elaboration.
2296 However, it is not possible to mix the tasking run time of GNAT and
2297 HP Ada 83, All the tasking operations must either be entirely within
2298 GNAT compiled sections of the program, or entirely within HP Ada 83
2299 compiled sections of the program.
2301 @cindex Interfacing to Assembly
2302 @cindex Convention Assembler
2304 Specifies assembler as the convention. In practice this has the
2305 same effect as convention Ada (but is not equivalent in the sense of being
2306 considered the same convention).
2308 @cindex Convention Asm
2311 Equivalent to Assembler.
2313 @cindex Interfacing to COBOL
2314 @cindex Convention COBOL
2317 Data will be passed according to the conventions described
2318 in section B.4 of the Ada Reference Manual.
2321 @cindex Interfacing to C
2322 @cindex Convention C
2324 Data will be passed according to the conventions described
2325 in section B.3 of the Ada Reference Manual.
2327 A note on interfacing to a C ``varargs'' function:
2328 @findex C varargs function
2329 @cindex Interfacing to C varargs function
2330 @cindex varargs function interfaces
2334 In C, @code{varargs} allows a function to take a variable number of
2335 arguments. There is no direct equivalent in this to Ada. One
2336 approach that can be used is to create a C wrapper for each
2337 different profile and then interface to this C wrapper. For
2338 example, to print an @code{int} value using @code{printf},
2339 create a C function @code{printfi} that takes two arguments, a
2340 pointer to a string and an int, and calls @code{printf}.
2341 Then in the Ada program, use pragma @code{Import} to
2342 interface to @code{printfi}.
2345 It may work on some platforms to directly interface to
2346 a @code{varargs} function by providing a specific Ada profile
2347 for a particular call. However, this does not work on
2348 all platforms, since there is no guarantee that the
2349 calling sequence for a two argument normal C function
2350 is the same as for calling a @code{varargs} C function with
2351 the same two arguments.
2354 @cindex Convention Default
2359 @cindex Convention External
2365 @cindex Interfacing to C++
2366 @cindex Convention C++
2367 @item C_Plus_Plus (or CPP)
2368 This stands for C++. For most purposes this is identical to C.
2369 See the separate description of the specialized GNAT pragmas relating to
2370 C++ interfacing for further details.
2373 @cindex Interfacing to Fortran
2374 @cindex Convention Fortran
2376 Data will be passed according to the conventions described
2377 in section B.5 of the Ada Reference Manual.
2380 This applies to an intrinsic operation, as defined in the Ada
2381 Reference Manual. If a pragma Import (Intrinsic) applies to a subprogram,
2382 this means that the body of the subprogram is provided by the compiler itself,
2383 usually by means of an efficient code sequence, and that the user does not
2384 supply an explicit body for it. In an application program, the pragma may
2385 be applied to the following sets of names:
2389 Rotate_Left, Rotate_Right, Shift_Left, Shift_Right,
2390 Shift_Right_Arithmetic. The corresponding subprogram declaration must have
2391 two formal parameters. The
2392 first one must be a signed integer type or a modular type with a binary
2393 modulus, and the second parameter must be of type Natural.
2394 The return type must be the same as the type of the first argument. The size
2395 of this type can only be 8, 16, 32, or 64.
2398 Binary arithmetic operators: ``+'', ``-'', ``*'', ``/''
2399 The corresponding operator declaration must have parameters and result type
2400 that have the same root numeric type (for example, all three are long_float
2401 types). This simplifies the definition of operations that use type checking
2402 to perform dimensional checks:
2404 @smallexample @c ada
2405 @b{type} Distance @b{is} @b{new} Long_Float;
2406 @b{type} Time @b{is} @b{new} Long_Float;
2407 @b{type} Velocity @b{is} @b{new} Long_Float;
2408 @b{function} "/" (D : Distance; T : Time)
2409 @b{return} Velocity;
2410 @b{pragma} Import (Intrinsic, "/");
2414 This common idiom is often programmed with a generic definition and an
2415 explicit body. The pragma makes it simpler to introduce such declarations.
2416 It incurs no overhead in compilation time or code size, because it is
2417 implemented as a single machine instruction.
2420 General subprogram entities, to bind an Ada subprogram declaration to
2421 a compiler builtin by name with back-ends where such interfaces are
2422 available. A typical example is the set of ``__builtin'' functions
2423 exposed by the GCC back-end, as in the following example:
2425 @smallexample @c ada
2426 @b{function} builtin_sqrt (F : Float) @b{return} Float;
2427 @b{pragma} Import (Intrinsic, builtin_sqrt, "__builtin_sqrtf");
2430 Most of the GCC builtins are accessible this way, and as for other
2431 import conventions (e.g. C), it is the user's responsibility to ensure
2432 that the Ada subprogram profile matches the underlying builtin
2439 @cindex Convention Stdcall
2441 This is relevant only to Windows XP/2000/NT implementations of GNAT,
2442 and specifies that the @code{Stdcall} calling sequence will be used,
2443 as defined by the NT API. Nevertheless, to ease building
2444 cross-platform bindings this convention will be handled as a @code{C} calling
2445 convention on non-Windows platforms.
2448 @cindex Convention DLL
2450 This is equivalent to @code{Stdcall}.
2453 @cindex Convention Win32
2455 This is equivalent to @code{Stdcall}.
2458 @cindex Convention Stubbed
2460 This is a special convention that indicates that the compiler
2461 should provide a stub body that raises @code{Program_Error}.
2465 GNAT additionally provides a useful pragma @code{Convention_Identifier}
2466 that can be used to parameterize conventions and allow additional synonyms
2467 to be specified. For example if you have legacy code in which the convention
2468 identifier Fortran77 was used for Fortran, you can use the configuration
2471 @smallexample @c ada
2472 @b{pragma} Convention_Identifier (Fortran77, Fortran);
2476 And from now on the identifier Fortran77 may be used as a convention
2477 identifier (for example in an @code{Import} pragma) with the same
2480 @node Building Mixed Ada & C++ Programs
2481 @section Building Mixed Ada and C++ Programs
2484 A programmer inexperienced with mixed-language development may find that
2485 building an application containing both Ada and C++ code can be a
2486 challenge. This section gives a few
2487 hints that should make this task easier. The first section addresses
2488 the differences between interfacing with C and interfacing with C++.
2490 looks into the delicate problem of linking the complete application from
2491 its Ada and C++ parts. The last section gives some hints on how the GNAT
2492 run-time library can be adapted in order to allow inter-language dispatching
2493 with a new C++ compiler.
2496 * Interfacing to C++::
2497 * Linking a Mixed C++ & Ada Program::
2498 * A Simple Example::
2499 * Interfacing with C++ constructors::
2500 * Interfacing with C++ at the Class Level::
2503 @node Interfacing to C++
2504 @subsection Interfacing to C++
2507 GNAT supports interfacing with the G++ compiler (or any C++ compiler
2508 generating code that is compatible with the G++ Application Binary
2509 Interface ---see http://www.codesourcery.com/archives/cxx-abi).
2512 Interfacing can be done at 3 levels: simple data, subprograms, and
2513 classes. In the first two cases, GNAT offers a specific @code{Convention
2514 C_Plus_Plus} (or @code{CPP}) that behaves exactly like @code{Convention C}.
2515 Usually, C++ mangles the names of subprograms. To generate proper mangled
2516 names automatically, see @ref{Generating Ada Bindings for C and C++ headers}).
2517 This problem can also be addressed manually in two ways:
2521 by modifying the C++ code in order to force a C convention using
2522 the @code{extern "C"} syntax.
2525 by figuring out the mangled name (using e.g. @command{nm}) and using it as the
2526 Link_Name argument of the pragma import.
2530 Interfacing at the class level can be achieved by using the GNAT specific
2531 pragmas such as @code{CPP_Constructor}. @xref{Interfacing to C++,,,
2532 gnat_rm, GNAT Reference Manual}, for additional information.
2534 @node Linking a Mixed C++ & Ada Program
2535 @subsection Linking a Mixed C++ & Ada Program
2538 Usually the linker of the C++ development system must be used to link
2539 mixed applications because most C++ systems will resolve elaboration
2540 issues (such as calling constructors on global class instances)
2541 transparently during the link phase. GNAT has been adapted to ease the
2542 use of a foreign linker for the last phase. Three cases can be
2547 Using GNAT and G++ (GNU C++ compiler) from the same GCC installation:
2548 The C++ linker can simply be called by using the C++ specific driver
2551 Note that if the C++ code uses inline functions, you will need to
2552 compile your C++ code with the @code{-fkeep-inline-functions} switch in
2553 order to provide an existing function implementation that the Ada code can
2557 $ g++ -c -fkeep-inline-functions file1.C
2558 $ g++ -c -fkeep-inline-functions file2.C
2559 $ gnatmake ada_unit -largs file1.o file2.o --LINK=g++
2563 Using GNAT and G++ from two different GCC installations: If both
2564 compilers are on the @env{PATH}, the previous method may be used. It is
2565 important to note that environment variables such as
2566 @env{C_INCLUDE_PATH}, @env{GCC_EXEC_PREFIX}, @env{BINUTILS_ROOT}, and
2567 @env{GCC_ROOT} will affect both compilers
2568 at the same time and may make one of the two compilers operate
2569 improperly if set during invocation of the wrong compiler. It is also
2570 very important that the linker uses the proper @file{libgcc.a} GCC
2571 library -- that is, the one from the C++ compiler installation. The
2572 implicit link command as suggested in the @command{gnatmake} command
2573 from the former example can be replaced by an explicit link command with
2574 the full-verbosity option in order to verify which library is used:
2577 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=c++
2579 If there is a problem due to interfering environment variables, it can
2580 be worked around by using an intermediate script. The following example
2581 shows the proper script to use when GNAT has not been installed at its
2582 default location and g++ has been installed at its default location:
2590 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=./my_script
2594 Using a non-GNU C++ compiler: The commands previously described can be
2595 used to insure that the C++ linker is used. Nonetheless, you need to add
2596 a few more parameters to the link command line, depending on the exception
2599 If the @code{setjmp/longjmp} exception mechanism is used, only the paths
2600 to the libgcc libraries are required:
2605 CC $* `gcc -print-file-name=libgcc.a` `gcc -print-file-name=libgcc_eh.a`
2606 $ gnatlink ada_unit file1.o file2.o --LINK=./my_script
2609 Where CC is the name of the non-GNU C++ compiler.
2611 If the @code{zero cost} exception mechanism is used, and the platform
2612 supports automatic registration of exception tables (e.g.@: Solaris),
2613 paths to more objects are required:
2618 CC `gcc -print-file-name=crtbegin.o` $* \
2619 `gcc -print-file-name=libgcc.a` `gcc -print-file-name=libgcc_eh.a` \
2620 `gcc -print-file-name=crtend.o`
2621 $ gnatlink ada_unit file1.o file2.o --LINK=./my_script
2624 If the @code{zero cost} exception mechanism is used, and the platform
2625 doesn't support automatic registration of exception tables (e.g.@: HP-UX
2626 or AIX), the simple approach described above will not work and
2627 a pre-linking phase using GNAT will be necessary.
2631 Another alternative is to use the @command{gprbuild} multi-language builder
2632 which has a large knowledge base and knows how to link Ada and C++ code
2633 together automatically in most cases.
2635 @node A Simple Example
2636 @subsection A Simple Example
2638 The following example, provided as part of the GNAT examples, shows how
2639 to achieve procedural interfacing between Ada and C++ in both
2640 directions. The C++ class A has two methods. The first method is exported
2641 to Ada by the means of an extern C wrapper function. The second method
2642 calls an Ada subprogram. On the Ada side, The C++ calls are modelled by
2643 a limited record with a layout comparable to the C++ class. The Ada
2644 subprogram, in turn, calls the C++ method. So, starting from the C++
2645 main program, the process passes back and forth between the two
2649 Here are the compilation commands:
2651 $ gnatmake -c simple_cpp_interface
2654 $ gnatbind -n simple_cpp_interface
2655 $ gnatlink simple_cpp_interface -o cpp_main --LINK=g++
2656 -lstdc++ ex7.o cpp_main.o
2660 Here are the corresponding sources:
2668 void adainit (void);
2669 void adafinal (void);
2670 void method1 (A *t);
2692 class A : public Origin @{
2694 void method1 (void);
2695 void method2 (int v);
2705 extern "C" @{ void ada_method2 (A *t, int v);@}
2707 void A::method1 (void)
2710 printf ("in A::method1, a_value = %d \n",a_value);
2714 void A::method2 (int v)
2716 ada_method2 (this, v);
2717 printf ("in A::method2, a_value = %d \n",a_value);
2724 printf ("in A::A, a_value = %d \n",a_value);
2728 @smallexample @c ada
2730 @b{package} @b{body} Simple_Cpp_Interface @b{is}
2732 @b{procedure} Ada_Method2 (This : @b{in} @b{out} A; V : Integer) @b{is}
2736 @b{end} Ada_Method2;
2738 @b{end} Simple_Cpp_Interface;
2741 @b{package} Simple_Cpp_Interface @b{is}
2742 @b{type} A @b{is} @b{limited}
2744 Vptr : System.Address;
2748 @b{pragma} Convention (C, A);
2750 @b{procedure} Method1 (This : @b{in} @b{out} A);
2751 @b{pragma} Import (C, Method1);
2753 @b{procedure} Ada_Method2 (This : @b{in} @b{out} A; V : Integer);
2754 @b{pragma} Export (C, Ada_Method2);
2756 @b{end} Simple_Cpp_Interface;
2759 @node Interfacing with C++ constructors
2760 @subsection Interfacing with C++ constructors
2763 In order to interface with C++ constructors GNAT provides the
2764 @code{pragma CPP_Constructor} (@xref{Interfacing to C++,,,
2765 gnat_rm, GNAT Reference Manual}, for additional information).
2766 In this section we present some common uses of C++ constructors
2767 in mixed-languages programs in GNAT.
2769 Let us assume that we need to interface with the following
2777 @b{virtual} int Get_Value ();
2778 Root(); // Default constructor
2779 Root(int v); // 1st non-default constructor
2780 Root(int v, int w); // 2nd non-default constructor
2784 For this purpose we can write the following package spec (further
2785 information on how to build this spec is available in
2786 @ref{Interfacing with C++ at the Class Level} and
2787 @ref{Generating Ada Bindings for C and C++ headers}).
2789 @smallexample @c ada
2790 @b{with} Interfaces.C; @b{use} Interfaces.C;
2791 @b{package} Pkg_Root @b{is}
2792 @b{type} Root @b{is} @b{tagged} @b{limited} @b{record}
2796 @b{pragma} Import (CPP, Root);
2798 @b{function} Get_Value (Obj : Root) @b{return} int;
2799 @b{pragma} Import (CPP, Get_Value);
2801 @b{function} Constructor @b{return} Root;
2802 @b{pragma} Cpp_Constructor (Constructor, "_ZN4RootC1Ev");
2804 @b{function} Constructor (v : Integer) @b{return} Root;
2805 @b{pragma} Cpp_Constructor (Constructor, "_ZN4RootC1Ei");
2807 @b{function} Constructor (v, w : Integer) @b{return} Root;
2808 @b{pragma} Cpp_Constructor (Constructor, "_ZN4RootC1Eii");
2812 On the Ada side the constructor is represented by a function (whose
2813 name is arbitrary) that returns the classwide type corresponding to
2814 the imported C++ class. Although the constructor is described as a
2815 function, it is typically a procedure with an extra implicit argument
2816 (the object being initialized) at the implementation level. GNAT
2817 issues the appropriate call, whatever it is, to get the object
2818 properly initialized.
2820 Constructors can only appear in the following contexts:
2824 On the right side of an initialization of an object of type @var{T}.
2826 On the right side of an initialization of a record component of type @var{T}.
2828 In an Ada 2005 limited aggregate.
2830 In an Ada 2005 nested limited aggregate.
2832 In an Ada 2005 limited aggregate that initializes an object built in
2833 place by an extended return statement.
2837 In a declaration of an object whose type is a class imported from C++,
2838 either the default C++ constructor is implicitly called by GNAT, or
2839 else the required C++ constructor must be explicitly called in the
2840 expression that initializes the object. For example:
2842 @smallexample @c ada
2844 Obj2 : Root := Constructor;
2845 Obj3 : Root := Constructor (v => 10);
2846 Obj4 : Root := Constructor (30, 40);
2849 The first two declarations are equivalent: in both cases the default C++
2850 constructor is invoked (in the former case the call to the constructor is
2851 implicit, and in the latter case the call is explicit in the object
2852 declaration). @code{Obj3} is initialized by the C++ non-default constructor
2853 that takes an integer argument, and @code{Obj4} is initialized by the
2854 non-default C++ constructor that takes two integers.
2856 Let us derive the imported C++ class in the Ada side. For example:
2858 @smallexample @c ada
2859 @b{type} DT @b{is} @b{new} Root @b{with} @b{record}
2860 C_Value : Natural := 2009;
2864 In this case the components DT inherited from the C++ side must be
2865 initialized by a C++ constructor, and the additional Ada components
2866 of type DT are initialized by GNAT. The initialization of such an
2867 object is done either by default, or by means of a function returning
2868 an aggregate of type DT, or by means of an extension aggregate.
2870 @smallexample @c ada
2872 Obj6 : DT := Function_Returning_DT (50);
2873 Obj7 : DT := (Constructor (30,40) @b{with} C_Value => 50);
2876 The declaration of @code{Obj5} invokes the default constructors: the
2877 C++ default constructor of the parent type takes care of the initialization
2878 of the components inherited from Root, and GNAT takes care of the default
2879 initialization of the additional Ada components of type DT (that is,
2880 @code{C_Value} is initialized to value 2009). The order of invocation of
2881 the constructors is consistent with the order of elaboration required by
2882 Ada and C++. That is, the constructor of the parent type is always called
2883 before the constructor of the derived type.
2885 Let us now consider a record that has components whose type is imported
2886 from C++. For example:
2888 @smallexample @c ada
2889 @b{type} Rec1 @b{is} @b{limited} @b{record}
2890 Data1 : Root := Constructor (10);
2891 Value : Natural := 1000;
2894 @b{type} Rec2 (D : Integer := 20) @b{is} @b{limited} @b{record}
2896 Data2 : Root := Constructor (D, 30);
2900 The initialization of an object of type @code{Rec2} will call the
2901 non-default C++ constructors specified for the imported components.
2904 @smallexample @c ada
2908 Using Ada 2005 we can use limited aggregates to initialize an object
2909 invoking C++ constructors that differ from those specified in the type
2910 declarations. For example:
2912 @smallexample @c ada
2913 Obj9 : Rec2 := (Rec => (Data1 => Constructor (15, 16),
2918 The above declaration uses an Ada 2005 limited aggregate to
2919 initialize @code{Obj9}, and the C++ constructor that has two integer
2920 arguments is invoked to initialize the @code{Data1} component instead
2921 of the constructor specified in the declaration of type @code{Rec1}. In
2922 Ada 2005 the box in the aggregate indicates that unspecified components
2923 are initialized using the expression (if any) available in the component
2924 declaration. That is, in this case discriminant @code{D} is initialized
2925 to value @code{20}, @code{Value} is initialized to value 1000, and the
2926 non-default C++ constructor that handles two integers takes care of
2927 initializing component @code{Data2} with values @code{20,30}.
2929 In Ada 2005 we can use the extended return statement to build the Ada
2930 equivalent to C++ non-default constructors. For example:
2932 @smallexample @c ada
2933 @b{function} Constructor (V : Integer) @b{return} Rec2 @b{is}
2935 @b{return} Obj : Rec2 := (Rec => (Data1 => Constructor (V, 20),
2937 @b{others} => <>) @b{do}
2938 --@i{ Further actions required for construction of}
2939 --@i{ objects of type Rec2}
2942 @b{end} Constructor;
2945 In this example the extended return statement construct is used to
2946 build in place the returned object whose components are initialized
2947 by means of a limited aggregate. Any further action associated with
2948 the constructor can be placed inside the construct.
2950 @node Interfacing with C++ at the Class Level
2951 @subsection Interfacing with C++ at the Class Level
2953 In this section we demonstrate the GNAT features for interfacing with
2954 C++ by means of an example making use of Ada 2005 abstract interface
2955 types. This example consists of a classification of animals; classes
2956 have been used to model our main classification of animals, and
2957 interfaces provide support for the management of secondary
2958 classifications. We first demonstrate a case in which the types and
2959 constructors are defined on the C++ side and imported from the Ada
2960 side, and latter the reverse case.
2962 The root of our derivation will be the @code{Animal} class, with a
2963 single private attribute (the @code{Age} of the animal), a constructor,
2964 and two public primitives to set and get the value of this attribute.
2969 @b{virtual} void Set_Age (int New_Age);
2970 @b{virtual} int Age ();
2971 Animal() @{Age_Count = 0;@};
2977 Abstract interface types are defined in C++ by means of classes with pure
2978 virtual functions and no data members. In our example we will use two
2979 interfaces that provide support for the common management of @code{Carnivore}
2980 and @code{Domestic} animals:
2983 @b{class} Carnivore @{
2985 @b{virtual} int Number_Of_Teeth () = 0;
2988 @b{class} Domestic @{
2990 @b{virtual void} Set_Owner (char* Name) = 0;
2994 Using these declarations, we can now say that a @code{Dog} is an animal that is
2995 both Carnivore and Domestic, that is:
2998 @b{class} Dog : Animal, Carnivore, Domestic @{
3000 @b{virtual} int Number_Of_Teeth ();
3001 @b{virtual} void Set_Owner (char* Name);
3003 Dog(); // Constructor
3010 In the following examples we will assume that the previous declarations are
3011 located in a file named @code{animals.h}. The following package demonstrates
3012 how to import these C++ declarations from the Ada side:
3014 @smallexample @c ada
3015 @b{with} Interfaces.C.Strings; @b{use} Interfaces.C.Strings;
3016 @b{package} Animals @b{is}
3017 @b{type} Carnivore @b{is} @b{limited} interface;
3018 @b{pragma} Convention (C_Plus_Plus, Carnivore);
3019 @b{function} Number_Of_Teeth (X : Carnivore)
3020 @b{return} Natural @b{is} @b{abstract};
3022 @b{type} Domestic @b{is} @b{limited} interface;
3023 @b{pragma} Convention (C_Plus_Plus, Domestic);
3024 @b{procedure} Set_Owner
3025 (X : @b{in} @b{out} Domestic;
3026 Name : Chars_Ptr) @b{is} @b{abstract};
3028 @b{type} Animal @b{is} @b{tagged} @b{limited} @b{record}
3031 @b{pragma} Import (C_Plus_Plus, Animal);
3033 @b{procedure} Set_Age (X : @b{in} @b{out} Animal; Age : Integer);
3034 @b{pragma} Import (C_Plus_Plus, Set_Age);
3036 @b{function} Age (X : Animal) @b{return} Integer;
3037 @b{pragma} Import (C_Plus_Plus, Age);
3039 @b{function} New_Animal @b{return} Animal;
3040 @b{pragma} CPP_Constructor (New_Animal);
3041 @b{pragma} Import (CPP, New_Animal, "_ZN6AnimalC1Ev");
3043 @b{type} Dog @b{is} @b{new} Animal @b{and} Carnivore @b{and} Domestic @b{with} @b{record}
3044 Tooth_Count : Natural;
3045 Owner : String (1 .. 30);
3047 @b{pragma} Import (C_Plus_Plus, Dog);
3049 @b{function} Number_Of_Teeth (A : Dog) @b{return} Natural;
3050 @b{pragma} Import (C_Plus_Plus, Number_Of_Teeth);
3052 @b{procedure} Set_Owner (A : @b{in} @b{out} Dog; Name : Chars_Ptr);
3053 @b{pragma} Import (C_Plus_Plus, Set_Owner);
3055 @b{function} New_Dog @b{return} Dog;
3056 @b{pragma} CPP_Constructor (New_Dog);
3057 @b{pragma} Import (CPP, New_Dog, "_ZN3DogC2Ev");
3061 Thanks to the compatibility between GNAT run-time structures and the C++ ABI,
3062 interfacing with these C++ classes is easy. The only requirement is that all
3063 the primitives and components must be declared exactly in the same order in
3066 Regarding the abstract interfaces, we must indicate to the GNAT compiler by
3067 means of a @code{pragma Convention (C_Plus_Plus)}, the convention used to pass
3068 the arguments to the called primitives will be the same as for C++. For the
3069 imported classes we use @code{pragma Import} with convention @code{C_Plus_Plus}
3070 to indicate that they have been defined on the C++ side; this is required
3071 because the dispatch table associated with these tagged types will be built
3072 in the C++ side and therefore will not contain the predefined Ada primitives
3073 which Ada would otherwise expect.
3075 As the reader can see there is no need to indicate the C++ mangled names
3076 associated with each subprogram because it is assumed that all the calls to
3077 these primitives will be dispatching calls. The only exception is the
3078 constructor, which must be registered with the compiler by means of
3079 @code{pragma CPP_Constructor} and needs to provide its associated C++
3080 mangled name because the Ada compiler generates direct calls to it.
3082 With the above packages we can now declare objects of type Dog on the Ada side
3083 and dispatch calls to the corresponding subprograms on the C++ side. We can
3084 also extend the tagged type Dog with further fields and primitives, and
3085 override some of its C++ primitives on the Ada side. For example, here we have
3086 a type derivation defined on the Ada side that inherits all the dispatching
3087 primitives of the ancestor from the C++ side.
3090 @b{with} Animals; @b{use} Animals;
3091 @b{package} Vaccinated_Animals @b{is}
3092 @b{type} Vaccinated_Dog @b{is new} Dog @b{with null record};
3093 @b{function} Vaccination_Expired (A : Vaccinated_Dog) @b{return} Boolean;
3094 @b{end} Vaccinated_Animals;
3097 It is important to note that, because of the ABI compatibility, the programmer
3098 does not need to add any further information to indicate either the object
3099 layout or the dispatch table entry associated with each dispatching operation.
3101 Now let us define all the types and constructors on the Ada side and export
3102 them to C++, using the same hierarchy of our previous example:
3104 @smallexample @c ada
3105 @b{with} Interfaces.C.Strings;
3106 @b{use} Interfaces.C.Strings;
3107 @b{package} Animals @b{is}
3108 @b{type} Carnivore @b{is} @b{limited} interface;
3109 @b{pragma} Convention (C_Plus_Plus, Carnivore);
3110 @b{function} Number_Of_Teeth (X : Carnivore)
3111 @b{return} Natural @b{is} @b{abstract};
3113 @b{type} Domestic @b{is} @b{limited} interface;
3114 @b{pragma} Convention (C_Plus_Plus, Domestic);
3115 @b{procedure} Set_Owner
3116 (X : @b{in} @b{out} Domestic;
3117 Name : Chars_Ptr) @b{is} @b{abstract};
3119 @b{type} Animal @b{is} @b{tagged} @b{record}
3122 @b{pragma} Convention (C_Plus_Plus, Animal);
3124 @b{procedure} Set_Age (X : @b{in} @b{out} Animal; Age : Integer);
3125 @b{pragma} Export (C_Plus_Plus, Set_Age);
3127 @b{function} Age (X : Animal) @b{return} Integer;
3128 @b{pragma} Export (C_Plus_Plus, Age);
3130 @b{function} New_Animal @b{return} Animal'Class;
3131 @b{pragma} Export (C_Plus_Plus, New_Animal);
3133 @b{type} Dog @b{is} @b{new} Animal @b{and} Carnivore @b{and} Domestic @b{with} @b{record}
3134 Tooth_Count : Natural;
3135 Owner : String (1 .. 30);
3137 @b{pragma} Convention (C_Plus_Plus, Dog);
3139 @b{function} Number_Of_Teeth (A : Dog) @b{return} Natural;
3140 @b{pragma} Export (C_Plus_Plus, Number_Of_Teeth);
3142 @b{procedure} Set_Owner (A : @b{in} @b{out} Dog; Name : Chars_Ptr);
3143 @b{pragma} Export (C_Plus_Plus, Set_Owner);
3145 @b{function} New_Dog @b{return} Dog'Class;
3146 @b{pragma} Export (C_Plus_Plus, New_Dog);
3150 Compared with our previous example the only differences are the use of
3151 @code{pragma Convention} (instead of @code{pragma Import}), and the use of
3152 @code{pragma Export} to indicate to the GNAT compiler that the primitives will
3153 be available to C++. Thanks to the ABI compatibility, on the C++ side there is
3154 nothing else to be done; as explained above, the only requirement is that all
3155 the primitives and components are declared in exactly the same order.
3157 For completeness, let us see a brief C++ main program that uses the
3158 declarations available in @code{animals.h} (presented in our first example) to
3159 import and use the declarations from the Ada side, properly initializing and
3160 finalizing the Ada run-time system along the way:
3163 @b{#include} "animals.h"
3164 @b{#include} <iostream>
3165 @b{using namespace} std;
3167 void Check_Carnivore (Carnivore *obj) @{@dots{}@}
3168 void Check_Domestic (Domestic *obj) @{@dots{}@}
3169 void Check_Animal (Animal *obj) @{@dots{}@}
3170 void Check_Dog (Dog *obj) @{@dots{}@}
3173 void adainit (void);
3174 void adafinal (void);
3180 Dog *obj = new_dog(); // Ada constructor
3181 Check_Carnivore (obj); // Check secondary DT
3182 Check_Domestic (obj); // Check secondary DT
3183 Check_Animal (obj); // Check primary DT
3184 Check_Dog (obj); // Check primary DT
3189 adainit (); test(); adafinal ();
3194 @node Comparison between GNAT and C/C++ Compilation Models
3195 @section Comparison between GNAT and C/C++ Compilation Models
3198 The GNAT model of compilation is close to the C and C++ models. You can
3199 think of Ada specs as corresponding to header files in C. As in C, you
3200 don't need to compile specs; they are compiled when they are used. The
3201 Ada @code{with} is similar in effect to the @code{#include} of a C
3204 One notable difference is that, in Ada, you may compile specs separately
3205 to check them for semantic and syntactic accuracy. This is not always
3206 possible with C headers because they are fragments of programs that have
3207 less specific syntactic or semantic rules.
3209 The other major difference is the requirement for running the binder,
3210 which performs two important functions. First, it checks for
3211 consistency. In C or C++, the only defense against assembling
3212 inconsistent programs lies outside the compiler, in a makefile, for
3213 example. The binder satisfies the Ada requirement that it be impossible
3214 to construct an inconsistent program when the compiler is used in normal
3217 @cindex Elaboration order control
3218 The other important function of the binder is to deal with elaboration
3219 issues. There are also elaboration issues in C++ that are handled
3220 automatically. This automatic handling has the advantage of being
3221 simpler to use, but the C++ programmer has no control over elaboration.
3222 Where @code{gnatbind} might complain there was no valid order of
3223 elaboration, a C++ compiler would simply construct a program that
3224 malfunctioned at run time.
3226 @node Comparison between GNAT and Conventional Ada Library Models
3227 @section Comparison between GNAT and Conventional Ada Library Models
3230 This section is intended for Ada programmers who have
3231 used an Ada compiler implementing the traditional Ada library
3232 model, as described in the Ada Reference Manual.
3234 @cindex GNAT library
3235 In GNAT, there is no ``library'' in the normal sense. Instead, the set of
3236 source files themselves acts as the library. Compiling Ada programs does
3237 not generate any centralized information, but rather an object file and
3238 a ALI file, which are of interest only to the binder and linker.
3239 In a traditional system, the compiler reads information not only from
3240 the source file being compiled, but also from the centralized library.
3241 This means that the effect of a compilation depends on what has been
3242 previously compiled. In particular:
3246 When a unit is @code{with}'ed, the unit seen by the compiler corresponds
3247 to the version of the unit most recently compiled into the library.
3250 Inlining is effective only if the necessary body has already been
3251 compiled into the library.
3254 Compiling a unit may obsolete other units in the library.
3258 In GNAT, compiling one unit never affects the compilation of any other
3259 units because the compiler reads only source files. Only changes to source
3260 files can affect the results of a compilation. In particular:
3264 When a unit is @code{with}'ed, the unit seen by the compiler corresponds
3265 to the source version of the unit that is currently accessible to the
3270 Inlining requires the appropriate source files for the package or
3271 subprogram bodies to be available to the compiler. Inlining is always
3272 effective, independent of the order in which units are complied.
3275 Compiling a unit never affects any other compilations. The editing of
3276 sources may cause previous compilations to be out of date if they
3277 depended on the source file being modified.
3281 The most important result of these differences is that order of compilation
3282 is never significant in GNAT. There is no situation in which one is
3283 required to do one compilation before another. What shows up as order of
3284 compilation requirements in the traditional Ada library becomes, in
3285 GNAT, simple source dependencies; in other words, there is only a set
3286 of rules saying what source files must be present when a file is
3290 @c *************************
3291 @node Compiling with gcc
3292 @chapter Compiling with @command{gcc}
3295 This chapter discusses how to compile Ada programs using the @command{gcc}
3296 command. It also describes the set of switches
3297 that can be used to control the behavior of the compiler.
3299 * Compiling Programs::
3300 * Switches for gcc::
3301 * Search Paths and the Run-Time Library (RTL)::
3302 * Order of Compilation Issues::
3306 @node Compiling Programs
3307 @section Compiling Programs
3310 The first step in creating an executable program is to compile the units
3311 of the program using the @command{gcc} command. You must compile the
3316 the body file (@file{.adb}) for a library level subprogram or generic
3320 the spec file (@file{.ads}) for a library level package or generic
3321 package that has no body
3324 the body file (@file{.adb}) for a library level package
3325 or generic package that has a body
3330 You need @emph{not} compile the following files
3335 the spec of a library unit which has a body
3342 because they are compiled as part of compiling related units. GNAT
3344 when the corresponding body is compiled, and subunits when the parent is
3347 @cindex cannot generate code
3348 If you attempt to compile any of these files, you will get one of the
3349 following error messages (where @var{fff} is the name of the file you
3353 cannot generate code for file @var{fff} (package spec)
3354 to check package spec, use -gnatc
3356 cannot generate code for file @var{fff} (missing subunits)
3357 to check parent unit, use -gnatc
3359 cannot generate code for file @var{fff} (subprogram spec)
3360 to check subprogram spec, use -gnatc
3362 cannot generate code for file @var{fff} (subunit)
3363 to check subunit, use -gnatc
3367 As indicated by the above error messages, if you want to submit
3368 one of these files to the compiler to check for correct semantics
3369 without generating code, then use the @option{-gnatc} switch.
3371 The basic command for compiling a file containing an Ada unit is
3374 @c $ gcc -c @ovar{switches} @file{file name}
3375 @c Expanding @ovar macro inline (explanation in macro def comments)
3376 $ gcc -c @r{[}@var{switches}@r{]} @file{file name}
3380 where @var{file name} is the name of the Ada file (usually
3382 @file{.ads} for a spec or @file{.adb} for a body).
3384 @option{-c} switch to tell @command{gcc} to compile, but not link, the file.
3385 The result of a successful compilation is an object file, which has the
3386 same name as the source file but an extension of @file{.o} and an Ada
3387 Library Information (ALI) file, which also has the same name as the
3388 source file, but with @file{.ali} as the extension. GNAT creates these
3389 two output files in the current directory, but you may specify a source
3390 file in any directory using an absolute or relative path specification
3391 containing the directory information.
3394 @command{gcc} is actually a driver program that looks at the extensions of
3395 the file arguments and loads the appropriate compiler. For example, the
3396 GNU C compiler is @file{cc1}, and the Ada compiler is @file{gnat1}.
3397 These programs are in directories known to the driver program (in some
3398 configurations via environment variables you set), but need not be in
3399 your path. The @command{gcc} driver also calls the assembler and any other
3400 utilities needed to complete the generation of the required object
3403 It is possible to supply several file names on the same @command{gcc}
3404 command. This causes @command{gcc} to call the appropriate compiler for
3405 each file. For example, the following command lists two separate
3406 files to be compiled:
3409 $ gcc -c x.adb y.adb
3413 calls @code{gnat1} (the Ada compiler) twice to compile @file{x.adb} and
3415 The compiler generates two object files @file{x.o} and @file{y.o}
3416 and the two ALI files @file{x.ali} and @file{y.ali}.
3417 Any switches apply to all the files listed,
3419 @node Switches for gcc
3420 @section Switches for @command{gcc}
3423 The @command{gcc} command accepts switches that control the
3424 compilation process. These switches are fully described in this section.
3425 First we briefly list all the switches, in alphabetical order, then we
3426 describe the switches in more detail in functionally grouped sections.
3428 More switches exist for GCC than those documented here, especially
3429 for specific targets. However, their use is not recommended as
3430 they may change code generation in ways that are incompatible with
3431 the Ada run-time library, or can cause inconsistencies between
3435 * Output and Error Message Control::
3436 * Warning Message Control::
3437 * Debugging and Assertion Control::
3438 * Validity Checking::
3441 * Using gcc for Syntax Checking::
3442 * Using gcc for Semantic Checking::
3443 * Compiling Different Versions of Ada::
3444 * Character Set Control::
3445 * File Naming Control::
3446 * Subprogram Inlining Control::
3447 * Auxiliary Output Control::
3448 * Debugging Control::
3449 * Exception Handling Control::
3450 * Units to Sources Mapping Files::
3451 * Integrated Preprocessing::
3452 * Code Generation Control::
3457 @cindex @option{-b} (@command{gcc})
3458 @item -b @var{target}
3459 Compile your program to run on @var{target}, which is the name of a
3460 system configuration. You must have a GNAT cross-compiler built if
3461 @var{target} is not the same as your host system.
3464 @cindex @option{-B} (@command{gcc})
3465 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
3466 from @var{dir} instead of the default location. Only use this switch
3467 when multiple versions of the GNAT compiler are available.
3468 @xref{Directory Options,, Options for Directory Search, gcc, Using the
3469 GNU Compiler Collection (GCC)}, for further details. You would normally
3470 use the @option{-b} or @option{-V} switch instead.
3473 @cindex @option{-c} (@command{gcc})
3474 Compile. Always use this switch when compiling Ada programs.
3476 Note: for some other languages when using @command{gcc}, notably in
3477 the case of C and C++, it is possible to use
3478 use @command{gcc} without a @option{-c} switch to
3479 compile and link in one step. In the case of GNAT, you
3480 cannot use this approach, because the binder must be run
3481 and @command{gcc} cannot be used to run the GNAT binder.
3483 @item -fcallgraph-info@r{[}=su,da@r{]}
3484 @cindex @option{-fcallgraph-info} (@command{gcc})
3485 Makes the compiler output callgraph information for the program, on a
3486 per-file basis. The information is generated in the VCG format. It can
3487 be decorated with additional, per-node and/or per-edge information, if a
3488 list of comma-separated markers is additionally specified. When the
3489 @var{su} marker is specified, the callgraph is decorated with stack usage information; it is equivalent to @option{-fstack-usage}. When the @var{da}
3490 marker is specified, the callgraph is decorated with information about
3491 dynamically allocated objects.
3494 @cindex @option{-fdump-scos} (@command{gcc})
3495 Generates SCO (Source Coverage Obligation) information in the ALI file.
3496 This information is used by advanced coverage tools. See unit @file{SCOs}
3497 in the compiler sources for details in files @file{scos.ads} and
3501 @cindex @option{-fdump-xref} (@command{gcc})
3502 Generates cross reference information in GLI files for C and C++ sources.
3503 The GLI files have the same syntax as the ALI files for Ada, and can be used
3504 for source navigation in IDEs and on the command line using e.g. gnatxref
3505 and the @option{--ext=gli} switch.
3507 @item -flto@r{[}=n@r{]}
3508 @cindex @option{-flto} (@command{gcc})
3509 Enables Link Time Optimization. This switch must be used in conjunction
3510 with the traditional @option{-Ox} switches and instructs the compiler to
3511 defer most optimizations until the link stage. The advantage of this
3512 approach is that the compiler can do a whole-program analysis and choose
3513 the best interprocedural optimization strategy based on a complete view
3514 of the program, instead of a fragmentary view with the usual approach.
3515 This can also speed up the compilation of big programs and reduce the
3516 size of the executable, compared with a traditional per-unit compilation
3517 with inlining across modules enabled by the @option{-gnatn} switch.
3518 The drawback of this approach is that it may require more memory and that
3519 the debugging information generated by -g with it might be hardly usable.
3520 The switch, as well as the accompanying @option{-Ox} switches, must be
3521 specified both for the compilation and the link phases.
3522 If the @var{n} parameter is specified, the optimization and final code
3523 generation at link time are executed using @var{n} parallel jobs by
3524 means of an installed @command{make} program.
3527 @cindex @option{-fno-inline} (@command{gcc})
3528 Suppresses all inlining, even if other optimization or inlining
3529 switches are set. This includes suppression of inlining that
3530 results from the use of the pragma @code{Inline_Always}.
3531 Any occurrences of pragma @code{Inline} or @code{Inline_Always}
3532 are ignored, and @option{-gnatn} and @option{-gnatN} have no
3533 effects if this switch is present. Note that inlining can also
3534 be suppressed on a finer-grained basis with pragma @code{No_Inline}.
3536 @item -fno-inline-functions
3537 @cindex @option{-fno-inline-functions} (@command{gcc})
3538 Suppresses automatic inlining of subprograms, which is enabled
3539 if @option{-O3} is used.
3541 @item -fno-inline-small-functions
3542 @cindex @option{-fno-inline-small-functions} (@command{gcc})
3543 Suppresses automatic inlining of small subprograms, which is enabled
3544 if @option{-O2} is used.
3546 @item -fno-inline-functions-called-once
3547 @cindex @option{-fno-inline-functions-called-once} (@command{gcc})
3548 Suppresses inlining of subprograms local to the unit and called once
3549 from within it, which is enabled if @option{-O1} is used.
3552 @cindex @option{-fno-ivopts} (@command{gcc})
3553 Suppresses high-level loop induction variable optimizations, which are
3554 enabled if @option{-O1} is used. These optimizations are generally
3555 profitable but, for some specific cases of loops with numerous uses
3556 of the iteration variable that follow a common pattern, they may end
3557 up destroying the regularity that could be exploited at a lower level
3558 and thus producing inferior code.
3560 @item -fno-strict-aliasing
3561 @cindex @option{-fno-strict-aliasing} (@command{gcc})
3562 Causes the compiler to avoid assumptions regarding non-aliasing
3563 of objects of different types. See
3564 @ref{Optimization and Strict Aliasing} for details.
3567 @cindex @option{-fstack-check} (@command{gcc})
3568 Activates stack checking.
3569 See @ref{Stack Overflow Checking} for details.
3572 @cindex @option{-fstack-usage} (@command{gcc})
3573 Makes the compiler output stack usage information for the program, on a
3574 per-subprogram basis. See @ref{Static Stack Usage Analysis} for details.
3577 @cindex @option{-g} (@command{gcc})
3578 Generate debugging information. This information is stored in the object
3579 file and copied from there to the final executable file by the linker,
3580 where it can be read by the debugger. You must use the
3581 @option{-g} switch if you plan on using the debugger.
3584 @cindex @option{-gnat83} (@command{gcc})
3585 Enforce Ada 83 restrictions.
3588 @cindex @option{-gnat95} (@command{gcc})
3589 Enforce Ada 95 restrictions.
3591 Note: for compatibility with some Ada 95 compilers which support only
3592 the @code{overriding} keyword of Ada 2005, the @option{-gnatd.D} switch can
3593 be used along with @option{-gnat95} to achieve a similar effect with GNAT.
3595 @option{-gnatd.D} instructs GNAT to consider @code{overriding} as a keyword
3596 and handle its associated semantic checks, even in Ada 95 mode.
3599 @cindex @option{-gnat05} (@command{gcc})
3600 Allow full Ada 2005 features.
3603 @cindex @option{-gnat2005} (@command{gcc})
3604 Allow full Ada 2005 features (same as @option{-gnat05})
3607 @cindex @option{-gnat12} (@command{gcc})
3610 @cindex @option{-gnat2012} (@command{gcc})
3611 Allow full Ada 2012 features (same as @option{-gnat12})
3614 @cindex @option{-gnata} (@command{gcc})
3615 Assertions enabled. @code{Pragma Assert} and @code{pragma Debug} to be
3616 activated. Note that these pragmas can also be controlled using the
3617 configuration pragmas @code{Assertion_Policy} and @code{Debug_Policy}.
3618 It also activates pragmas @code{Check}, @code{Precondition}, and
3619 @code{Postcondition}. Note that these pragmas can also be controlled
3620 using the configuration pragma @code{Check_Policy}. In Ada 2012, it
3621 also activates all assertions defined in the RM as aspects: preconditions,
3622 postconditions, type invariants and (sub)type predicates. In all Ada modes,
3623 corresponding pragmas for type invariants and (sub)type predicates are
3624 also activated. The default is that all these assertions are disabled,
3625 and have no effect, other than being checked for syntactic validity, and
3626 in the case of subtype predicates, constructions such as membership tests
3627 still test predicates even if assertions are turned off.
3630 @cindex @option{-gnatA} (@command{gcc})
3631 Avoid processing @file{gnat.adc}. If a @file{gnat.adc} file is present,
3635 @cindex @option{-gnatb} (@command{gcc})
3636 Generate brief messages to @file{stderr} even if verbose mode set.
3639 @cindex @option{-gnatB} (@command{gcc})
3640 Assume no invalid (bad) values except for 'Valid attribute use
3641 (@pxref{Validity Checking}).
3644 @cindex @option{-gnatc} (@command{gcc})
3645 Check syntax and semantics only (no code generation attempted). When the
3646 compiler is invoked by @command{gnatmake}, if the switch @option{-gnatc} is
3647 only given to the compiler (after @option{-cargs} or in package Compiler of
3648 the project file, @command{gnatmake} will fail because it will not find the
3649 object file after compilation. If @command{gnatmake} is called with
3650 @option{-gnatc} as a builder switch (before @option{-cargs} or in package
3651 Builder of the project file) then @command{gnatmake} will not fail because
3652 it will not look for the object files after compilation, and it will not try
3653 to build and link. This switch may not be given if a previous @code{-gnatR}
3654 switch has been given, since @code{-gnatR} requires that the code generator
3655 be called to complete determination of representation information.
3658 @cindex @option{-gnatC} (@command{gcc})
3659 Generate CodePeer intermediate format (no code generation attempted).
3660 This switch will generate an intermediate representation suitable for
3661 use by CodePeer (@file{.scil} files). This switch is not compatible with
3662 code generation (it will, among other things, disable some switches such
3663 as -gnatn, and enable others such as -gnata).
3666 @cindex @option{-gnatd} (@command{gcc})
3667 Specify debug options for the compiler. The string of characters after
3668 the @option{-gnatd} specify the specific debug options. The possible
3669 characters are 0-9, a-z, A-Z, optionally preceded by a dot. See
3670 compiler source file @file{debug.adb} for details of the implemented
3671 debug options. Certain debug options are relevant to applications
3672 programmers, and these are documented at appropriate points in this
3676 @cindex @option{-gnatD[nn]} (@command{gcc})
3677 Create expanded source files for source level debugging. This switch
3678 also suppress generation of cross-reference information
3679 (see @option{-gnatx}). Note that this switch is not allowed if a previous
3680 -gnatR switch has been given, since these two switches are not compatible.
3683 @cindex @option{-gnateA} (@command{gcc})
3684 Check that the actual parameters of a subprogram call are not aliases of one
3685 another. To qualify as aliasing, the actuals must denote objects of a composite
3686 type, their memory locations must be identical or overlapping, and at least one
3687 of the corresponding formal parameters must be of mode OUT or IN OUT.
3690 type Rec_Typ is record
3691 Data : Integer := 0;
3694 function Self (Val : Rec_Typ) return Rec_Typ is
3699 procedure Detect_Aliasing (Val_1 : in out Rec_Typ; Val_2 : Rec_Typ) is
3702 end Detect_Aliasing;
3706 Detect_Aliasing (Obj, Obj);
3707 Detect_Aliasing (Obj, Self (Obj));
3710 In the example above, the first call to @code{Detect_Aliasing} fails with a
3711 @code{Program_Error} at runtime because the actuals for @code{Val_1} and
3712 @code{Val_2} denote the same object. The second call executes without raising
3713 an exception because @code{Self(Obj)} produces an anonymous object which does
3714 not share the memory location of @code{Obj}.
3716 @item -gnatec=@var{path}
3717 @cindex @option{-gnatec} (@command{gcc})
3718 Specify a configuration pragma file
3719 (the equal sign is optional)
3720 (@pxref{The Configuration Pragmas Files}).
3723 @cindex @option{-gnateC} (@command{gcc})
3724 Generate CodePeer messages in a compiler-like format. This switch is only
3725 effective if @option{-gnatcC} is also specified and requires an installation
3729 @cindex @option{-gnated} (@command{gcc})
3730 Disable atomic synchronization
3732 @item -gnateDsymbol@r{[}=@var{value}@r{]}
3733 @cindex @option{-gnateD} (@command{gcc})
3734 Defines a symbol, associated with @var{value}, for preprocessing.
3735 (@pxref{Integrated Preprocessing}).
3738 @cindex @option{-gnateE} (@command{gcc})
3739 Generate extra information in exception messages. In particular, display
3740 extra column information and the value and range associated with index and
3741 range check failures, and extra column information for access checks.
3742 In cases where the compiler is able to determine at compile time that
3743 a check will fail, it gives a warning, and the extra information is not
3744 produced at run time.
3747 @cindex @option{-gnatef} (@command{gcc})
3748 Display full source path name in brief error messages.
3751 @cindex @option{-gnateF} (@command{gcc})
3752 Check for overflow on all floating-point operations, including those
3753 for unconstrained predefined types. See description of pragma
3754 @code{Check_Float_Overflow} in GNAT RM.
3757 @cindex @option{-gnateG} (@command{gcc})
3758 Save result of preprocessing in a text file.
3760 @item -gnatei@var{nnn}
3761 @cindex @option{-gnatei} (@command{gcc})
3762 Set maximum number of instantiations during compilation of a single unit to
3763 @var{nnn}. This may be useful in increasing the default maximum of 8000 for
3764 the rare case when a single unit legitimately exceeds this limit.
3766 @item -gnateI@var{nnn}
3767 @cindex @option{-gnateI} (@command{gcc})
3768 Indicates that the source is a multi-unit source and that the index of the
3769 unit to compile is @var{nnn}. @var{nnn} needs to be a positive number and need
3770 to be a valid index in the multi-unit source.
3773 @cindex @option{-gnatel} (@command{gcc})
3774 This switch can be used with the static elaboration model to issue info
3776 where implicit @code{pragma Elaborate} and @code{pragma Elaborate_All}
3777 are generated. This is useful in diagnosing elaboration circularities
3778 caused by these implicit pragmas when using the static elaboration
3779 model. See See the section in this guide on elaboration checking for
3780 further details. These messages are not generated by default, and are
3781 intended only for temporary use when debugging circularity problems.
3784 @cindex @option{-gnatel} (@command{gcc})
3785 This switch turns off the info messages about implicit elaboration pragmas.
3787 @item -gnatem=@var{path}
3788 @cindex @option{-gnatem} (@command{gcc})
3789 Specify a mapping file
3790 (the equal sign is optional)
3791 (@pxref{Units to Sources Mapping Files}).
3793 @item -gnatep=@var{file}
3794 @cindex @option{-gnatep} (@command{gcc})
3795 Specify a preprocessing data file
3796 (the equal sign is optional)
3797 (@pxref{Integrated Preprocessing}).
3800 @cindex @option{-gnateP} (@command{gcc})
3801 Turn categorization dependency errors into warnings.
3802 Ada requires that units that WITH one another have compatible categories, for
3803 example a Pure unit cannot WITH a Preelaborate unit. If this switch is used,
3804 these errors become warnings (which can be ignored, or suppressed in the usual
3805 manner). This can be useful in some specialized circumstances such as the
3806 temporary use of special test software.
3809 @cindex @option{-gnateS} (@command{gcc})
3810 Synonym of @option{-fdump-scos}, kept for backwards compatibility.
3812 @item -gnatet=@var{path}
3813 @cindex @option{-gnatet=file} (@command{gcc})
3814 Generate target dependent information. The format of the output file is
3815 described in the section about switch @option{-gnateT}.
3817 @item -gnateT=@var{path}
3818 @cindex @option{-gnateT} (@command{gcc})
3819 Read target dependent information, such as endianness or sizes and alignments
3820 of base type. If this switch is passed, the default target dependent
3821 information of the compiler is replaced by the one read from the input file.
3822 This is used by tools other than the compiler, e.g. to do
3823 semantic analysis of programs that will run on some other target than
3824 the machine on which the tool is run.
3826 The following target dependent values should be defined,
3827 where @code{Nat} denotes a natural integer value, @code{Pos} denotes a
3828 positive integer value, and fields marked with a question mark are
3829 boolean fields, where a value of 0 is False, and a value of 1 is True:
3832 Bits_BE : Nat; -- Bits stored big-endian?
3833 Bits_Per_Unit : Pos; -- Bits in a storage unit
3834 Bits_Per_Word : Pos; -- Bits in a word
3835 Bytes_BE : Nat; -- Bytes stored big-endian?
3836 Char_Size : Pos; -- Standard.Character'Size
3837 Double_Float_Alignment : Nat; -- Alignment of double float
3838 Double_Scalar_Alignment : Nat; -- Alignment of double length scalar
3839 Double_Size : Pos; -- Standard.Long_Float'Size
3840 Float_Size : Pos; -- Standard.Float'Size
3841 Float_Words_BE : Nat; -- Float words stored big-endian?
3842 Int_Size : Pos; -- Standard.Integer'Size
3843 Long_Double_Size : Pos; -- Standard.Long_Long_Float'Size
3844 Long_Long_Size : Pos; -- Standard.Long_Long_Integer'Size
3845 Long_Size : Pos; -- Standard.Long_Integer'Size
3846 Maximum_Alignment : Pos; -- Maximum permitted alignment
3847 Max_Unaligned_Field : Pos; -- Maximum size for unaligned bit field
3848 Pointer_Size : Pos; -- System.Address'Size
3849 Short_Enums : Nat; -- Short foreign convention enums?
3850 Short_Size : Pos; -- Standard.Short_Integer'Size
3851 Strict_Alignment : Nat; -- Strict alignment?
3852 System_Allocator_Alignment : Nat; -- Alignment for malloc calls
3853 Wchar_T_Size : Pos; -- Interfaces.C.wchar_t'Size
3854 Words_BE : Nat; -- Words stored big-endian?
3857 The format of the input file is as follows. First come the values of
3858 the variables defined above, with one line per value:
3864 where @code{name} is the name of the parameter, spelled out in full,
3865 and cased as in the above list, and @code{value} is an unsigned decimal
3866 integer. Two or more blanks separates the name from the value.
3868 All the variables must be present, in alphabetical order (i.e. the
3869 same order as the list above).
3871 Then there is a blank line to separate the two parts of the file. Then
3872 come the lines showing the floating-point types to be registered, with
3873 one line per registered mode:
3876 name digs float_rep size alignment
3879 where @code{name} is the string name of the type (which can have
3880 single spaces embedded in the name (e.g. long double), @code{digs} is
3881 the number of digits for the floating-point type, @code{float_rep} is
3882 the float representation (I/V/A for IEEE-754-Binary, Vax_Native,
3883 AAMP), @code{size} is the size in bits, @code{alignment} is the
3884 alignment in bits. The name is followed by at least two blanks, fields
3885 are separated by at least one blank, and a LF character immediately
3886 follows the alignment field.
3888 Here is an example of a target parameterization file:
3896 Double_Float_Alignment 0
3897 Double_Scalar_Alignment 0
3902 Long_Double_Size 128
3905 Maximum_Alignment 16
3906 Max_Unaligned_Field 64
3910 System_Allocator_Alignment 16
3916 long double 18 I 80 128
3921 @cindex @option{-gnateu} (@command{gcc})
3922 Ignore unrecognized validity, warning, and style switches that
3923 appear after this switch is given. This may be useful when
3924 compiling sources developed on a later version of the compiler
3925 with an earlier version. Of course the earlier version must
3926 support this switch.
3929 @cindex @option{-gnateV} (@command{gcc})
3930 Check that all actual parameters of a subprogram call are valid according to
3931 the rules of validity checking (@pxref{Validity Checking}).
3934 @cindex @option{-gnateY} (@command{gcc})
3935 Ignore all STYLE_CHECKS pragmas. Full legality checks
3936 are still carried out, but the pragmas have no effect
3937 on what style checks are active. This allows all style
3938 checking options to be controlled from the command line.
3941 @cindex @option{-gnatE} (@command{gcc})
3942 Full dynamic elaboration checks.
3945 @cindex @option{-gnatf} (@command{gcc})
3946 Full errors. Multiple errors per line, all undefined references, do not
3947 attempt to suppress cascaded errors.
3950 @cindex @option{-gnatF} (@command{gcc})
3951 Externals names are folded to all uppercase.
3954 @cindex @option{-gnatg} (@command{gcc})
3955 Internal GNAT implementation mode. This should not be used for
3956 applications programs, it is intended only for use by the compiler
3957 and its run-time library. For documentation, see the GNAT sources.
3958 Note that @option{-gnatg} implies
3959 @option{-gnatw.ge} and
3961 so that all standard warnings and all standard style options are turned on.
3962 All warnings and style messages are treated as errors.
3965 @cindex @option{-gnatG[nn]} (@command{gcc})
3966 List generated expanded code in source form.
3969 @cindex @option{-gnath} (@command{gcc})
3970 Output usage information. The output is written to @file{stdout}.
3973 @cindex @option{-gnati} (@command{gcc})
3974 Identifier character set
3975 (@var{c}=1/2/3/4/8/9/p/f/n/w).
3976 For details of the possible selections for @var{c},
3977 see @ref{Character Set Control}.
3980 @cindex @option{-gnatI} (@command{gcc})
3981 Ignore representation clauses. When this switch is used,
3982 representation clauses are treated as comments. This is useful
3983 when initially porting code where you want to ignore rep clause
3984 problems, and also for compiling foreign code (particularly
3985 for use with ASIS). The representation clauses that are ignored
3986 are: enumeration_representation_clause, record_representation_clause,
3987 and attribute_definition_clause for the following attributes:
3988 Address, Alignment, Bit_Order, Component_Size, Machine_Radix,
3989 Object_Size, Size, Small, Stream_Size, and Value_Size.
3990 Note that this option should be used only for compiling -- the
3991 code is likely to malfunction at run time.
3993 Note that when @code{-gnatct} is used to generate trees for input
3994 into @code{ASIS} tools, these representation clauses are removed
3995 from the tree and ignored. This means that the tool will not see them.
3998 @cindex @option{-gnatjnn} (@command{gcc})
3999 Reformat error messages to fit on nn character lines
4001 @item -gnatk=@var{n}
4002 @cindex @option{-gnatk} (@command{gcc})
4003 Limit file names to @var{n} (1-999) characters (@code{k} = krunch).
4006 @cindex @option{-gnatl} (@command{gcc})
4007 Output full source listing with embedded error messages.
4010 @cindex @option{-gnatL} (@command{gcc})
4011 Used in conjunction with -gnatG or -gnatD to intersperse original
4012 source lines (as comment lines with line numbers) in the expanded
4015 @item -gnatm=@var{n}
4016 @cindex @option{-gnatm} (@command{gcc})
4017 Limit number of detected error or warning messages to @var{n}
4018 where @var{n} is in the range 1..999999. The default setting if
4019 no switch is given is 9999. If the number of warnings reaches this
4020 limit, then a message is output and further warnings are suppressed,
4021 but the compilation is continued. If the number of error messages
4022 reaches this limit, then a message is output and the compilation
4023 is abandoned. The equal sign here is optional. A value of zero
4024 means that no limit applies.
4027 @cindex @option{-gnatn} (@command{gcc})
4028 Activate inlining for subprograms for which pragma @code{Inline} is
4029 specified. This inlining is performed by the GCC back-end. An optional
4030 digit sets the inlining level: 1 for moderate inlining across modules
4031 or 2 for full inlining across modules. If no inlining level is specified,
4032 the compiler will pick it based on the optimization level.
4035 @cindex @option{-gnatN} (@command{gcc})
4036 Activate front end inlining for subprograms for which
4037 pragma @code{Inline} is specified. This inlining is performed
4038 by the front end and will be visible in the
4039 @option{-gnatG} output.
4041 When using a gcc-based back end (in practice this means using any version
4042 of GNAT other than the JGNAT, .NET or GNAAMP versions), then the use of
4043 @option{-gnatN} is deprecated, and the use of @option{-gnatn} is preferred.
4044 Historically front end inlining was more extensive than the gcc back end
4045 inlining, but that is no longer the case.
4048 @cindex @option{-gnato0} (@command{gcc})
4049 Suppresses overflow checking. This causes the behavior of the compiler to
4050 match the default for older versions where overflow checking was suppressed
4051 by default. This is equivalent to having
4052 @code{pragma Suppress (Overflow_Mode)} in a configuration pragma file.
4055 @cindex @option{-gnato??} (@command{gcc})
4056 Set default mode for handling generation of code to avoid intermediate
4057 arithmetic overflow. Here `@code{??}' is two digits, a
4058 single digit, or nothing. Each digit is one of the digits `@code{1}'
4063 all intermediate overflows checked against base type (@code{STRICT})
4065 minimize intermediate overflows (@code{MINIMIZED})
4067 eliminate intermediate overflows (@code{ELIMINATED})
4070 If only one digit appears then it applies to all
4071 cases; if two digits are given, then the first applies outside
4072 assertions, and the second within assertions.
4074 If no digits follow the @option{-gnato}, then it is equivalent to
4076 causing all intermediate overflows to be handled in strict mode.
4078 This switch also causes arithmetic overflow checking to be performed
4079 (as though @code{pragma Unsuppress (Overflow_Mode)} had been specified.
4081 The default if no option @option{-gnato} is given is that overflow handling
4082 is in @code{STRICT} mode (computations done using the base type), and that
4083 overflow checking is enabled.
4085 Note that division by zero is a separate check that is not
4086 controlled by this switch (division by zero checking is on by default).
4088 See also @ref{Specifying the Desired Mode}.
4091 @cindex @option{-gnatp} (@command{gcc})
4092 Suppress all checks. See @ref{Run-Time Checks} for details. This switch
4093 has no effect if cancelled by a subsequent @option{-gnat-p} switch.
4096 @cindex @option{-gnat-p} (@command{gcc})
4097 Cancel effect of previous @option{-gnatp} switch.
4100 @cindex @option{-gnatP} (@command{gcc})
4101 Enable polling. This is required on some systems (notably Windows NT) to
4102 obtain asynchronous abort and asynchronous transfer of control capability.
4103 @xref{Pragma Polling,,, gnat_rm, GNAT Reference Manual}, for full
4107 @cindex @option{-gnatq} (@command{gcc})
4108 Don't quit. Try semantics, even if parse errors.
4111 @cindex @option{-gnatQ} (@command{gcc})
4112 Don't quit. Generate @file{ALI} and tree files even if illegalities.
4113 Note that code generation is still suppressed in the presence of any
4114 errors, so even with @option{-gnatQ} no object file is generated.
4117 @cindex @option{-gnatr} (@command{gcc})
4118 Treat pragma Restrictions as Restriction_Warnings.
4120 @item -gnatR@r{[}0@r{/}1@r{/}2@r{/}3@r{[}s@r{]]}
4121 @cindex @option{-gnatR} (@command{gcc})
4122 Output representation information for declared types and objects.
4123 Note that this switch is not allowed if a previous @code{-gnatD} switch has
4124 been given, since these two switches are not compatible.
4127 Output convention and parameter passing mechanisms for all subprograms.
4130 @cindex @option{-gnats} (@command{gcc})
4134 @cindex @option{-gnatS} (@command{gcc})
4135 Print package Standard.
4138 @cindex @option{-gnatt} (@command{gcc})
4139 Generate tree output file.
4141 @item -gnatT@var{nnn}
4142 @cindex @option{-gnatT} (@command{gcc})
4143 All compiler tables start at @var{nnn} times usual starting size.
4146 @cindex @option{-gnatu} (@command{gcc})
4147 List units for this compilation.
4150 @cindex @option{-gnatU} (@command{gcc})
4151 Tag all error messages with the unique string ``error:''
4154 @cindex @option{-gnatv} (@command{gcc})
4155 Verbose mode. Full error output with source lines to @file{stdout}.
4158 @cindex @option{-gnatV} (@command{gcc})
4159 Control level of validity checking (@pxref{Validity Checking}).
4161 @item -gnatw@var{xxx}
4162 @cindex @option{-gnatw} (@command{gcc})
4164 @var{xxx} is a string of option letters that denotes
4165 the exact warnings that
4166 are enabled or disabled (@pxref{Warning Message Control}).
4169 @cindex @option{-gnatW} (@command{gcc})
4170 Wide character encoding method
4171 (@var{e}=n/h/u/s/e/8).
4174 @cindex @option{-gnatx} (@command{gcc})
4175 Suppress generation of cross-reference information.
4178 @cindex @option{-gnatX} (@command{gcc})
4179 Enable GNAT implementation extensions and latest Ada version.
4182 @cindex @option{-gnaty} (@command{gcc})
4183 Enable built-in style checks (@pxref{Style Checking}).
4186 @cindex @option{-gnatz} (@command{gcc})
4187 Distribution stub generation and compilation
4188 (@var{m}=r/c for receiver/caller stubs).
4191 @cindex @option{-I} (@command{gcc})
4193 Direct GNAT to search the @var{dir} directory for source files needed by
4194 the current compilation
4195 (@pxref{Search Paths and the Run-Time Library (RTL)}).
4198 @cindex @option{-I-} (@command{gcc})
4200 Except for the source file named in the command line, do not look for source
4201 files in the directory containing the source file named in the command line
4202 (@pxref{Search Paths and the Run-Time Library (RTL)}).
4205 @cindex @option{-mbig-switch} (@command{gcc})
4206 @cindex @code{case} statement (effect of @option{-mbig-switch} option)
4207 This standard gcc switch causes the compiler to use larger offsets in its
4208 jump table representation for @code{case} statements.
4209 This may result in less efficient code, but is sometimes necessary
4210 (for example on HP-UX targets)
4211 @cindex HP-UX and @option{-mbig-switch} option
4212 in order to compile large and/or nested @code{case} statements.
4215 @cindex @option{-o} (@command{gcc})
4216 This switch is used in @command{gcc} to redirect the generated object file
4217 and its associated ALI file. Beware of this switch with GNAT, because it may
4218 cause the object file and ALI file to have different names which in turn
4219 may confuse the binder and the linker.
4222 @cindex @option{-nostdinc} (@command{gcc})
4223 Inhibit the search of the default location for the GNAT Run Time
4224 Library (RTL) source files.
4227 @cindex @option{-nostdlib} (@command{gcc})
4228 Inhibit the search of the default location for the GNAT Run Time
4229 Library (RTL) ALI files.
4232 @c Expanding @ovar macro inline (explanation in macro def comments)
4233 @item -O@r{[}@var{n}@r{]}
4234 @cindex @option{-O} (@command{gcc})
4235 @var{n} controls the optimization level.
4239 No optimization, the default setting if no @option{-O} appears
4242 Normal optimization, the default if you specify @option{-O} without
4243 an operand. A good compromise between code quality and compilation
4247 Extensive optimization, may improve execution time, possibly at the cost of
4248 substantially increased compilation time.
4251 Same as @option{-O2}, and also includes inline expansion for small subprograms
4255 Optimize space usage
4259 See also @ref{Optimization Levels}.
4262 @item -pass-exit-codes
4263 @cindex @option{-pass-exit-codes} (@command{gcc})
4264 Catch exit codes from the compiler and use the most meaningful as
4267 @item --RTS=@var{rts-path}
4268 @cindex @option{--RTS} (@command{gcc})
4269 Specifies the default location of the runtime library. Same meaning as the
4270 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
4273 @cindex @option{-S} (@command{gcc})
4274 Used in place of @option{-c} to
4275 cause the assembler source file to be
4276 generated, using @file{.s} as the extension,
4277 instead of the object file.
4278 This may be useful if you need to examine the generated assembly code.
4281 @cindex @option{-fverbose-asm} (@command{gcc})
4282 Used in conjunction with @option{-S}
4283 to cause the generated assembly code file to be annotated with variable
4284 names, making it significantly easier to follow.
4287 @cindex @option{-v} (@command{gcc})
4288 Show commands generated by the @command{gcc} driver. Normally used only for
4289 debugging purposes or if you need to be sure what version of the
4290 compiler you are executing.
4293 @cindex @option{-V} (@command{gcc})
4294 Execute @var{ver} version of the compiler. This is the @command{gcc}
4295 version, not the GNAT version.
4298 @cindex @option{-w} (@command{gcc})
4299 Turn off warnings generated by the back end of the compiler. Use of
4300 this switch also causes the default for front end warnings to be set
4301 to suppress (as though @option{-gnatws} had appeared at the start of
4306 @c Combining qualifiers does not work on VMS
4307 You may combine a sequence of GNAT switches into a single switch. For
4308 example, the combined switch
4310 @cindex Combining GNAT switches
4316 is equivalent to specifying the following sequence of switches:
4319 -gnato -gnatf -gnati3
4323 The following restrictions apply to the combination of switches
4328 The switch @option{-gnatc} if combined with other switches must come
4329 first in the string.
4332 The switch @option{-gnats} if combined with other switches must come
4333 first in the string.
4338 @option{-gnatzc} and @option{-gnatzr} may not be combined with any other
4339 switches, and only one of them may appear in the command line.
4342 The switch @option{-gnat-p} may not be combined with any other switch.
4345 Once a ``y'' appears in the string (that is a use of the @option{-gnaty}
4346 switch), then all further characters in the switch are interpreted
4347 as style modifiers (see description of @option{-gnaty}).
4350 Once a ``d'' appears in the string (that is a use of the @option{-gnatd}
4351 switch), then all further characters in the switch are interpreted
4352 as debug flags (see description of @option{-gnatd}).
4355 Once a ``w'' appears in the string (that is a use of the @option{-gnatw}
4356 switch), then all further characters in the switch are interpreted
4357 as warning mode modifiers (see description of @option{-gnatw}).
4360 Once a ``V'' appears in the string (that is a use of the @option{-gnatV}
4361 switch), then all further characters in the switch are interpreted
4362 as validity checking options (@pxref{Validity Checking}).
4365 Option ``em'', ``ec'', ``ep'', ``l='' and ``R'' must be the last options in
4366 a combined list of options.
4369 @node Output and Error Message Control
4370 @subsection Output and Error Message Control
4374 The standard default format for error messages is called ``brief format''.
4375 Brief format messages are written to @file{stderr} (the standard error
4376 file) and have the following form:
4379 e.adb:3:04: Incorrect spelling of keyword "function"
4380 e.adb:4:20: ";" should be "is"
4384 The first integer after the file name is the line number in the file,
4385 and the second integer is the column number within the line.
4386 @code{GPS} can parse the error messages
4387 and point to the referenced character.
4388 The following switches provide control over the error message
4394 @cindex @option{-gnatv} (@command{gcc})
4396 The v stands for verbose.
4397 The effect of this setting is to write long-format error
4398 messages to @file{stdout} (the standard output file.
4399 The same program compiled with the
4400 @option{-gnatv} switch would generate:
4404 3. funcion X (Q : Integer)
4406 >>> Incorrect spelling of keyword "function"
4409 >>> ";" should be "is"
4414 The vertical bar indicates the location of the error, and the @samp{>>>}
4415 prefix can be used to search for error messages. When this switch is
4416 used the only source lines output are those with errors.
4419 @cindex @option{-gnatl} (@command{gcc})
4420 The @code{l} stands for list.
4421 This switch causes a full listing of
4422 the file to be generated. In the case where a body is
4423 compiled, the corresponding spec is also listed, along
4424 with any subunits. Typical output from compiling a package
4425 body @file{p.adb} might look like:
4427 @smallexample @c ada
4431 1. @b{package} @b{body} p @b{is}
4433 3. @b{procedure} a @b{is} @b{separate};
4443 1. @b{package} p @b{is}
4444 2. @b{pragma} Elaborate_Body
4456 2. @b{procedure} a @b{is}
4468 When you specify the @option{-gnatv} or @option{-gnatl} switches and
4469 standard output is redirected, a brief summary is written to
4470 @file{stderr} (standard error) giving the number of error messages and
4471 warning messages generated.
4474 @cindex @option{-gnatl=fname} (@command{gcc})
4475 This has the same effect as @option{-gnatl} except that the output is
4476 written to a file instead of to standard output. If the given name
4477 @file{fname} does not start with a period, then it is the full name
4478 of the file to be written. If @file{fname} is an extension, it is
4479 appended to the name of the file being compiled. For example, if
4480 file @file{xyz.adb} is compiled with @option{-gnatl=.lst},
4481 then the output is written to file xyz.adb.lst.
4484 @cindex @option{-gnatU} (@command{gcc})
4485 This switch forces all error messages to be preceded by the unique
4486 string ``error:''. This means that error messages take a few more
4487 characters in space, but allows easy searching for and identification
4491 @cindex @option{-gnatb} (@command{gcc})
4492 The @code{b} stands for brief.
4493 This switch causes GNAT to generate the
4494 brief format error messages to @file{stderr} (the standard error
4495 file) as well as the verbose
4496 format message or full listing (which as usual is written to
4497 @file{stdout} (the standard output file).
4499 @item -gnatm=@var{n}
4500 @cindex @option{-gnatm} (@command{gcc})
4501 The @code{m} stands for maximum.
4502 @var{n} is a decimal integer in the
4503 range of 1 to 999999 and limits the number of error or warning
4504 messages to be generated. For example, using
4505 @option{-gnatm2} might yield
4508 e.adb:3:04: Incorrect spelling of keyword "function"
4509 e.adb:5:35: missing ".."
4510 fatal error: maximum number of errors detected
4511 compilation abandoned
4515 The default setting if
4516 no switch is given is 9999. If the number of warnings reaches this
4517 limit, then a message is output and further warnings are suppressed,
4518 but the compilation is continued. If the number of error messages
4519 reaches this limit, then a message is output and the compilation
4520 is abandoned. A value of zero means that no limit applies.
4523 Note that the equal sign is optional, so the switches
4524 @option{-gnatm2} and @option{-gnatm=2} are equivalent.
4527 @cindex @option{-gnatf} (@command{gcc})
4528 @cindex Error messages, suppressing
4529 The @code{f} stands for full.
4530 Normally, the compiler suppresses error messages that are likely to be
4531 redundant. This switch causes all error
4532 messages to be generated. In particular, in the case of
4533 references to undefined variables. If a given variable is referenced
4534 several times, the normal format of messages is
4536 e.adb:7:07: "V" is undefined (more references follow)
4540 where the parenthetical comment warns that there are additional
4541 references to the variable @code{V}. Compiling the same program with the
4542 @option{-gnatf} switch yields
4545 e.adb:7:07: "V" is undefined
4546 e.adb:8:07: "V" is undefined
4547 e.adb:8:12: "V" is undefined
4548 e.adb:8:16: "V" is undefined
4549 e.adb:9:07: "V" is undefined
4550 e.adb:9:12: "V" is undefined
4554 The @option{-gnatf} switch also generates additional information for
4555 some error messages. Some examples are:
4559 Details on possibly non-portable unchecked conversion
4561 List possible interpretations for ambiguous calls
4563 Additional details on incorrect parameters
4567 @cindex @option{-gnatjnn} (@command{gcc})
4568 In normal operation mode (or if @option{-gnatj0} is used), then error messages
4569 with continuation lines are treated as though the continuation lines were
4570 separate messages (and so a warning with two continuation lines counts as
4571 three warnings, and is listed as three separate messages).
4573 If the @option{-gnatjnn} switch is used with a positive value for nn, then
4574 messages are output in a different manner. A message and all its continuation
4575 lines are treated as a unit, and count as only one warning or message in the
4576 statistics totals. Furthermore, the message is reformatted so that no line
4577 is longer than nn characters.
4580 @cindex @option{-gnatq} (@command{gcc})
4581 The @code{q} stands for quit (really ``don't quit'').
4582 In normal operation mode, the compiler first parses the program and
4583 determines if there are any syntax errors. If there are, appropriate
4584 error messages are generated and compilation is immediately terminated.
4586 GNAT to continue with semantic analysis even if syntax errors have been
4587 found. This may enable the detection of more errors in a single run. On
4588 the other hand, the semantic analyzer is more likely to encounter some
4589 internal fatal error when given a syntactically invalid tree.
4592 @cindex @option{-gnatQ} (@command{gcc})
4593 In normal operation mode, the @file{ALI} file is not generated if any
4594 illegalities are detected in the program. The use of @option{-gnatQ} forces
4595 generation of the @file{ALI} file. This file is marked as being in
4596 error, so it cannot be used for binding purposes, but it does contain
4597 reasonably complete cross-reference information, and thus may be useful
4598 for use by tools (e.g., semantic browsing tools or integrated development
4599 environments) that are driven from the @file{ALI} file. This switch
4600 implies @option{-gnatq}, since the semantic phase must be run to get a
4601 meaningful ALI file.
4603 In addition, if @option{-gnatt} is also specified, then the tree file is
4604 generated even if there are illegalities. It may be useful in this case
4605 to also specify @option{-gnatq} to ensure that full semantic processing
4606 occurs. The resulting tree file can be processed by ASIS, for the purpose
4607 of providing partial information about illegal units, but if the error
4608 causes the tree to be badly malformed, then ASIS may crash during the
4611 When @option{-gnatQ} is used and the generated @file{ALI} file is marked as
4612 being in error, @command{gnatmake} will attempt to recompile the source when it
4613 finds such an @file{ALI} file, including with switch @option{-gnatc}.
4615 Note that @option{-gnatQ} has no effect if @option{-gnats} is specified,
4616 since ALI files are never generated if @option{-gnats} is set.
4620 @node Warning Message Control
4621 @subsection Warning Message Control
4622 @cindex Warning messages
4624 In addition to error messages, which correspond to illegalities as defined
4625 in the Ada Reference Manual, the compiler detects two kinds of warning
4628 First, the compiler considers some constructs suspicious and generates a
4629 warning message to alert you to a possible error. Second, if the
4630 compiler detects a situation that is sure to raise an exception at
4631 run time, it generates a warning message. The following shows an example
4632 of warning messages:
4634 e.adb:4:24: warning: creation of object may raise Storage_Error
4635 e.adb:10:17: warning: static value out of range
4636 e.adb:10:17: warning: "Constraint_Error" will be raised at run time
4640 GNAT considers a large number of situations as appropriate
4641 for the generation of warning messages. As always, warnings are not
4642 definite indications of errors. For example, if you do an out-of-range
4643 assignment with the deliberate intention of raising a
4644 @code{Constraint_Error} exception, then the warning that may be
4645 issued does not indicate an error. Some of the situations for which GNAT
4646 issues warnings (at least some of the time) are given in the following
4647 list. This list is not complete, and new warnings are often added to
4648 subsequent versions of GNAT. The list is intended to give a general idea
4649 of the kinds of warnings that are generated.
4653 Possible infinitely recursive calls
4656 Out-of-range values being assigned
4659 Possible order of elaboration problems
4662 Size not a multiple of alignment for a record type
4665 Assertions (pragma Assert) that are sure to fail
4671 Address clauses with possibly unaligned values, or where an attempt is
4672 made to overlay a smaller variable with a larger one.
4675 Fixed-point type declarations with a null range
4678 Direct_IO or Sequential_IO instantiated with a type that has access values
4681 Variables that are never assigned a value
4684 Variables that are referenced before being initialized
4687 Task entries with no corresponding @code{accept} statement
4690 Duplicate accepts for the same task entry in a @code{select}
4693 Objects that take too much storage
4696 Unchecked conversion between types of differing sizes
4699 Missing @code{return} statement along some execution path in a function
4702 Incorrect (unrecognized) pragmas
4705 Incorrect external names
4708 Allocation from empty storage pool
4711 Potentially blocking operation in protected type
4714 Suspicious parenthesization of expressions
4717 Mismatching bounds in an aggregate
4720 Attempt to return local value by reference
4723 Premature instantiation of a generic body
4726 Attempt to pack aliased components
4729 Out of bounds array subscripts
4732 Wrong length on string assignment
4735 Violations of style rules if style checking is enabled
4738 Unused @code{with} clauses
4741 @code{Bit_Order} usage that does not have any effect
4744 @code{Standard.Duration} used to resolve universal fixed expression
4747 Dereference of possibly null value
4750 Declaration that is likely to cause storage error
4753 Internal GNAT unit @code{with}'ed by application unit
4756 Values known to be out of range at compile time
4759 Unreferenced or unmodified variables. Note that a special
4760 exemption applies to variables which contain any of the substrings
4761 @code{DISCARD, DUMMY, IGNORE, JUNK, UNUSED}, in any casing. Such variables
4762 are considered likely to be intentionally used in a situation where
4763 otherwise a warning would be given, so warnings of this kind are
4764 always suppressed for such variables.
4767 Address overlays that could clobber memory
4770 Unexpected initialization when address clause present
4773 Bad alignment for address clause
4776 Useless type conversions
4779 Redundant assignment statements and other redundant constructs
4782 Useless exception handlers
4785 Accidental hiding of name by child unit
4788 Access before elaboration detected at compile time
4791 A range in a @code{for} loop that is known to be null or might be null
4796 The following section lists compiler switches that are available
4797 to control the handling of warning messages. It is also possible
4798 to exercise much finer control over what warnings are issued and
4799 suppressed using the GNAT pragma Warnings, @xref{Pragma Warnings,,,
4800 gnat_rm, GNAT Reference manual}.
4805 @emph{Activate most optional warnings.}
4806 @cindex @option{-gnatwa} (@command{gcc})
4807 This switch activates most optional warning messages. See the remaining list
4808 in this section for details on optional warning messages that can be
4809 individually controlled. The warnings that are not turned on by this
4813 @item @option{-gnatwd} (implicit dereferencing)
4814 @item @option{-gnatw.d} (tag warnings with -gnatw switch)
4815 @item @option{-gnatwh} (hiding)
4816 @item @option{-gnatw.h} (holes in record layouts)
4817 @item @option{-gnatw.k} (redefinition of names in standard)
4818 @item @option{-gnatwl} (elaboration warnings)
4819 @item @option{-gnatw.l} (inherited aspects)
4820 @item @option{-gnatw.n} (atomic synchronization)
4821 @item @option{-gnatwo} (address clause overlay)
4822 @item @option{-gnatw.o} (values set by out parameters ignored)
4823 @item @option{-gnatw.s} (overridden size clause)
4824 @item @option{-gnatwt} (tracking of deleted conditional code)
4825 @item @option{-gnatw.u} (unordered enumeration)
4826 @item @option{-gnatw.w} (use of Warnings Off)
4827 @item @option{-gnatw.y} (reasons for package needing body)
4830 All other optional warnings are turned on.
4833 @emph{Suppress all optional errors.}
4834 @cindex @option{-gnatwA} (@command{gcc})
4835 This switch suppresses all optional warning messages, see remaining list
4836 in this section for details on optional warning messages that can be
4837 individually controlled. Note that unlike switch @option{-gnatws}, the
4838 use of switch @option{-gnatwA} does not suppress warnings that are
4839 normally given unconditionally and cannot be individually controlled
4840 (for example, the warning about a missing exit path in a function).
4841 Also, again unlike switch @option{-gnatws}, warnings suppressed by
4842 the use of switch @option{-gnatwA} can be individually turned back
4843 on. For example the use of switch @option{-gnatwA} followed by
4844 switch @option{-gnatwd} will suppress all optional warnings except
4845 the warnings for implicit dereferencing.
4848 @emph{Activate warnings on failing assertions.}
4849 @cindex @option{-gnatw.a} (@command{gcc})
4850 @cindex Assert failures
4851 This switch activates warnings for assertions where the compiler can tell at
4852 compile time that the assertion will fail. Note that this warning is given
4853 even if assertions are disabled. The default is that such warnings are
4857 @emph{Suppress warnings on failing assertions.}
4858 @cindex @option{-gnatw.A} (@command{gcc})
4859 @cindex Assert failures
4860 This switch suppresses warnings for assertions where the compiler can tell at
4861 compile time that the assertion will fail.
4864 @emph{Activate warnings on bad fixed values.}
4865 @cindex @option{-gnatwb} (@command{gcc})
4866 @cindex Bad fixed values
4867 @cindex Fixed-point Small value
4869 This switch activates warnings for static fixed-point expressions whose
4870 value is not an exact multiple of Small. Such values are implementation
4871 dependent, since an implementation is free to choose either of the multiples
4872 that surround the value. GNAT always chooses the closer one, but this is not
4873 required behavior, and it is better to specify a value that is an exact
4874 multiple, ensuring predictable execution. The default is that such warnings
4878 @emph{Suppress warnings on bad fixed values.}
4879 @cindex @option{-gnatwB} (@command{gcc})
4880 This switch suppresses warnings for static fixed-point expressions whose
4881 value is not an exact multiple of Small.
4884 @emph{Activate warnings on biased representation.}
4885 @cindex @option{-gnatw.b} (@command{gcc})
4886 @cindex Biased representation
4887 This switch activates warnings when a size clause, value size clause, component
4888 clause, or component size clause forces the use of biased representation for an
4889 integer type (e.g. representing a range of 10..11 in a single bit by using 0/1
4890 to represent 10/11). The default is that such warnings are generated.
4893 @emph{Suppress warnings on biased representation.}
4894 @cindex @option{-gnatwB} (@command{gcc})
4895 This switch suppresses warnings for representation clauses that force the use
4896 of biased representation.
4899 @emph{Activate warnings on conditionals.}
4900 @cindex @option{-gnatwc} (@command{gcc})
4901 @cindex Conditionals, constant
4902 This switch activates warnings for conditional expressions used in
4903 tests that are known to be True or False at compile time. The default
4904 is that such warnings are not generated.
4905 Note that this warning does
4906 not get issued for the use of boolean variables or constants whose
4907 values are known at compile time, since this is a standard technique
4908 for conditional compilation in Ada, and this would generate too many
4909 false positive warnings.
4911 This warning option also activates a special test for comparisons using
4912 the operators ``>='' and`` <=''.
4913 If the compiler can tell that only the equality condition is possible,
4914 then it will warn that the ``>'' or ``<'' part of the test
4915 is useless and that the operator could be replaced by ``=''.
4916 An example would be comparing a @code{Natural} variable <= 0.
4918 This warning option also generates warnings if
4919 one or both tests is optimized away in a membership test for integer
4920 values if the result can be determined at compile time. Range tests on
4921 enumeration types are not included, since it is common for such tests
4922 to include an end point.
4924 This warning can also be turned on using @option{-gnatwa}.
4927 @emph{Suppress warnings on conditionals.}
4928 @cindex @option{-gnatwC} (@command{gcc})
4929 This switch suppresses warnings for conditional expressions used in
4930 tests that are known to be True or False at compile time.
4933 @emph{Activate warnings on missing component clauses.}
4934 @cindex @option{-gnatw.c} (@command{gcc})
4935 @cindex Component clause, missing
4936 This switch activates warnings for record components where a record
4937 representation clause is present and has component clauses for the
4938 majority, but not all, of the components. A warning is given for each
4939 component for which no component clause is present.
4942 @emph{Suppress warnings on missing component clauses.}
4943 @cindex @option{-gnatwC} (@command{gcc})
4944 This switch suppresses warnings for record components that are
4945 missing a component clause in the situation described above.
4948 @emph{Activate warnings on implicit dereferencing.}
4949 @cindex @option{-gnatwd} (@command{gcc})
4950 If this switch is set, then the use of a prefix of an access type
4951 in an indexed component, slice, or selected component without an
4952 explicit @code{.all} will generate a warning. With this warning
4953 enabled, access checks occur only at points where an explicit
4954 @code{.all} appears in the source code (assuming no warnings are
4955 generated as a result of this switch). The default is that such
4956 warnings are not generated.
4959 @emph{Suppress warnings on implicit dereferencing.}
4960 @cindex @option{-gnatwD} (@command{gcc})
4961 @cindex Implicit dereferencing
4962 @cindex Dereferencing, implicit
4963 This switch suppresses warnings for implicit dereferences in
4964 indexed components, slices, and selected components.
4967 @emph{Activate tagging of warning and info messages.}
4968 @cindex @option{-gnatw.d} (@command{gcc})
4969 If this switch is set, then warning messages are tagged, with one of the
4975 Used to tag warnings controlled by the switch @option{-gnatwx} where x
4979 Used to tag warnings controlled by the switch @option{-gnatw.x} where x
4983 Used to tag elaboration information (info) messages generated when the
4984 static model of elaboration is used and the @option{-gnatel} switch is set.
4986 @item [restriction warning]
4987 Used to tag warning messages for restriction violations, activated by use
4988 of the pragma @option{Restriction_Warnings}.
4990 @item [warning-as-error]
4991 Used to tag warning messages that have been converted to error messages by
4992 use of the pragma Warning_As_Error. Note that such warnings are prefixed by
4993 the string "error: " rather than "warning: ".
4995 @item [enabled by default]
4996 Used to tag all other warnings that are always given by default, unless
4997 warnings are completely suppressed using pragma @option{Warnings(Off)} or
4998 the switch @option{-gnatws}.
5003 @emph{Deactivate tagging of warning and info messages messages.}
5004 @cindex @option{-gnatw.d} (@command{gcc})
5005 If this switch is set, then warning messages return to the default
5006 mode in which warnings and info messages are not tagged as described above for
5010 @emph{Treat warnings and style checks as errors.}
5011 @cindex @option{-gnatwe} (@command{gcc})
5012 @cindex Warnings, treat as error
5013 This switch causes warning messages and style check messages to be
5015 The warning string still appears, but the warning messages are counted
5016 as errors, and prevent the generation of an object file. Note that this
5017 is the only -gnatw switch that affects the handling of style check messages.
5018 Note also that this switch has no effect on info (information) messages, which
5019 are not treated as errors if this switch is present.
5022 @emph{Activate every optional warning}
5023 @cindex @option{-gnatw.e} (@command{gcc})
5024 @cindex Warnings, activate every optional warning
5025 This switch activates all optional warnings, including those which
5026 are not activated by @code{-gnatwa}. The use of this switch is not
5027 recommended for normal use. If you turn this switch on, it is almost
5028 certain that you will get large numbers of useless warnings. The
5029 warnings that are excluded from @code{-gnatwa} are typically highly
5030 specialized warnings that are suitable for use only in code that has
5031 been specifically designed according to specialized coding rules.
5034 @emph{Activate warnings on unreferenced formals.}
5035 @cindex @option{-gnatwf} (@command{gcc})
5036 @cindex Formals, unreferenced
5037 This switch causes a warning to be generated if a formal parameter
5038 is not referenced in the body of the subprogram. This warning can
5039 also be turned on using @option{-gnatwu}. The
5040 default is that these warnings are not generated.
5043 @emph{Suppress warnings on unreferenced formals.}
5044 @cindex @option{-gnatwF} (@command{gcc})
5045 This switch suppresses warnings for unreferenced formal
5046 parameters. Note that the
5047 combination @option{-gnatwu} followed by @option{-gnatwF} has the
5048 effect of warning on unreferenced entities other than subprogram
5052 @emph{Activate warnings on unrecognized pragmas.}
5053 @cindex @option{-gnatwg} (@command{gcc})
5054 @cindex Pragmas, unrecognized
5055 This switch causes a warning to be generated if an unrecognized
5056 pragma is encountered. Apart from issuing this warning, the
5057 pragma is ignored and has no effect. The default
5058 is that such warnings are issued (satisfying the Ada Reference
5059 Manual requirement that such warnings appear).
5062 @emph{Suppress warnings on unrecognized pragmas.}
5063 @cindex @option{-gnatwG} (@command{gcc})
5064 This switch suppresses warnings for unrecognized pragmas.
5067 @emph{Warnings used for GNAT sources}
5068 @cindex @option{-gnatw.g} (@command{gcc})
5069 This switch sets the warning categories that are used by the standard
5070 GNAT style. Currently this is equivalent to
5071 @option{-gnatwAao.sI.C.V.X}
5072 but more warnings may be added in the future without advanced notice.
5075 @emph{Activate warnings on hiding.}
5076 @cindex @option{-gnatwh} (@command{gcc})
5077 @cindex Hiding of Declarations
5078 This switch activates warnings on hiding declarations.
5079 A declaration is considered hiding
5080 if it is for a non-overloadable entity, and it declares an entity with the
5081 same name as some other entity that is directly or use-visible. The default
5082 is that such warnings are not generated.
5085 @emph{Suppress warnings on hiding.}
5086 @cindex @option{-gnatwH} (@command{gcc})
5087 This switch suppresses warnings on hiding declarations.
5090 @emph{Activate warnings on holes/gaps in records.}
5091 @cindex @option{-gnatw.h} (@command{gcc})
5092 @cindex Record Representation (gaps)
5093 This switch activates warnings on component clauses in record
5094 representation clauses that leave holes (gaps) in the record layout.
5095 If this warning option is active, then record representation clauses
5096 should specify a contiguous layout, adding unused fill fields if needed.
5099 @emph{Suppress warnings on holes/gaps in records.}
5100 @cindex @option{-gnatw.H} (@command{gcc})
5101 This switch suppresses warnings on component clauses in record
5102 representation clauses that leave holes (haps) in the record layout.
5105 @emph{Activate warnings on implementation units.}
5106 @cindex @option{-gnatwi} (@command{gcc})
5107 This switch activates warnings for a @code{with} of an internal GNAT
5108 implementation unit, defined as any unit from the @code{Ada},
5109 @code{Interfaces}, @code{GNAT},
5111 hierarchies that is not
5112 documented in either the Ada Reference Manual or the GNAT
5113 Programmer's Reference Manual. Such units are intended only
5114 for internal implementation purposes and should not be @code{with}'ed
5115 by user programs. The default is that such warnings are generated
5118 @emph{Disable warnings on implementation units.}
5119 @cindex @option{-gnatwI} (@command{gcc})
5120 This switch disables warnings for a @code{with} of an internal GNAT
5121 implementation unit.
5124 @emph{Activate warnings on overlapping actuals.}
5125 @cindex @option{-gnatw.i} (@command{gcc})
5126 This switch enables a warning on statically detectable overlapping actuals in
5127 a subprogram call, when one of the actuals is an in-out parameter, and the
5128 types of the actuals are not by-copy types. This warning is off by default.
5131 @emph{Disable warnings on overlapping actuals.}
5132 @cindex @option{-gnatw.I} (@command{gcc})
5133 This switch disables warnings on overlapping actuals in a call..
5136 @emph{Activate warnings on obsolescent features (Annex J).}
5137 @cindex @option{-gnatwj} (@command{gcc})
5138 @cindex Features, obsolescent
5139 @cindex Obsolescent features
5140 If this warning option is activated, then warnings are generated for
5141 calls to subprograms marked with @code{pragma Obsolescent} and
5142 for use of features in Annex J of the Ada Reference Manual. In the
5143 case of Annex J, not all features are flagged. In particular use
5144 of the renamed packages (like @code{Text_IO}) and use of package
5145 @code{ASCII} are not flagged, since these are very common and
5146 would generate many annoying positive warnings. The default is that
5147 such warnings are not generated.
5149 In addition to the above cases, warnings are also generated for
5150 GNAT features that have been provided in past versions but which
5151 have been superseded (typically by features in the new Ada standard).
5152 For example, @code{pragma Ravenscar} will be flagged since its
5153 function is replaced by @code{pragma Profile(Ravenscar)}, and
5154 @code{pragma Interface_Name} will be flagged since its function
5155 is replaced by @code{pragma Import}.
5157 Note that this warning option functions differently from the
5158 restriction @code{No_Obsolescent_Features} in two respects.
5159 First, the restriction applies only to annex J features.
5160 Second, the restriction does flag uses of package @code{ASCII}.
5163 @emph{Suppress warnings on obsolescent features (Annex J).}
5164 @cindex @option{-gnatwJ} (@command{gcc})
5165 This switch disables warnings on use of obsolescent features.
5168 @emph{Activate warnings on variables that could be constants.}
5169 @cindex @option{-gnatwk} (@command{gcc})
5170 This switch activates warnings for variables that are initialized but
5171 never modified, and then could be declared constants. The default is that
5172 such warnings are not given.
5175 @emph{Suppress warnings on variables that could be constants.}
5176 @cindex @option{-gnatwK} (@command{gcc})
5177 This switch disables warnings on variables that could be declared constants.
5180 @emph{Activate warnings on redefinition of names in standard.}
5181 @cindex @option{-gnatw.k} (@command{gcc})
5182 This switch activates warnings for declarations that declare a name that
5183 is defined in package Standard. Such declarations can be confusing,
5184 especially since the names in package Standard continue to be directly
5185 visible, meaning that use visibiliy on such redeclared names does not
5186 work as expected. Names of discriminants and components in records are
5187 not included in this check.
5190 @emph{Suppress warnings on redefinition of names in standard.}
5191 @cindex @option{-gnatwK} (@command{gcc})
5192 This switch activates warnings for declarations that declare a name that
5193 is defined in package Standard.
5196 @emph{Activate warnings for elaboration pragmas.}
5197 @cindex @option{-gnatwl} (@command{gcc})
5198 @cindex Elaboration, warnings
5199 This switch activates warnings for possible elaboration problems,
5200 including suspicious use
5201 of @code{Elaborate} pragmas, when using the static elaboration model, and
5202 possible situations that may raise @code{Program_Error} when using the
5203 dynamic elaboration model.
5204 See the section in this guide on elaboration checking for further details.
5205 The default is that such warnings
5209 @emph{Suppress warnings for elaboration pragmas.}
5210 @cindex @option{-gnatwL} (@command{gcc})
5211 This switch suppresses warnings for possible elaboration problems.
5214 @emph{List inherited aspects.}
5215 @cindex @option{-gnatw.l} (@command{gcc})
5216 This switch causes the compiler to list inherited invariants,
5217 preconditions, and postconditions from Type_Invariant'Class, Invariant'Class,
5218 Pre'Class, and Post'Class aspects. Also list inherited subtype predicates.
5221 @emph{Suppress listing of inherited aspects.}
5222 @cindex @option{-gnatw.L} (@command{gcc})
5223 This switch suppresses listing of inherited aspects.
5226 @emph{Activate warnings on modified but unreferenced variables.}
5227 @cindex @option{-gnatwm} (@command{gcc})
5228 This switch activates warnings for variables that are assigned (using
5229 an initialization value or with one or more assignment statements) but
5230 whose value is never read. The warning is suppressed for volatile
5231 variables and also for variables that are renamings of other variables
5232 or for which an address clause is given.
5233 The default is that these warnings are not given.
5236 @emph{Disable warnings on modified but unreferenced variables.}
5237 @cindex @option{-gnatwM} (@command{gcc})
5238 This switch disables warnings for variables that are assigned or
5239 initialized, but never read.
5242 @emph{Activate warnings on suspicious modulus values.}
5243 @cindex @option{-gnatw.m} (@command{gcc})
5244 This switch activates warnings for modulus values that seem suspicious.
5245 The cases caught are where the size is the same as the modulus (e.g.
5246 a modulus of 7 with a size of 7 bits), and modulus values of 32 or 64
5247 with no size clause. The guess in both cases is that 2**x was intended
5248 rather than x. In addition expressions of the form 2*x for small x
5249 generate a warning (the almost certainly accurate guess being that
5250 2**x was intended). The default is that these warnings are given.
5253 @emph{Disable warnings on suspicious modulus values.}
5254 @cindex @option{-gnatw.M} (@command{gcc})
5255 This switch disables warnings for suspicious modulus values.
5258 @emph{Set normal warnings mode.}
5259 @cindex @option{-gnatwn} (@command{gcc})
5260 This switch sets normal warning mode, in which enabled warnings are
5261 issued and treated as warnings rather than errors. This is the default
5262 mode. the switch @option{-gnatwn} can be used to cancel the effect of
5263 an explicit @option{-gnatws} or
5264 @option{-gnatwe}. It also cancels the effect of the
5265 implicit @option{-gnatwe} that is activated by the
5266 use of @option{-gnatg}.
5269 @emph{Activate warnings on atomic synchronization.}
5270 @cindex @option{-gnatw.n} (@command{gcc})
5271 @cindex Atomic Synchronization, warnings
5272 This switch actives warnings when an access to an atomic variable
5273 requires the generation of atomic synchronization code. These
5274 warnings are off by default.
5276 @emph{Suppress warnings on atomic synchronization.}
5277 @cindex @option{-gnatw.n} (@command{gcc})
5278 @cindex Atomic Synchronization, warnings
5279 This switch suppresses warnings when an access to an atomic variable
5280 requires the generation of atomic synchronization code.
5283 @emph{Activate warnings on address clause overlays.}
5284 @cindex @option{-gnatwo} (@command{gcc})
5285 @cindex Address Clauses, warnings
5286 This switch activates warnings for possibly unintended initialization
5287 effects of defining address clauses that cause one variable to overlap
5288 another. The default is that such warnings are generated.
5291 @emph{Suppress warnings on address clause overlays.}
5292 @cindex @option{-gnatwO} (@command{gcc})
5293 This switch suppresses warnings on possibly unintended initialization
5294 effects of defining address clauses that cause one variable to overlap
5298 @emph{Activate warnings on modified but unreferenced out parameters.}
5299 @cindex @option{-gnatw.o} (@command{gcc})
5300 This switch activates warnings for variables that are modified by using
5301 them as actuals for a call to a procedure with an out mode formal, where
5302 the resulting assigned value is never read. It is applicable in the case
5303 where there is more than one out mode formal. If there is only one out
5304 mode formal, the warning is issued by default (controlled by -gnatwu).
5305 The warning is suppressed for volatile
5306 variables and also for variables that are renamings of other variables
5307 or for which an address clause is given.
5308 The default is that these warnings are not given.
5311 @emph{Disable warnings on modified but unreferenced out parameters.}
5312 @cindex @option{-gnatw.O} (@command{gcc})
5313 This switch suppresses warnings for variables that are modified by using
5314 them as actuals for a call to a procedure with an out mode formal, where
5315 the resulting assigned value is never read.
5318 @emph{Activate warnings on ineffective pragma Inlines.}
5319 @cindex @option{-gnatwp} (@command{gcc})
5320 @cindex Inlining, warnings
5321 This switch activates warnings for failure of front end inlining
5322 (activated by @option{-gnatN}) to inline a particular call. There are
5323 many reasons for not being able to inline a call, including most
5324 commonly that the call is too complex to inline. The default is
5325 that such warnings are not given.
5326 Warnings on ineffective inlining by the gcc back-end can be activated
5327 separately, using the gcc switch -Winline.
5330 @emph{Suppress warnings on ineffective pragma Inlines.}
5331 @cindex @option{-gnatwP} (@command{gcc})
5332 This switch suppresses warnings on ineffective pragma Inlines. If the
5333 inlining mechanism cannot inline a call, it will simply ignore the
5337 @emph{Activate warnings on parameter ordering.}
5338 @cindex @option{-gnatw.p} (@command{gcc})
5339 @cindex Parameter order, warnings
5340 This switch activates warnings for cases of suspicious parameter
5341 ordering when the list of arguments are all simple identifiers that
5342 match the names of the formals, but are in a different order. The
5343 warning is suppressed if any use of named parameter notation is used,
5344 so this is the appropriate way to suppress a false positive (and
5345 serves to emphasize that the "misordering" is deliberate). The
5346 default is that such warnings are not given.
5349 @emph{Suppress warnings on parameter ordering.}
5350 @cindex @option{-gnatw.P} (@command{gcc})
5351 This switch suppresses warnings on cases of suspicious parameter
5355 @emph{Activate warnings on questionable missing parentheses.}
5356 @cindex @option{-gnatwq} (@command{gcc})
5357 @cindex Parentheses, warnings
5358 This switch activates warnings for cases where parentheses are not used and
5359 the result is potential ambiguity from a readers point of view. For example
5360 (not a > b) when a and b are modular means ((not a) > b) and very likely the
5361 programmer intended (not (a > b)). Similarly (-x mod 5) means (-(x mod 5)) and
5362 quite likely ((-x) mod 5) was intended. In such situations it seems best to
5363 follow the rule of always parenthesizing to make the association clear, and
5364 this warning switch warns if such parentheses are not present. The default
5365 is that these warnings are given.
5368 @emph{Suppress warnings on questionable missing parentheses.}
5369 @cindex @option{-gnatwQ} (@command{gcc})
5370 This switch suppresses warnings for cases where the association is not
5371 clear and the use of parentheses is preferred.
5374 @emph{Activate warnings on redundant constructs.}
5375 @cindex @option{-gnatwr} (@command{gcc})
5376 This switch activates warnings for redundant constructs. The following
5377 is the current list of constructs regarded as redundant:
5381 Assignment of an item to itself.
5383 Type conversion that converts an expression to its own type.
5385 Use of the attribute @code{Base} where @code{typ'Base} is the same
5388 Use of pragma @code{Pack} when all components are placed by a record
5389 representation clause.
5391 Exception handler containing only a reraise statement (raise with no
5392 operand) which has no effect.
5394 Use of the operator abs on an operand that is known at compile time
5397 Comparison of boolean expressions to an explicit True value.
5400 The default is that warnings for redundant constructs are not given.
5403 @emph{Suppress warnings on redundant constructs.}
5404 @cindex @option{-gnatwR} (@command{gcc})
5405 This switch suppresses warnings for redundant constructs.
5408 @emph{Activate warnings for object renaming function.}
5409 @cindex @option{-gnatw.r} (@command{gcc})
5410 This switch activates warnings for an object renaming that renames a
5411 function call, which is equivalent to a constant declaration (as
5412 opposed to renaming the function itself). The default is that these
5416 @emph{Suppress warnings for object renaming function.}
5417 @cindex @option{-gnatwT} (@command{gcc})
5418 This switch suppresses warnings for object renaming function.
5421 @emph{Suppress all warnings.}
5422 @cindex @option{-gnatws} (@command{gcc})
5423 This switch completely suppresses the
5424 output of all warning messages from the GNAT front end, including
5425 both warnings that can be controlled by switches described in this
5426 section, and those that are normally given unconditionally. The
5427 effect of this suppress action can only be cancelled by a subsequent
5428 use of the switch @option{-gnatwn}.
5430 Note that switch @option{-gnatws} does not suppress
5431 warnings from the @command{gcc} back end.
5432 To suppress these back end warnings as well, use the switch @option{-w}
5433 in addition to @option{-gnatws}. Also this switch has no effect on the
5434 handling of style check messages.
5437 @emph{Activate warnings on overridden size clauses.}
5438 @cindex @option{-gnatw.s} (@command{gcc})
5439 @cindex Record Representation (component sizes)
5440 This switch activates warnings on component clauses in record
5441 representation clauses where the length given overrides that
5442 specified by an explicit size clause for the component type. A
5443 warning is similarly given in the array case if a specified
5444 component size overrides an explicit size clause for the array
5448 @emph{Suppress warnings on overridden size clauses.}
5449 @cindex @option{-gnatw.S} (@command{gcc})
5450 This switch suppresses warnings on component clauses in record
5451 representation clauses that override size clauses, and similar
5452 warnings when an array component size overrides a size clause.
5455 @emph{Activate warnings for tracking of deleted conditional code.}
5456 @cindex @option{-gnatwt} (@command{gcc})
5457 @cindex Deactivated code, warnings
5458 @cindex Deleted code, warnings
5459 This switch activates warnings for tracking of code in conditionals (IF and
5460 CASE statements) that is detected to be dead code which cannot be executed, and
5461 which is removed by the front end. This warning is off by default. This may be
5462 useful for detecting deactivated code in certified applications.
5465 @emph{Suppress warnings for tracking of deleted conditional code.}
5466 @cindex @option{-gnatwT} (@command{gcc})
5467 This switch suppresses warnings for tracking of deleted conditional code.
5470 @emph{Activate warnings on suspicious contracts.}
5471 @cindex @option{-gnatw.t} (@command{gcc})
5472 This switch activates warnings on suspicious postconditions (whether a
5473 pragma @code{Postcondition} or a @code{Post} aspect in Ada 2012)
5474 and suspicious contract cases (pragma @code{Contract_Cases}). A
5475 function postcondition or contract case is suspicious when no postcondition
5476 or contract case for this function mentions the result of the function.
5477 A procedure postcondition or contract case is suspicious when it only
5478 refers to the pre-state of the procedure, because in that case it should
5479 rather be expressed as a precondition. The default is that such warnings
5483 @emph{Suppress warnings on suspicious contracts.}
5484 @cindex @option{-gnatw.T} (@command{gcc})
5485 This switch suppresses warnings on suspicious postconditions.
5488 @emph{Activate warnings on unused entities.}
5489 @cindex @option{-gnatwu} (@command{gcc})
5490 This switch activates warnings to be generated for entities that
5491 are declared but not referenced, and for units that are @code{with}'ed
5493 referenced. In the case of packages, a warning is also generated if
5494 no entities in the package are referenced. This means that if a with'ed
5495 package is referenced but the only references are in @code{use}
5496 clauses or @code{renames}
5497 declarations, a warning is still generated. A warning is also generated
5498 for a generic package that is @code{with}'ed but never instantiated.
5499 In the case where a package or subprogram body is compiled, and there
5500 is a @code{with} on the corresponding spec
5501 that is only referenced in the body,
5502 a warning is also generated, noting that the
5503 @code{with} can be moved to the body. The default is that
5504 such warnings are not generated.
5505 This switch also activates warnings on unreferenced formals
5506 (it includes the effect of @option{-gnatwf}).
5509 @emph{Suppress warnings on unused entities.}
5510 @cindex @option{-gnatwU} (@command{gcc})
5511 This switch suppresses warnings for unused entities and packages.
5512 It also turns off warnings on unreferenced formals (and thus includes
5513 the effect of @option{-gnatwF}).
5516 @emph{Activate warnings on unordered enumeration types.}
5517 @cindex @option{-gnatw.u} (@command{gcc})
5518 This switch causes enumeration types to be considered as conceptually
5519 unordered, unless an explicit pragma @code{Ordered} is given for the type.
5520 The effect is to generate warnings in clients that use explicit comparisons
5521 or subranges, since these constructs both treat objects of the type as
5522 ordered. (A @emph{client} is defined as a unit that is other than the unit in
5523 which the type is declared, or its body or subunits.) Please refer to
5524 the description of pragma @code{Ordered} in the
5525 @cite{@value{EDITION} Reference Manual} for further details.
5526 The default is that such warnings are not generated.
5529 @emph{Deactivate warnings on unordered enumeration types.}
5530 @cindex @option{-gnatw.U} (@command{gcc})
5531 This switch causes all enumeration types to be considered as ordered, so
5532 that no warnings are given for comparisons or subranges for any type.
5535 @emph{Activate warnings on unassigned variables.}
5536 @cindex @option{-gnatwv} (@command{gcc})
5537 @cindex Unassigned variable warnings
5538 This switch activates warnings for access to variables which
5539 may not be properly initialized. The default is that
5540 such warnings are generated.
5543 @emph{Suppress warnings on unassigned variables.}
5544 @cindex @option{-gnatwV} (@command{gcc})
5545 This switch suppresses warnings for access to variables which
5546 may not be properly initialized.
5547 For variables of a composite type, the warning can also be suppressed in
5548 Ada 2005 by using a default initialization with a box. For example, if
5549 Table is an array of records whose components are only partially uninitialized,
5550 then the following code:
5552 @smallexample @c ada
5553 Tab : Table := (@b{others} => <>);
5556 will suppress warnings on subsequent statements that access components
5560 @emph{Activate info messages for non-default bit order.}
5561 @cindex @option{-gnatw.v} (@command{gcc})
5562 @cindex bit order warnings
5563 This switch activates messages (labeled "info", they are not warnings,
5564 just informational messages) about the effects of non-default bit-order
5565 on records to which a component clause is applied. The effect of specifying
5566 non-default bit ordering is a bit subtle (and changed with Ada 2005), so
5567 these messages, which are given by default, are useful in understanding the
5568 exact consequences of using this feature.
5571 @emph{Suppress info messages for non-default bit order.}
5572 @cindex @option{-gnatw.V} (@command{gcc})
5573 This switch suppresses information messages for the effects of specifying
5574 non-default bit order on record components with component clauses.
5577 @emph{Activate warnings on wrong low bound assumption.}
5578 @cindex @option{-gnatww} (@command{gcc})
5579 @cindex String indexing warnings
5580 This switch activates warnings for indexing an unconstrained string parameter
5581 with a literal or S'Length. This is a case where the code is assuming that the
5582 low bound is one, which is in general not true (for example when a slice is
5583 passed). The default is that such warnings are generated.
5586 @emph{Suppress warnings on wrong low bound assumption.}
5587 @cindex @option{-gnatwW} (@command{gcc})
5588 This switch suppresses warnings for indexing an unconstrained string parameter
5589 with a literal or S'Length. Note that this warning can also be suppressed
5590 in a particular case by adding an
5591 assertion that the lower bound is 1,
5592 as shown in the following example.
5594 @smallexample @c ada
5595 @b{procedure} K (S : String) @b{is}
5596 @b{pragma} Assert (S'First = 1);
5601 @emph{Activate warnings on Warnings Off pragmas}
5602 @cindex @option{-gnatw.w} (@command{gcc})
5603 @cindex Warnings Off control
5604 This switch activates warnings for use of @code{pragma Warnings (Off, entity)}
5605 where either the pragma is entirely useless (because it suppresses no
5606 warnings), or it could be replaced by @code{pragma Unreferenced} or
5607 @code{pragma Unmodified}.
5608 Also activates warnings for the case of
5609 Warnings (Off, String), where either there is no matching
5610 Warnings (On, String), or the Warnings (Off) did not suppress any warning.
5611 The default is that these warnings are not given.
5614 @emph{Suppress warnings on unnecessary Warnings Off pragmas}
5615 @cindex @option{-gnatw.W} (@command{gcc})
5616 This switch suppresses warnings for use of @code{pragma Warnings (Off, ...)}.
5619 @emph{Activate warnings on Export/Import pragmas.}
5620 @cindex @option{-gnatwx} (@command{gcc})
5621 @cindex Export/Import pragma warnings
5622 This switch activates warnings on Export/Import pragmas when
5623 the compiler detects a possible conflict between the Ada and
5624 foreign language calling sequences. For example, the use of
5625 default parameters in a convention C procedure is dubious
5626 because the C compiler cannot supply the proper default, so
5627 a warning is issued. The default is that such warnings are
5631 @emph{Suppress warnings on Export/Import pragmas.}
5632 @cindex @option{-gnatwX} (@command{gcc})
5633 This switch suppresses warnings on Export/Import pragmas.
5634 The sense of this is that you are telling the compiler that
5635 you know what you are doing in writing the pragma, and it
5636 should not complain at you.
5639 @emph{Activate warnings for No_Exception_Propagation mode.}
5640 @cindex @option{-gnatwm} (@command{gcc})
5641 This switch activates warnings for exception usage when pragma Restrictions
5642 (No_Exception_Propagation) is in effect. Warnings are given for implicit or
5643 explicit exception raises which are not covered by a local handler, and for
5644 exception handlers which do not cover a local raise. The default is that these
5645 warnings are not given.
5648 @emph{Disable warnings for No_Exception_Propagation mode.}
5649 This switch disables warnings for exception usage when pragma Restrictions
5650 (No_Exception_Propagation) is in effect.
5653 @emph{Activate warnings for Ada compatibility issues.}
5654 @cindex @option{-gnatwy} (@command{gcc})
5655 @cindex Ada compatibility issues warnings
5656 For the most part, newer versions of Ada are upwards compatible
5657 with older versions. For example, Ada 2005 programs will almost
5658 always work when compiled as Ada 2012.
5659 However there are some exceptions (for example the fact that
5660 @code{some} is now a reserved word in Ada 2012). This
5661 switch activates several warnings to help in identifying
5662 and correcting such incompatibilities. The default is that
5663 these warnings are generated. Note that at one point Ada 2005
5664 was called Ada 0Y, hence the choice of character.
5667 @emph{Disable warnings for Ada compatibility issues.}
5668 @cindex @option{-gnatwY} (@command{gcc})
5669 @cindex Ada compatibility issues warnings
5670 This switch suppresses the warnings intended to help in identifying
5671 incompatibilities between Ada language versions.
5674 @emph{Activate information messages for why package spec needs body}
5675 @cindex @option{-gnatw.y} (@command{gcc})
5676 @cindex Package spec needing body
5677 There are a number of cases in which a package spec needs a body.
5678 For example, the use of pragma Elaborate_Body, or the declaration
5679 of a procedure specification requiring a completion. This switch
5680 causes information messages to be output showing why a package
5681 specification requires a body. This can be useful in the case of
5682 a large package specification which is unexpectedly requiring a
5683 body. The default is that such information messages are not output.
5686 @emph{Disable information messages for why package spec needs body}
5687 @cindex @option{-gnatw.Y} (@command{gcc})
5688 @cindex No information messages for why package spec needs body
5689 This switch suppresses the output of information messages showing why
5690 a package specification needs a body.
5693 @emph{Activate warnings on unchecked conversions.}
5694 @cindex @option{-gnatwz} (@command{gcc})
5695 @cindex Unchecked_Conversion warnings
5696 This switch activates warnings for unchecked conversions
5697 where the types are known at compile time to have different
5699 is that such warnings are generated. Warnings are also
5700 generated for subprogram pointers with different conventions,
5701 and, on VMS only, for data pointers with different conventions.
5704 @emph{Suppress warnings on unchecked conversions.}
5705 @cindex @option{-gnatwZ} (@command{gcc})
5706 This switch suppresses warnings for unchecked conversions
5707 where the types are known at compile time to have different
5708 sizes or conventions.
5711 @emph{Activate warnings for size not a multiple of alignment.}
5712 @cindex @option{-gnatw.z} (@command{gcc})
5713 @cindex Size/Alignment warnings
5714 This switch activates warnings for cases of record types with
5715 specified @code{Size} and @code{Alignment} attributes where the
5716 size is not a multiple of the alignment, resulting in an object
5717 size that is greater than the specified size. The default
5718 is that such warnings are generated.
5721 @emph{Suppress warnings for size not a multiple of alignment.}
5722 @cindex @option{-gnatw.Z} (@command{gcc})
5723 @cindex Size/Alignment warnings
5724 This switch suppresses warnings for cases of record types with
5725 specified @code{Size} and @code{Alignment} attributes where the
5726 size is not a multiple of the alignment, resulting in an object
5727 size that is greater than the specified size.
5728 The warning can also be
5729 suppressed by giving an explicit @code{Object_Size} value.
5732 @cindex @option{-Wunused}
5733 The warnings controlled by the @option{-gnatw} switch are generated by
5734 the front end of the compiler. The @option{GCC} back end can provide
5735 additional warnings and they are controlled by the @option{-W} switch.
5736 For example, @option{-Wunused} activates back end
5737 warnings for entities that are declared but not referenced.
5739 @item -Wuninitialized
5740 @cindex @option{-Wuninitialized}
5741 Similarly, @option{-Wuninitialized} activates
5742 the back end warning for uninitialized variables. This switch must be
5743 used in conjunction with an optimization level greater than zero.
5745 @item -Wstack-usage=@var{len}
5746 @cindex @option{-Wstack-usage}
5747 Warn if the stack usage of a subprogram might be larger than @var{len} bytes.
5748 See @ref{Static Stack Usage Analysis} for details.
5751 @cindex @option{-Wall}
5752 This switch enables most warnings from the @option{GCC} back end.
5753 The code generator detects a number of warning situations that are missed
5754 by the @option{GNAT} front end, and this switch can be used to activate them.
5755 The use of this switch also sets the default front end warning mode to
5756 @option{-gnatwa}, that is, most front end warnings activated as well.
5760 Conversely, this switch suppresses warnings from the @option{GCC} back end.
5761 The use of this switch also sets the default front end warning mode to
5762 @option{-gnatws}, that is, front end warnings suppressed as well.
5765 @cindex @option{-Werror}
5766 This switch causes warnings from the @option{GCC} back end to be treated as
5767 errors. The warning string still appears, but the warning messages are
5768 counted as errors, and prevent the generation of an object file.
5773 A string of warning parameters can be used in the same parameter. For example:
5780 will turn on all optional warnings except for unrecognized pragma warnings,
5781 and also specify that warnings should be treated as errors.
5783 When no switch @option{-gnatw} is used, this is equivalent to:
5826 @node Debugging and Assertion Control
5827 @subsection Debugging and Assertion Control
5831 @cindex @option{-gnata} (@command{gcc})
5837 The pragmas @code{Assert} and @code{Debug} normally have no effect and
5838 are ignored. This switch, where @samp{a} stands for assert, causes
5839 @code{Assert} and @code{Debug} pragmas to be activated.
5841 The pragmas have the form:
5845 @b{pragma} Assert (@var{Boolean-expression} @r{[},
5846 @var{static-string-expression}@r{]})
5847 @b{pragma} Debug (@var{procedure call})
5852 The @code{Assert} pragma causes @var{Boolean-expression} to be tested.
5853 If the result is @code{True}, the pragma has no effect (other than
5854 possible side effects from evaluating the expression). If the result is
5855 @code{False}, the exception @code{Assert_Failure} declared in the package
5856 @code{System.Assertions} is
5857 raised (passing @var{static-string-expression}, if present, as the
5858 message associated with the exception). If no string expression is
5859 given the default is a string giving the file name and line number
5862 The @code{Debug} pragma causes @var{procedure} to be called. Note that
5863 @code{pragma Debug} may appear within a declaration sequence, allowing
5864 debugging procedures to be called between declarations.
5868 @node Validity Checking
5869 @subsection Validity Checking
5870 @findex Validity Checking
5873 The Ada Reference Manual defines the concept of invalid values (see
5874 RM 13.9.1). The primary source of invalid values is uninitialized
5875 variables. A scalar variable that is left uninitialized may contain
5876 an invalid value; the concept of invalid does not apply to access or
5879 It is an error to read an invalid value, but the RM does not require
5880 run-time checks to detect such errors, except for some minimal
5881 checking to prevent erroneous execution (i.e. unpredictable
5882 behavior). This corresponds to the @option{-gnatVd} switch below,
5883 which is the default. For example, by default, if the expression of a
5884 case statement is invalid, it will raise Constraint_Error rather than
5885 causing a wild jump, and if an array index on the left-hand side of an
5886 assignment is invalid, it will raise Constraint_Error rather than
5887 overwriting an arbitrary memory location.
5889 The @option{-gnatVa} may be used to enable additional validity checks,
5890 which are not required by the RM. These checks are often very
5891 expensive (which is why the RM does not require them). These checks
5892 are useful in tracking down uninitialized variables, but they are
5893 not usually recommended for production builds, and in particular
5894 we do not recommend using these extra validity checking options in
5895 combination with optimization, since this can confuse the optimizer.
5896 If performance is a consideration, leading to the need to optimize,
5897 then the validity checking options should not be used.
5899 The other @option{-gnatV@var{x}} switches below allow finer-grained
5900 control; you can enable whichever validity checks you desire. However,
5901 for most debugging purposes, @option{-gnatVa} is sufficient, and the
5902 default @option{-gnatVd} (i.e. standard Ada behavior) is usually
5903 sufficient for non-debugging use.
5905 The @option{-gnatB} switch tells the compiler to assume that all
5906 values are valid (that is, within their declared subtype range)
5907 except in the context of a use of the Valid attribute. This means
5908 the compiler can generate more efficient code, since the range
5909 of values is better known at compile time. However, an uninitialized
5910 variable can cause wild jumps and memory corruption in this mode.
5912 The @option{-gnatV@var{x}} switch allows control over the validity
5913 checking mode as described below.
5914 The @code{x} argument is a string of letters that
5915 indicate validity checks that are performed or not performed in addition
5916 to the default checks required by Ada as described above.
5921 @emph{All validity checks.}
5922 @cindex @option{-gnatVa} (@command{gcc})
5923 All validity checks are turned on.
5924 That is, @option{-gnatVa} is
5925 equivalent to @option{gnatVcdfimorst}.
5928 @emph{Validity checks for copies.}
5929 @cindex @option{-gnatVc} (@command{gcc})
5930 The right hand side of assignments, and the initializing values of
5931 object declarations are validity checked.
5934 @emph{Default (RM) validity checks.}
5935 @cindex @option{-gnatVd} (@command{gcc})
5936 Some validity checks are done by default following normal Ada semantics
5938 A check is done in case statements that the expression is within the range
5939 of the subtype. If it is not, Constraint_Error is raised.
5940 For assignments to array components, a check is done that the expression used
5941 as index is within the range. If it is not, Constraint_Error is raised.
5942 Both these validity checks may be turned off using switch @option{-gnatVD}.
5943 They are turned on by default. If @option{-gnatVD} is specified, a subsequent
5944 switch @option{-gnatVd} will leave the checks turned on.
5945 Switch @option{-gnatVD} should be used only if you are sure that all such
5946 expressions have valid values. If you use this switch and invalid values
5947 are present, then the program is erroneous, and wild jumps or memory
5948 overwriting may occur.
5951 @emph{Validity checks for elementary components.}
5952 @cindex @option{-gnatVe} (@command{gcc})
5953 In the absence of this switch, assignments to record or array components are
5954 not validity checked, even if validity checks for assignments generally
5955 (@option{-gnatVc}) are turned on. In Ada, assignment of composite values do not
5956 require valid data, but assignment of individual components does. So for
5957 example, there is a difference between copying the elements of an array with a
5958 slice assignment, compared to assigning element by element in a loop. This
5959 switch allows you to turn off validity checking for components, even when they
5960 are assigned component by component.
5963 @emph{Validity checks for floating-point values.}
5964 @cindex @option{-gnatVf} (@command{gcc})
5965 In the absence of this switch, validity checking occurs only for discrete
5966 values. If @option{-gnatVf} is specified, then validity checking also applies
5967 for floating-point values, and NaNs and infinities are considered invalid,
5968 as well as out of range values for constrained types. Note that this means
5969 that standard IEEE infinity mode is not allowed. The exact contexts
5970 in which floating-point values are checked depends on the setting of other
5971 options. For example,
5972 @option{-gnatVif} or
5974 (the order does not matter) specifies that floating-point parameters of mode
5975 @code{in} should be validity checked.
5978 @emph{Validity checks for @code{in} mode parameters}
5979 @cindex @option{-gnatVi} (@command{gcc})
5980 Arguments for parameters of mode @code{in} are validity checked in function
5981 and procedure calls at the point of call.
5984 @emph{Validity checks for @code{in out} mode parameters.}
5985 @cindex @option{-gnatVm} (@command{gcc})
5986 Arguments for parameters of mode @code{in out} are validity checked in
5987 procedure calls at the point of call. The @code{'m'} here stands for
5988 modify, since this concerns parameters that can be modified by the call.
5989 Note that there is no specific option to test @code{out} parameters,
5990 but any reference within the subprogram will be tested in the usual
5991 manner, and if an invalid value is copied back, any reference to it
5992 will be subject to validity checking.
5995 @emph{No validity checks.}
5996 @cindex @option{-gnatVn} (@command{gcc})
5997 This switch turns off all validity checking, including the default checking
5998 for case statements and left hand side subscripts. Note that the use of
5999 the switch @option{-gnatp} suppresses all run-time checks, including
6000 validity checks, and thus implies @option{-gnatVn}. When this switch
6001 is used, it cancels any other @option{-gnatV} previously issued.
6004 @emph{Validity checks for operator and attribute operands.}
6005 @cindex @option{-gnatVo} (@command{gcc})
6006 Arguments for predefined operators and attributes are validity checked.
6007 This includes all operators in package @code{Standard},
6008 the shift operators defined as intrinsic in package @code{Interfaces}
6009 and operands for attributes such as @code{Pos}. Checks are also made
6010 on individual component values for composite comparisons, and on the
6011 expressions in type conversions and qualified expressions. Checks are
6012 also made on explicit ranges using @samp{..} (e.g.@: slices, loops etc).
6015 @emph{Validity checks for parameters.}
6016 @cindex @option{-gnatVp} (@command{gcc})
6017 This controls the treatment of parameters within a subprogram (as opposed
6018 to @option{-gnatVi} and @option{-gnatVm} which control validity testing
6019 of parameters on a call. If either of these call options is used, then
6020 normally an assumption is made within a subprogram that the input arguments
6021 have been validity checking at the point of call, and do not need checking
6022 again within a subprogram). If @option{-gnatVp} is set, then this assumption
6023 is not made, and parameters are not assumed to be valid, so their validity
6024 will be checked (or rechecked) within the subprogram.
6027 @emph{Validity checks for function returns.}
6028 @cindex @option{-gnatVr} (@command{gcc})
6029 The expression in @code{return} statements in functions is validity
6033 @emph{Validity checks for subscripts.}
6034 @cindex @option{-gnatVs} (@command{gcc})
6035 All subscripts expressions are checked for validity, whether they appear
6036 on the right side or left side (in default mode only left side subscripts
6037 are validity checked).
6040 @emph{Validity checks for tests.}
6041 @cindex @option{-gnatVt} (@command{gcc})
6042 Expressions used as conditions in @code{if}, @code{while} or @code{exit}
6043 statements are checked, as well as guard expressions in entry calls.
6048 The @option{-gnatV} switch may be followed by
6050 to turn on a series of validity checking options.
6053 specifies that in addition to the default validity checking, copies and
6054 function return expressions are to be validity checked.
6055 In order to make it easier
6056 to specify the desired combination of effects,
6057 the upper case letters @code{CDFIMORST} may
6058 be used to turn off the corresponding lower case option.
6061 turns on all validity checking options except for
6062 checking of @code{@b{in out}} procedure arguments.
6064 The specification of additional validity checking generates extra code (and
6065 in the case of @option{-gnatVa} the code expansion can be substantial).
6066 However, these additional checks can be very useful in detecting
6067 uninitialized variables, incorrect use of unchecked conversion, and other
6068 errors leading to invalid values. The use of pragma @code{Initialize_Scalars}
6069 is useful in conjunction with the extra validity checking, since this
6070 ensures that wherever possible uninitialized variables have invalid values.
6072 See also the pragma @code{Validity_Checks} which allows modification of
6073 the validity checking mode at the program source level, and also allows for
6074 temporary disabling of validity checks.
6076 @node Style Checking
6077 @subsection Style Checking
6078 @findex Style checking
6081 The @option{-gnatyx} switch
6082 @cindex @option{-gnaty} (@command{gcc})
6083 causes the compiler to
6084 enforce specified style rules. A limited set of style rules has been used
6085 in writing the GNAT sources themselves. This switch allows user programs
6086 to activate all or some of these checks. If the source program fails a
6087 specified style check, an appropriate message is given, preceded by
6088 the character sequence ``(style)''. This message does not prevent
6089 successful compilation (unless the @option{-gnatwe} switch is used).
6091 Note that this is by no means intended to be a general facility for
6092 checking arbitrary coding standards. It is simply an embedding of the
6093 style rules we have chosen for the GNAT sources. If you are starting
6094 a project which does not have established style standards, you may
6095 find it useful to adopt the entire set of GNAT coding standards, or
6096 some subset of them.
6098 If you already have an established set of coding
6099 standards, then the selected style checking options may
6100 indeed correspond to choices you have made, but for general checking
6101 of an existing set of coding rules, you should look to the gnatcheck
6102 tool, which is designed for that purpose.
6105 The string @var{x} is a sequence of letters or digits
6106 indicating the particular style
6107 checks to be performed. The following checks are defined:
6112 @emph{Specify indentation level.}
6113 If a digit from 1-9 appears
6114 in the string after @option{-gnaty}
6115 then proper indentation is checked, with the digit indicating the
6116 indentation level required. A value of zero turns off this style check.
6117 The general style of required indentation is as specified by
6118 the examples in the Ada Reference Manual. Full line comments must be
6119 aligned with the @code{--} starting on a column that is a multiple of
6120 the alignment level, or they may be aligned the same way as the following
6121 non-blank line (this is useful when full line comments appear in the middle
6122 of a statement, or they may be aligned with the source line on the previous
6126 @emph{Check attribute casing.}
6127 Attribute names, including the case of keywords such as @code{digits}
6128 used as attributes names, must be written in mixed case, that is, the
6129 initial letter and any letter following an underscore must be uppercase.
6130 All other letters must be lowercase.
6133 @emph{Use of array index numbers in array attributes.}
6134 When using the array attributes First, Last, Range,
6135 or Length, the index number must be omitted for one-dimensional arrays
6136 and is required for multi-dimensional arrays.
6139 @emph{Blanks not allowed at statement end.}
6140 Trailing blanks are not allowed at the end of statements. The purpose of this
6141 rule, together with h (no horizontal tabs), is to enforce a canonical format
6142 for the use of blanks to separate source tokens.
6145 @emph{Check Boolean operators.}
6146 The use of AND/OR operators is not permitted except in the cases of modular
6147 operands, array operands, and simple stand-alone boolean variables or
6148 boolean constants. In all other cases @code{and then}/@code{or else} are
6152 @emph{Check comments, double space.}
6153 Comments must meet the following set of rules:
6158 The ``@code{--}'' that starts the column must either start in column one,
6159 or else at least one blank must precede this sequence.
6162 Comments that follow other tokens on a line must have at least one blank
6163 following the ``@code{--}'' at the start of the comment.
6166 Full line comments must have at least two blanks following the
6167 ``@code{--}'' that starts the comment, with the following exceptions.
6170 A line consisting only of the ``@code{--}'' characters, possibly preceded
6171 by blanks is permitted.
6174 A comment starting with ``@code{--x}'' where @code{x} is a special character
6176 This allows proper processing of the output generated by specialized tools
6177 including @command{gnatprep} (where ``@code{--!}'' is used) and the SPARK
6179 language (where ``@code{--#}'' is used). For the purposes of this rule, a
6180 special character is defined as being in one of the ASCII ranges
6181 @code{16#21#@dots{}16#2F#} or @code{16#3A#@dots{}16#3F#}.
6182 Note that this usage is not permitted
6183 in GNAT implementation units (i.e., when @option{-gnatg} is used).
6186 A line consisting entirely of minus signs, possibly preceded by blanks, is
6187 permitted. This allows the construction of box comments where lines of minus
6188 signs are used to form the top and bottom of the box.
6191 A comment that starts and ends with ``@code{--}'' is permitted as long as at
6192 least one blank follows the initial ``@code{--}''. Together with the preceding
6193 rule, this allows the construction of box comments, as shown in the following
6196 ---------------------------
6197 -- This is a box comment --
6198 -- with two text lines. --
6199 ---------------------------
6204 @emph{Check comments, single space.}
6205 This is identical to @code{c} except that only one space
6206 is required following the @code{--} of a comment instead of two.
6209 @emph{Check no DOS line terminators present.}
6210 All lines must be terminated by a single ASCII.LF
6211 character (in particular the DOS line terminator sequence CR/LF is not
6215 @emph{Check end/exit labels.}
6216 Optional labels on @code{end} statements ending subprograms and on
6217 @code{exit} statements exiting named loops, are required to be present.
6220 @emph{No form feeds or vertical tabs.}
6221 Neither form feeds nor vertical tab characters are permitted
6225 @emph{GNAT style mode.}
6226 The set of style check switches is set to match that used by the GNAT sources.
6227 This may be useful when developing code that is eventually intended to be
6228 incorporated into GNAT. Currently this is equivalent to @option{-gnatwydISux})
6229 but additional style switches may be added to this set in the future without
6233 @emph{No horizontal tabs.}
6234 Horizontal tab characters are not permitted in the source text.
6235 Together with the b (no blanks at end of line) check, this
6236 enforces a canonical form for the use of blanks to separate
6240 @emph{Check if-then layout.}
6241 The keyword @code{then} must appear either on the same
6242 line as corresponding @code{if}, or on a line on its own, lined
6243 up under the @code{if}.
6246 @emph{check mode IN keywords.}
6247 Mode @code{in} (the default mode) is not
6248 allowed to be given explicitly. @code{in out} is fine,
6249 but not @code{in} on its own.
6252 @emph{Check keyword casing.}
6253 All keywords must be in lower case (with the exception of keywords
6254 such as @code{digits} used as attribute names to which this check
6258 @emph{Check layout.}
6259 Layout of statement and declaration constructs must follow the
6260 recommendations in the Ada Reference Manual, as indicated by the
6261 form of the syntax rules. For example an @code{else} keyword must
6262 be lined up with the corresponding @code{if} keyword.
6264 There are two respects in which the style rule enforced by this check
6265 option are more liberal than those in the Ada Reference Manual. First
6266 in the case of record declarations, it is permissible to put the
6267 @code{record} keyword on the same line as the @code{type} keyword, and
6268 then the @code{end} in @code{end record} must line up under @code{type}.
6269 This is also permitted when the type declaration is split on two lines.
6270 For example, any of the following three layouts is acceptable:
6272 @smallexample @c ada
6274 @b{type} q @b{is} @b{record}
6295 Second, in the case of a block statement, a permitted alternative
6296 is to put the block label on the same line as the @code{declare} or
6297 @code{begin} keyword, and then line the @code{end} keyword up under
6298 the block label. For example both the following are permitted:
6300 @smallexample @c ada
6318 The same alternative format is allowed for loops. For example, both of
6319 the following are permitted:
6321 @smallexample @c ada
6323 Clear : @b{while} J < 10 @b{loop}
6325 @b{end} @b{loop} Clear;
6328 @b{while} J < 10 @b{loop}
6330 @b{end} @b{loop} Clear;
6335 @emph{Set maximum nesting level.}
6336 The maximum level of nesting of constructs (including subprograms, loops,
6337 blocks, packages, and conditionals) may not exceed the given value
6338 @option{nnn}. A value of zero disconnects this style check.
6341 @emph{Check maximum line length.}
6342 The length of source lines must not exceed 79 characters, including
6343 any trailing blanks. The value of 79 allows convenient display on an
6344 80 character wide device or window, allowing for possible special
6345 treatment of 80 character lines. Note that this count is of
6346 characters in the source text. This means that a tab character counts
6347 as one character in this count and a wide character sequence counts as
6348 a single character (however many bytes are needed in the encoding).
6351 @emph{Set maximum line length.}
6352 The length of lines must not exceed the
6353 given value @option{nnn}. The maximum value that can be specified is 32767.
6354 If neither style option for setting the line length is used, then the
6355 default is 255. This also controls the maximum length of lexical elements,
6356 where the only restriction is that they must fit on a single line.
6359 @emph{Check casing of entities in Standard.}
6360 Any identifier from Standard must be cased
6361 to match the presentation in the Ada Reference Manual (for example,
6362 @code{Integer} and @code{ASCII.NUL}).
6365 @emph{Turn off all style checks.}
6366 All style check options are turned off.
6369 @emph{Check order of subprogram bodies.}
6370 All subprogram bodies in a given scope
6371 (e.g.@: a package body) must be in alphabetical order. The ordering
6372 rule uses normal Ada rules for comparing strings, ignoring casing
6373 of letters, except that if there is a trailing numeric suffix, then
6374 the value of this suffix is used in the ordering (e.g.@: Junk2 comes
6378 @emph{Check that overriding subprograms are explicitly marked as such.}
6379 The declaration of a primitive operation of a type extension that overrides
6380 an inherited operation must carry an overriding indicator.
6383 @emph{Check pragma casing.}
6384 Pragma names must be written in mixed case, that is, the
6385 initial letter and any letter following an underscore must be uppercase.
6386 All other letters must be lowercase. An exception is that SPARK_Mode is
6387 allowed as an alternative for Spark_Mode.
6390 @emph{Check references.}
6391 All identifier references must be cased in the same way as the
6392 corresponding declaration. No specific casing style is imposed on
6393 identifiers. The only requirement is for consistency of references
6397 @emph{Check separate specs.}
6398 Separate declarations (``specs'') are required for subprograms (a
6399 body is not allowed to serve as its own declaration). The only
6400 exception is that parameterless library level procedures are
6401 not required to have a separate declaration. This exception covers
6402 the most frequent form of main program procedures.
6405 @emph{Check no statements after @code{then}/@code{else}.}
6406 No statements are allowed
6407 on the same line as a @code{then} or @code{else} keyword following the
6408 keyword in an @code{if} statement. @code{or else} and @code{and then} are not
6409 affected, and a special exception allows a pragma to appear after @code{else}.
6412 @emph{Check token spacing.}
6413 The following token spacing rules are enforced:
6418 The keywords @code{abs} and @code{not} must be followed by a space.
6421 The token @code{=>} must be surrounded by spaces.
6424 The token @code{<>} must be preceded by a space or a left parenthesis.
6427 Binary operators other than @code{**} must be surrounded by spaces.
6428 There is no restriction on the layout of the @code{**} binary operator.
6431 Colon must be surrounded by spaces.
6434 Colon-equal (assignment, initialization) must be surrounded by spaces.
6437 Comma must be the first non-blank character on the line, or be
6438 immediately preceded by a non-blank character, and must be followed
6442 If the token preceding a left parenthesis ends with a letter or digit, then
6443 a space must separate the two tokens.
6446 if the token following a right parenthesis starts with a letter or digit, then
6447 a space must separate the two tokens.
6450 A right parenthesis must either be the first non-blank character on
6451 a line, or it must be preceded by a non-blank character.
6454 A semicolon must not be preceded by a space, and must not be followed by
6455 a non-blank character.
6458 A unary plus or minus may not be followed by a space.
6461 A vertical bar must be surrounded by spaces.
6464 Exactly one blank (and no other white space) must appear between
6465 a @code{not} token and a following @code{in} token.
6468 @emph{Check unnecessary blank lines.}
6469 Unnecessary blank lines are not allowed. A blank line is considered
6470 unnecessary if it appears at the end of the file, or if more than
6471 one blank line occurs in sequence.
6474 @emph{Check extra parentheses.}
6475 Unnecessary extra level of parentheses (C-style) are not allowed
6476 around conditions in @code{if} statements, @code{while} statements and
6477 @code{exit} statements.
6480 @emph{Set all standard style check options}
6481 This is equivalent to @code{gnaty3aAbcefhiklmnprst}, that is all checking
6482 options enabled with the exception of @option{-gnatyB}, @option{-gnatyd},
6483 @option{-gnatyI}, @option{-gnatyLnnn}, @option{-gnatyo}, @option{-gnatyO},
6484 @option{-gnatyS}, @option{-gnatyu}, and @option{-gnatyx}.
6487 @emph{Remove style check options}
6488 This causes any subsequent options in the string to act as canceling the
6489 corresponding style check option. To cancel maximum nesting level control,
6490 use @option{L} parameter witout any integer value after that, because any
6491 digit following @option{-} in the parameter string of the @option{-gnaty}
6492 option will be threated as canceling indentation check. The same is true
6493 for @option{M} parameter. @option{y} and @option{N} parameters are not
6494 allowed after @option{-}.
6497 This causes any subsequent options in the string to enable the corresponding
6498 style check option. That is, it cancels the effect of a previous -,
6504 In the above rules, appearing in column one is always permitted, that is,
6505 counts as meeting either a requirement for a required preceding space,
6506 or as meeting a requirement for no preceding space.
6508 Appearing at the end of a line is also always permitted, that is, counts
6509 as meeting either a requirement for a following space, or as meeting
6510 a requirement for no following space.
6513 If any of these style rules is violated, a message is generated giving
6514 details on the violation. The initial characters of such messages are
6515 always ``@code{(style)}''. Note that these messages are treated as warning
6516 messages, so they normally do not prevent the generation of an object
6517 file. The @option{-gnatwe} switch can be used to treat warning messages,
6518 including style messages, as fatal errors.
6521 @option{-gnaty} on its own (that is not
6522 followed by any letters or digits) is equivalent
6523 to the use of @option{-gnatyy} as described above, that is all
6524 built-in standard style check options are enabled.
6529 clears any previously set style checks.
6531 @node Run-Time Checks
6532 @subsection Run-Time Checks
6533 @cindex Division by zero
6534 @cindex Access before elaboration
6535 @cindex Checks, division by zero
6536 @cindex Checks, access before elaboration
6537 @cindex Checks, stack overflow checking
6540 By default, the following checks are suppressed: integer overflow
6541 checks, stack overflow checks, and checks for access before
6542 elaboration on subprogram calls. All other checks, including range
6543 checks and array bounds checks, are turned on by default. The
6544 following @command{gcc} switches refine this default behavior.
6549 @cindex @option{-gnatp} (@command{gcc})
6550 @cindex Suppressing checks
6551 @cindex Checks, suppressing
6553 This switch causes the unit to be compiled
6554 as though @code{pragma Suppress (All_checks)}
6555 had been present in the source. Validity checks are also eliminated (in
6556 other words @option{-gnatp} also implies @option{-gnatVn}.
6557 Use this switch to improve the performance
6558 of the code at the expense of safety in the presence of invalid data or
6561 Note that when checks are suppressed, the compiler is allowed, but not
6562 required, to omit the checking code. If the run-time cost of the
6563 checking code is zero or near-zero, the compiler will generate it even
6564 if checks are suppressed. In particular, if the compiler can prove
6565 that a certain check will necessarily fail, it will generate code to
6566 do an unconditional ``raise'', even if checks are suppressed. The
6567 compiler warns in this case. Another case in which checks may not be
6568 eliminated is when they are embedded in certain run time routines such
6569 as math library routines.
6571 Of course, run-time checks are omitted whenever the compiler can prove
6572 that they will not fail, whether or not checks are suppressed.
6574 Note that if you suppress a check that would have failed, program
6575 execution is erroneous, which means the behavior is totally
6576 unpredictable. The program might crash, or print wrong answers, or
6577 do anything else. It might even do exactly what you wanted it to do
6578 (and then it might start failing mysteriously next week or next
6579 year). The compiler will generate code based on the assumption that
6580 the condition being checked is true, which can result in erroneous
6581 execution if that assumption is wrong.
6583 The checks subject to suppression include all the checks defined by
6584 the Ada standard, the additional implementation defined checks
6585 @code{Alignment_Check},
6586 @code{Duplicated_Tag_Check}, @code{Predicate_Check}, and
6587 @code{Validity_Check}, as well as any checks introduced using
6588 @code{pragma Check_Name}. Note that @code{Atomic_Synchronization}
6589 is not automatically suppressed by use of this option.
6591 If the code depends on certain checks being active, you can use
6592 pragma @code{Unsuppress} either as a configuration pragma or as
6593 a local pragma to make sure that a specified check is performed
6594 even if @option{gnatp} is specified.
6596 The @option{-gnatp} switch has no effect if a subsequent
6597 @option{-gnat-p} switch appears.
6600 @cindex @option{-gnat-p} (@command{gcc})
6601 @cindex Suppressing checks
6602 @cindex Checks, suppressing
6604 This switch cancels the effect of a previous @option{gnatp} switch.
6607 @cindex @option{-gnato??} (@command{gcc})
6608 @cindex Overflow checks
6609 @cindex Overflow mode
6610 @cindex Check, overflow
6611 This switch controls the mode used for computing intermediate
6612 arithmetic integer operations, and also enables overflow checking.
6613 For a full description of overflow mode and checking control, see
6614 the ``Overflow Check Handling in GNAT'' appendix in this
6617 Overflow checks are always enabled by this switch. The argument
6618 controls the mode, using the codes
6622 In STRICT mode, intermediate operations are always done using the
6623 base type, and overflow checking ensures that the result is within
6624 the base type range.
6627 In MINIMIZED mode, overflows in intermediate operations are avoided
6628 where possible by using a larger integer type for the computation
6629 (typically @code{Long_Long_Integer}). Overflow checking ensures that
6630 the result fits in this larger integer type.
6632 @item 3 = ELIMINATED
6633 In ELIMINATED mode, overflows in intermediate operations are avoided
6634 by using multi-precision arithmetic. In this case, overflow checking
6635 has no effect on intermediate operations (since overflow is impossible).
6638 If two digits are present after @option{-gnato} then the first digit
6639 sets the mode for expressions outside assertions, and the second digit
6640 sets the mode for expressions within assertions. Here assertions is used
6641 in the technical sense (which includes for example precondition and
6642 postcondition expressions).
6644 If one digit is present, the corresponding mode is applicable to both
6645 expressions within and outside assertion expressions.
6647 If no digits are present, the default is to enable overflow checks
6648 and set STRICT mode for both kinds of expressions. This is compatible
6649 with the use of @option{-gnato} in previous versions of GNAT.
6651 @findex Machine_Overflows
6652 Note that the @option{-gnato??} switch does not affect the code generated
6653 for any floating-point operations; it applies only to integer semantics.
6654 For floating-point, @value{EDITION} has the @code{Machine_Overflows}
6655 attribute set to @code{False} and the normal mode of operation is to
6656 generate IEEE NaN and infinite values on overflow or invalid operations
6657 (such as dividing 0.0 by 0.0).
6659 The reason that we distinguish overflow checking from other kinds of
6660 range constraint checking is that a failure of an overflow check, unlike
6661 for example the failure of a range check, can result in an incorrect
6662 value, but cannot cause random memory destruction (like an out of range
6663 subscript), or a wild jump (from an out of range case value). Overflow
6664 checking is also quite expensive in time and space, since in general it
6665 requires the use of double length arithmetic.
6667 Note again that the default is @option{-gnato00},
6668 so overflow checking is not performed in default mode. This means that out of
6669 the box, with the default settings, @value{EDITION} does not do all the checks
6670 expected from the language description in the Ada Reference Manual.
6671 If you want all constraint checks to be performed, as described in this Manual,
6672 then you must explicitly use the @option{-gnato??}
6673 switch either on the @command{gnatmake} or @command{gcc} command.
6676 @cindex @option{-gnatE} (@command{gcc})
6677 @cindex Elaboration checks
6678 @cindex Check, elaboration
6679 Enables dynamic checks for access-before-elaboration
6680 on subprogram calls and generic instantiations.
6681 Note that @option{-gnatE} is not necessary for safety, because in the
6682 default mode, GNAT ensures statically that the checks would not fail.
6683 For full details of the effect and use of this switch,
6684 @xref{Compiling with gcc}.
6687 @cindex @option{-fstack-check} (@command{gcc})
6688 @cindex Stack Overflow Checking
6689 @cindex Checks, stack overflow checking
6690 Activates stack overflow checking. For full details of the effect and use of
6691 this switch see @ref{Stack Overflow Checking}.
6696 The setting of these switches only controls the default setting of the
6697 checks. You may modify them using either @code{Suppress} (to remove
6698 checks) or @code{Unsuppress} (to add back suppressed checks) pragmas in
6701 @node Using gcc for Syntax Checking
6702 @subsection Using @command{gcc} for Syntax Checking
6705 @cindex @option{-gnats} (@command{gcc})
6708 The @code{s} stands for ``syntax''.
6710 Run GNAT in syntax checking only mode. For
6711 example, the command
6714 $ gcc -c -gnats x.adb
6718 compiles file @file{x.adb} in syntax-check-only mode. You can check a
6719 series of files in a single command
6720 , and can use wild cards to specify such a group of files.
6721 Note that you must specify the @option{-c} (compile
6722 only) flag in addition to the @option{-gnats} flag.
6724 You may use other switches in conjunction with @option{-gnats}. In
6725 particular, @option{-gnatl} and @option{-gnatv} are useful to control the
6726 format of any generated error messages.
6728 When the source file is empty or contains only empty lines and/or comments,
6729 the output is a warning:
6732 $ gcc -c -gnats -x ada toto.txt
6733 toto.txt:1:01: warning: empty file, contains no compilation units
6737 Otherwise, the output is simply the error messages, if any. No object file or
6738 ALI file is generated by a syntax-only compilation. Also, no units other
6739 than the one specified are accessed. For example, if a unit @code{X}
6740 @code{with}'s a unit @code{Y}, compiling unit @code{X} in syntax
6741 check only mode does not access the source file containing unit
6744 @cindex Multiple units, syntax checking
6745 Normally, GNAT allows only a single unit in a source file. However, this
6746 restriction does not apply in syntax-check-only mode, and it is possible
6747 to check a file containing multiple compilation units concatenated
6748 together. This is primarily used by the @code{gnatchop} utility
6749 (@pxref{Renaming Files with gnatchop}).
6752 @node Using gcc for Semantic Checking
6753 @subsection Using @command{gcc} for Semantic Checking
6756 @cindex @option{-gnatc} (@command{gcc})
6759 The @code{c} stands for ``check''.
6760 Causes the compiler to operate in semantic check mode,
6761 with full checking for all illegalities specified in the
6762 Ada Reference Manual, but without generation of any object code
6763 (no object file is generated).
6765 Because dependent files must be accessed, you must follow the GNAT
6766 semantic restrictions on file structuring to operate in this mode:
6770 The needed source files must be accessible
6771 (@pxref{Search Paths and the Run-Time Library (RTL)}).
6774 Each file must contain only one compilation unit.
6777 The file name and unit name must match (@pxref{File Naming Rules}).
6780 The output consists of error messages as appropriate. No object file is
6781 generated. An @file{ALI} file is generated for use in the context of
6782 cross-reference tools, but this file is marked as not being suitable
6783 for binding (since no object file is generated).
6784 The checking corresponds exactly to the notion of
6785 legality in the Ada Reference Manual.
6787 Any unit can be compiled in semantics-checking-only mode, including
6788 units that would not normally be compiled (subunits,
6789 and specifications where a separate body is present).
6792 @node Compiling Different Versions of Ada
6793 @subsection Compiling Different Versions of Ada
6796 The switches described in this section allow you to explicitly specify
6797 the version of the Ada language that your programs are written in.
6798 The default mode is Ada 2012,
6799 but you can also specify Ada 95, Ada 2005 mode, or
6800 indicate Ada 83 compatibility mode.
6803 @cindex Compatibility with Ada 83
6805 @item -gnat83 (Ada 83 Compatibility Mode)
6806 @cindex @option{-gnat83} (@command{gcc})
6807 @cindex ACVC, Ada 83 tests
6811 Although GNAT is primarily an Ada 95 / Ada 2005 compiler, this switch
6812 specifies that the program is to be compiled in Ada 83 mode. With
6813 @option{-gnat83}, GNAT rejects most post-Ada 83 extensions and applies Ada 83
6814 semantics where this can be done easily.
6815 It is not possible to guarantee this switch does a perfect
6816 job; some subtle tests, such as are
6817 found in earlier ACVC tests (and that have been removed from the ACATS suite
6818 for Ada 95), might not compile correctly.
6819 Nevertheless, this switch may be useful in some circumstances, for example
6820 where, due to contractual reasons, existing code needs to be maintained
6821 using only Ada 83 features.
6823 With few exceptions (most notably the need to use @code{<>} on
6824 @cindex Generic formal parameters
6825 unconstrained generic formal parameters, the use of the new Ada 95 / Ada 2005
6826 reserved words, and the use of packages
6827 with optional bodies), it is not necessary to specify the
6828 @option{-gnat83} switch when compiling Ada 83 programs, because, with rare
6829 exceptions, Ada 95 and Ada 2005 are upwardly compatible with Ada 83. Thus
6830 a correct Ada 83 program is usually also a correct program
6831 in these later versions of the language standard.
6832 For further information, please refer to @ref{Compatibility and Porting Guide}.
6834 @item -gnat95 (Ada 95 mode)
6835 @cindex @option{-gnat95} (@command{gcc})
6839 This switch directs the compiler to implement the Ada 95 version of the
6841 Since Ada 95 is almost completely upwards
6842 compatible with Ada 83, Ada 83 programs may generally be compiled using
6843 this switch (see the description of the @option{-gnat83} switch for further
6844 information about Ada 83 mode).
6845 If an Ada 2005 program is compiled in Ada 95 mode,
6846 uses of the new Ada 2005 features will cause error
6847 messages or warnings.
6849 This switch also can be used to cancel the effect of a previous
6850 @option{-gnat83}, @option{-gnat05/2005}, or @option{-gnat12/2012}
6851 switch earlier in the command line.
6853 @item -gnat05 or -gnat2005 (Ada 2005 mode)
6854 @cindex @option{-gnat05} (@command{gcc})
6855 @cindex @option{-gnat2005} (@command{gcc})
6856 @cindex Ada 2005 mode
6859 This switch directs the compiler to implement the Ada 2005 version of the
6860 language, as documented in the official Ada standards document.
6861 Since Ada 2005 is almost completely upwards
6862 compatible with Ada 95 (and thus also with Ada 83), Ada 83 and Ada 95 programs
6863 may generally be compiled using this switch (see the description of the
6864 @option{-gnat83} and @option{-gnat95} switches for further
6867 @item -gnat12 or -gnat2012 (Ada 2012 mode)
6868 @cindex @option{-gnat12} (@command{gcc})
6869 @cindex @option{-gnat2012} (@command{gcc})
6870 @cindex Ada 2012 mode
6873 This switch directs the compiler to implement the Ada 2012 version of the
6874 language (also the default).
6875 Since Ada 2012 is almost completely upwards
6876 compatible with Ada 2005 (and thus also with Ada 83, and Ada 95),
6877 Ada 83 and Ada 95 programs
6878 may generally be compiled using this switch (see the description of the
6879 @option{-gnat83}, @option{-gnat95}, and @option{-gnat05/2005} switches
6880 for further information).
6882 @item -gnatX (Enable GNAT Extensions)
6883 @cindex @option{-gnatX} (@command{gcc})
6884 @cindex Ada language extensions
6885 @cindex GNAT extensions
6888 This switch directs the compiler to implement the latest version of the
6889 language (currently Ada 2012) and also to enable certain GNAT implementation
6890 extensions that are not part of any Ada standard. For a full list of these
6891 extensions, see the GNAT reference manual.
6895 @node Character Set Control
6896 @subsection Character Set Control
6899 @cindex @option{-gnati} (@command{gcc})
6902 Normally GNAT recognizes the Latin-1 character set in source program
6903 identifiers, as described in the Ada Reference Manual.
6905 GNAT to recognize alternate character sets in identifiers. @var{c} is a
6906 single character indicating the character set, as follows:
6910 ISO 8859-1 (Latin-1) identifiers
6913 ISO 8859-2 (Latin-2) letters allowed in identifiers
6916 ISO 8859-3 (Latin-3) letters allowed in identifiers
6919 ISO 8859-4 (Latin-4) letters allowed in identifiers
6922 ISO 8859-5 (Cyrillic) letters allowed in identifiers
6925 ISO 8859-15 (Latin-9) letters allowed in identifiers
6928 IBM PC letters (code page 437) allowed in identifiers
6931 IBM PC letters (code page 850) allowed in identifiers
6934 Full upper-half codes allowed in identifiers
6937 No upper-half codes allowed in identifiers
6940 Wide-character codes (that is, codes greater than 255)
6941 allowed in identifiers
6944 @xref{Foreign Language Representation}, for full details on the
6945 implementation of these character sets.
6948 @cindex @option{-gnatW} (@command{gcc})
6949 Specify the method of encoding for wide characters.
6950 @var{e} is one of the following:
6955 Hex encoding (brackets coding also recognized)
6958 Upper half encoding (brackets encoding also recognized)
6961 Shift/JIS encoding (brackets encoding also recognized)
6964 EUC encoding (brackets encoding also recognized)
6967 UTF-8 encoding (brackets encoding also recognized)
6970 Brackets encoding only (default value)
6972 For full details on these encoding
6973 methods see @ref{Wide_Character Encodings}.
6974 Note that brackets coding is always accepted, even if one of the other
6975 options is specified, so for example @option{-gnatW8} specifies that both
6976 brackets and UTF-8 encodings will be recognized. The units that are
6977 with'ed directly or indirectly will be scanned using the specified
6978 representation scheme, and so if one of the non-brackets scheme is
6979 used, it must be used consistently throughout the program. However,
6980 since brackets encoding is always recognized, it may be conveniently
6981 used in standard libraries, allowing these libraries to be used with
6982 any of the available coding schemes.
6984 Note that brackets encoding only applies to program text. Within comments,
6985 brackets are considered to be normal graphic characters, and bracket sequences
6986 are never recognized as wide characters.
6988 If no @option{-gnatW?} parameter is present, then the default
6989 representation is normally Brackets encoding only. However, if the
6990 first three characters of the file are 16#EF# 16#BB# 16#BF# (the standard
6991 byte order mark or BOM for UTF-8), then these three characters are
6992 skipped and the default representation for the file is set to UTF-8.
6994 Note that the wide character representation that is specified (explicitly
6995 or by default) for the main program also acts as the default encoding used
6996 for Wide_Text_IO files if not specifically overridden by a WCEM form
7001 When no @option{-gnatW?} is specified, then characters (other than wide
7002 characters represented using brackets notation) are treated as 8-bit
7003 Latin-1 codes. The codes recognized are the Latin-1 graphic characters,
7004 and ASCII format effectors (CR, LF, HT, VT). Other lower half control
7005 characters in the range 16#00#..16#1F# are not accepted in program text
7006 or in comments. Upper half control characters (16#80#..16#9F#) are rejected
7007 in program text, but allowed and ignored in comments. Note in particular
7008 that the Next Line (NEL) character whose encoding is 16#85# is not recognized
7009 as an end of line in this default mode. If your source program contains
7010 instances of the NEL character used as a line terminator,
7011 you must use UTF-8 encoding for the whole
7012 source program. In default mode, all lines must be ended by a standard
7013 end of line sequence (CR, CR/LF, or LF).
7015 Note that the convention of simply accepting all upper half characters in
7016 comments means that programs that use standard ASCII for program text, but
7017 UTF-8 encoding for comments are accepted in default mode, providing that the
7018 comments are ended by an appropriate (CR, or CR/LF, or LF) line terminator.
7019 This is a common mode for many programs with foreign language comments.
7021 @node File Naming Control
7022 @subsection File Naming Control
7026 @cindex @option{-gnatk} (@command{gcc})
7027 Activates file name ``krunching''. @var{n}, a decimal integer in the range
7028 1-999, indicates the maximum allowable length of a file name (not
7029 including the @file{.ads} or @file{.adb} extension). The default is not
7030 to enable file name krunching.
7032 For the source file naming rules, @xref{File Naming Rules}.
7035 @node Subprogram Inlining Control
7036 @subsection Subprogram Inlining Control
7041 @cindex @option{-gnatn} (@command{gcc})
7042 The @code{n} here is intended to suggest the first syllable of the
7044 GNAT recognizes and processes @code{Inline} pragmas. However, for the
7045 inlining to actually occur, optimization must be enabled and, in order
7046 to enable inlining of subprograms specified by pragma @code{Inline},
7047 you must also specify this switch.
7048 In the absence of this switch, GNAT does not attempt
7049 inlining and does not need to access the bodies of
7050 subprograms for which @code{pragma Inline} is specified if they are not
7051 in the current unit.
7053 You can optionally specify the inlining level: 1 for moderate inlining across
7054 modules, which is a good compromise between compilation times and performances
7055 at run time, or 2 for full inlining across modules, which may bring about
7056 longer compilation times. If no inlining level is specified, the compiler will
7057 pick it based on the optimization level: 1 for @option{-O1}, @option{-O2} or
7058 @option{-Os} and 2 for @option{-O3}.
7060 If you specify this switch the compiler will access these bodies,
7061 creating an extra source dependency for the resulting object file, and
7062 where possible, the call will be inlined.
7063 For further details on when inlining is possible
7064 see @ref{Inlining of Subprograms}.
7067 @cindex @option{-gnatN} (@command{gcc})
7068 This switch activates front-end inlining which also
7069 generates additional dependencies.
7071 When using a gcc-based back end (in practice this means using any version
7072 of GNAT other than the JGNAT, .NET or GNAAMP versions), then the use of
7073 @option{-gnatN} is deprecated, and the use of @option{-gnatn} is preferred.
7074 Historically front end inlining was more extensive than the gcc back end
7075 inlining, but that is no longer the case.
7078 @node Auxiliary Output Control
7079 @subsection Auxiliary Output Control
7083 @cindex @option{-gnatt} (@command{gcc})
7084 @cindex Writing internal trees
7085 @cindex Internal trees, writing to file
7086 Causes GNAT to write the internal tree for a unit to a file (with the
7087 extension @file{.adt}.
7088 This not normally required, but is used by separate analysis tools.
7090 these tools do the necessary compilations automatically, so you should
7091 not have to specify this switch in normal operation.
7092 Note that the combination of switches @option{-gnatct}
7093 generates a tree in the form required by ASIS applications.
7096 @cindex @option{-gnatu} (@command{gcc})
7097 Print a list of units required by this compilation on @file{stdout}.
7098 The listing includes all units on which the unit being compiled depends
7099 either directly or indirectly.
7101 @item -pass-exit-codes
7102 @cindex @option{-pass-exit-codes} (@command{gcc})
7103 If this switch is not used, the exit code returned by @command{gcc} when
7104 compiling multiple files indicates whether all source files have
7105 been successfully used to generate object files or not.
7107 When @option{-pass-exit-codes} is used, @command{gcc} exits with an extended
7108 exit status and allows an integrated development environment to better
7109 react to a compilation failure. Those exit status are:
7113 There was an error in at least one source file.
7115 At least one source file did not generate an object file.
7117 The compiler died unexpectedly (internal error for example).
7119 An object file has been generated for every source file.
7123 @node Debugging Control
7124 @subsection Debugging Control
7128 @cindex Debugging options
7130 @cindex @option{-gnatd} (@command{gcc})
7131 Activate internal debugging switches. @var{x} is a letter or digit, or
7132 string of letters or digits, which specifies the type of debugging
7133 outputs desired. Normally these are used only for internal development
7134 or system debugging purposes. You can find full documentation for these
7135 switches in the body of the @code{Debug} unit in the compiler source
7136 file @file{debug.adb}.
7139 @cindex @option{-gnatG} (@command{gcc})
7140 This switch causes the compiler to generate auxiliary output containing
7141 a pseudo-source listing of the generated expanded code. Like most Ada
7142 compilers, GNAT works by first transforming the high level Ada code into
7143 lower level constructs. For example, tasking operations are transformed
7144 into calls to the tasking run-time routines. A unique capability of GNAT
7145 is to list this expanded code in a form very close to normal Ada source.
7146 This is very useful in understanding the implications of various Ada
7147 usage on the efficiency of the generated code. There are many cases in
7148 Ada (e.g.@: the use of controlled types), where simple Ada statements can
7149 generate a lot of run-time code. By using @option{-gnatG} you can identify
7150 these cases, and consider whether it may be desirable to modify the coding
7151 approach to improve efficiency.
7153 The optional parameter @code{nn} if present after -gnatG specifies an
7154 alternative maximum line length that overrides the normal default of 72.
7155 This value is in the range 40-999999, values less than 40 being silently
7156 reset to 40. The equal sign is optional.
7158 The format of the output is very similar to standard Ada source, and is
7159 easily understood by an Ada programmer. The following special syntactic
7160 additions correspond to low level features used in the generated code that
7161 do not have any exact analogies in pure Ada source form. The following
7162 is a partial list of these special constructions. See the spec
7163 of package @code{Sprint} in file @file{sprint.ads} for a full list.
7165 If the switch @option{-gnatL} is used in conjunction with
7166 @cindex @option{-gnatL} (@command{gcc})
7167 @option{-gnatG}, then the original source lines are interspersed
7168 in the expanded source (as comment lines with the original line number).
7171 @item new @var{xxx} @r{[}storage_pool = @var{yyy}@r{]}
7172 Shows the storage pool being used for an allocator.
7174 @item at end @var{procedure-name};
7175 Shows the finalization (cleanup) procedure for a scope.
7177 @item (if @var{expr} then @var{expr} else @var{expr})
7178 Conditional expression equivalent to the @code{x?y:z} construction in C.
7180 @item @var{target}^(@var{source})
7181 A conversion with floating-point truncation instead of rounding.
7183 @item @var{target}?(@var{source})
7184 A conversion that bypasses normal Ada semantic checking. In particular
7185 enumeration types and fixed-point types are treated simply as integers.
7187 @item @var{target}?^(@var{source})
7188 Combines the above two cases.
7190 @item @var{x} #/ @var{y}
7191 @itemx @var{x} #mod @var{y}
7192 @itemx @var{x} #* @var{y}
7193 @itemx @var{x} #rem @var{y}
7194 A division or multiplication of fixed-point values which are treated as
7195 integers without any kind of scaling.
7197 @item free @var{expr} @r{[}storage_pool = @var{xxx}@r{]}
7198 Shows the storage pool associated with a @code{free} statement.
7200 @item [subtype or type declaration]
7201 Used to list an equivalent declaration for an internally generated
7202 type that is referenced elsewhere in the listing.
7204 @c @item freeze @var{type-name} @ovar{actions}
7205 @c Expanding @ovar macro inline (explanation in macro def comments)
7206 @item freeze @var{type-name} @r{[}@var{actions}@r{]}
7207 Shows the point at which @var{type-name} is frozen, with possible
7208 associated actions to be performed at the freeze point.
7210 @item reference @var{itype}
7211 Reference (and hence definition) to internal type @var{itype}.
7213 @item @var{function-name}! (@var{arg}, @var{arg}, @var{arg})
7214 Intrinsic function call.
7216 @item @var{label-name} : label
7217 Declaration of label @var{labelname}.
7219 @item #$ @var{subprogram-name}
7220 An implicit call to a run-time support routine
7221 (to meet the requirement of H.3.1(9) in a
7224 @item @var{expr} && @var{expr} && @var{expr} @dots{} && @var{expr}
7225 A multiple concatenation (same effect as @var{expr} & @var{expr} &
7226 @var{expr}, but handled more efficiently).
7228 @item [constraint_error]
7229 Raise the @code{Constraint_Error} exception.
7231 @item @var{expression}'reference
7232 A pointer to the result of evaluating @var{expression}.
7234 @item @var{target-type}!(@var{source-expression})
7235 An unchecked conversion of @var{source-expression} to @var{target-type}.
7237 @item [@var{numerator}/@var{denominator}]
7238 Used to represent internal real literals (that) have no exact
7239 representation in base 2-16 (for example, the result of compile time
7240 evaluation of the expression 1.0/27.0).
7244 @cindex @option{-gnatD} (@command{gcc})
7245 When used in conjunction with @option{-gnatG}, this switch causes
7246 the expanded source, as described above for
7247 @option{-gnatG} to be written to files with names
7248 @file{xxx.dg}, where @file{xxx} is the normal file name,
7249 instead of to the standard output file. For
7250 example, if the source file name is @file{hello.adb}, then a file
7251 @file{hello.adb.dg} will be written. The debugging
7252 information generated by the @command{gcc} @option{-g} switch
7253 will refer to the generated @file{xxx.dg} file. This allows
7254 you to do source level debugging using the generated code which is
7255 sometimes useful for complex code, for example to find out exactly
7256 which part of a complex construction raised an exception. This switch
7257 also suppress generation of cross-reference information (see
7258 @option{-gnatx}) since otherwise the cross-reference information
7259 would refer to the @file{.dg} file, which would cause
7260 confusion since this is not the original source file.
7262 Note that @option{-gnatD} actually implies @option{-gnatG}
7263 automatically, so it is not necessary to give both options.
7264 In other words @option{-gnatD} is equivalent to @option{-gnatDG}).
7266 If the switch @option{-gnatL} is used in conjunction with
7267 @cindex @option{-gnatL} (@command{gcc})
7268 @option{-gnatDG}, then the original source lines are interspersed
7269 in the expanded source (as comment lines with the original line number).
7271 The optional parameter @code{nn} if present after -gnatD specifies an
7272 alternative maximum line length that overrides the normal default of 72.
7273 This value is in the range 40-999999, values less than 40 being silently
7274 reset to 40. The equal sign is optional.
7277 @cindex @option{-gnatr} (@command{gcc})
7278 @cindex pragma Restrictions
7279 This switch causes pragma Restrictions to be treated as Restriction_Warnings
7280 so that violation of restrictions causes warnings rather than illegalities.
7281 This is useful during the development process when new restrictions are added
7282 or investigated. The switch also causes pragma Profile to be treated as
7283 Profile_Warnings, and pragma Restricted_Run_Time and pragma Ravenscar set
7284 restriction warnings rather than restrictions.
7286 @item -gnatR@r{[}0@r{|}1@r{|}2@r{|}3@r{[}s@r{]]}
7287 @cindex @option{-gnatR} (@command{gcc})
7288 This switch controls output from the compiler of a listing showing
7289 representation information for declared types and objects. For
7290 @option{-gnatR0}, no information is output (equivalent to omitting
7291 the @option{-gnatR} switch). For @option{-gnatR1} (which is the default,
7292 so @option{-gnatR} with no parameter has the same effect), size and alignment
7293 information is listed for declared array and record types. For
7294 @option{-gnatR2}, size and alignment information is listed for all
7295 declared types and objects. The @code{Linker_Section} is also listed for any
7296 entity for which the @code{Linker_Section} is set explicitly or implicitly (the
7297 latter case occurs for objects of a type for which a @code{Linker_Section}
7300 Finally @option{-gnatR3} includes symbolic
7301 expressions for values that are computed at run time for
7302 variant records. These symbolic expressions have a mostly obvious
7303 format with #n being used to represent the value of the n'th
7304 discriminant. See source files @file{repinfo.ads/adb} in the
7305 @code{GNAT} sources for full details on the format of @option{-gnatR3}
7306 output. If the switch is followed by an s (e.g.@: @option{-gnatR2s}), then
7307 the output is to a file with the name @file{file.rep} where
7308 file is the name of the corresponding source file.
7311 This form of the switch controls output of subprogram conventions
7312 and parameter passing mechanisms for all subprograms. A following
7313 @code{s} means output to a file as described above.
7315 Note that it is possible for record components to have zero size. In
7316 this case, the component clause uses an obvious extension of permitted
7317 Ada syntax, for example @code{at 0 range 0 .. -1}.
7319 Representation information requires that code be generated (since it is the
7320 code generator that lays out complex data structures). If an attempt is made
7321 to output representation information when no code is generated, for example
7322 when a subunit is compiled on its own, then no information can be generated
7323 and the compiler outputs a message to this effect.
7326 @cindex @option{-gnatS} (@command{gcc})
7327 The use of the switch @option{-gnatS} for an
7328 Ada compilation will cause the compiler to output a
7329 representation of package Standard in a form very
7330 close to standard Ada. It is not quite possible to
7331 do this entirely in standard Ada (since new
7332 numeric base types cannot be created in standard
7333 Ada), but the output is easily
7334 readable to any Ada programmer, and is useful to
7335 determine the characteristics of target dependent
7336 types in package Standard.
7339 @cindex @option{-gnatx} (@command{gcc})
7340 Normally the compiler generates full cross-referencing information in
7341 the @file{ALI} file. This information is used by a number of tools,
7342 including @code{gnatfind} and @code{gnatxref}. The @option{-gnatx} switch
7343 suppresses this information. This saves some space and may slightly
7344 speed up compilation, but means that these tools cannot be used.
7347 @node Exception Handling Control
7348 @subsection Exception Handling Control
7351 GNAT uses two methods for handling exceptions at run-time. The
7352 @code{setjmp/longjmp} method saves the context when entering
7353 a frame with an exception handler. Then when an exception is
7354 raised, the context can be restored immediately, without the
7355 need for tracing stack frames. This method provides very fast
7356 exception propagation, but introduces significant overhead for
7357 the use of exception handlers, even if no exception is raised.
7359 The other approach is called ``zero cost'' exception handling.
7360 With this method, the compiler builds static tables to describe
7361 the exception ranges. No dynamic code is required when entering
7362 a frame containing an exception handler. When an exception is
7363 raised, the tables are used to control a back trace of the
7364 subprogram invocation stack to locate the required exception
7365 handler. This method has considerably poorer performance for
7366 the propagation of exceptions, but there is no overhead for
7367 exception handlers if no exception is raised. Note that in this
7368 mode and in the context of mixed Ada and C/C++ programming,
7369 to propagate an exception through a C/C++ code, the C/C++ code
7370 must be compiled with the @option{-funwind-tables} GCC's
7373 The following switches may be used to control which of the
7374 two exception handling methods is used.
7380 @cindex @option{--RTS=sjlj} (@command{gnatmake})
7381 This switch causes the setjmp/longjmp run-time (when available) to be used
7382 for exception handling. If the default
7383 mechanism for the target is zero cost exceptions, then
7384 this switch can be used to modify this default, and must be
7385 used for all units in the partition.
7386 This option is rarely used. One case in which it may be
7387 advantageous is if you have an application where exception
7388 raising is common and the overall performance of the
7389 application is improved by favoring exception propagation.
7392 @cindex @option{--RTS=zcx} (@command{gnatmake})
7393 @cindex Zero Cost Exceptions
7394 This switch causes the zero cost approach to be used
7395 for exception handling. If this is the default mechanism for the
7396 target (see below), then this switch is unneeded. If the default
7397 mechanism for the target is setjmp/longjmp exceptions, then
7398 this switch can be used to modify this default, and must be
7399 used for all units in the partition.
7400 This option can only be used if the zero cost approach
7401 is available for the target in use, otherwise it will generate an error.
7405 The same option @option{--RTS} must be used both for @command{gcc}
7406 and @command{gnatbind}. Passing this option to @command{gnatmake}
7407 (@pxref{Switches for gnatmake}) will ensure the required consistency
7408 through the compilation and binding steps.
7410 @node Units to Sources Mapping Files
7411 @subsection Units to Sources Mapping Files
7415 @item -gnatem=@var{path}
7416 @cindex @option{-gnatem} (@command{gcc})
7417 A mapping file is a way to communicate to the compiler two mappings:
7418 from unit names to file names (without any directory information) and from
7419 file names to path names (with full directory information). These mappings
7420 are used by the compiler to short-circuit the path search.
7422 The use of mapping files is not required for correct operation of the
7423 compiler, but mapping files can improve efficiency, particularly when
7424 sources are read over a slow network connection. In normal operation,
7425 you need not be concerned with the format or use of mapping files,
7426 and the @option{-gnatem} switch is not a switch that you would use
7427 explicitly. It is intended primarily for use by automatic tools such as
7428 @command{gnatmake} running under the project file facility. The
7429 description here of the format of mapping files is provided
7430 for completeness and for possible use by other tools.
7432 A mapping file is a sequence of sets of three lines. In each set, the
7433 first line is the unit name, in lower case, with @code{%s} appended
7434 for specs and @code{%b} appended for bodies; the second line is the
7435 file name; and the third line is the path name.
7441 /gnat/project1/sources/main.2.ada
7444 When the switch @option{-gnatem} is specified, the compiler will
7445 create in memory the two mappings from the specified file. If there is
7446 any problem (nonexistent file, truncated file or duplicate entries),
7447 no mapping will be created.
7449 Several @option{-gnatem} switches may be specified; however, only the
7450 last one on the command line will be taken into account.
7452 When using a project file, @command{gnatmake} creates a temporary
7453 mapping file and communicates it to the compiler using this switch.
7457 @node Integrated Preprocessing
7458 @subsection Integrated Preprocessing
7461 GNAT sources may be preprocessed immediately before compilation.
7462 In this case, the actual
7463 text of the source is not the text of the source file, but is derived from it
7464 through a process called preprocessing. Integrated preprocessing is specified
7465 through switches @option{-gnatep} and/or @option{-gnateD}. @option{-gnatep}
7466 indicates, through a text file, the preprocessing data to be used.
7467 @option{-gnateD} specifies or modifies the values of preprocessing symbol.
7468 Note that integrated preprocessing applies only to Ada source files, it is
7469 not available for configuration pragma files.
7472 Note that when integrated preprocessing is used, the output from the
7473 preprocessor is not written to any external file. Instead it is passed
7474 internally to the compiler. If you need to preserve the result of
7475 preprocessing in a file, then you should use @command{gnatprep}
7476 to perform the desired preprocessing in stand-alone mode.
7479 It is recommended that @command{gnatmake} switch -s should be
7480 used when Integrated Preprocessing is used. The reason is that preprocessing
7481 with another Preprocessing Data file without changing the sources will
7482 not trigger recompilation without this switch.
7485 Note that @command{gnatmake} switch -m will almost
7486 always trigger recompilation for sources that are preprocessed,
7487 because @command{gnatmake} cannot compute the checksum of the source after
7491 The actual preprocessing function is described in details in section
7492 @ref{Preprocessing with gnatprep}. This section only describes how integrated
7493 preprocessing is triggered and parameterized.
7497 @item -gnatep=@var{file}
7498 @cindex @option{-gnatep} (@command{gcc})
7499 This switch indicates to the compiler the file name (without directory
7500 information) of the preprocessor data file to use. The preprocessor data file
7501 should be found in the source directories. Note that when the compiler is
7502 called by a builder such as (@command{gnatmake} with a project
7503 file, if the object directory is not also a source directory, the builder needs
7504 to be called with @option{-x}.
7507 A preprocessing data file is a text file with significant lines indicating
7508 how should be preprocessed either a specific source or all sources not
7509 mentioned in other lines. A significant line is a nonempty, non-comment line.
7510 Comments are similar to Ada comments.
7513 Each significant line starts with either a literal string or the character '*'.
7514 A literal string is the file name (without directory information) of the source
7515 to preprocess. A character '*' indicates the preprocessing for all the sources
7516 that are not specified explicitly on other lines (order of the lines is not
7517 significant). It is an error to have two lines with the same file name or two
7518 lines starting with the character '*'.
7521 After the file name or the character '*', another optional literal string
7522 indicating the file name of the definition file to be used for preprocessing
7523 (@pxref{Form of Definitions File}). The definition files are found by the
7524 compiler in one of the source directories. In some cases, when compiling
7525 a source in a directory other than the current directory, if the definition
7526 file is in the current directory, it may be necessary to add the current
7527 directory as a source directory through switch -I., otherwise
7528 the compiler would not find the definition file.
7531 Then, optionally, switches similar to those of @code{gnatprep} may
7532 be found. Those switches are:
7537 Causes both preprocessor lines and the lines deleted by
7538 preprocessing to be replaced by blank lines, preserving the line number.
7539 This switch is always implied; however, if specified after @option{-c}
7540 it cancels the effect of @option{-c}.
7543 Causes both preprocessor lines and the lines deleted
7544 by preprocessing to be retained as comments marked
7545 with the special string ``@code{--! }''.
7547 @item -Dsymbol=value
7548 Define or redefine a symbol, associated with value. A symbol is an Ada
7549 identifier, or an Ada reserved word, with the exception of @code{if},
7550 @code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}.
7551 @code{value} is either a literal string, an Ada identifier or any Ada reserved
7552 word. A symbol declared with this switch replaces a symbol with the
7553 same name defined in a definition file.
7556 Causes a sorted list of symbol names and values to be
7557 listed on the standard output file.
7560 Causes undefined symbols to be treated as having the value @code{FALSE}
7562 of a preprocessor test. In the absence of this option, an undefined symbol in
7563 a @code{#if} or @code{#elsif} test will be treated as an error.
7568 Examples of valid lines in a preprocessor data file:
7571 "toto.adb" "prep.def" -u
7572 -- preprocess "toto.adb", using definition file "prep.def",
7573 -- undefined symbol are False.
7576 -- preprocess all other sources without a definition file;
7577 -- suppressed lined are commented; symbol VERSION has the value V101.
7579 "titi.adb" "prep2.def" -s
7580 -- preprocess "titi.adb", using definition file "prep2.def";
7581 -- list all symbols with their values.
7584 @item -gnateDsymbol@r{[}=value@r{]}
7585 @cindex @option{-gnateD} (@command{gcc})
7586 Define or redefine a preprocessing symbol, associated with value. If no value
7587 is given on the command line, then the value of the symbol is @code{True}.
7588 A symbol is an identifier, following normal Ada (case-insensitive)
7589 rules for its syntax, and value is either an arbitrary string between double
7590 quotes or any sequence (including an empty sequence) of characters from the
7591 set (letters, digits, period, underline).
7592 Ada reserved words may be used as symbols, with the exceptions of @code{if},
7593 @code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}.
7601 -gnateDFoo=\"Foo-Bar\"
7605 A symbol declared with this switch on the command line replaces a
7606 symbol with the same name either in a definition file or specified with a
7607 switch -D in the preprocessor data file.
7610 This switch is similar to switch @option{-D} of @code{gnatprep}.
7613 When integrated preprocessing is performed and the preprocessor modifies
7614 the source text, write the result of this preprocessing into a file
7619 @node Code Generation Control
7620 @subsection Code Generation Control
7624 The GCC technology provides a wide range of target dependent
7625 @option{-m} switches for controlling
7626 details of code generation with respect to different versions of
7627 architectures. This includes variations in instruction sets (e.g.@:
7628 different members of the power pc family), and different requirements
7629 for optimal arrangement of instructions (e.g.@: different members of
7630 the x86 family). The list of available @option{-m} switches may be
7631 found in the GCC documentation.
7633 Use of these @option{-m} switches may in some cases result in improved
7636 The @value{EDITION} technology is tested and qualified without any
7637 @option{-m} switches,
7638 so generally the most reliable approach is to avoid the use of these
7639 switches. However, we generally expect most of these switches to work
7640 successfully with @value{EDITION}, and many customers have reported successful
7641 use of these options.
7643 Our general advice is to avoid the use of @option{-m} switches unless
7644 special needs lead to requirements in this area. In particular,
7645 there is no point in using @option{-m} switches to improve performance
7646 unless you actually see a performance improvement.
7649 @node Search Paths and the Run-Time Library (RTL)
7650 @section Search Paths and the Run-Time Library (RTL)
7653 With the GNAT source-based library system, the compiler must be able to
7654 find source files for units that are needed by the unit being compiled.
7655 Search paths are used to guide this process.
7657 The compiler compiles one source file whose name must be given
7658 explicitly on the command line. In other words, no searching is done
7659 for this file. To find all other source files that are needed (the most
7660 common being the specs of units), the compiler examines the following
7661 directories, in the following order:
7665 The directory containing the source file of the main unit being compiled
7666 (the file name on the command line).
7669 Each directory named by an @option{-I} switch given on the
7670 @command{gcc} command line, in the order given.
7673 @findex ADA_PRJ_INCLUDE_FILE
7674 Each of the directories listed in the text file whose name is given
7675 by the @env{ADA_PRJ_INCLUDE_FILE} environment variable.
7678 @env{ADA_PRJ_INCLUDE_FILE} is normally set by gnatmake or by the gnat
7679 driver when project files are used. It should not normally be set
7683 @findex ADA_INCLUDE_PATH
7684 Each of the directories listed in the value of the
7685 @env{ADA_INCLUDE_PATH} environment variable.
7686 Construct this value
7687 exactly as the @env{PATH} environment variable: a list of directory
7688 names separated by colons (semicolons when working with the NT version).
7691 The content of the @file{ada_source_path} file which is part of the GNAT
7692 installation tree and is used to store standard libraries such as the
7693 GNAT Run Time Library (RTL) source files.
7694 @ref{Installing a library}
7698 Specifying the switch @option{-I-}
7699 inhibits the use of the directory
7700 containing the source file named in the command line. You can still
7701 have this directory on your search path, but in this case it must be
7702 explicitly requested with a @option{-I} switch.
7704 Specifying the switch @option{-nostdinc}
7705 inhibits the search of the default location for the GNAT Run Time
7706 Library (RTL) source files.
7708 The compiler outputs its object files and ALI files in the current
7710 Caution: The object file can be redirected with the @option{-o} switch;
7711 however, @command{gcc} and @code{gnat1} have not been coordinated on this
7712 so the @file{ALI} file will not go to the right place. Therefore, you should
7713 avoid using the @option{-o} switch.
7716 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
7717 children make up the GNAT RTL, together with the simple @code{System.IO}
7718 package used in the @code{"Hello World"} example. The sources for these units
7719 are needed by the compiler and are kept together in one directory. Not
7720 all of the bodies are needed, but all of the sources are kept together
7721 anyway. In a normal installation, you need not specify these directory
7722 names when compiling or binding. Either the environment variables or
7723 the built-in defaults cause these files to be found.
7725 In addition to the language-defined hierarchies (@code{System}, @code{Ada} and
7726 @code{Interfaces}), the GNAT distribution provides a fourth hierarchy,
7727 consisting of child units of @code{GNAT}. This is a collection of generally
7728 useful types, subprograms, etc. @xref{Top, GNAT Reference Manual, About
7729 This Guid, gnat_rm, GNAT Reference Manual}, for further details.
7731 Besides simplifying access to the RTL, a major use of search paths is
7732 in compiling sources from multiple directories. This can make
7733 development environments much more flexible.
7735 @node Order of Compilation Issues
7736 @section Order of Compilation Issues
7739 If, in our earlier example, there was a spec for the @code{hello}
7740 procedure, it would be contained in the file @file{hello.ads}; yet this
7741 file would not have to be explicitly compiled. This is the result of the
7742 model we chose to implement library management. Some of the consequences
7743 of this model are as follows:
7747 There is no point in compiling specs (except for package
7748 specs with no bodies) because these are compiled as needed by clients. If
7749 you attempt a useless compilation, you will receive an error message.
7750 It is also useless to compile subunits because they are compiled as needed
7754 There are no order of compilation requirements: performing a
7755 compilation never obsoletes anything. The only way you can obsolete
7756 something and require recompilations is to modify one of the
7757 source files on which it depends.
7760 There is no library as such, apart from the ALI files
7761 (@pxref{The Ada Library Information Files}, for information on the format
7762 of these files). For now we find it convenient to create separate ALI files,
7763 but eventually the information therein may be incorporated into the object
7767 When you compile a unit, the source files for the specs of all units
7768 that it @code{with}'s, all its subunits, and the bodies of any generics it
7769 instantiates must be available (reachable by the search-paths mechanism
7770 described above), or you will receive a fatal error message.
7777 The following are some typical Ada compilation command line examples:
7780 @item $ gcc -c xyz.adb
7781 Compile body in file @file{xyz.adb} with all default options.
7783 @item $ gcc -c -O2 -gnata xyz-def.adb
7785 Compile the child unit package in file @file{xyz-def.adb} with extensive
7786 optimizations, and pragma @code{Assert}/@code{Debug} statements
7789 @item $ gcc -c -gnatc abc-def.adb
7790 Compile the subunit in file @file{abc-def.adb} in semantic-checking-only
7794 @node Binding with gnatbind
7795 @chapter Binding with @code{gnatbind}
7799 * Running gnatbind::
7800 * Switches for gnatbind::
7801 * Command-Line Access::
7802 * Search Paths for gnatbind::
7803 * Examples of gnatbind Usage::
7807 This chapter describes the GNAT binder, @code{gnatbind}, which is used
7808 to bind compiled GNAT objects.
7810 Note: to invoke @code{gnatbind} with a project file, use the @code{gnat}
7811 driver (see @ref{The GNAT Driver and Project Files}).
7813 The @code{gnatbind} program performs four separate functions:
7817 Checks that a program is consistent, in accordance with the rules in
7818 Chapter 10 of the Ada Reference Manual. In particular, error
7819 messages are generated if a program uses inconsistent versions of a
7823 Checks that an acceptable order of elaboration exists for the program
7824 and issues an error message if it cannot find an order of elaboration
7825 that satisfies the rules in Chapter 10 of the Ada Language Manual.
7828 Generates a main program incorporating the given elaboration order.
7829 This program is a small Ada package (body and spec) that
7830 must be subsequently compiled
7831 using the GNAT compiler. The necessary compilation step is usually
7832 performed automatically by @command{gnatlink}. The two most important
7833 functions of this program
7834 are to call the elaboration routines of units in an appropriate order
7835 and to call the main program.
7838 Determines the set of object files required by the given main program.
7839 This information is output in the forms of comments in the generated program,
7840 to be read by the @command{gnatlink} utility used to link the Ada application.
7843 @node Running gnatbind
7844 @section Running @code{gnatbind}
7847 The form of the @code{gnatbind} command is
7850 @c $ gnatbind @ovar{switches} @var{mainprog}@r{[}.ali@r{]} @ovar{switches}
7851 @c Expanding @ovar macro inline (explanation in macro def comments)
7852 $ gnatbind @r{[}@var{switches}@r{]} @var{mainprog}@r{[}.ali@r{]} @r{[}@var{switches}@r{]}
7856 where @file{@var{mainprog}.adb} is the Ada file containing the main program
7857 unit body. @code{gnatbind} constructs an Ada
7858 package in two files whose names are
7859 @file{b~@var{mainprog}.ads}, and @file{b~@var{mainprog}.adb}.
7860 For example, if given the
7861 parameter @file{hello.ali}, for a main program contained in file
7862 @file{hello.adb}, the binder output files would be @file{b~hello.ads}
7863 and @file{b~hello.adb}.
7865 When doing consistency checking, the binder takes into consideration
7866 any source files it can locate. For example, if the binder determines
7867 that the given main program requires the package @code{Pack}, whose
7869 file is @file{pack.ali} and whose corresponding source spec file is
7870 @file{pack.ads}, it attempts to locate the source file @file{pack.ads}
7871 (using the same search path conventions as previously described for the
7872 @command{gcc} command). If it can locate this source file, it checks that
7874 or source checksums of the source and its references to in @file{ALI} files
7875 match. In other words, any @file{ALI} files that mentions this spec must have
7876 resulted from compiling this version of the source file (or in the case
7877 where the source checksums match, a version close enough that the
7878 difference does not matter).
7880 @cindex Source files, use by binder
7881 The effect of this consistency checking, which includes source files, is
7882 that the binder ensures that the program is consistent with the latest
7883 version of the source files that can be located at bind time. Editing a
7884 source file without compiling files that depend on the source file cause
7885 error messages to be generated by the binder.
7887 For example, suppose you have a main program @file{hello.adb} and a
7888 package @code{P}, from file @file{p.ads} and you perform the following
7893 Enter @code{gcc -c hello.adb} to compile the main program.
7896 Enter @code{gcc -c p.ads} to compile package @code{P}.
7899 Edit file @file{p.ads}.
7902 Enter @code{gnatbind hello}.
7906 At this point, the file @file{p.ali} contains an out-of-date time stamp
7907 because the file @file{p.ads} has been edited. The attempt at binding
7908 fails, and the binder generates the following error messages:
7911 error: "hello.adb" must be recompiled ("p.ads" has been modified)
7912 error: "p.ads" has been modified and must be recompiled
7916 Now both files must be recompiled as indicated, and then the bind can
7917 succeed, generating a main program. You need not normally be concerned
7918 with the contents of this file, but for reference purposes a sample
7919 binder output file is given in @ref{Example of Binder Output File}.
7921 In most normal usage, the default mode of @command{gnatbind} which is to
7922 generate the main package in Ada, as described in the previous section.
7923 In particular, this means that any Ada programmer can read and understand
7924 the generated main program. It can also be debugged just like any other
7925 Ada code provided the @option{-g} switch is used for
7926 @command{gnatbind} and @command{gnatlink}.
7928 @node Switches for gnatbind
7929 @section Switches for @command{gnatbind}
7932 The following switches are available with @code{gnatbind}; details will
7933 be presented in subsequent sections.
7936 * Consistency-Checking Modes::
7937 * Binder Error Message Control::
7938 * Elaboration Control::
7940 * Dynamic Allocation Control::
7941 * Binding with Non-Ada Main Programs::
7942 * Binding Programs with No Main Subprogram::
7949 @cindex @option{--version} @command{gnatbind}
7950 Display Copyright and version, then exit disregarding all other options.
7953 @cindex @option{--help} @command{gnatbind}
7954 If @option{--version} was not used, display usage, then exit disregarding
7958 @cindex @option{-a} @command{gnatbind}
7959 Indicates that, if supported by the platform, the adainit procedure should
7960 be treated as an initialisation routine by the linker (a constructor). This
7961 is intended to be used by the Project Manager to automatically initialize
7962 shared Stand-Alone Libraries.
7965 @cindex @option{-aO} (@command{gnatbind})
7966 Specify directory to be searched for ALI files.
7969 @cindex @option{-aI} (@command{gnatbind})
7970 Specify directory to be searched for source file.
7972 @item -A@r{[=}@var{filename}@r{]}
7973 @cindex @option{-A} (@command{gnatbind})
7974 Output ALI list (to standard output or to the named file).
7977 @cindex @option{-b} (@command{gnatbind})
7978 Generate brief messages to @file{stderr} even if verbose mode set.
7981 @cindex @option{-c} (@command{gnatbind})
7982 Check only, no generation of binder output file.
7984 @item -d@var{nn}@r{[}k@r{|}m@r{]}
7985 @cindex @option{-d@var{nn}@r{[}k@r{|}m@r{]}} (@command{gnatbind})
7986 This switch can be used to change the default task stack size value
7987 to a specified size @var{nn}, which is expressed in bytes by default, or
7988 in kilobytes when suffixed with @var{k} or in megabytes when suffixed
7990 In the absence of a @samp{@r{[}k@r{|}m@r{]}} suffix, this switch is equivalent,
7991 in effect, to completing all task specs with
7992 @smallexample @c ada
7993 @b{pragma} Storage_Size (nn);
7995 When they do not already have such a pragma.
7997 @item -D@var{nn}@r{[}k@r{|}m@r{]}
7998 @cindex @option{-D} (@command{gnatbind})
7999 This switch can be used to change the default secondary stack size value
8000 to a specified size @var{nn}, which is expressed in bytes by default, or
8001 in kilobytes when suffixed with @var{k} or in megabytes when suffixed
8004 The secondary stack is used to deal with functions that return a variable
8005 sized result, for example a function returning an unconstrained
8006 String. There are two ways in which this secondary stack is allocated.
8008 For most targets, the secondary stack is growing on demand and is allocated
8009 as a chain of blocks in the heap. The -D option is not very
8010 relevant. It only give some control over the size of the allocated
8011 blocks (whose size is the minimum of the default secondary stack size value,
8012 and the actual size needed for the current allocation request).
8014 For certain targets, notably VxWorks 653,
8015 the secondary stack is allocated by carving off a fixed ratio chunk of the
8016 primary task stack. The -D option is used to define the
8017 size of the environment task's secondary stack.
8020 @cindex @option{-e} (@command{gnatbind})
8021 Output complete list of elaboration-order dependencies.
8024 @cindex @option{-E} (@command{gnatbind})
8025 Store tracebacks in exception occurrences when the target supports it.
8027 @c The following may get moved to an appendix
8028 This option is currently supported on the following targets:
8029 all x86 ports, Solaris, Windows, HP-UX, AIX, PowerPC VxWorks and Alpha VxWorks.
8031 See also the packages @code{GNAT.Traceback} and
8032 @code{GNAT.Traceback.Symbolic} for more information.
8033 Note that on x86 ports, you must not use @option{-fomit-frame-pointer}
8034 @command{gcc} option.
8037 @cindex @option{-F} (@command{gnatbind})
8038 Force the checks of elaboration flags. @command{gnatbind} does not normally
8039 generate checks of elaboration flags for the main executable, except when
8040 a Stand-Alone Library is used. However, there are cases when this cannot be
8041 detected by gnatbind. An example is importing an interface of a Stand-Alone
8042 Library through a pragma Import and only specifying through a linker switch
8043 this Stand-Alone Library. This switch is used to guarantee that elaboration
8044 flag checks are generated.
8047 @cindex @option{-h} (@command{gnatbind})
8048 Output usage (help) information
8051 @cindex @option{-H32} (@command{gnatbind})
8052 Use 32-bit allocations for @code{__gnat_malloc} (and thus for access types).
8053 For further details see @ref{Dynamic Allocation Control}.
8056 @cindex @option{-H64} (@command{gnatbind})
8057 Use 64-bit allocations for @code{__gnat_malloc} (and thus for access types).
8058 @cindex @code{__gnat_malloc}
8059 For further details see @ref{Dynamic Allocation Control}.
8062 @cindex @option{-I} (@command{gnatbind})
8063 Specify directory to be searched for source and ALI files.
8066 @cindex @option{-I-} (@command{gnatbind})
8067 Do not look for sources in the current directory where @code{gnatbind} was
8068 invoked, and do not look for ALI files in the directory containing the
8069 ALI file named in the @code{gnatbind} command line.
8072 @cindex @option{-l} (@command{gnatbind})
8073 Output chosen elaboration order.
8076 @cindex @option{-L} (@command{gnatbind})
8077 Bind the units for library building. In this case the adainit and
8078 adafinal procedures (@pxref{Binding with Non-Ada Main Programs})
8079 are renamed to @var{xxx}init and
8082 (@xref{GNAT and Libraries}, for more details.)
8085 @cindex @option{-M} (@command{gnatbind})
8086 Rename generated main program from main to xyz. This option is
8087 supported on cross environments only.
8090 @cindex @option{-m} (@command{gnatbind})
8091 Limit number of detected errors or warnings to @var{n}, where @var{n} is
8092 in the range 1..999999. The default value if no switch is
8093 given is 9999. If the number of warnings reaches this limit, then a
8094 message is output and further warnings are suppressed, the bind
8095 continues in this case. If the number of errors reaches this
8096 limit, then a message is output and the bind is abandoned.
8097 A value of zero means that no limit is enforced. The equal
8101 @cindex @option{-n} (@command{gnatbind})
8105 @cindex @option{-nostdinc} (@command{gnatbind})
8106 Do not look for sources in the system default directory.
8109 @cindex @option{-nostdlib} (@command{gnatbind})
8110 Do not look for library files in the system default directory.
8112 @item --RTS=@var{rts-path}
8113 @cindex @option{--RTS} (@code{gnatbind})
8114 Specifies the default location of the runtime library. Same meaning as the
8115 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
8118 @cindex @option{-o } (@command{gnatbind})
8119 Name the output file @var{file} (default is @file{b~@var{xxx}.adb}).
8120 Note that if this option is used, then linking must be done manually,
8121 gnatlink cannot be used.
8123 @item -O@r{[=}@var{filename}@r{]}
8124 @cindex @option{-O} (@command{gnatbind})
8125 Output object list (to standard output or to the named file).
8128 @cindex @option{-p} (@command{gnatbind})
8129 Pessimistic (worst-case) elaboration order
8132 @cindex @option{-P} (@command{gnatbind})
8133 Generate binder file suitable for CodePeer.
8136 @cindex @option{-R} (@command{gnatbind})
8137 Output closure source list, which includes all non-run-time units that are
8138 included in the bind.
8141 @cindex @option{-Ra} (@command{gnatbind})
8142 Like @option{-R} but the list includes run-time units.
8145 @cindex @option{-s} (@command{gnatbind})
8146 Require all source files to be present.
8149 @cindex @option{-S} (@command{gnatbind})
8150 Specifies the value to be used when detecting uninitialized scalar
8151 objects with pragma Initialize_Scalars.
8152 The @var{xxx} string specified with the switch is one of:
8155 @item ``@option{in}'' for an invalid value
8156 If zero is invalid for the discrete type in question,
8157 then the scalar value is set to all zero bits.
8158 For signed discrete types, the largest possible negative value of
8159 the underlying scalar is set (i.e. a one bit followed by all zero bits).
8160 For unsigned discrete types, the underlying scalar value is set to all
8161 one bits. For floating-point types, a NaN value is set
8162 (see body of package System.Scalar_Values for exact values).
8164 @item ``@option{lo}'' for low value
8165 If zero is invalid for the discrete type in question,
8166 then the scalar value is set to all zero bits.
8167 For signed discrete types, the largest possible negative value of
8168 the underlying scalar is set (i.e. a one bit followed by all zero bits).
8169 For unsigned discrete types, the underlying scalar value is set to all
8170 zero bits. For floating-point, a small value is set
8171 (see body of package System.Scalar_Values for exact values).
8173 @item ``@option{hi}'' for high value
8174 If zero is invalid for the discrete type in question,
8175 then the scalar value is set to all one bits.
8176 For signed discrete types, the largest possible positive value of
8177 the underlying scalar is set (i.e. a zero bit followed by all one bits).
8178 For unsigned discrete types, the underlying scalar value is set to all
8179 one bits. For floating-point, a large value is set
8180 (see body of package System.Scalar_Values for exact values).
8182 @item ``@option{@var{xx}}'' for hex value (two hex digits)
8183 The underlying scalar is set to a value consisting of repeated bytes, whose
8184 value corresponds to the given value. For example if @option{BF} is given,
8185 then a 32-bit scalar value will be set to the bit patterm 16#BFBFBFBF#.
8188 In addition, you can specify @option{-Sev} to indicate that the value is
8189 to be set at run time. In this case, the program will look for an environment
8190 @cindex GNAT_INIT_SCALARS
8191 variable of the form @env{GNAT_INIT_SCALARS=@var{xx}}, where @var{xx} is one
8192 of @option{in/lo/hi/@var{xx}} with the same meanings as above.
8193 If no environment variable is found, or if it does not have a valid value,
8194 then the default is @option{in} (invalid values).
8197 @cindex @option{-static} (@code{gnatbind})
8198 Link against a static GNAT run time.
8201 @cindex @option{-shared} (@code{gnatbind})
8202 Link against a shared GNAT run time when available.
8205 @cindex @option{-t} (@code{gnatbind})
8206 Tolerate time stamp and other consistency errors
8209 @cindex @option{-T} (@code{gnatbind})
8210 Set the time slice value to @var{n} milliseconds. If the system supports
8211 the specification of a specific time slice value, then the indicated value
8212 is used. If the system does not support specific time slice values, but
8213 does support some general notion of round-robin scheduling, then any
8214 nonzero value will activate round-robin scheduling.
8216 A value of zero is treated specially. It turns off time
8217 slicing, and in addition, indicates to the tasking run time that the
8218 semantics should match as closely as possible the Annex D
8219 requirements of the Ada RM, and in particular sets the default
8220 scheduling policy to @code{FIFO_Within_Priorities}.
8223 @cindex @option{-u} (@code{gnatbind})
8224 Enable dynamic stack usage, with @var{n} results stored and displayed
8225 at program termination. A result is generated when a task
8226 terminates. Results that can't be stored are displayed on the fly, at
8227 task termination. This option is currently not supported on Itanium
8228 platforms. (See @ref{Dynamic Stack Usage Analysis} for details.)
8231 @cindex @option{-v} (@code{gnatbind})
8232 Verbose mode. Write error messages, header, summary output to
8236 @cindex @option{-w} (@code{gnatbind})
8237 Warning mode (@var{x}=s/e for suppress/treat as error)
8241 @cindex @option{-Wx} (@code{gnatbind})
8242 Override default wide character encoding for standard Text_IO files.
8245 @cindex @option{-x} (@code{gnatbind})
8246 Exclude source files (check object consistency only).
8250 @cindex @option{-X@var{nnn}} (@code{gnatbind})
8251 Set default exit status value, normally 0 for POSIX compliance.
8255 @cindex @option{-y} (@code{gnatbind})
8256 Enable leap seconds support in @code{Ada.Calendar} and its children.
8259 @cindex @option{-z} (@code{gnatbind})
8264 You may obtain this listing of switches by running @code{gnatbind} with
8267 @node Consistency-Checking Modes
8268 @subsection Consistency-Checking Modes
8271 As described earlier, by default @code{gnatbind} checks
8272 that object files are consistent with one another and are consistent
8273 with any source files it can locate. The following switches control binder
8279 @cindex @option{-s} (@code{gnatbind})
8280 Require source files to be present. In this mode, the binder must be
8281 able to locate all source files that are referenced, in order to check
8282 their consistency. In normal mode, if a source file cannot be located it
8283 is simply ignored. If you specify this switch, a missing source
8287 @cindex @option{-Wx} (@code{gnatbind})
8288 Override default wide character encoding for standard Text_IO files.
8289 Normally the default wide character encoding method used for standard
8290 [Wide_[Wide_]]Text_IO files is taken from the encoding specified for
8291 the main source input (see description of switch
8292 @option{-gnatWx} for the compiler). The
8293 use of this switch for the binder (which has the same set of
8294 possible arguments) overrides this default as specified.
8297 @cindex @option{-x} (@code{gnatbind})
8298 Exclude source files. In this mode, the binder only checks that ALI
8299 files are consistent with one another. Source files are not accessed.
8300 The binder runs faster in this mode, and there is still a guarantee that
8301 the resulting program is self-consistent.
8302 If a source file has been edited since it was last compiled, and you
8303 specify this switch, the binder will not detect that the object
8304 file is out of date with respect to the source file. Note that this is the
8305 mode that is automatically used by @command{gnatmake} because in this
8306 case the checking against sources has already been performed by
8307 @command{gnatmake} in the course of compilation (i.e.@: before binding).
8311 @node Binder Error Message Control
8312 @subsection Binder Error Message Control
8315 The following switches provide control over the generation of error
8316 messages from the binder:
8321 @cindex @option{-v} (@code{gnatbind})
8322 Verbose mode. In the normal mode, brief error messages are generated to
8323 @file{stderr}. If this switch is present, a header is written
8324 to @file{stdout} and any error messages are directed to @file{stdout}.
8325 All that is written to @file{stderr} is a brief summary message.
8328 @cindex @option{-b} (@code{gnatbind})
8329 Generate brief error messages to @file{stderr} even if verbose mode is
8330 specified. This is relevant only when used with the
8334 @cindex @option{-m} (@code{gnatbind})
8335 Limits the number of error messages to @var{n}, a decimal integer in the
8336 range 1-999. The binder terminates immediately if this limit is reached.
8339 @cindex @option{-M} (@code{gnatbind})
8340 Renames the generated main program from @code{main} to @code{xxx}.
8341 This is useful in the case of some cross-building environments, where
8342 the actual main program is separate from the one generated
8346 @cindex @option{-ws} (@code{gnatbind})
8348 Suppress all warning messages.
8351 @cindex @option{-we} (@code{gnatbind})
8352 Treat any warning messages as fatal errors.
8356 @cindex @option{-t} (@code{gnatbind})
8357 @cindex Time stamp checks, in binder
8358 @cindex Binder consistency checks
8359 @cindex Consistency checks, in binder
8360 The binder performs a number of consistency checks including:
8364 Check that time stamps of a given source unit are consistent
8366 Check that checksums of a given source unit are consistent
8368 Check that consistent versions of @code{GNAT} were used for compilation
8370 Check consistency of configuration pragmas as required
8374 Normally failure of such checks, in accordance with the consistency
8375 requirements of the Ada Reference Manual, causes error messages to be
8376 generated which abort the binder and prevent the output of a binder
8377 file and subsequent link to obtain an executable.
8379 The @option{-t} switch converts these error messages
8380 into warnings, so that
8381 binding and linking can continue to completion even in the presence of such
8382 errors. The result may be a failed link (due to missing symbols), or a
8383 non-functional executable which has undefined semantics.
8384 @emph{This means that
8385 @option{-t} should be used only in unusual situations,
8389 @node Elaboration Control
8390 @subsection Elaboration Control
8393 The following switches provide additional control over the elaboration
8394 order. For full details see @ref{Elaboration Order Handling in GNAT}.
8398 @cindex @option{-p} (@code{gnatbind})
8399 Normally the binder attempts to choose an elaboration order that is
8400 likely to minimize the likelihood of an elaboration order error resulting
8401 in raising a @code{Program_Error} exception. This switch reverses the
8402 action of the binder, and requests that it deliberately choose an order
8403 that is likely to maximize the likelihood of an elaboration error.
8404 This is useful in ensuring portability and avoiding dependence on
8405 accidental fortuitous elaboration ordering.
8407 Normally it only makes sense to use the @option{-p}
8409 elaboration checking is used (@option{-gnatE} switch used for compilation).
8410 This is because in the default static elaboration mode, all necessary
8411 @code{Elaborate} and @code{Elaborate_All} pragmas are implicitly inserted.
8412 These implicit pragmas are still respected by the binder in
8413 @option{-p} mode, so a
8414 safe elaboration order is assured.
8416 Note that @option{-p} is not intended for
8417 production use; it is more for debugging/experimental use.
8420 @node Output Control
8421 @subsection Output Control
8424 The following switches allow additional control over the output
8425 generated by the binder.
8431 @cindex @option{-c} (@code{gnatbind})
8432 Check only. Do not generate the binder output file. In this mode the
8433 binder performs all error checks but does not generate an output file.
8436 @cindex @option{-e} (@code{gnatbind})
8437 Output complete list of elaboration-order dependencies, showing the
8438 reason for each dependency. This output can be rather extensive but may
8439 be useful in diagnosing problems with elaboration order. The output is
8440 written to @file{stdout}.
8443 @cindex @option{-h} (@code{gnatbind})
8444 Output usage information. The output is written to @file{stdout}.
8447 @cindex @option{-K} (@code{gnatbind})
8448 Output linker options to @file{stdout}. Includes library search paths,
8449 contents of pragmas Ident and Linker_Options, and libraries added
8453 @cindex @option{-l} (@code{gnatbind})
8454 Output chosen elaboration order. The output is written to @file{stdout}.
8457 @cindex @option{-O} (@code{gnatbind})
8458 Output full names of all the object files that must be linked to provide
8459 the Ada component of the program. The output is written to @file{stdout}.
8460 This list includes the files explicitly supplied and referenced by the user
8461 as well as implicitly referenced run-time unit files. The latter are
8462 omitted if the corresponding units reside in shared libraries. The
8463 directory names for the run-time units depend on the system configuration.
8466 @cindex @option{-o} (@code{gnatbind})
8467 Set name of output file to @var{file} instead of the normal
8468 @file{b~@var{mainprog}.adb} default. Note that @var{file} denote the Ada
8469 binder generated body filename.
8470 Note that if this option is used, then linking must be done manually.
8471 It is not possible to use gnatlink in this case, since it cannot locate
8475 @cindex @option{-r} (@code{gnatbind})
8476 Generate list of @code{pragma Restrictions} that could be applied to
8477 the current unit. This is useful for code audit purposes, and also may
8478 be used to improve code generation in some cases.
8482 @node Dynamic Allocation Control
8483 @subsection Dynamic Allocation Control
8486 The heap control switches -- @option{-H32} and @option{-H64} --
8487 determine whether dynamic allocation uses 32-bit or 64-bit memory.
8488 They only affect compiler-generated allocations via @code{__gnat_malloc};
8489 explicit calls to @code{malloc} and related functions from the C
8490 run-time library are unaffected.
8494 Allocate memory on 32-bit heap
8497 Allocate memory on 64-bit heap. This is the default
8498 unless explicitly overridden by a @code{'Size} clause on the access type.
8502 These switches are only effective on VMS platforms.
8505 @node Binding with Non-Ada Main Programs
8506 @subsection Binding with Non-Ada Main Programs
8509 In our description so far we have assumed that the main
8510 program is in Ada, and that the task of the binder is to generate a
8511 corresponding function @code{main} that invokes this Ada main
8512 program. GNAT also supports the building of executable programs where
8513 the main program is not in Ada, but some of the called routines are
8514 written in Ada and compiled using GNAT (@pxref{Mixed Language Programming}).
8515 The following switch is used in this situation:
8519 @cindex @option{-n} (@code{gnatbind})
8520 No main program. The main program is not in Ada.
8524 In this case, most of the functions of the binder are still required,
8525 but instead of generating a main program, the binder generates a file
8526 containing the following callable routines:
8531 You must call this routine to initialize the Ada part of the program by
8532 calling the necessary elaboration routines. A call to @code{adainit} is
8533 required before the first call to an Ada subprogram.
8535 Note that it is assumed that the basic execution environment must be setup
8536 to be appropriate for Ada execution at the point where the first Ada
8537 subprogram is called. In particular, if the Ada code will do any
8538 floating-point operations, then the FPU must be setup in an appropriate
8539 manner. For the case of the x86, for example, full precision mode is
8540 required. The procedure GNAT.Float_Control.Reset may be used to ensure
8541 that the FPU is in the right state.
8545 You must call this routine to perform any library-level finalization
8546 required by the Ada subprograms. A call to @code{adafinal} is required
8547 after the last call to an Ada subprogram, and before the program
8552 If the @option{-n} switch
8553 @cindex @option{-n} (@command{gnatbind})
8554 @cindex Binder, multiple input files
8555 is given, more than one ALI file may appear on
8556 the command line for @code{gnatbind}. The normal @dfn{closure}
8557 calculation is performed for each of the specified units. Calculating
8558 the closure means finding out the set of units involved by tracing
8559 @code{with} references. The reason it is necessary to be able to
8560 specify more than one ALI file is that a given program may invoke two or
8561 more quite separate groups of Ada units.
8563 The binder takes the name of its output file from the last specified ALI
8564 file, unless overridden by the use of the @option{-o file}.
8565 @cindex @option{-o} (@command{gnatbind})
8566 The output is an Ada unit in source form that can be compiled with GNAT.
8567 This compilation occurs automatically as part of the @command{gnatlink}
8570 Currently the GNAT run time requires a FPU using 80 bits mode
8571 precision. Under targets where this is not the default it is required to
8572 call GNAT.Float_Control.Reset before using floating point numbers (this
8573 include float computation, float input and output) in the Ada code. A
8574 side effect is that this could be the wrong mode for the foreign code
8575 where floating point computation could be broken after this call.
8577 @node Binding Programs with No Main Subprogram
8578 @subsection Binding Programs with No Main Subprogram
8581 It is possible to have an Ada program which does not have a main
8582 subprogram. This program will call the elaboration routines of all the
8583 packages, then the finalization routines.
8585 The following switch is used to bind programs organized in this manner:
8589 @cindex @option{-z} (@code{gnatbind})
8590 Normally the binder checks that the unit name given on the command line
8591 corresponds to a suitable main subprogram. When this switch is used,
8592 a list of ALI files can be given, and the execution of the program
8593 consists of elaboration of these units in an appropriate order. Note
8594 that the default wide character encoding method for standard Text_IO
8595 files is always set to Brackets if this switch is set (you can use
8597 @option{-Wx} to override this default).
8600 @node Command-Line Access
8601 @section Command-Line Access
8604 The package @code{Ada.Command_Line} provides access to the command-line
8605 arguments and program name. In order for this interface to operate
8606 correctly, the two variables
8618 are declared in one of the GNAT library routines. These variables must
8619 be set from the actual @code{argc} and @code{argv} values passed to the
8620 main program. With no @option{n} present, @code{gnatbind}
8621 generates the C main program to automatically set these variables.
8622 If the @option{n} switch is used, there is no automatic way to
8623 set these variables. If they are not set, the procedures in
8624 @code{Ada.Command_Line} will not be available, and any attempt to use
8625 them will raise @code{Constraint_Error}. If command line access is
8626 required, your main program must set @code{gnat_argc} and
8627 @code{gnat_argv} from the @code{argc} and @code{argv} values passed to
8630 @node Search Paths for gnatbind
8631 @section Search Paths for @code{gnatbind}
8634 The binder takes the name of an ALI file as its argument and needs to
8635 locate source files as well as other ALI files to verify object consistency.
8637 For source files, it follows exactly the same search rules as @command{gcc}
8638 (@pxref{Search Paths and the Run-Time Library (RTL)}). For ALI files the
8639 directories searched are:
8643 The directory containing the ALI file named in the command line, unless
8644 the switch @option{-I-} is specified.
8647 All directories specified by @option{-I}
8648 switches on the @code{gnatbind}
8649 command line, in the order given.
8652 @findex ADA_PRJ_OBJECTS_FILE
8653 Each of the directories listed in the text file whose name is given
8654 by the @env{ADA_PRJ_OBJECTS_FILE} environment variable.
8657 @env{ADA_PRJ_OBJECTS_FILE} is normally set by gnatmake or by the gnat
8658 driver when project files are used. It should not normally be set
8662 @findex ADA_OBJECTS_PATH
8663 Each of the directories listed in the value of the
8664 @env{ADA_OBJECTS_PATH} environment variable.
8665 Construct this value
8666 exactly as the @env{PATH} environment variable: a list of directory
8667 names separated by colons (semicolons when working with the NT version
8671 The content of the @file{ada_object_path} file which is part of the GNAT
8672 installation tree and is used to store standard libraries such as the
8673 GNAT Run Time Library (RTL) unless the switch @option{-nostdlib} is
8675 @ref{Installing a library}
8679 In the binder the switch @option{-I}
8680 @cindex @option{-I} (@command{gnatbind})
8681 is used to specify both source and
8682 library file paths. Use @option{-aI}
8683 @cindex @option{-aI} (@command{gnatbind})
8684 instead if you want to specify
8685 source paths only, and @option{-aO}
8686 @cindex @option{-aO} (@command{gnatbind})
8687 if you want to specify library paths
8688 only. This means that for the binder
8689 @option{-I}@var{dir} is equivalent to
8690 @option{-aI}@var{dir}
8691 @option{-aO}@var{dir}.
8692 The binder generates the bind file (a C language source file) in the
8693 current working directory.
8699 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
8700 children make up the GNAT Run-Time Library, together with the package
8701 GNAT and its children, which contain a set of useful additional
8702 library functions provided by GNAT. The sources for these units are
8703 needed by the compiler and are kept together in one directory. The ALI
8704 files and object files generated by compiling the RTL are needed by the
8705 binder and the linker and are kept together in one directory, typically
8706 different from the directory containing the sources. In a normal
8707 installation, you need not specify these directory names when compiling
8708 or binding. Either the environment variables or the built-in defaults
8709 cause these files to be found.
8711 Besides simplifying access to the RTL, a major use of search paths is
8712 in compiling sources from multiple directories. This can make
8713 development environments much more flexible.
8715 @node Examples of gnatbind Usage
8716 @section Examples of @code{gnatbind} Usage
8719 This section contains a number of examples of using the GNAT binding
8720 utility @code{gnatbind}.
8723 @item gnatbind hello
8724 The main program @code{Hello} (source program in @file{hello.adb}) is
8725 bound using the standard switch settings. The generated main program is
8726 @file{b~hello.adb}. This is the normal, default use of the binder.
8728 @item gnatbind hello -o mainprog.adb
8729 The main program @code{Hello} (source program in @file{hello.adb}) is
8730 bound using the standard switch settings. The generated main program is
8731 @file{mainprog.adb} with the associated spec in
8732 @file{mainprog.ads}. Note that you must specify the body here not the
8733 spec. Note that if this option is used, then linking must be done manually,
8734 since gnatlink will not be able to find the generated file.
8737 @c ------------------------------------
8738 @node Linking with gnatlink
8739 @chapter Linking with @command{gnatlink}
8740 @c ------------------------------------
8744 This chapter discusses @command{gnatlink}, a tool that links
8745 an Ada program and builds an executable file. This utility
8746 invokes the system linker (via the @command{gcc} command)
8747 with a correct list of object files and library references.
8748 @command{gnatlink} automatically determines the list of files and
8749 references for the Ada part of a program. It uses the binder file
8750 generated by the @command{gnatbind} to determine this list.
8752 Note: to invoke @code{gnatlink} with a project file, use the @code{gnat}
8753 driver (see @ref{The GNAT Driver and Project Files}).
8756 * Running gnatlink::
8757 * Switches for gnatlink::
8760 @node Running gnatlink
8761 @section Running @command{gnatlink}
8764 The form of the @command{gnatlink} command is
8767 @c $ gnatlink @ovar{switches} @var{mainprog}@r{[}.ali@r{]}
8768 @c @ovar{non-Ada objects} @ovar{linker options}
8769 @c Expanding @ovar macro inline (explanation in macro def comments)
8770 $ gnatlink @r{[}@var{switches}@r{]} @var{mainprog}@r{[}.ali@r{]}
8771 @r{[}@var{non-Ada objects}@r{]} @r{[}@var{linker options}@r{]}
8776 The arguments of @command{gnatlink} (switches, main @file{ALI} file,
8778 or linker options) may be in any order, provided that no non-Ada object may
8779 be mistaken for a main @file{ALI} file.
8780 Any file name @file{F} without the @file{.ali}
8781 extension will be taken as the main @file{ALI} file if a file exists
8782 whose name is the concatenation of @file{F} and @file{.ali}.
8785 @file{@var{mainprog}.ali} references the ALI file of the main program.
8786 The @file{.ali} extension of this file can be omitted. From this
8787 reference, @command{gnatlink} locates the corresponding binder file
8788 @file{b~@var{mainprog}.adb} and, using the information in this file along
8789 with the list of non-Ada objects and linker options, constructs a
8790 linker command file to create the executable.
8792 The arguments other than the @command{gnatlink} switches and the main
8793 @file{ALI} file are passed to the linker uninterpreted.
8794 They typically include the names of
8795 object files for units written in other languages than Ada and any library
8796 references required to resolve references in any of these foreign language
8797 units, or in @code{Import} pragmas in any Ada units.
8799 @var{linker options} is an optional list of linker specific
8801 The default linker called by gnatlink is @command{gcc} which in
8802 turn calls the appropriate system linker.
8804 One useful option for the linker is @option{-s}: it reduces the size of the
8805 executable by removing all symbol table and relocation information from the
8808 Standard options for the linker such as @option{-lmy_lib} or
8809 @option{-Ldir} can be added as is.
8810 For options that are not recognized by
8811 @command{gcc} as linker options, use the @command{gcc} switches
8812 @option{-Xlinker} or @option{-Wl,}.
8814 Refer to the GCC documentation for
8817 Here is an example showing how to generate a linker map:
8820 $ gnatlink my_prog -Wl,-Map,MAPFILE
8823 Using @var{linker options} it is possible to set the program stack and
8825 See @ref{Setting Stack Size from gnatlink} and
8826 @ref{Setting Heap Size from gnatlink}.
8828 @command{gnatlink} determines the list of objects required by the Ada
8829 program and prepends them to the list of objects passed to the linker.
8830 @command{gnatlink} also gathers any arguments set by the use of
8831 @code{pragma Linker_Options} and adds them to the list of arguments
8832 presented to the linker.
8835 @node Switches for gnatlink
8836 @section Switches for @command{gnatlink}
8839 The following switches are available with the @command{gnatlink} utility:
8845 @cindex @option{--version} @command{gnatlink}
8846 Display Copyright and version, then exit disregarding all other options.
8849 @cindex @option{--help} @command{gnatlink}
8850 If @option{--version} was not used, display usage, then exit disregarding
8854 @cindex Command line length
8855 @cindex @option{-f} (@command{gnatlink})
8856 On some targets, the command line length is limited, and @command{gnatlink}
8857 will generate a separate file for the linker if the list of object files
8859 The @option{-f} switch forces this file
8860 to be generated even if
8861 the limit is not exceeded. This is useful in some cases to deal with
8862 special situations where the command line length is exceeded.
8865 @cindex Debugging information, including
8866 @cindex @option{-g} (@command{gnatlink})
8867 The option to include debugging information causes the Ada bind file (in
8868 other words, @file{b~@var{mainprog}.adb}) to be compiled with
8870 In addition, the binder does not delete the @file{b~@var{mainprog}.adb},
8871 @file{b~@var{mainprog}.o} and @file{b~@var{mainprog}.ali} files.
8872 Without @option{-g}, the binder removes these files by
8873 default. The same procedure apply if a C bind file was generated using
8874 @option{-C} @code{gnatbind} option, in this case the filenames
8875 are @file{b_@var{mainprog}.c} and @file{b_@var{mainprog}.o}.
8878 @cindex @option{-n} (@command{gnatlink})
8879 Do not compile the file generated by the binder. This may be used when
8880 a link is rerun with different options, but there is no need to recompile
8884 @cindex @option{-v} (@command{gnatlink})
8885 Causes additional information to be output, including a full list of the
8886 included object files. This switch option is most useful when you want
8887 to see what set of object files are being used in the link step.
8890 @cindex @option{-v -v} (@command{gnatlink})
8891 Very verbose mode. Requests that the compiler operate in verbose mode when
8892 it compiles the binder file, and that the system linker run in verbose mode.
8894 @item -o @var{exec-name}
8895 @cindex @option{-o} (@command{gnatlink})
8896 @var{exec-name} specifies an alternate name for the generated
8897 executable program. If this switch is omitted, the executable has the same
8898 name as the main unit. For example, @code{gnatlink try.ali} creates
8899 an executable called @file{try}.
8901 @item -b @var{target}
8902 @cindex @option{-b} (@command{gnatlink})
8903 Compile your program to run on @var{target}, which is the name of a
8904 system configuration. You must have a GNAT cross-compiler built if
8905 @var{target} is not the same as your host system.
8908 @cindex @option{-B} (@command{gnatlink})
8909 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
8910 from @var{dir} instead of the default location. Only use this switch
8911 when multiple versions of the GNAT compiler are available.
8912 @xref{Directory Options,,, gcc, The GNU Compiler Collection},
8913 for further details. You would normally use the @option{-b} or
8914 @option{-V} switch instead.
8917 When linking an executable, create a map file. The name of the map file
8918 has the same name as the executable with extension ".map".
8921 When linking an executable, create a map file. The name of the map file is
8924 @item --GCC=@var{compiler_name}
8925 @cindex @option{--GCC=compiler_name} (@command{gnatlink})
8926 Program used for compiling the binder file. The default is
8927 @command{gcc}. You need to use quotes around @var{compiler_name} if
8928 @code{compiler_name} contains spaces or other separator characters.
8929 As an example @option{--GCC="foo -x -y"} will instruct @command{gnatlink} to
8930 use @code{foo -x -y} as your compiler. Note that switch @option{-c} is always
8931 inserted after your command name. Thus in the above example the compiler
8932 command that will be used by @command{gnatlink} will be @code{foo -c -x -y}.
8933 A limitation of this syntax is that the name and path name of the executable
8934 itself must not include any embedded spaces. If the compiler executable is
8935 different from the default one (gcc or <prefix>-gcc), then the back-end
8936 switches in the ALI file are not used to compile the binder generated source.
8937 For example, this is the case with @option{--GCC="foo -x -y"}. But the back end
8938 switches will be used for @option{--GCC="gcc -gnatv"}. If several
8939 @option{--GCC=compiler_name} are used, only the last @var{compiler_name}
8940 is taken into account. However, all the additional switches are also taken
8942 @option{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
8943 @option{--GCC="bar -x -y -z -t"}.
8945 @item --LINK=@var{name}
8946 @cindex @option{--LINK=} (@command{gnatlink})
8947 @var{name} is the name of the linker to be invoked. This is especially
8948 useful in mixed language programs since languages such as C++ require
8949 their own linker to be used. When this switch is omitted, the default
8950 name for the linker is @command{gcc}. When this switch is used, the
8951 specified linker is called instead of @command{gcc} with exactly the same
8952 parameters that would have been passed to @command{gcc} so if the desired
8953 linker requires different parameters it is necessary to use a wrapper
8954 script that massages the parameters before invoking the real linker. It
8955 may be useful to control the exact invocation by using the verbose
8962 @node The GNAT Make Program gnatmake
8963 @chapter The GNAT Make Program @command{gnatmake}
8967 * Running gnatmake::
8968 * Switches for gnatmake::
8969 * Mode Switches for gnatmake::
8970 * Notes on the Command Line::
8971 * How gnatmake Works::
8972 * Examples of gnatmake Usage::
8975 A typical development cycle when working on an Ada program consists of
8976 the following steps:
8980 Edit some sources to fix bugs.
8986 Compile all sources affected.
8996 The third step can be tricky, because not only do the modified files
8997 @cindex Dependency rules
8998 have to be compiled, but any files depending on these files must also be
8999 recompiled. The dependency rules in Ada can be quite complex, especially
9000 in the presence of overloading, @code{use} clauses, generics and inlined
9003 @command{gnatmake} automatically takes care of the third and fourth steps
9004 of this process. It determines which sources need to be compiled,
9005 compiles them, and binds and links the resulting object files.
9007 Unlike some other Ada make programs, the dependencies are always
9008 accurately recomputed from the new sources. The source based approach of
9009 the GNAT compilation model makes this possible. This means that if
9010 changes to the source program cause corresponding changes in
9011 dependencies, they will always be tracked exactly correctly by
9014 @node Running gnatmake
9015 @section Running @command{gnatmake}
9018 The usual form of the @command{gnatmake} command is
9021 @c $ gnatmake @ovar{switches} @var{file_name}
9022 @c @ovar{file_names} @ovar{mode_switches}
9023 @c Expanding @ovar macro inline (explanation in macro def comments)
9024 $ gnatmake @r{[}@var{switches}@r{]} @var{file_name}
9025 @r{[}@var{file_names}@r{]} @r{[}@var{mode_switches}@r{]}
9029 The only required argument is one @var{file_name}, which specifies
9030 a compilation unit that is a main program. Several @var{file_names} can be
9031 specified: this will result in several executables being built.
9032 If @code{switches} are present, they can be placed before the first
9033 @var{file_name}, between @var{file_names} or after the last @var{file_name}.
9034 If @var{mode_switches} are present, they must always be placed after
9035 the last @var{file_name} and all @code{switches}.
9037 If you are using standard file extensions (@file{.adb} and @file{.ads}), then the
9038 extension may be omitted from the @var{file_name} arguments. However, if
9039 you are using non-standard extensions, then it is required that the
9040 extension be given. A relative or absolute directory path can be
9041 specified in a @var{file_name}, in which case, the input source file will
9042 be searched for in the specified directory only. Otherwise, the input
9043 source file will first be searched in the directory where
9044 @command{gnatmake} was invoked and if it is not found, it will be search on
9045 the source path of the compiler as described in
9046 @ref{Search Paths and the Run-Time Library (RTL)}.
9048 All @command{gnatmake} output (except when you specify
9050 @file{stderr}. The output produced by the
9051 @option{-M} switch is send to
9054 @node Switches for gnatmake
9055 @section Switches for @command{gnatmake}
9058 You may specify any of the following switches to @command{gnatmake}:
9064 @cindex @option{--version} @command{gnatmake}
9065 Display Copyright and version, then exit disregarding all other options.
9068 @cindex @option{--help} @command{gnatmake}
9069 If @option{--version} was not used, display usage, then exit disregarding
9072 @item --GCC=@var{compiler_name}
9073 @cindex @option{--GCC=compiler_name} (@command{gnatmake})
9074 Program used for compiling. The default is `@command{gcc}'. You need to use
9075 quotes around @var{compiler_name} if @code{compiler_name} contains
9076 spaces or other separator characters. As an example @option{--GCC="foo -x
9077 -y"} will instruct @command{gnatmake} to use @code{foo -x -y} as your
9078 compiler. A limitation of this syntax is that the name and path name of
9079 the executable itself must not include any embedded spaces. Note that
9080 switch @option{-c} is always inserted after your command name. Thus in the
9081 above example the compiler command that will be used by @command{gnatmake}
9082 will be @code{foo -c -x -y}. If several @option{--GCC=compiler_name} are
9083 used, only the last @var{compiler_name} is taken into account. However,
9084 all the additional switches are also taken into account. Thus,
9085 @option{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
9086 @option{--GCC="bar -x -y -z -t"}.
9088 @item --GNATBIND=@var{binder_name}
9089 @cindex @option{--GNATBIND=binder_name} (@command{gnatmake})
9090 Program used for binding. The default is `@code{gnatbind}'. You need to
9091 use quotes around @var{binder_name} if @var{binder_name} contains spaces
9092 or other separator characters. As an example @option{--GNATBIND="bar -x
9093 -y"} will instruct @command{gnatmake} to use @code{bar -x -y} as your
9094 binder. Binder switches that are normally appended by @command{gnatmake}
9095 to `@code{gnatbind}' are now appended to the end of @code{bar -x -y}.
9096 A limitation of this syntax is that the name and path name of the executable
9097 itself must not include any embedded spaces.
9099 @item --GNATLINK=@var{linker_name}
9100 @cindex @option{--GNATLINK=linker_name} (@command{gnatmake})
9101 Program used for linking. The default is `@command{gnatlink}'. You need to
9102 use quotes around @var{linker_name} if @var{linker_name} contains spaces
9103 or other separator characters. As an example @option{--GNATLINK="lan -x
9104 -y"} will instruct @command{gnatmake} to use @code{lan -x -y} as your
9105 linker. Linker switches that are normally appended by @command{gnatmake} to
9106 `@command{gnatlink}' are now appended to the end of @code{lan -x -y}.
9107 A limitation of this syntax is that the name and path name of the executable
9108 itself must not include any embedded spaces.
9111 @item --subdirs=subdir
9112 Actual object directory of each project file is the subdirectory subdir of the
9113 object directory specified or defaulted in the project file.
9115 @item --single-compile-per-obj-dir
9116 Disallow simultaneous compilations in the same object directory when
9117 project files are used.
9119 @item --unchecked-shared-lib-imports
9120 By default, shared library projects are not allowed to import static library
9121 projects. When this switch is used on the command line, this restriction is
9124 @item --source-info=<source info file>
9125 Specify a source info file. This switch is active only when project files
9126 are used. If the source info file is specified as a relative path, then it is
9127 relative to the object directory of the main project. If the source info file
9128 does not exist, then after the Project Manager has successfully parsed and
9129 processed the project files and found the sources, it creates the source info
9130 file. If the source info file already exists and can be read successfully,
9131 then the Project Manager will get all the needed information about the sources
9132 from the source info file and will not look for them. This reduces the time
9133 to process the project files, especially when looking for sources that take a
9134 long time. If the source info file exists but cannot be parsed successfully,
9135 the Project Manager will attempt to recreate it. If the Project Manager fails
9136 to create the source info file, a message is issued, but gnatmake does not
9137 fail. @command{gnatmake} "trusts" the source info file. This means that
9138 if the source files have changed (addition, deletion, moving to a different
9139 source directory), then the source info file need to be deleted and recreated.
9141 @item --create-map-file
9142 When linking an executable, create a map file. The name of the map file
9143 has the same name as the executable with extension ".map".
9145 @item --create-map-file=mapfile
9146 When linking an executable, create a map file. The name of the map file is
9151 @cindex @option{-a} (@command{gnatmake})
9152 Consider all files in the make process, even the GNAT internal system
9153 files (for example, the predefined Ada library files), as well as any
9154 locked files. Locked files are files whose ALI file is write-protected.
9156 @command{gnatmake} does not check these files,
9157 because the assumption is that the GNAT internal files are properly up
9158 to date, and also that any write protected ALI files have been properly
9159 installed. Note that if there is an installation problem, such that one
9160 of these files is not up to date, it will be properly caught by the
9162 You may have to specify this switch if you are working on GNAT
9163 itself. The switch @option{-a} is also useful
9164 in conjunction with @option{-f}
9165 if you need to recompile an entire application,
9166 including run-time files, using special configuration pragmas,
9167 such as a @code{Normalize_Scalars} pragma.
9170 @code{gnatmake -a} compiles all GNAT
9172 @code{gcc -c -gnatpg} rather than @code{gcc -c}.
9175 @cindex @option{-b} (@command{gnatmake})
9176 Bind only. Can be combined with @option{-c} to do
9177 compilation and binding, but no link.
9178 Can be combined with @option{-l}
9179 to do binding and linking. When not combined with
9181 all the units in the closure of the main program must have been previously
9182 compiled and must be up to date. The root unit specified by @var{file_name}
9183 may be given without extension, with the source extension or, if no GNAT
9184 Project File is specified, with the ALI file extension.
9187 @cindex @option{-c} (@command{gnatmake})
9188 Compile only. Do not perform binding, except when @option{-b}
9189 is also specified. Do not perform linking, except if both
9191 @option{-l} are also specified.
9192 If the root unit specified by @var{file_name} is not a main unit, this is the
9193 default. Otherwise @command{gnatmake} will attempt binding and linking
9194 unless all objects are up to date and the executable is more recent than
9198 @cindex @option{-C} (@command{gnatmake})
9199 Use a temporary mapping file. A mapping file is a way to communicate
9200 to the compiler two mappings: from unit names to file names (without
9201 any directory information) and from file names to path names (with
9202 full directory information). A mapping file can make the compiler's
9203 file searches faster, especially if there are many source directories,
9204 or the sources are read over a slow network connection. If
9205 @option{-P} is used, a mapping file is always used, so
9206 @option{-C} is unnecessary; in this case the mapping file
9207 is initially populated based on the project file. If
9208 @option{-C} is used without
9210 the mapping file is initially empty. Each invocation of the compiler
9211 will add any newly accessed sources to the mapping file.
9214 @cindex @option{-C=} (@command{gnatmake})
9215 Use a specific mapping file. The file, specified as a path name (absolute or
9216 relative) by this switch, should already exist, otherwise the switch is
9217 ineffective. The specified mapping file will be communicated to the compiler.
9218 This switch is not compatible with a project file
9219 (-P@var{file}) or with multiple compiling processes
9220 (-jnnn, when nnn is greater than 1).
9223 @cindex @option{-d} (@command{gnatmake})
9224 Display progress for each source, up to date or not, as a single line
9227 completed x out of y (zz%)
9230 If the file needs to be compiled this is displayed after the invocation of
9231 the compiler. These lines are displayed even in quiet output mode.
9234 @cindex @option{-D} (@command{gnatmake})
9235 Put all object files and ALI file in directory @var{dir}.
9236 If the @option{-D} switch is not used, all object files
9237 and ALI files go in the current working directory.
9239 This switch cannot be used when using a project file.
9242 @cindex @option{-eI} (@command{gnatmake})
9243 Indicates that the main source is a multi-unit source and the rank of the unit
9244 in the source file is nnn. nnn needs to be a positive number and a valid
9245 index in the source. This switch cannot be used when @command{gnatmake} is
9246 invoked for several mains.
9249 @cindex @option{-eL} (@command{gnatmake})
9250 @cindex symbolic links
9251 Follow all symbolic links when processing project files.
9252 This should be used if your project uses symbolic links for files or
9253 directories, but is not needed in other cases.
9255 @cindex naming scheme
9256 This also assumes that no directory matches the naming scheme for files (for
9257 instance that you do not have a directory called "sources.ads" when using the
9258 default GNAT naming scheme).
9260 When you do not have to use this switch (i.e.@: by default), gnatmake is able to
9261 save a lot of system calls (several per source file and object file), which
9262 can result in a significant speed up to load and manipulate a project file,
9263 especially when using source files from a remote system.
9267 @cindex @option{-eS} (@command{gnatmake})
9268 Output the commands for the compiler, the binder and the linker
9270 instead of standard error.
9273 @cindex @option{-f} (@command{gnatmake})
9274 Force recompilations. Recompile all sources, even though some object
9275 files may be up to date, but don't recompile predefined or GNAT internal
9276 files or locked files (files with a write-protected ALI file),
9277 unless the @option{-a} switch is also specified.
9280 @cindex @option{-F} (@command{gnatmake})
9281 When using project files, if some errors or warnings are detected during
9282 parsing and verbose mode is not in effect (no use of switch
9283 -v), then error lines start with the full path name of the project
9284 file, rather than its simple file name.
9287 @cindex @option{-g} (@command{gnatmake})
9288 Enable debugging. This switch is simply passed to the compiler and to the
9292 @cindex @option{-i} (@command{gnatmake})
9293 In normal mode, @command{gnatmake} compiles all object files and ALI files
9294 into the current directory. If the @option{-i} switch is used,
9295 then instead object files and ALI files that already exist are overwritten
9296 in place. This means that once a large project is organized into separate
9297 directories in the desired manner, then @command{gnatmake} will automatically
9298 maintain and update this organization. If no ALI files are found on the
9299 Ada object path (@ref{Search Paths and the Run-Time Library (RTL)}),
9300 the new object and ALI files are created in the
9301 directory containing the source being compiled. If another organization
9302 is desired, where objects and sources are kept in different directories,
9303 a useful technique is to create dummy ALI files in the desired directories.
9304 When detecting such a dummy file, @command{gnatmake} will be forced to
9305 recompile the corresponding source file, and it will be put the resulting
9306 object and ALI files in the directory where it found the dummy file.
9309 @cindex @option{-j} (@command{gnatmake})
9310 @cindex Parallel make
9311 Use @var{n} processes to carry out the (re)compilations. On a multiprocessor
9312 machine compilations will occur in parallel. If @var{n} is 0, then the
9313 maximum number of parallel compilations is the number of core processors
9314 on the platform. In the event of compilation errors, messages from various
9315 compilations might get interspersed (but @command{gnatmake} will give you the
9316 full ordered list of failing compiles at the end). If this is problematic,
9317 rerun the make process with n set to 1 to get a clean list of messages.
9320 @cindex @option{-k} (@command{gnatmake})
9321 Keep going. Continue as much as possible after a compilation error. To
9322 ease the programmer's task in case of compilation errors, the list of
9323 sources for which the compile fails is given when @command{gnatmake}
9326 If @command{gnatmake} is invoked with several @file{file_names} and with this
9327 switch, if there are compilation errors when building an executable,
9328 @command{gnatmake} will not attempt to build the following executables.
9331 @cindex @option{-l} (@command{gnatmake})
9332 Link only. Can be combined with @option{-b} to binding
9333 and linking. Linking will not be performed if combined with
9335 but not with @option{-b}.
9336 When not combined with @option{-b}
9337 all the units in the closure of the main program must have been previously
9338 compiled and must be up to date, and the main program needs to have been bound.
9339 The root unit specified by @var{file_name}
9340 may be given without extension, with the source extension or, if no GNAT
9341 Project File is specified, with the ALI file extension.
9344 @cindex @option{-m} (@command{gnatmake})
9345 Specify that the minimum necessary amount of recompilations
9346 be performed. In this mode @command{gnatmake} ignores time
9347 stamp differences when the only
9348 modifications to a source file consist in adding/removing comments,
9349 empty lines, spaces or tabs. This means that if you have changed the
9350 comments in a source file or have simply reformatted it, using this
9351 switch will tell @command{gnatmake} not to recompile files that depend on it
9352 (provided other sources on which these files depend have undergone no
9353 semantic modifications). Note that the debugging information may be
9354 out of date with respect to the sources if the @option{-m} switch causes
9355 a compilation to be switched, so the use of this switch represents a
9356 trade-off between compilation time and accurate debugging information.
9359 @cindex Dependencies, producing list
9360 @cindex @option{-M} (@command{gnatmake})
9361 Check if all objects are up to date. If they are, output the object
9362 dependences to @file{stdout} in a form that can be directly exploited in
9363 a @file{Makefile}. By default, each source file is prefixed with its
9364 (relative or absolute) directory name. This name is whatever you
9365 specified in the various @option{-aI}
9366 and @option{-I} switches. If you use
9369 (see below), only the source file names,
9370 without relative paths, are output. If you just specify the
9372 switch, dependencies of the GNAT internal system files are omitted. This
9373 is typically what you want. If you also specify
9374 the @option{-a} switch,
9375 dependencies of the GNAT internal files are also listed. Note that
9376 dependencies of the objects in external Ada libraries (see switch
9377 @option{-aL}@var{dir} in the following list)
9381 @cindex @option{-n} (@command{gnatmake})
9382 Don't compile, bind, or link. Checks if all objects are up to date.
9383 If they are not, the full name of the first file that needs to be
9384 recompiled is printed.
9385 Repeated use of this option, followed by compiling the indicated source
9386 file, will eventually result in recompiling all required units.
9388 @item -o @var{exec_name}
9389 @cindex @option{-o} (@command{gnatmake})
9390 Output executable name. The name of the final executable program will be
9391 @var{exec_name}. If the @option{-o} switch is omitted the default
9392 name for the executable will be the name of the input file in appropriate form
9393 for an executable file on the host system.
9395 This switch cannot be used when invoking @command{gnatmake} with several
9398 @item -p or --create-missing-dirs
9399 @cindex @option{-p} (@command{gnatmake})
9400 When using project files (-P@var{project}), create
9401 automatically missing object directories, library directories and exec
9404 @item -P@var{project}
9405 @cindex @option{-P} (@command{gnatmake})
9406 Use project file @var{project}. Only one such switch can be used.
9407 @xref{gnatmake and Project Files}.
9410 @cindex @option{-q} (@command{gnatmake})
9411 Quiet. When this flag is not set, the commands carried out by
9412 @command{gnatmake} are displayed.
9415 @cindex @option{-s} (@command{gnatmake})
9416 Recompile if compiler switches have changed since last compilation.
9417 All compiler switches but -I and -o are taken into account in the
9419 orders between different ``first letter'' switches are ignored, but
9420 orders between same switches are taken into account. For example,
9421 @option{-O -O2} is different than @option{-O2 -O}, but @option{-g -O}
9422 is equivalent to @option{-O -g}.
9424 This switch is recommended when Integrated Preprocessing is used.
9427 @cindex @option{-u} (@command{gnatmake})
9428 Unique. Recompile at most the main files. It implies -c. Combined with
9429 -f, it is equivalent to calling the compiler directly. Note that using
9430 -u with a project file and no main has a special meaning
9431 (@pxref{Project Files and Main Subprograms}).
9434 @cindex @option{-U} (@command{gnatmake})
9435 When used without a project file or with one or several mains on the command
9436 line, is equivalent to -u. When used with a project file and no main
9437 on the command line, all sources of all project files are checked and compiled
9438 if not up to date, and libraries are rebuilt, if necessary.
9441 @cindex @option{-v} (@command{gnatmake})
9442 Verbose. Display the reason for all recompilations @command{gnatmake}
9443 decides are necessary, with the highest verbosity level.
9446 @cindex @option{-vl} (@command{gnatmake})
9447 Verbosity level Low. Display fewer lines than in verbosity Medium.
9450 @cindex @option{-vm} (@command{gnatmake})
9451 Verbosity level Medium. Potentially display fewer lines than in verbosity High.
9454 @cindex @option{-vm} (@command{gnatmake})
9455 Verbosity level High. Equivalent to -v.
9458 Indicate the verbosity of the parsing of GNAT project files.
9459 @xref{Switches Related to Project Files}.
9462 @cindex @option{-x} (@command{gnatmake})
9463 Indicate that sources that are not part of any Project File may be compiled.
9464 Normally, when using Project Files, only sources that are part of a Project
9465 File may be compile. When this switch is used, a source outside of all Project
9466 Files may be compiled. The ALI file and the object file will be put in the
9467 object directory of the main Project. The compilation switches used will only
9468 be those specified on the command line. Even when
9469 @option{-x} is used, mains specified on the
9470 command line need to be sources of a project file.
9472 @item -X@var{name=value}
9473 Indicate that external variable @var{name} has the value @var{value}.
9474 The Project Manager will use this value for occurrences of
9475 @code{external(name)} when parsing the project file.
9476 @xref{Switches Related to Project Files}.
9479 @cindex @option{-z} (@command{gnatmake})
9480 No main subprogram. Bind and link the program even if the unit name
9481 given on the command line is a package name. The resulting executable
9482 will execute the elaboration routines of the package and its closure,
9483 then the finalization routines.
9488 @item @command{gcc} @asis{switches}
9489 Any uppercase or multi-character switch that is not a @command{gnatmake} switch
9490 is passed to @command{gcc} (e.g.@: @option{-O}, @option{-gnato,} etc.)
9494 Source and library search path switches:
9499 @cindex @option{-aI} (@command{gnatmake})
9500 When looking for source files also look in directory @var{dir}.
9501 The order in which source files search is undertaken is
9502 described in @ref{Search Paths and the Run-Time Library (RTL)}.
9505 @cindex @option{-aL} (@command{gnatmake})
9506 Consider @var{dir} as being an externally provided Ada library.
9507 Instructs @command{gnatmake} to skip compilation units whose @file{.ALI}
9508 files have been located in directory @var{dir}. This allows you to have
9509 missing bodies for the units in @var{dir} and to ignore out of date bodies
9510 for the same units. You still need to specify
9511 the location of the specs for these units by using the switches
9512 @option{-aI@var{dir}}
9513 or @option{-I@var{dir}}.
9514 Note: this switch is provided for compatibility with previous versions
9515 of @command{gnatmake}. The easier method of causing standard libraries
9516 to be excluded from consideration is to write-protect the corresponding
9520 @cindex @option{-aO} (@command{gnatmake})
9521 When searching for library and object files, look in directory
9522 @var{dir}. The order in which library files are searched is described in
9523 @ref{Search Paths for gnatbind}.
9526 @cindex Search paths, for @command{gnatmake}
9527 @cindex @option{-A} (@command{gnatmake})
9528 Equivalent to @option{-aL@var{dir}
9532 @cindex @option{-I} (@command{gnatmake})
9533 Equivalent to @option{-aO@var{dir}
9537 @cindex @option{-I-} (@command{gnatmake})
9538 @cindex Source files, suppressing search
9539 Do not look for source files in the directory containing the source
9540 file named in the command line.
9541 Do not look for ALI or object files in the directory
9542 where @command{gnatmake} was invoked.
9545 @cindex @option{-L} (@command{gnatmake})
9546 @cindex Linker libraries
9547 Add directory @var{dir} to the list of directories in which the linker
9548 will search for libraries. This is equivalent to
9549 @option{-largs -L}@var{dir}.
9550 Furthermore, under Windows, the sources pointed to by the libraries path
9551 set in the registry are not searched for.
9554 @cindex @option{-nostdinc} (@command{gnatmake})
9555 Do not look for source files in the system default directory.
9558 @cindex @option{-nostdlib} (@command{gnatmake})
9559 Do not look for library files in the system default directory.
9561 @item --RTS=@var{rts-path}
9562 @cindex @option{--RTS} (@command{gnatmake})
9563 Specifies the default location of the runtime library. GNAT looks for the
9565 in the following directories, and stops as soon as a valid runtime is found
9566 (@file{adainclude} or @file{ada_source_path}, and @file{adalib} or
9567 @file{ada_object_path} present):
9570 @item <current directory>/$rts_path
9572 @item <default-search-dir>/$rts_path
9574 @item <default-search-dir>/rts-$rts_path
9578 The selected path is handled like a normal RTS path.
9582 @node Mode Switches for gnatmake
9583 @section Mode Switches for @command{gnatmake}
9586 The mode switches (referred to as @code{mode_switches}) allow the
9587 inclusion of switches that are to be passed to the compiler itself, the
9588 binder or the linker. The effect of a mode switch is to cause all
9589 subsequent switches up to the end of the switch list, or up to the next
9590 mode switch, to be interpreted as switches to be passed on to the
9591 designated component of GNAT.
9595 @item -cargs @var{switches}
9596 @cindex @option{-cargs} (@command{gnatmake})
9597 Compiler switches. Here @var{switches} is a list of switches
9598 that are valid switches for @command{gcc}. They will be passed on to
9599 all compile steps performed by @command{gnatmake}.
9601 @item -bargs @var{switches}
9602 @cindex @option{-bargs} (@command{gnatmake})
9603 Binder switches. Here @var{switches} is a list of switches
9604 that are valid switches for @code{gnatbind}. They will be passed on to
9605 all bind steps performed by @command{gnatmake}.
9607 @item -largs @var{switches}
9608 @cindex @option{-largs} (@command{gnatmake})
9609 Linker switches. Here @var{switches} is a list of switches
9610 that are valid switches for @command{gnatlink}. They will be passed on to
9611 all link steps performed by @command{gnatmake}.
9613 @item -margs @var{switches}
9614 @cindex @option{-margs} (@command{gnatmake})
9615 Make switches. The switches are directly interpreted by @command{gnatmake},
9616 regardless of any previous occurrence of @option{-cargs}, @option{-bargs}
9620 @node Notes on the Command Line
9621 @section Notes on the Command Line
9624 This section contains some additional useful notes on the operation
9625 of the @command{gnatmake} command.
9629 @cindex Recompilation, by @command{gnatmake}
9630 If @command{gnatmake} finds no ALI files, it recompiles the main program
9631 and all other units required by the main program.
9632 This means that @command{gnatmake}
9633 can be used for the initial compile, as well as during subsequent steps of
9634 the development cycle.
9637 If you enter @code{gnatmake @var{file}.adb}, where @file{@var{file}.adb}
9638 is a subunit or body of a generic unit, @command{gnatmake} recompiles
9639 @file{@var{file}.adb} (because it finds no ALI) and stops, issuing a
9643 In @command{gnatmake} the switch @option{-I}
9644 is used to specify both source and
9645 library file paths. Use @option{-aI}
9646 instead if you just want to specify
9647 source paths only and @option{-aO}
9648 if you want to specify library paths
9652 @command{gnatmake} will ignore any files whose ALI file is write-protected.
9653 This may conveniently be used to exclude standard libraries from
9654 consideration and in particular it means that the use of the
9655 @option{-f} switch will not recompile these files
9656 unless @option{-a} is also specified.
9659 @command{gnatmake} has been designed to make the use of Ada libraries
9660 particularly convenient. Assume you have an Ada library organized
9661 as follows: @i{obj-dir} contains the objects and ALI files for
9662 of your Ada compilation units,
9663 whereas @i{include-dir} contains the
9664 specs of these units, but no bodies. Then to compile a unit
9665 stored in @code{main.adb}, which uses this Ada library you would just type
9668 $ gnatmake -aI@var{include-dir} -aL@var{obj-dir} main
9672 Using @command{gnatmake} along with the
9673 @option{-m (minimal recompilation)}
9674 switch provides a mechanism for avoiding unnecessary recompilations. Using
9676 you can update the comments/format of your
9677 source files without having to recompile everything. Note, however, that
9678 adding or deleting lines in a source files may render its debugging
9679 info obsolete. If the file in question is a spec, the impact is rather
9680 limited, as that debugging info will only be useful during the
9681 elaboration phase of your program. For bodies the impact can be more
9682 significant. In all events, your debugger will warn you if a source file
9683 is more recent than the corresponding object, and alert you to the fact
9684 that the debugging information may be out of date.
9687 @node How gnatmake Works
9688 @section How @command{gnatmake} Works
9691 Generally @command{gnatmake} automatically performs all necessary
9692 recompilations and you don't need to worry about how it works. However,
9693 it may be useful to have some basic understanding of the @command{gnatmake}
9694 approach and in particular to understand how it uses the results of
9695 previous compilations without incorrectly depending on them.
9697 First a definition: an object file is considered @dfn{up to date} if the
9698 corresponding ALI file exists and if all the source files listed in the
9699 dependency section of this ALI file have time stamps matching those in
9700 the ALI file. This means that neither the source file itself nor any
9701 files that it depends on have been modified, and hence there is no need
9702 to recompile this file.
9704 @command{gnatmake} works by first checking if the specified main unit is up
9705 to date. If so, no compilations are required for the main unit. If not,
9706 @command{gnatmake} compiles the main program to build a new ALI file that
9707 reflects the latest sources. Then the ALI file of the main unit is
9708 examined to find all the source files on which the main program depends,
9709 and @command{gnatmake} recursively applies the above procedure on all these
9712 This process ensures that @command{gnatmake} only trusts the dependencies
9713 in an existing ALI file if they are known to be correct. Otherwise it
9714 always recompiles to determine a new, guaranteed accurate set of
9715 dependencies. As a result the program is compiled ``upside down'' from what may
9716 be more familiar as the required order of compilation in some other Ada
9717 systems. In particular, clients are compiled before the units on which
9718 they depend. The ability of GNAT to compile in any order is critical in
9719 allowing an order of compilation to be chosen that guarantees that
9720 @command{gnatmake} will recompute a correct set of new dependencies if
9723 When invoking @command{gnatmake} with several @var{file_names}, if a unit is
9724 imported by several of the executables, it will be recompiled at most once.
9726 Note: when using non-standard naming conventions
9727 (@pxref{Using Other File Names}), changing through a configuration pragmas
9728 file the version of a source and invoking @command{gnatmake} to recompile may
9729 have no effect, if the previous version of the source is still accessible
9730 by @command{gnatmake}. It may be necessary to use the switch
9733 @node Examples of gnatmake Usage
9734 @section Examples of @command{gnatmake} Usage
9737 @item gnatmake hello.adb
9738 Compile all files necessary to bind and link the main program
9739 @file{hello.adb} (containing unit @code{Hello}) and bind and link the
9740 resulting object files to generate an executable file @file{hello}.
9742 @item gnatmake main1 main2 main3
9743 Compile all files necessary to bind and link the main programs
9744 @file{main1.adb} (containing unit @code{Main1}), @file{main2.adb}
9745 (containing unit @code{Main2}) and @file{main3.adb}
9746 (containing unit @code{Main3}) and bind and link the resulting object files
9747 to generate three executable files @file{main1},
9751 @item gnatmake -q Main_Unit -cargs -O2 -bargs -l
9753 Compile all files necessary to bind and link the main program unit
9754 @code{Main_Unit} (from file @file{main_unit.adb}). All compilations will
9755 be done with optimization level 2 and the order of elaboration will be
9756 listed by the binder. @command{gnatmake} will operate in quiet mode, not
9757 displaying commands it is executing.
9760 @c *************************
9761 @node Improving Performance
9762 @chapter Improving Performance
9763 @cindex Improving performance
9766 This chapter presents several topics related to program performance.
9767 It first describes some of the tradeoffs that need to be considered
9768 and some of the techniques for making your program run faster.
9771 the @command{gnatelim} tool and
9773 unused subprogram/data
9774 elimination feature, which can reduce the size of program executables.
9778 * Performance Considerations::
9779 * Text_IO Suggestions::
9781 * Reducing Size of Ada Executables with gnatelim::
9783 * Reducing Size of Executables with unused subprogram/data elimination::
9787 @c *****************************
9788 @node Performance Considerations
9789 @section Performance Considerations
9792 The GNAT system provides a number of options that allow a trade-off
9797 performance of the generated code
9800 speed of compilation
9803 minimization of dependences and recompilation
9806 the degree of run-time checking.
9810 The defaults (if no options are selected) aim at improving the speed
9811 of compilation and minimizing dependences, at the expense of performance
9812 of the generated code:
9819 no inlining of subprogram calls
9822 all run-time checks enabled except overflow and elaboration checks
9826 These options are suitable for most program development purposes. This
9827 chapter describes how you can modify these choices, and also provides
9828 some guidelines on debugging optimized code.
9831 * Controlling Run-Time Checks::
9832 * Use of Restrictions::
9833 * Optimization Levels::
9834 * Debugging Optimized Code::
9835 * Inlining of Subprograms::
9836 * Vectorization of loops::
9837 * Other Optimization Switches::
9838 * Optimization and Strict Aliasing::
9839 * Aliased Variables and Optimization::
9840 * Atomic Variables and Optimization::
9841 * Passive Task Optimization::
9845 @node Controlling Run-Time Checks
9846 @subsection Controlling Run-Time Checks
9849 By default, GNAT generates all run-time checks, except integer overflow
9850 checks, stack overflow checks, and checks for access before elaboration on
9851 subprogram calls. The latter are not required in default mode, because all
9852 necessary checking is done at compile time.
9853 @cindex @option{-gnatp} (@command{gcc})
9854 @cindex @option{-gnato} (@command{gcc})
9855 Two gnat switches, @option{-gnatp} and @option{-gnato} allow this default to
9856 be modified. @xref{Run-Time Checks}.
9858 Our experience is that the default is suitable for most development
9861 We treat integer overflow specially because these
9862 are quite expensive and in our experience are not as important as other
9863 run-time checks in the development process. Note that division by zero
9864 is not considered an overflow check, and divide by zero checks are
9865 generated where required by default.
9867 Elaboration checks are off by default, and also not needed by default, since
9868 GNAT uses a static elaboration analysis approach that avoids the need for
9869 run-time checking. This manual contains a full chapter discussing the issue
9870 of elaboration checks, and if the default is not satisfactory for your use,
9871 you should read this chapter.
9873 For validity checks, the minimal checks required by the Ada Reference
9874 Manual (for case statements and assignments to array elements) are on
9875 by default. These can be suppressed by use of the @option{-gnatVn} switch.
9876 Note that in Ada 83, there were no validity checks, so if the Ada 83 mode
9877 is acceptable (or when comparing GNAT performance with an Ada 83 compiler),
9878 it may be reasonable to routinely use @option{-gnatVn}. Validity checks
9879 are also suppressed entirely if @option{-gnatp} is used.
9881 @cindex Overflow checks
9882 @cindex Checks, overflow
9885 @cindex pragma Suppress
9886 @cindex pragma Unsuppress
9887 Note that the setting of the switches controls the default setting of
9888 the checks. They may be modified using either @code{pragma Suppress} (to
9889 remove checks) or @code{pragma Unsuppress} (to add back suppressed
9890 checks) in the program source.
9892 @node Use of Restrictions
9893 @subsection Use of Restrictions
9896 The use of pragma Restrictions allows you to control which features are
9897 permitted in your program. Apart from the obvious point that if you avoid
9898 relatively expensive features like finalization (enforceable by the use
9899 of pragma Restrictions (No_Finalization), the use of this pragma does not
9900 affect the generated code in most cases.
9902 One notable exception to this rule is that the possibility of task abort
9903 results in some distributed overhead, particularly if finalization or
9904 exception handlers are used. The reason is that certain sections of code
9905 have to be marked as non-abortable.
9907 If you use neither the @code{abort} statement, nor asynchronous transfer
9908 of control (@code{select @dots{} then abort}), then this distributed overhead
9909 is removed, which may have a general positive effect in improving
9910 overall performance. Especially code involving frequent use of tasking
9911 constructs and controlled types will show much improved performance.
9912 The relevant restrictions pragmas are
9914 @smallexample @c ada
9915 @b{pragma} Restrictions (No_Abort_Statements);
9916 @b{pragma} Restrictions (Max_Asynchronous_Select_Nesting => 0);
9920 It is recommended that these restriction pragmas be used if possible. Note
9921 that this also means that you can write code without worrying about the
9922 possibility of an immediate abort at any point.
9924 @node Optimization Levels
9925 @subsection Optimization Levels
9926 @cindex @option{-O} (@command{gcc})
9929 Without any optimization option,
9930 the compiler's goal is to reduce the cost of
9931 compilation and to make debugging produce the expected results.
9932 Statements are independent: if you stop the program with a breakpoint between
9933 statements, you can then assign a new value to any variable or change
9934 the program counter to any other statement in the subprogram and get exactly
9935 the results you would expect from the source code.
9937 Turning on optimization makes the compiler attempt to improve the
9938 performance and/or code size at the expense of compilation time and
9939 possibly the ability to debug the program.
9942 -O options, with or without level numbers,
9943 the last such option is the one that is effective.
9946 The default is optimization off. This results in the fastest compile
9947 times, but GNAT makes absolutely no attempt to optimize, and the
9948 generated programs are considerably larger and slower than when
9949 optimization is enabled. You can use the
9950 @option{-O} switch (the permitted forms are @option{-O0}, @option{-O1}
9951 @option{-O2}, @option{-O3}, and @option{-Os})
9952 to @command{gcc} to control the optimization level:
9956 No optimization (the default);
9957 generates unoptimized code but has
9958 the fastest compilation time.
9960 Note that many other compilers do fairly extensive optimization
9961 even if ``no optimization'' is specified. With gcc, it is
9962 very unusual to use -O0 for production if
9963 execution time is of any concern, since -O0
9964 really does mean no optimization at all. This difference between
9965 gcc and other compilers should be kept in mind when doing
9966 performance comparisons.
9969 Moderate optimization;
9970 optimizes reasonably well but does not
9971 degrade compilation time significantly.
9975 generates highly optimized code and has
9976 the slowest compilation time.
9979 Full optimization as in @option{-O2};
9980 also uses more aggressive automatic inlining of subprograms within a unit
9981 (@pxref{Inlining of Subprograms}) and attempts to vectorize loops.
9984 Optimize space usage (code and data) of resulting program.
9988 Higher optimization levels perform more global transformations on the
9989 program and apply more expensive analysis algorithms in order to generate
9990 faster and more compact code. The price in compilation time, and the
9991 resulting improvement in execution time,
9992 both depend on the particular application and the hardware environment.
9993 You should experiment to find the best level for your application.
9995 Since the precise set of optimizations done at each level will vary from
9996 release to release (and sometime from target to target), it is best to think
9997 of the optimization settings in general terms.
9998 @xref{Optimize Options,, Options That Control Optimization, gcc, Using
9999 the GNU Compiler Collection (GCC)}, for details about
10000 the @option{-O} settings and a number of @option{-f} options that
10001 individually enable or disable specific optimizations.
10003 Unlike some other compilation systems, @command{gcc} has
10004 been tested extensively at all optimization levels. There are some bugs
10005 which appear only with optimization turned on, but there have also been
10006 bugs which show up only in @emph{unoptimized} code. Selecting a lower
10007 level of optimization does not improve the reliability of the code
10008 generator, which in practice is highly reliable at all optimization
10011 Note regarding the use of @option{-O3}: The use of this optimization level
10012 is generally discouraged with GNAT, since it often results in larger
10013 executables which may run more slowly. See further discussion of this point
10014 in @ref{Inlining of Subprograms}.
10016 @node Debugging Optimized Code
10017 @subsection Debugging Optimized Code
10018 @cindex Debugging optimized code
10019 @cindex Optimization and debugging
10022 Although it is possible to do a reasonable amount of debugging at
10023 nonzero optimization levels,
10024 the higher the level the more likely that
10025 source-level constructs will have been eliminated by optimization.
10026 For example, if a loop is strength-reduced, the loop
10027 control variable may be completely eliminated and thus cannot be
10028 displayed in the debugger.
10029 This can only happen at @option{-O2} or @option{-O3}.
10030 Explicit temporary variables that you code might be eliminated at
10031 level @option{-O1} or higher.
10033 The use of the @option{-g} switch,
10034 @cindex @option{-g} (@command{gcc})
10035 which is needed for source-level debugging,
10036 affects the size of the program executable on disk,
10037 and indeed the debugging information can be quite large.
10038 However, it has no effect on the generated code (and thus does not
10039 degrade performance)
10041 Since the compiler generates debugging tables for a compilation unit before
10042 it performs optimizations, the optimizing transformations may invalidate some
10043 of the debugging data. You therefore need to anticipate certain
10044 anomalous situations that may arise while debugging optimized code.
10045 These are the most common cases:
10049 @i{The ``hopping Program Counter'':} Repeated @code{step} or @code{next}
10051 the PC bouncing back and forth in the code. This may result from any of
10052 the following optimizations:
10056 @i{Common subexpression elimination:} using a single instance of code for a
10057 quantity that the source computes several times. As a result you
10058 may not be able to stop on what looks like a statement.
10061 @i{Invariant code motion:} moving an expression that does not change within a
10062 loop, to the beginning of the loop.
10065 @i{Instruction scheduling:} moving instructions so as to
10066 overlap loads and stores (typically) with other code, or in
10067 general to move computations of values closer to their uses. Often
10068 this causes you to pass an assignment statement without the assignment
10069 happening and then later bounce back to the statement when the
10070 value is actually needed. Placing a breakpoint on a line of code
10071 and then stepping over it may, therefore, not always cause all the
10072 expected side-effects.
10076 @i{The ``big leap'':} More commonly known as @emph{cross-jumping}, in which
10077 two identical pieces of code are merged and the program counter suddenly
10078 jumps to a statement that is not supposed to be executed, simply because
10079 it (and the code following) translates to the same thing as the code
10080 that @emph{was} supposed to be executed. This effect is typically seen in
10081 sequences that end in a jump, such as a @code{goto}, a @code{return}, or
10082 a @code{break} in a C @code{switch} statement.
10085 @i{The ``roving variable'':} The symptom is an unexpected value in a variable.
10086 There are various reasons for this effect:
10090 In a subprogram prologue, a parameter may not yet have been moved to its
10094 A variable may be dead, and its register re-used. This is
10095 probably the most common cause.
10098 As mentioned above, the assignment of a value to a variable may
10102 A variable may be eliminated entirely by value propagation or
10103 other means. In this case, GCC may incorrectly generate debugging
10104 information for the variable
10108 In general, when an unexpected value appears for a local variable or parameter
10109 you should first ascertain if that value was actually computed by
10110 your program, as opposed to being incorrectly reported by the debugger.
10112 array elements in an object designated by an access value
10113 are generally less of a problem, once you have ascertained that the access
10115 Typically, this means checking variables in the preceding code and in the
10116 calling subprogram to verify that the value observed is explainable from other
10117 values (one must apply the procedure recursively to those
10118 other values); or re-running the code and stopping a little earlier
10119 (perhaps before the call) and stepping to better see how the variable obtained
10120 the value in question; or continuing to step @emph{from} the point of the
10121 strange value to see if code motion had simply moved the variable's
10126 In light of such anomalies, a recommended technique is to use @option{-O0}
10127 early in the software development cycle, when extensive debugging capabilities
10128 are most needed, and then move to @option{-O1} and later @option{-O2} as
10129 the debugger becomes less critical.
10130 Whether to use the @option{-g} switch in the release version is
10131 a release management issue.
10132 Note that if you use @option{-g} you can then use the @command{strip} program
10133 on the resulting executable,
10134 which removes both debugging information and global symbols.
10136 @node Inlining of Subprograms
10137 @subsection Inlining of Subprograms
10140 A call to a subprogram in the current unit is inlined if all the
10141 following conditions are met:
10145 The optimization level is at least @option{-O1}.
10148 The called subprogram is suitable for inlining: It must be small enough
10149 and not contain something that @command{gcc} cannot support in inlined
10153 @cindex pragma Inline
10155 Any one of the following applies: @code{pragma Inline} is applied to the
10156 subprogram and the @option{-gnatn} switch is specified; the
10157 subprogram is local to the unit and called once from within it; the
10158 subprogram is small and optimization level @option{-O2} is specified;
10159 optimization level @option{-O3} is specified.
10163 Calls to subprograms in @code{with}'ed units are normally not inlined.
10164 To achieve actual inlining (that is, replacement of the call by the code
10165 in the body of the subprogram), the following conditions must all be true:
10169 The optimization level is at least @option{-O1}.
10172 The called subprogram is suitable for inlining: It must be small enough
10173 and not contain something that @command{gcc} cannot support in inlined
10177 The call appears in a body (not in a package spec).
10180 There is a @code{pragma Inline} for the subprogram.
10183 The @option{-gnatn} switch is used on the command line.
10186 Even if all these conditions are met, it may not be possible for
10187 the compiler to inline the call, due to the length of the body,
10188 or features in the body that make it impossible for the compiler
10189 to do the inlining.
10191 Note that specifying the @option{-gnatn} switch causes additional
10192 compilation dependencies. Consider the following:
10194 @smallexample @c ada
10196 @b{package} R @b{is}
10198 @b{pragma} Inline (Q);
10200 @b{package} @b{body} R @b{is}
10205 @b{procedure} Main @b{is}
10214 With the default behavior (no @option{-gnatn} switch specified), the
10215 compilation of the @code{Main} procedure depends only on its own source,
10216 @file{main.adb}, and the spec of the package in file @file{r.ads}. This
10217 means that editing the body of @code{R} does not require recompiling
10220 On the other hand, the call @code{R.Q} is not inlined under these
10221 circumstances. If the @option{-gnatn} switch is present when @code{Main}
10222 is compiled, the call will be inlined if the body of @code{Q} is small
10223 enough, but now @code{Main} depends on the body of @code{R} in
10224 @file{r.adb} as well as on the spec. This means that if this body is edited,
10225 the main program must be recompiled. Note that this extra dependency
10226 occurs whether or not the call is in fact inlined by @command{gcc}.
10228 The use of front end inlining with @option{-gnatN} generates similar
10229 additional dependencies.
10231 @cindex @option{-fno-inline} (@command{gcc})
10232 Note: The @option{-fno-inline} switch
10233 can be used to prevent
10234 all inlining. This switch overrides all other conditions and ensures
10235 that no inlining occurs. The extra dependences resulting from
10236 @option{-gnatn} will still be active, even if
10237 this switch is used to suppress the resulting inlining actions.
10239 @cindex @option{-fno-inline-functions} (@command{gcc})
10240 Note: The @option{-fno-inline-functions} switch can be used to prevent
10241 automatic inlining of subprograms if @option{-O3} is used.
10243 @cindex @option{-fno-inline-small-functions} (@command{gcc})
10244 Note: The @option{-fno-inline-small-functions} switch can be used to prevent
10245 automatic inlining of small subprograms if @option{-O2} is used.
10247 @cindex @option{-fno-inline-functions-called-once} (@command{gcc})
10248 Note: The @option{-fno-inline-functions-called-once} switch
10249 can be used to prevent inlining of subprograms local to the unit
10250 and called once from within it if @option{-O1} is used.
10252 Note regarding the use of @option{-O3}: @option{-gnatn} is made up of two
10253 sub-switches @option{-gnatn1} and @option{-gnatn2} that can be directly
10254 specified in lieu of it, @option{-gnatn} being translated into one of them
10255 based on the optimization level. With @option{-O2} or below, @option{-gnatn}
10256 is equivalent to @option{-gnatn1} which activates pragma @code{Inline} with
10257 moderate inlining across modules. With @option{-O3}, @option{-gnatn} is
10258 equivalent to @option{-gnatn2} which activates pragma @code{Inline} with
10259 full inlining across modules. If you have used pragma @code{Inline} in appropriate cases, then it is usually much better to use @option{-O2} and @option{-gnatn} and avoid the use of @option{-O3} which has the additional
10260 effect of inlining subprograms you did not think should be inlined. We have
10261 found that the use of @option{-O3} may slow down the compilation and increase
10262 the code size by performing excessive inlining, leading to increased
10263 instruction cache pressure from the increased code size and thus minor
10264 performance improvements. So the bottom line here is that you should not
10265 automatically assume that @option{-O3} is better than @option{-O2}, and
10266 indeed you should use @option{-O3} only if tests show that it actually
10267 improves performance for your program.
10269 @node Vectorization of loops
10270 @subsection Vectorization of loops
10271 @cindex Optimization Switches
10273 You can take advantage of the auto-vectorizer present in the @command{gcc}
10274 back end to vectorize loops with GNAT. The corresponding command line switch
10275 is @option{-ftree-vectorize} but, as it is enabled by default at @option{-O3}
10276 and other aggressive optimizations helpful for vectorization also are enabled
10277 by default at this level, using @option{-O3} directly is recommended.
10279 You also need to make sure that the target architecture features a supported
10280 SIMD instruction set. For example, for the x86 architecture, you should at
10281 least specify @option{-msse2} to get significant vectorization (but you don't
10282 need to specify it for x86-64 as it is part of the base 64-bit architecture).
10283 Similarly, for the PowerPC architecture, you should specify @option{-maltivec}.
10285 The preferred loop form for vectorization is the @code{for} iteration scheme.
10286 Loops with a @code{while} iteration scheme can also be vectorized if they are
10287 very simple, but the vectorizer will quickly give up otherwise. With either
10288 iteration scheme, the flow of control must be straight, in particular no
10289 @code{exit} statement may appear in the loop body. The loop may however
10290 contain a single nested loop, if it can be vectorized when considered alone:
10292 @smallexample @c ada
10294 A : @b{array} (1..4, 1..4) @b{of} Long_Float;
10295 S : @b{array} (1..4) @b{of} Long_Float;
10297 @b{procedure} Sum @b{is}
10299 @b{for} I @b{in} A'Range(1) @b{loop}
10300 @b{for} J @b{in} A'Range(2) @b{loop}
10301 S (I) := S (I) + A (I, J);
10308 The vectorizable operations depend on the targeted SIMD instruction set, but
10309 the adding and some of the multiplying operators are generally supported, as
10310 well as the logical operators for modular types. Note that, in the former
10311 case, enabling overflow checks, for example with @option{-gnato}, totally
10312 disables vectorization. The other checks are not supposed to have the same
10313 definitive effect, although compiling with @option{-gnatp} might well reveal
10314 cases where some checks do thwart vectorization.
10316 Type conversions may also prevent vectorization if they involve semantics that
10317 are not directly supported by the code generator or the SIMD instruction set.
10318 A typical example is direct conversion from floating-point to integer types.
10319 The solution in this case is to use the following idiom:
10321 @smallexample @c ada
10322 Integer (S'Truncation (F))
10326 if @code{S} is the subtype of floating-point object @code{F}.
10328 In most cases, the vectorizable loops are loops that iterate over arrays.
10329 All kinds of array types are supported, i.e. constrained array types with
10332 @smallexample @c ada
10333 @b{type} Array_Type @b{is} @b{array} (1 .. 4) @b{of} Long_Float;
10337 constrained array types with dynamic bounds:
10339 @smallexample @c ada
10340 @b{type} Array_Type @b{is} @b{array} (1 .. Q.N) @b{of} Long_Float;
10342 @b{type} Array_Type @b{is} @b{array} (Q.K .. 4) @b{of} Long_Float;
10344 @b{type} Array_Type @b{is} @b{array} (Q.K .. Q.N) @b{of} Long_Float;
10348 or unconstrained array types:
10350 @smallexample @c ada
10351 @b{type} Array_Type @b{is} @b{array} (Positive @b{range} <>) @b{of} Long_Float;
10355 The quality of the generated code decreases when the dynamic aspect of the
10356 array type increases, the worst code being generated for unconstrained array
10357 types. This is so because, the less information the compiler has about the
10358 bounds of the array, the more fallback code it needs to generate in order to
10359 fix things up at run time.
10361 It is possible to specify that a given loop should be subject to vectorization
10362 preferably to other optimizations by means of pragma @code{Loop_Optimize}:
10364 @smallexample @c ada
10365 @b{pragma} Loop_Optimize (Vector);
10369 placed immediately within the loop will convey the appropriate hint to the
10370 compiler for this loop.
10372 It is also possible to help the compiler generate better vectorized code
10373 for a given loop by asserting that there are no loop-carried dependencies
10374 in the loop. Consider for example the procedure:
10376 @smallexample @c ada
10377 @b{type} Arr @b{is} @b{array} (1 .. 4) @b{of} Long_Float;
10379 @b{procedure} Add (X, Y : @b{not} @b{null} @b{access} Arr; R : @b{not} @b{null} @b{access} Arr) @b{is}
10381 @b{for} I @b{in} Arr'Range @b{loop}
10382 R(I) := X(I) + Y(I);
10388 By default, the compiler cannot unconditionally vectorize the loop because
10389 assigning to a component of the array designated by R in one iteration could
10390 change the value read from the components of the array designated by X or Y
10391 in a later iteration. As a result, the compiler will generate two versions
10392 of the loop in the object code, one vectorized and the other not vectorized,
10393 as well as a test to select the appropriate version at run time. This can
10394 be overcome by another hint:
10396 @smallexample @c ada
10397 @b{pragma} Loop_Optimize (Ivdep);
10401 placed immediately within the loop will tell the compiler that it can safely
10402 omit the non-vectorized version of the loop as well as the run-time test.
10404 @node Other Optimization Switches
10405 @subsection Other Optimization Switches
10406 @cindex Optimization Switches
10408 Since @code{GNAT} uses the @command{gcc} back end, all the specialized
10409 @command{gcc} optimization switches are potentially usable. These switches
10410 have not been extensively tested with GNAT but can generally be expected
10411 to work. Examples of switches in this category are @option{-funroll-loops}
10412 and the various target-specific @option{-m} options (in particular, it has
10413 been observed that @option{-march=xxx} can significantly improve performance
10414 on appropriate machines). For full details of these switches, see
10415 @ref{Submodel Options,, Hardware Models and Configurations, gcc, Using
10416 the GNU Compiler Collection (GCC)}.
10418 @node Optimization and Strict Aliasing
10419 @subsection Optimization and Strict Aliasing
10421 @cindex Strict Aliasing
10422 @cindex No_Strict_Aliasing
10425 The strong typing capabilities of Ada allow an optimizer to generate
10426 efficient code in situations where other languages would be forced to
10427 make worst case assumptions preventing such optimizations. Consider
10428 the following example:
10430 @smallexample @c ada
10432 @b{procedure} R @b{is}
10433 @b{type} Int1 @b{is} @b{new} Integer;
10434 @b{type} Int2 @b{is} @b{new} Integer;
10435 @b{type} Int1A @b{is} @b{access} Int1;
10436 @b{type} Int2A @b{is} @b{access} Int2;
10443 @b{for} J @b{in} Data'Range @b{loop}
10444 @b{if} Data (J) = Int1V.@b{all} @b{then}
10445 Int2V.@b{all} := Int2V.@b{all} + 1;
10454 In this example, since the variable @code{Int1V} can only access objects
10455 of type @code{Int1}, and @code{Int2V} can only access objects of type
10456 @code{Int2}, there is no possibility that the assignment to
10457 @code{Int2V.all} affects the value of @code{Int1V.all}. This means that
10458 the compiler optimizer can "know" that the value @code{Int1V.all} is constant
10459 for all iterations of the loop and avoid the extra memory reference
10460 required to dereference it each time through the loop.
10462 This kind of optimization, called strict aliasing analysis, is
10463 triggered by specifying an optimization level of @option{-O2} or
10464 higher or @option{-Os} and allows @code{GNAT} to generate more efficient code
10465 when access values are involved.
10467 However, although this optimization is always correct in terms of
10468 the formal semantics of the Ada Reference Manual, difficulties can
10469 arise if features like @code{Unchecked_Conversion} are used to break
10470 the typing system. Consider the following complete program example:
10472 @smallexample @c ada
10474 @b{package} p1 @b{is}
10475 @b{type} int1 @b{is} @b{new} integer;
10476 @b{type} int2 @b{is} @b{new} integer;
10477 @b{type} a1 @b{is} @b{access} int1;
10478 @b{type} a2 @b{is} @b{access} int2;
10481 @b{with} p1; @b{use} p1;
10482 @b{package} p2 @b{is}
10483 @b{function} to_a2 (Input : a1) @b{return} a2;
10486 @b{with} Unchecked_Conversion;
10487 @b{package} @b{body} p2 @b{is}
10488 @b{function} to_a2 (Input : a1) @b{return} a2 @b{is}
10489 @b{function} to_a2u @b{is}
10490 @b{new} Unchecked_Conversion (a1, a2);
10492 @b{return} to_a2u (Input);
10496 @b{with} p2; @b{use} p2;
10497 @b{with} p1; @b{use} p1;
10498 @b{with} Text_IO; @b{use} Text_IO;
10499 @b{procedure} m @b{is}
10500 v1 : a1 := @b{new} int1;
10501 v2 : a2 := to_a2 (v1);
10505 put_line (int1'image (v1.@b{all}));
10511 This program prints out 0 in @option{-O0} or @option{-O1}
10512 mode, but it prints out 1 in @option{-O2} mode. That's
10513 because in strict aliasing mode, the compiler can and
10514 does assume that the assignment to @code{v2.all} could not
10515 affect the value of @code{v1.all}, since different types
10518 This behavior is not a case of non-conformance with the standard, since
10519 the Ada RM specifies that an unchecked conversion where the resulting
10520 bit pattern is not a correct value of the target type can result in an
10521 abnormal value and attempting to reference an abnormal value makes the
10522 execution of a program erroneous. That's the case here since the result
10523 does not point to an object of type @code{int2}. This means that the
10524 effect is entirely unpredictable.
10526 However, although that explanation may satisfy a language
10527 lawyer, in practice an applications programmer expects an
10528 unchecked conversion involving pointers to create true
10529 aliases and the behavior of printing 1 seems plain wrong.
10530 In this case, the strict aliasing optimization is unwelcome.
10532 Indeed the compiler recognizes this possibility, and the
10533 unchecked conversion generates a warning:
10536 p2.adb:5:07: warning: possible aliasing problem with type "a2"
10537 p2.adb:5:07: warning: use -fno-strict-aliasing switch for references
10538 p2.adb:5:07: warning: or use "pragma No_Strict_Aliasing (a2);"
10542 Unfortunately the problem is recognized when compiling the body of
10543 package @code{p2}, but the actual "bad" code is generated while
10544 compiling the body of @code{m} and this latter compilation does not see
10545 the suspicious @code{Unchecked_Conversion}.
10547 As implied by the warning message, there are approaches you can use to
10548 avoid the unwanted strict aliasing optimization in a case like this.
10550 One possibility is to simply avoid the use of @option{-O2}, but
10551 that is a bit drastic, since it throws away a number of useful
10552 optimizations that do not involve strict aliasing assumptions.
10554 A less drastic approach is to compile the program using the
10555 option @option{-fno-strict-aliasing}. Actually it is only the
10556 unit containing the dereferencing of the suspicious pointer
10557 that needs to be compiled. So in this case, if we compile
10558 unit @code{m} with this switch, then we get the expected
10559 value of zero printed. Analyzing which units might need
10560 the switch can be painful, so a more reasonable approach
10561 is to compile the entire program with options @option{-O2}
10562 and @option{-fno-strict-aliasing}. If the performance is
10563 satisfactory with this combination of options, then the
10564 advantage is that the entire issue of possible "wrong"
10565 optimization due to strict aliasing is avoided.
10567 To avoid the use of compiler switches, the configuration
10568 pragma @code{No_Strict_Aliasing} with no parameters may be
10569 used to specify that for all access types, the strict
10570 aliasing optimization should be suppressed.
10572 However, these approaches are still overkill, in that they causes
10573 all manipulations of all access values to be deoptimized. A more
10574 refined approach is to concentrate attention on the specific
10575 access type identified as problematic.
10577 First, if a careful analysis of uses of the pointer shows
10578 that there are no possible problematic references, then
10579 the warning can be suppressed by bracketing the
10580 instantiation of @code{Unchecked_Conversion} to turn
10583 @smallexample @c ada
10584 @b{pragma} Warnings (Off);
10585 @b{function} to_a2u @b{is}
10586 @b{new} Unchecked_Conversion (a1, a2);
10587 @b{pragma} Warnings (On);
10591 Of course that approach is not appropriate for this particular
10592 example, since indeed there is a problematic reference. In this
10593 case we can take one of two other approaches.
10595 The first possibility is to move the instantiation of unchecked
10596 conversion to the unit in which the type is declared. In
10597 this example, we would move the instantiation of
10598 @code{Unchecked_Conversion} from the body of package
10599 @code{p2} to the spec of package @code{p1}. Now the
10600 warning disappears. That's because any use of the
10601 access type knows there is a suspicious unchecked
10602 conversion, and the strict aliasing optimization
10603 is automatically suppressed for the type.
10605 If it is not practical to move the unchecked conversion to the same unit
10606 in which the destination access type is declared (perhaps because the
10607 source type is not visible in that unit), you may use pragma
10608 @code{No_Strict_Aliasing} for the type. This pragma must occur in the
10609 same declarative sequence as the declaration of the access type:
10611 @smallexample @c ada
10612 @b{type} a2 @b{is} @b{access} int2;
10613 @b{pragma} No_Strict_Aliasing (a2);
10617 Here again, the compiler now knows that the strict aliasing optimization
10618 should be suppressed for any reference to type @code{a2} and the
10619 expected behavior is obtained.
10621 Finally, note that although the compiler can generate warnings for
10622 simple cases of unchecked conversions, there are tricker and more
10623 indirect ways of creating type incorrect aliases which the compiler
10624 cannot detect. Examples are the use of address overlays and unchecked
10625 conversions involving composite types containing access types as
10626 components. In such cases, no warnings are generated, but there can
10627 still be aliasing problems. One safe coding practice is to forbid the
10628 use of address clauses for type overlaying, and to allow unchecked
10629 conversion only for primitive types. This is not really a significant
10630 restriction since any possible desired effect can be achieved by
10631 unchecked conversion of access values.
10633 The aliasing analysis done in strict aliasing mode can certainly
10634 have significant benefits. We have seen cases of large scale
10635 application code where the time is increased by up to 5% by turning
10636 this optimization off. If you have code that includes significant
10637 usage of unchecked conversion, you might want to just stick with
10638 @option{-O1} and avoid the entire issue. If you get adequate
10639 performance at this level of optimization level, that's probably
10640 the safest approach. If tests show that you really need higher
10641 levels of optimization, then you can experiment with @option{-O2}
10642 and @option{-O2 -fno-strict-aliasing} to see how much effect this
10643 has on size and speed of the code. If you really need to use
10644 @option{-O2} with strict aliasing in effect, then you should
10645 review any uses of unchecked conversion of access types,
10646 particularly if you are getting the warnings described above.
10648 @node Aliased Variables and Optimization
10649 @subsection Aliased Variables and Optimization
10651 There are scenarios in which programs may
10652 use low level techniques to modify variables
10653 that otherwise might be considered to be unassigned. For example,
10654 a variable can be passed to a procedure by reference, which takes
10655 the address of the parameter and uses the address to modify the
10656 variable's value, even though it is passed as an IN parameter.
10657 Consider the following example:
10659 @smallexample @c ada
10660 @b{procedure} P @b{is}
10661 Max_Length : @b{constant} Natural := 16;
10662 @b{type} Char_Ptr @b{is} @b{access} @b{all} Character;
10664 @b{procedure} Get_String(Buffer: Char_Ptr; Size : Integer);
10665 @b{pragma} Import (C, Get_String, "get_string");
10667 Name : @b{aliased} String (1 .. Max_Length) := (@b{others} => ' ');
10670 @b{function} Addr (S : String) @b{return} Char_Ptr @b{is}
10671 @b{function} To_Char_Ptr @b{is}
10672 @b{new} Ada.Unchecked_Conversion (System.Address, Char_Ptr);
10674 @b{return} To_Char_Ptr (S (S'First)'Address);
10678 Temp := Addr (Name);
10679 Get_String (Temp, Max_Length);
10684 where Get_String is a C function that uses the address in Temp to
10685 modify the variable @code{Name}. This code is dubious, and arguably
10686 erroneous, and the compiler would be entitled to assume that
10687 @code{Name} is never modified, and generate code accordingly.
10689 However, in practice, this would cause some existing code that
10690 seems to work with no optimization to start failing at high
10691 levels of optimzization.
10693 What the compiler does for such cases is to assume that marking
10694 a variable as aliased indicates that some "funny business" may
10695 be going on. The optimizer recognizes the aliased keyword and
10696 inhibits optimizations that assume the value cannot be assigned.
10697 This means that the above example will in fact "work" reliably,
10698 that is, it will produce the expected results.
10700 @node Atomic Variables and Optimization
10701 @subsection Atomic Variables and Optimization
10703 There are two considerations with regard to performance when
10704 atomic variables are used.
10706 First, the RM only guarantees that access to atomic variables
10707 be atomic, it has nothing to say about how this is achieved,
10708 though there is a strong implication that this should not be
10709 achieved by explicit locking code. Indeed GNAT will never
10710 generate any locking code for atomic variable access (it will
10711 simply reject any attempt to make a variable or type atomic
10712 if the atomic access cannot be achieved without such locking code).
10714 That being said, it is important to understand that you cannot
10715 assume that the entire variable will always be accessed. Consider
10718 @smallexample @c ada
10719 @b{type} R @b{is} @b{record}
10720 A,B,C,D : Character;
10721 @b{end} @b{record};
10722 @b{for} R'Size @b{use} 32;
10723 @b{for} R'Alignment @b{use} 4;
10726 @b{pragma} Atomic (RV);
10733 You cannot assume that the reference to @code{RV.B}
10734 will read the entire 32-bit
10735 variable with a single load instruction. It is perfectly legitimate if
10736 the hardware allows it to do a byte read of just the B field. This read
10737 is still atomic, which is all the RM requires. GNAT can and does take
10738 advantage of this, depending on the architecture and optimization level.
10739 Any assumption to the contrary is non-portable and risky. Even if you
10740 examine the assembly language and see a full 32-bit load, this might
10741 change in a future version of the compiler.
10743 If your application requires that all accesses to @code{RV} in this
10744 example be full 32-bit loads, you need to make a copy for the access
10747 @smallexample @c ada
10749 RV_Copy : @b{constant} R := RV;
10757 Now the reference to RV must read the whole variable.
10758 Actually one can imagine some compiler which figures
10759 out that the whole copy is not required (because only
10760 the B field is actually accessed), but GNAT
10761 certainly won't do that, and we don't know of any
10762 compiler that would not handle this right, and the
10763 above code will in practice work portably across
10764 all architectures (that permit the Atomic declaration).
10766 The second issue with atomic variables has to do with
10767 the possible requirement of generating synchronization
10768 code. For more details on this, consult the sections on
10769 the pragmas Enable/Disable_Atomic_Synchronization in the
10770 GNAT Reference Manual. If performance is critical, and
10771 such synchronization code is not required, it may be
10772 useful to disable it.
10774 @node Passive Task Optimization
10775 @subsection Passive Task Optimization
10776 @cindex Passive Task
10778 A passive task is one which is sufficiently simple that
10779 in theory a compiler could recognize it an implement it
10780 efficiently without creating a new thread. The original design
10781 of Ada 83 had in mind this kind of passive task optimization, but
10782 only a few Ada 83 compilers attempted it. The problem was that
10783 it was difficult to determine the exact conditions under which
10784 the optimization was possible. The result is a very fragile
10785 optimization where a very minor change in the program can
10786 suddenly silently make a task non-optimizable.
10788 With the revisiting of this issue in Ada 95, there was general
10789 agreement that this approach was fundamentally flawed, and the
10790 notion of protected types was introduced. When using protected
10791 types, the restrictions are well defined, and you KNOW that the
10792 operations will be optimized, and furthermore this optimized
10793 performance is fully portable.
10795 Although it would theoretically be possible for GNAT to attempt to
10796 do this optimization, but it really doesn't make sense in the
10797 context of Ada 95, and none of the Ada 95 compilers implement
10798 this optimization as far as we know. In particular GNAT never
10799 attempts to perform this optimization.
10801 In any new Ada 95 code that is written, you should always
10802 use protected types in place of tasks that might be able to
10803 be optimized in this manner.
10804 Of course this does not help if you have legacy Ada 83 code
10805 that depends on this optimization, but it is unusual to encounter
10806 a case where the performance gains from this optimization
10809 Your program should work correctly without this optimization. If
10810 you have performance problems, then the most practical
10811 approach is to figure out exactly where these performance problems
10812 arise, and update those particular tasks to be protected types. Note
10813 that typically clients of the tasks who call entries, will not have
10814 to be modified, only the task definition itself.
10818 @node Text_IO Suggestions
10819 @section @code{Text_IO} Suggestions
10820 @cindex @code{Text_IO} and performance
10823 The @code{Ada.Text_IO} package has fairly high overheads due in part to
10824 the requirement of maintaining page and line counts. If performance
10825 is critical, a recommendation is to use @code{Stream_IO} instead of
10826 @code{Text_IO} for volume output, since this package has less overhead.
10828 If @code{Text_IO} must be used, note that by default output to the standard
10829 output and standard error files is unbuffered (this provides better
10830 behavior when output statements are used for debugging, or if the
10831 progress of a program is observed by tracking the output, e.g. by
10832 using the Unix @command{tail -f} command to watch redirected output.
10834 If you are generating large volumes of output with @code{Text_IO} and
10835 performance is an important factor, use a designated file instead
10836 of the standard output file, or change the standard output file to
10837 be buffered using @code{Interfaces.C_Streams.setvbuf}.
10840 @ifclear FSFEDITION
10841 @node Reducing Size of Ada Executables with gnatelim
10842 @section Reducing Size of Ada Executables with @code{gnatelim}
10846 This section describes @command{gnatelim}, a tool which detects unused
10847 subprograms and helps the compiler to create a smaller executable for your
10852 * Running gnatelim::
10853 * Processing Precompiled Libraries::
10854 * Correcting the List of Eliminate Pragmas::
10855 * Making Your Executables Smaller::
10856 * Summary of the gnatelim Usage Cycle::
10859 @node About gnatelim
10860 @subsection About @code{gnatelim}
10863 When a program shares a set of Ada
10864 packages with other programs, it may happen that this program uses
10865 only a fraction of the subprograms defined in these packages. The code
10866 created for these unused subprograms increases the size of the executable.
10868 @code{gnatelim} tracks unused subprograms in an Ada program and
10869 outputs a list of GNAT-specific pragmas @code{Eliminate} marking all the
10870 subprograms that are declared but never called. By placing the list of
10871 @code{Eliminate} pragmas in the GNAT configuration file @file{gnat.adc} and
10872 recompiling your program, you may decrease the size of its executable,
10873 because the compiler will not generate the code for 'eliminated' subprograms.
10874 @xref{Pragma Eliminate,,, gnat_rm, GNAT Reference Manual}, for more
10875 information about this pragma.
10877 @code{gnatelim} needs as its input data the name of the main subprogram.
10879 If a set of source files is specified as @code{gnatelim} arguments, it
10880 treats these files as a complete set of sources making up a program to
10881 analyse, and analyses only these sources.
10883 After a full successful build of the main subprogram @code{gnatelim} can be
10884 called without specifying sources to analyse, in this case it computes
10885 the source closure of the main unit from the @file{ALI} files.
10887 If the set of sources to be processed by @code{gnatelim} contains sources with
10888 preprocessing directives
10889 then the needed options should be provided to run preprocessor as a part of
10890 the @command{gnatelim} call, and the generated set of pragmas @code{Eliminate}
10891 will correspond to preprocessed sources.
10893 The following command will create the set of @file{ALI} files needed for
10897 $ gnatmake -c Main_Prog
10900 Note that @code{gnatelim} does not need object files.
10902 @node Running gnatelim
10903 @subsection Running @code{gnatelim}
10906 @code{gnatelim} has the following command-line interface:
10909 $ gnatelim [@var{switches}] -main=@var{main_unit_name} @{@var{filename}@} @r{[}-cargs @var{gcc_switches}@r{]}
10913 @var{main_unit_name} should be a name of a source file that contains the main
10914 subprogram of a program (partition).
10916 Each @var{filename} is the name (including the extension) of a source
10917 file to process. ``Wildcards'' are allowed, and
10918 the file name may contain path information.
10920 @samp{@var{gcc_switches}} is a list of switches for
10921 @command{gcc}. They will be passed on to all compiler invocations made by
10922 @command{gnatelim} to generate the ASIS trees. Here you can provide
10923 @option{-I} switches to form the source search path,
10924 use the @option{-gnatec} switch to set the configuration file,
10925 use the @option{-gnat05} switch if sources should be compiled in
10928 @code{gnatelim} has the following switches:
10933 @cindex @option{--version} @command{gnatelim}
10934 Display Copyright and version, then exit disregarding all other options.
10937 @cindex @option{--help} @command{gnatelim}
10938 Display usage, then exit disregarding all other options.
10940 @item -P @var{file}
10941 @cindex @option{-P} @command{gnatelim}
10942 Indicates the name of the project file that describes the set of sources
10945 @item -X@var{name}=@var{value}
10946 @cindex @option{-X} @command{gnatelim}
10947 Indicates that external variable @var{name} in the argument project
10948 has the value @var{value}. Has no effect if no project is specified as
10951 @item --RTS=@var{rts-path}
10952 @cindex @option{--RTS} (@command{gnatelim})
10953 Specifies the default location of the runtime library. Same meaning as the
10954 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
10956 @item -files=@var{filename}
10957 @cindex @option{-files} (@code{gnatelim})
10958 Take the argument source files from the specified file. This file should be an
10959 ordinary text file containing file names separated by spaces or
10960 line breaks. You can use this switch more than once in the same call to
10961 @command{gnatelim}. You also can combine this switch with
10962 an explicit list of files.
10965 @cindex @option{-log} (@command{gnatelim})
10966 Duplicate all the output sent to @file{stderr} into a log file. The log file
10967 is named @file{gnatelim.log} and is located in the current directory.
10970 @item -log=@var{filename}
10971 @cindex @option{-log} (@command{gnatelim})
10972 Duplicate all the output sent to @file{stderr} into a specified log file.
10975 @cindex @option{--no-elim-dispatch} (@command{gnatelim})
10976 @item --no-elim-dispatch
10977 Do not generate pragmas for dispatching operations.
10979 @item --ignore=@var{filename}
10980 @cindex @option{--ignore} (@command{gnatelim})
10981 Do not generate pragmas for subprograms declared in the sources
10982 listed in a specified file
10984 @cindex @option{-o} (@command{gnatelim})
10985 @item -o=@var{report_file}
10986 Put @command{gnatelim} output into a specified file. If this file already exists,
10987 it is overridden. If this switch is not used, @command{gnatelim} outputs its results
10991 @cindex @option{-j} (@command{gnatelim})
10992 Use @var{n} processes to carry out the tree creations (internal representations
10993 of the argument sources). On a multiprocessor machine this speeds up processing
10994 of big sets of argument sources. If @var{n} is 0, then the maximum number of
10995 parallel tree creations is the number of core processors on the platform.
10998 @cindex @option{-q} (@command{gnatelim})
10999 Quiet mode: by default @code{gnatelim} outputs to the standard error
11000 stream the number of program units left to be processed. This option turns
11003 @cindex @option{-t} (@command{gnatelim})
11005 Print out execution time.
11008 @cindex @option{-v} (@command{gnatelim})
11009 Verbose mode: @code{gnatelim} version information is printed as Ada
11010 comments to the standard output stream. Also, in addition to the number of
11011 program units left @code{gnatelim} will output the name of the current unit
11015 @cindex @option{-wq} (@command{gnatelim})
11016 Quiet warning mode - some warnings are suppressed. In particular warnings that
11017 indicate that the analysed set of sources is incomplete to make up a
11018 partition and that some subprogram bodies are missing are not generated.
11022 Note: to invoke @command{gnatelim} with a project file, use the @code{gnat}
11023 driver (see @ref{The GNAT Driver and Project Files}).
11025 @node Processing Precompiled Libraries
11026 @subsection Processing Precompiled Libraries
11029 If some program uses a precompiled Ada library, it can be processed by
11030 @code{gnatelim} in a usual way. @code{gnatelim} will newer generate an
11031 Eliminate pragma for a subprogram if the body of this subprogram has not
11032 been analysed, this is a typical case for subprograms from precompiled
11033 libraries. Switch @option{-wq} may be used to suppress
11034 warnings about missing source files and non-analyzed subprogram bodies
11035 that can be generated when processing precompiled Ada libraries.
11037 @node Correcting the List of Eliminate Pragmas
11038 @subsection Correcting the List of Eliminate Pragmas
11041 In some rare cases @code{gnatelim} may try to eliminate
11042 subprograms that are actually called in the program. In this case, the
11043 compiler will generate an error message of the form:
11046 main.adb:4:08: cannot reference subprogram "P" eliminated at elim.out:5
11050 You will need to manually remove the wrong @code{Eliminate} pragmas from
11051 the configuration file indicated in the error message. You should recompile
11052 your program from scratch after that, because you need a consistent
11053 configuration file(s) during the entire compilation.
11055 @node Making Your Executables Smaller
11056 @subsection Making Your Executables Smaller
11059 In order to get a smaller executable for your program you now have to
11060 recompile the program completely with the configuration file containing
11061 pragmas Eliminate generated by gnatelim. If these pragmas are placed in
11062 @file{gnat.adc} file located in your current directory, just do:
11065 $ gnatmake -f main_prog
11069 (Use the @option{-f} option for @command{gnatmake} to
11070 recompile everything
11071 with the set of pragmas @code{Eliminate} that you have obtained with
11072 @command{gnatelim}).
11074 Be aware that the set of @code{Eliminate} pragmas is specific to each
11075 program. It is not recommended to merge sets of @code{Eliminate}
11076 pragmas created for different programs in one configuration file.
11078 @node Summary of the gnatelim Usage Cycle
11079 @subsection Summary of the @code{gnatelim} Usage Cycle
11082 Here is a quick summary of the steps to be taken in order to reduce
11083 the size of your executables with @code{gnatelim}. You may use
11084 other GNAT options to control the optimization level,
11085 to produce the debugging information, to set search path, etc.
11089 Create a complete set of @file{ALI} files (if the program has not been
11093 $ gnatmake -c main_prog
11097 Generate a list of @code{Eliminate} pragmas in default configuration file
11098 @file{gnat.adc} in the current directory
11100 $ gnatelim main_prog >@r{[}>@r{]} gnat.adc
11104 Recompile the application
11107 $ gnatmake -f main_prog
11113 @node Reducing Size of Executables with unused subprogram/data elimination
11114 @section Reducing Size of Executables with Unused Subprogram/Data Elimination
11115 @findex unused subprogram/data elimination
11118 This section describes how you can eliminate unused subprograms and data from
11119 your executable just by setting options at compilation time.
11122 * About unused subprogram/data elimination::
11123 * Compilation options::
11124 * Example of unused subprogram/data elimination::
11127 @node About unused subprogram/data elimination
11128 @subsection About unused subprogram/data elimination
11131 By default, an executable contains all code and data of its composing objects
11132 (directly linked or coming from statically linked libraries), even data or code
11133 never used by this executable.
11135 This feature will allow you to eliminate such unused code from your
11136 executable, making it smaller (in disk and in memory).
11138 This functionality is available on all Linux platforms except for the IA-64
11139 architecture and on all cross platforms using the ELF binary file format.
11140 In both cases GNU binutils version 2.16 or later are required to enable it.
11142 @node Compilation options
11143 @subsection Compilation options
11146 The operation of eliminating the unused code and data from the final executable
11147 is directly performed by the linker.
11149 In order to do this, it has to work with objects compiled with the
11151 @option{-ffunction-sections} @option{-fdata-sections}.
11152 @cindex @option{-ffunction-sections} (@command{gcc})
11153 @cindex @option{-fdata-sections} (@command{gcc})
11154 These options are usable with C and Ada files.
11155 They will place respectively each
11156 function or data in a separate section in the resulting object file.
11158 Once the objects and static libraries are created with these options, the
11159 linker can perform the dead code elimination. You can do this by setting
11160 the @option{-Wl,--gc-sections} option to gcc command or in the
11161 @option{-largs} section of @command{gnatmake}. This will perform a
11162 garbage collection of code and data never referenced.
11164 If the linker performs a partial link (@option{-r} linker option), then you
11165 will need to provide the entry point using the @option{-e} / @option{--entry}
11168 Note that objects compiled without the @option{-ffunction-sections} and
11169 @option{-fdata-sections} options can still be linked with the executable.
11170 However, no dead code elimination will be performed on those objects (they will
11173 The GNAT static library is now compiled with -ffunction-sections and
11174 -fdata-sections on some platforms. This allows you to eliminate the unused code
11175 and data of the GNAT library from your executable.
11177 @node Example of unused subprogram/data elimination
11178 @subsection Example of unused subprogram/data elimination
11181 Here is a simple example:
11183 @smallexample @c ada
11186 @b{procedure} Test @b{is}
11191 @b{package} Aux @b{is}
11192 Used_Data : Integer;
11193 Unused_Data : Integer;
11195 @b{procedure} Used (Data : Integer);
11196 @b{procedure} Unused (Data : Integer);
11199 @b{package} @b{body} Aux @b{is}
11200 @b{procedure} Used (Data : Integer) @b{is}
11205 @b{procedure} Unused (Data : Integer) @b{is}
11207 Unused_Data := Data;
11213 @code{Unused} and @code{Unused_Data} are never referenced in this code
11214 excerpt, and hence they may be safely removed from the final executable.
11219 $ nm test | grep used
11220 020015f0 T aux__unused
11221 02005d88 B aux__unused_data
11222 020015cc T aux__used
11223 02005d84 B aux__used_data
11225 $ gnatmake test -cargs -fdata-sections -ffunction-sections \
11226 -largs -Wl,--gc-sections
11228 $ nm test | grep used
11229 02005350 T aux__used
11230 0201ffe0 B aux__used_data
11234 It can be observed that the procedure @code{Unused} and the object
11235 @code{Unused_Data} are removed by the linker when using the
11236 appropriate options.
11238 @c ********************************
11239 @node Renaming Files with gnatchop
11240 @chapter Renaming Files with @code{gnatchop}
11244 This chapter discusses how to handle files with multiple units by using
11245 the @code{gnatchop} utility. This utility is also useful in renaming
11246 files to meet the standard GNAT default file naming conventions.
11249 * Handling Files with Multiple Units::
11250 * Operating gnatchop in Compilation Mode::
11251 * Command Line for gnatchop::
11252 * Switches for gnatchop::
11253 * Examples of gnatchop Usage::
11256 @node Handling Files with Multiple Units
11257 @section Handling Files with Multiple Units
11260 The basic compilation model of GNAT requires that a file submitted to the
11261 compiler have only one unit and there be a strict correspondence
11262 between the file name and the unit name.
11264 The @code{gnatchop} utility allows both of these rules to be relaxed,
11265 allowing GNAT to process files which contain multiple compilation units
11266 and files with arbitrary file names. @code{gnatchop}
11267 reads the specified file and generates one or more output files,
11268 containing one unit per file. The unit and the file name correspond,
11269 as required by GNAT.
11271 If you want to permanently restructure a set of ``foreign'' files so that
11272 they match the GNAT rules, and do the remaining development using the
11273 GNAT structure, you can simply use @command{gnatchop} once, generate the
11274 new set of files and work with them from that point on.
11276 Alternatively, if you want to keep your files in the ``foreign'' format,
11277 perhaps to maintain compatibility with some other Ada compilation
11278 system, you can set up a procedure where you use @command{gnatchop} each
11279 time you compile, regarding the source files that it writes as temporary
11280 files that you throw away.
11282 Note that if your file containing multiple units starts with a byte order
11283 mark (BOM) specifying UTF-8 encoding, then the files generated by gnatchop
11284 will each start with a copy of this BOM, meaning that they can be compiled
11285 automatically in UTF-8 mode without needing to specify an explicit encoding.
11287 @node Operating gnatchop in Compilation Mode
11288 @section Operating gnatchop in Compilation Mode
11291 The basic function of @code{gnatchop} is to take a file with multiple units
11292 and split it into separate files. The boundary between files is reasonably
11293 clear, except for the issue of comments and pragmas. In default mode, the
11294 rule is that any pragmas between units belong to the previous unit, except
11295 that configuration pragmas always belong to the following unit. Any comments
11296 belong to the following unit. These rules
11297 almost always result in the right choice of
11298 the split point without needing to mark it explicitly and most users will
11299 find this default to be what they want. In this default mode it is incorrect to
11300 submit a file containing only configuration pragmas, or one that ends in
11301 configuration pragmas, to @code{gnatchop}.
11303 However, using a special option to activate ``compilation mode'',
11305 can perform another function, which is to provide exactly the semantics
11306 required by the RM for handling of configuration pragmas in a compilation.
11307 In the absence of configuration pragmas (at the main file level), this
11308 option has no effect, but it causes such configuration pragmas to be handled
11309 in a quite different manner.
11311 First, in compilation mode, if @code{gnatchop} is given a file that consists of
11312 only configuration pragmas, then this file is appended to the
11313 @file{gnat.adc} file in the current directory. This behavior provides
11314 the required behavior described in the RM for the actions to be taken
11315 on submitting such a file to the compiler, namely that these pragmas
11316 should apply to all subsequent compilations in the same compilation
11317 environment. Using GNAT, the current directory, possibly containing a
11318 @file{gnat.adc} file is the representation
11319 of a compilation environment. For more information on the
11320 @file{gnat.adc} file, see @ref{Handling of Configuration Pragmas}.
11322 Second, in compilation mode, if @code{gnatchop}
11323 is given a file that starts with
11324 configuration pragmas, and contains one or more units, then these
11325 configuration pragmas are prepended to each of the chopped files. This
11326 behavior provides the required behavior described in the RM for the
11327 actions to be taken on compiling such a file, namely that the pragmas
11328 apply to all units in the compilation, but not to subsequently compiled
11331 Finally, if configuration pragmas appear between units, they are appended
11332 to the previous unit. This results in the previous unit being illegal,
11333 since the compiler does not accept configuration pragmas that follow
11334 a unit. This provides the required RM behavior that forbids configuration
11335 pragmas other than those preceding the first compilation unit of a
11338 For most purposes, @code{gnatchop} will be used in default mode. The
11339 compilation mode described above is used only if you need exactly
11340 accurate behavior with respect to compilations, and you have files
11341 that contain multiple units and configuration pragmas. In this
11342 circumstance the use of @code{gnatchop} with the compilation mode
11343 switch provides the required behavior, and is for example the mode
11344 in which GNAT processes the ACVC tests.
11346 @node Command Line for gnatchop
11347 @section Command Line for @code{gnatchop}
11350 The @code{gnatchop} command has the form:
11353 @c $ gnatchop switches @var{file name} @r{[}@var{file name} @dots{}@r{]}
11354 @c @ovar{directory}
11355 @c Expanding @ovar macro inline (explanation in macro def comments)
11356 $ gnatchop switches @var{file name} @r{[}@var{file name} @dots{}@r{]}
11357 @r{[}@var{directory}@r{]}
11361 The only required argument is the file name of the file to be chopped.
11362 There are no restrictions on the form of this file name. The file itself
11363 contains one or more Ada units, in normal GNAT format, concatenated
11364 together. As shown, more than one file may be presented to be chopped.
11366 When run in default mode, @code{gnatchop} generates one output file in
11367 the current directory for each unit in each of the files.
11369 @var{directory}, if specified, gives the name of the directory to which
11370 the output files will be written. If it is not specified, all files are
11371 written to the current directory.
11373 For example, given a
11374 file called @file{hellofiles} containing
11376 @smallexample @c ada
11379 @b{procedure} hello;
11381 @b{with} Text_IO; @b{use} Text_IO;
11382 @b{procedure} hello @b{is}
11384 Put_Line ("Hello");
11394 $ gnatchop hellofiles
11398 generates two files in the current directory, one called
11399 @file{hello.ads} containing the single line that is the procedure spec,
11400 and the other called @file{hello.adb} containing the remaining text. The
11401 original file is not affected. The generated files can be compiled in
11405 When gnatchop is invoked on a file that is empty or that contains only empty
11406 lines and/or comments, gnatchop will not fail, but will not produce any
11409 For example, given a
11410 file called @file{toto.txt} containing
11412 @smallexample @c ada
11415 --@i{ Just a comment}
11424 $ gnatchop toto.txt
11428 will not produce any new file and will result in the following warnings:
11431 toto.txt:1:01: warning: empty file, contains no compilation units
11432 no compilation units found
11433 no source files written
11436 @node Switches for gnatchop
11437 @section Switches for @code{gnatchop}
11440 @command{gnatchop} recognizes the following switches:
11446 @cindex @option{--version} @command{gnatchop}
11447 Display Copyright and version, then exit disregarding all other options.
11450 @cindex @option{--help} @command{gnatchop}
11451 If @option{--version} was not used, display usage, then exit disregarding
11455 @cindex @option{-c} (@code{gnatchop})
11456 Causes @code{gnatchop} to operate in compilation mode, in which
11457 configuration pragmas are handled according to strict RM rules. See
11458 previous section for a full description of this mode.
11460 @item -gnat@var{xxx}
11461 This passes the given @option{-gnat@var{xxx}} switch to @code{gnat} which is
11462 used to parse the given file. Not all @var{xxx} options make sense,
11463 but for example, the use of @option{-gnati2} allows @code{gnatchop} to
11464 process a source file that uses Latin-2 coding for identifiers.
11467 Causes @code{gnatchop} to generate a brief help summary to the standard
11468 output file showing usage information.
11471 @cindex @option{-k} (@code{gnatchop})
11472 Limit generated file names to the specified number @code{mm}
11474 This is useful if the
11475 resulting set of files is required to be interoperable with systems
11476 which limit the length of file names.
11477 No space is allowed between the @option{-k} and the numeric value. The numeric
11478 value may be omitted in which case a default of @option{-k8},
11480 with DOS-like file systems, is used. If no @option{-k} switch
11482 there is no limit on the length of file names.
11485 @cindex @option{-p} (@code{gnatchop})
11486 Causes the file modification time stamp of the input file to be
11487 preserved and used for the time stamp of the output file(s). This may be
11488 useful for preserving coherency of time stamps in an environment where
11489 @code{gnatchop} is used as part of a standard build process.
11492 @cindex @option{-q} (@code{gnatchop})
11493 Causes output of informational messages indicating the set of generated
11494 files to be suppressed. Warnings and error messages are unaffected.
11497 @cindex @option{-r} (@code{gnatchop})
11498 @findex Source_Reference
11499 Generate @code{Source_Reference} pragmas. Use this switch if the output
11500 files are regarded as temporary and development is to be done in terms
11501 of the original unchopped file. This switch causes
11502 @code{Source_Reference} pragmas to be inserted into each of the
11503 generated files to refers back to the original file name and line number.
11504 The result is that all error messages refer back to the original
11506 In addition, the debugging information placed into the object file (when
11507 the @option{-g} switch of @command{gcc} or @command{gnatmake} is
11509 also refers back to this original file so that tools like profilers and
11510 debuggers will give information in terms of the original unchopped file.
11512 If the original file to be chopped itself contains
11513 a @code{Source_Reference}
11514 pragma referencing a third file, then gnatchop respects
11515 this pragma, and the generated @code{Source_Reference} pragmas
11516 in the chopped file refer to the original file, with appropriate
11517 line numbers. This is particularly useful when @code{gnatchop}
11518 is used in conjunction with @code{gnatprep} to compile files that
11519 contain preprocessing statements and multiple units.
11522 @cindex @option{-v} (@code{gnatchop})
11523 Causes @code{gnatchop} to operate in verbose mode. The version
11524 number and copyright notice are output, as well as exact copies of
11525 the gnat1 commands spawned to obtain the chop control information.
11528 @cindex @option{-w} (@code{gnatchop})
11529 Overwrite existing file names. Normally @code{gnatchop} regards it as a
11530 fatal error if there is already a file with the same name as a
11531 file it would otherwise output, in other words if the files to be
11532 chopped contain duplicated units. This switch bypasses this
11533 check, and causes all but the last instance of such duplicated
11534 units to be skipped.
11536 @item --GCC=@var{xxxx}
11537 @cindex @option{--GCC=} (@code{gnatchop})
11538 Specify the path of the GNAT parser to be used. When this switch is used,
11539 no attempt is made to add the prefix to the GNAT parser executable.
11542 @node Examples of gnatchop Usage
11543 @section Examples of @code{gnatchop} Usage
11546 @item gnatchop -w hello_s.ada prerelease/files
11548 Chops the source file @file{hello_s.ada}. The output files will be
11549 placed in the directory @file{prerelease/files},
11551 files with matching names in that directory (no files in the current
11552 directory are modified).
11554 @item gnatchop archive
11555 Chops the source file @file{archive}
11556 into the current directory. One
11557 useful application of @code{gnatchop} is in sending sets of sources
11558 around, for example in email messages. The required sources are simply
11559 concatenated (for example, using a Unix @code{cat}
11561 @command{gnatchop} is used at the other end to reconstitute the original
11564 @item gnatchop file1 file2 file3 direc
11565 Chops all units in files @file{file1}, @file{file2}, @file{file3}, placing
11566 the resulting files in the directory @file{direc}. Note that if any units
11567 occur more than once anywhere within this set of files, an error message
11568 is generated, and no files are written. To override this check, use the
11569 @option{-w} switch,
11570 in which case the last occurrence in the last file will
11571 be the one that is output, and earlier duplicate occurrences for a given
11572 unit will be skipped.
11575 @node Configuration Pragmas
11576 @chapter Configuration Pragmas
11577 @cindex Configuration pragmas
11578 @cindex Pragmas, configuration
11581 * Handling of Configuration Pragmas::
11582 * The Configuration Pragmas Files::
11586 Configuration pragmas include those pragmas described as
11587 such in the Ada Reference Manual, as well as
11588 implementation-dependent pragmas that are configuration pragmas.
11589 @xref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference Manual},
11590 for details on these additional GNAT-specific configuration pragmas.
11591 Most notably, the pragma @code{Source_File_Name}, which allows
11592 specifying non-default names for source files, is a configuration
11593 pragma. The following is a complete list of configuration pragmas
11594 recognized by GNAT:
11603 Allow_Integer_Address
11606 Assume_No_Invalid_Values
11611 Compile_Time_Warning
11613 Component_Alignment
11614 Convention_Identifier
11617 Default_Storage_Pool
11623 External_Name_Casing
11626 Float_Representation
11639 Priority_Specific_Dispatching
11642 Propagate_Exceptions
11645 Restricted_Run_Time
11647 Restrictions_Warnings
11649 Short_Circuit_And_Or
11651 Source_File_Name_Project
11655 Suppress_Exception_Locations
11656 Task_Dispatching_Policy
11662 Wide_Character_Encoding
11665 @node Handling of Configuration Pragmas
11666 @section Handling of Configuration Pragmas
11668 Configuration pragmas may either appear at the start of a compilation
11669 unit, or they can appear in a configuration pragma file to apply to
11670 all compilations performed in a given compilation environment.
11672 GNAT also provides the @code{gnatchop} utility to provide an automatic
11673 way to handle configuration pragmas following the semantics for
11674 compilations (that is, files with multiple units), described in the RM.
11675 See @ref{Operating gnatchop in Compilation Mode} for details.
11676 However, for most purposes, it will be more convenient to edit the
11677 @file{gnat.adc} file that contains configuration pragmas directly,
11678 as described in the following section.
11680 In the case of @code{Restrictions} pragmas appearing as configuration
11681 pragmas in individual compilation units, the exact handling depends on
11682 the type of restriction.
11684 Restrictions that require partition-wide consistency (like
11685 @code{No_Tasking}) are
11686 recognized wherever they appear
11687 and can be freely inherited, e.g. from a with'ed unit to the with'ing
11688 unit. This makes sense since the binder will in any case insist on seeing
11689 consistent use, so any unit not conforming to any restrictions that are
11690 anywhere in the partition will be rejected, and you might as well find
11691 that out at compile time rather than at bind time.
11693 For restrictions that do not require partition-wide consistency, e.g.
11694 SPARK or No_Implementation_Attributes, in general the restriction applies
11695 only to the unit in which the pragma appears, and not to any other units.
11697 The exception is No_Elaboration_Code which always applies to the entire
11698 object file from a compilation, i.e. to the body, spec, and all subunits.
11699 This restriction can be specified in a configuration pragma file, or it
11700 can be on the body and/or the spec (in eithe case it applies to all the
11701 relevant units). It can appear on a subunit only if it has previously
11702 appeared in the body of spec.
11704 @node The Configuration Pragmas Files
11705 @section The Configuration Pragmas Files
11706 @cindex @file{gnat.adc}
11709 In GNAT a compilation environment is defined by the current
11710 directory at the time that a compile command is given. This current
11711 directory is searched for a file whose name is @file{gnat.adc}. If
11712 this file is present, it is expected to contain one or more
11713 configuration pragmas that will be applied to the current compilation.
11714 However, if the switch @option{-gnatA} is used, @file{gnat.adc} is not
11715 considered. When taken into account, @file{gnat.adc} is added to the
11716 dependencies, so that if @file{gnat.adc} is modified later, an invocation of
11717 @command{gnatmake} will recompile the source.
11719 Configuration pragmas may be entered into the @file{gnat.adc} file
11720 either by running @code{gnatchop} on a source file that consists only of
11721 configuration pragmas, or more conveniently by direct editing of the
11722 @file{gnat.adc} file, which is a standard format source file.
11724 In addition to @file{gnat.adc}, additional files containing configuration
11725 pragmas may be applied to the current compilation using the switch
11726 @option{-gnatec=}@var{path}. @var{path} must designate an existing file that
11727 contains only configuration pragmas. These configuration pragmas are
11728 in addition to those found in @file{gnat.adc} (provided @file{gnat.adc}
11729 is present and switch @option{-gnatA} is not used).
11731 It is allowable to specify several switches @option{-gnatec=}, all of which
11732 will be taken into account.
11734 Files containing configuration pragmas specified with switches
11735 @option{-gnatec=} are added to the dependencies, unless they are
11736 temporary files. A file is considered temporary if its name ends in
11737 @file{.tmp} or @file{.TMP}. Certain tools follow this naming
11738 convention because they pass information to @command{gcc} via
11739 temporary files that are immediately deleted; it doesn't make sense to
11740 depend on a file that no longer exists. Such tools include
11741 @command{gprbuild}, @command{gnatmake}, and @command{gnatcheck}.
11743 If you are using project file, a separate mechanism is provided using
11744 project attributes, see @ref{Specifying Configuration Pragmas} for more
11748 @node Handling Arbitrary File Naming Conventions with gnatname
11749 @chapter Handling Arbitrary File Naming Conventions with @code{gnatname}
11750 @cindex Arbitrary File Naming Conventions
11753 * Arbitrary File Naming Conventions::
11754 * Running gnatname::
11755 * Switches for gnatname::
11756 * Examples of gnatname Usage::
11759 @node Arbitrary File Naming Conventions
11760 @section Arbitrary File Naming Conventions
11763 The GNAT compiler must be able to know the source file name of a compilation
11764 unit. When using the standard GNAT default file naming conventions
11765 (@code{.ads} for specs, @code{.adb} for bodies), the GNAT compiler
11766 does not need additional information.
11769 When the source file names do not follow the standard GNAT default file naming
11770 conventions, the GNAT compiler must be given additional information through
11771 a configuration pragmas file (@pxref{Configuration Pragmas})
11773 When the non-standard file naming conventions are well-defined,
11774 a small number of pragmas @code{Source_File_Name} specifying a naming pattern
11775 (@pxref{Alternative File Naming Schemes}) may be sufficient. However,
11776 if the file naming conventions are irregular or arbitrary, a number
11777 of pragma @code{Source_File_Name} for individual compilation units
11779 To help maintain the correspondence between compilation unit names and
11780 source file names within the compiler,
11781 GNAT provides a tool @code{gnatname} to generate the required pragmas for a
11784 @node Running gnatname
11785 @section Running @code{gnatname}
11788 The usual form of the @code{gnatname} command is
11791 @c $ gnatname @ovar{switches} @var{naming_pattern} @ovar{naming_patterns}
11792 @c @r{[}--and @ovar{switches} @var{naming_pattern} @ovar{naming_patterns}@r{]}
11793 @c Expanding @ovar macro inline (explanation in macro def comments)
11794 $ gnatname @r{[}@var{switches}@r{]} @var{naming_pattern} @r{[}@var{naming_patterns}@r{]}
11795 @r{[}--and @r{[}@var{switches}@r{]} @var{naming_pattern} @r{[}@var{naming_patterns}@r{]}@r{]}
11799 All of the arguments are optional. If invoked without any argument,
11800 @code{gnatname} will display its usage.
11803 When used with at least one naming pattern, @code{gnatname} will attempt to
11804 find all the compilation units in files that follow at least one of the
11805 naming patterns. To find these compilation units,
11806 @code{gnatname} will use the GNAT compiler in syntax-check-only mode on all
11810 One or several Naming Patterns may be given as arguments to @code{gnatname}.
11811 Each Naming Pattern is enclosed between double quotes (or single
11812 quotes on Windows).
11813 A Naming Pattern is a regular expression similar to the wildcard patterns
11814 used in file names by the Unix shells or the DOS prompt.
11817 @code{gnatname} may be called with several sections of directories/patterns.
11818 Sections are separated by switch @code{--and}. In each section, there must be
11819 at least one pattern. If no directory is specified in a section, the current
11820 directory (or the project directory is @code{-P} is used) is implied.
11821 The options other that the directory switches and the patterns apply globally
11822 even if they are in different sections.
11825 Examples of Naming Patterns are
11834 For a more complete description of the syntax of Naming Patterns,
11835 see the second kind of regular expressions described in @file{g-regexp.ads}
11836 (the ``Glob'' regular expressions).
11839 When invoked with no switch @code{-P}, @code{gnatname} will create a
11840 configuration pragmas file @file{gnat.adc} in the current working directory,
11841 with pragmas @code{Source_File_Name} for each file that contains a valid Ada
11844 @node Switches for gnatname
11845 @section Switches for @code{gnatname}
11848 Switches for @code{gnatname} must precede any specified Naming Pattern.
11851 You may specify any of the following switches to @code{gnatname}:
11857 @cindex @option{--version} @command{gnatname}
11858 Display Copyright and version, then exit disregarding all other options.
11861 @cindex @option{--help} @command{gnatname}
11862 If @option{--version} was not used, display usage, then exit disregarding
11865 @item --subdirs=<dir>
11866 Real object, library or exec directories are subdirectories <dir> of the
11870 Do not create a backup copy of an existing project file.
11873 Start another section of directories/patterns.
11875 @item -c@file{file}
11876 @cindex @option{-c} (@code{gnatname})
11877 Create a configuration pragmas file @file{file} (instead of the default
11879 There may be zero, one or more space between @option{-c} and
11881 @file{file} may include directory information. @file{file} must be
11882 writable. There may be only one switch @option{-c}.
11883 When a switch @option{-c} is
11884 specified, no switch @option{-P} may be specified (see below).
11887 @cindex @option{-d} (@code{gnatname})
11888 Look for source files in directory @file{dir}. There may be zero, one or more
11889 spaces between @option{-d} and @file{dir}.
11890 @file{dir} may end with @code{/**}, that is it may be of the form
11891 @code{root_dir/**}. In this case, the directory @code{root_dir} and all of its
11892 subdirectories, recursively, have to be searched for sources.
11893 When a switch @option{-d}
11894 is specified, the current working directory will not be searched for source
11895 files, unless it is explicitly specified with a @option{-d}
11896 or @option{-D} switch.
11897 Several switches @option{-d} may be specified.
11898 If @file{dir} is a relative path, it is relative to the directory of
11899 the configuration pragmas file specified with switch
11901 or to the directory of the project file specified with switch
11903 if neither switch @option{-c}
11904 nor switch @option{-P} are specified, it is relative to the
11905 current working directory. The directory
11906 specified with switch @option{-d} must exist and be readable.
11908 @item -D@file{file}
11909 @cindex @option{-D} (@code{gnatname})
11910 Look for source files in all directories listed in text file @file{file}.
11911 There may be zero, one or more spaces between @option{-D}
11913 @file{file} must be an existing, readable text file.
11914 Each nonempty line in @file{file} must be a directory.
11915 Specifying switch @option{-D} is equivalent to specifying as many
11916 switches @option{-d} as there are nonempty lines in
11920 Follow symbolic links when processing project files.
11922 @item -f@file{pattern}
11923 @cindex @option{-f} (@code{gnatname})
11924 Foreign patterns. Using this switch, it is possible to add sources of languages
11925 other than Ada to the list of sources of a project file.
11926 It is only useful if a -P switch is used.
11929 gnatname -Pprj -f"*.c" "*.ada"
11932 will look for Ada units in all files with the @file{.ada} extension,
11933 and will add to the list of file for project @file{prj.gpr} the C files
11934 with extension @file{.c}.
11937 @cindex @option{-h} (@code{gnatname})
11938 Output usage (help) information. The output is written to @file{stdout}.
11940 @item -P@file{proj}
11941 @cindex @option{-P} (@code{gnatname})
11942 Create or update project file @file{proj}. There may be zero, one or more space
11943 between @option{-P} and @file{proj}. @file{proj} may include directory
11944 information. @file{proj} must be writable.
11945 There may be only one switch @option{-P}.
11946 When a switch @option{-P} is specified,
11947 no switch @option{-c} may be specified.
11948 On all platforms, except on VMS, when @code{gnatname} is invoked for an
11949 existing project file <proj>.gpr, a backup copy of the project file is created
11950 in the project directory with file name <proj>.gpr.saved_x. 'x' is the first
11951 non negative number that makes this backup copy a new file.
11954 @cindex @option{-v} (@code{gnatname})
11955 Verbose mode. Output detailed explanation of behavior to @file{stdout}.
11956 This includes name of the file written, the name of the directories to search
11957 and, for each file in those directories whose name matches at least one of
11958 the Naming Patterns, an indication of whether the file contains a unit,
11959 and if so the name of the unit.
11962 @cindex @option{-v -v} (@code{gnatname})
11963 Very Verbose mode. In addition to the output produced in verbose mode,
11964 for each file in the searched directories whose name matches none of
11965 the Naming Patterns, an indication is given that there is no match.
11967 @item -x@file{pattern}
11968 @cindex @option{-x} (@code{gnatname})
11969 Excluded patterns. Using this switch, it is possible to exclude some files
11970 that would match the name patterns. For example,
11972 gnatname -x "*_nt.ada" "*.ada"
11975 will look for Ada units in all files with the @file{.ada} extension,
11976 except those whose names end with @file{_nt.ada}.
11980 @node Examples of gnatname Usage
11981 @section Examples of @code{gnatname} Usage
11985 $ gnatname -c /home/me/names.adc -d sources "[a-z]*.ada*"
11989 In this example, the directory @file{/home/me} must already exist
11990 and be writable. In addition, the directory
11991 @file{/home/me/sources} (specified by
11992 @option{-d sources}) must exist and be readable.
11994 Note the optional spaces after @option{-c} and @option{-d}.
11997 $ gnatname -P/home/me/proj -x "*_nt_body.ada"
11998 -dsources -dsources/plus -Dcommon_dirs.txt "body_*" "spec_*"
12001 Note that several switches @option{-d} may be used,
12002 even in conjunction with one or several switches
12003 @option{-D}. Several Naming Patterns and one excluded pattern
12004 are used in this example.
12006 @c *****************************************
12007 @c * G N A T P r o j e c t M a n a g e r *
12008 @c *****************************************
12010 @c ------ macros for projects.texi
12011 @c These macros are needed when building the gprbuild documentation, but
12012 @c should have no effect in the gnat user's guide
12014 @macro CODESAMPLE{TXT}
12022 @macro PROJECTFILE{TXT}
12026 @c simulates a newline when in a @CODESAMPLE
12037 @macro TIPHTML{TXT}
12041 @macro IMPORTANT{TXT}
12056 @include projects.texi
12058 @c ---------------------------------------------
12059 @c Tools Supporting Project Files
12060 @c ---------------------------------------------
12062 @node Tools Supporting Project Files
12063 @chapter Tools Supporting Project Files
12068 * gnatmake and Project Files::
12069 * The GNAT Driver and Project Files::
12072 @c ---------------------------------------------
12073 @node gnatmake and Project Files
12074 @section gnatmake and Project Files
12075 @c ---------------------------------------------
12078 This section covers several topics related to @command{gnatmake} and
12079 project files: defining switches for @command{gnatmake}
12080 and for the tools that it invokes; specifying configuration pragmas;
12081 the use of the @code{Main} attribute; building and rebuilding library project
12085 * Switches Related to Project Files::
12086 * Switches and Project Files::
12087 * Specifying Configuration Pragmas::
12088 * Project Files and Main Subprograms::
12089 * Library Project Files::
12092 @c ---------------------------------------------
12093 @node Switches Related to Project Files
12094 @subsection Switches Related to Project Files
12095 @c ---------------------------------------------
12098 The following switches are used by GNAT tools that support project files:
12102 @item -P@var{project}
12103 @cindex @option{-P} (any project-aware tool)
12104 Indicates the name of a project file. This project file will be parsed with
12105 the verbosity indicated by @option{-vP@emph{x}},
12106 if any, and using the external references indicated
12107 by @option{-X} switches, if any.
12108 There may zero, one or more spaces between @option{-P} and @var{project}.
12110 There must be only one @option{-P} switch on the command line.
12112 Since the Project Manager parses the project file only after all the switches
12113 on the command line are checked, the order of the switches
12115 @option{-vP@emph{x}}
12116 or @option{-X} is not significant.
12118 @item -X@var{name=value}
12119 @cindex @option{-X} (any project-aware tool)
12120 Indicates that external variable @var{name} has the value @var{value}.
12121 The Project Manager will use this value for occurrences of
12122 @code{external(name)} when parsing the project file.
12124 If @var{name} or @var{value} includes a space, then @var{name=value} should be
12125 put between quotes.
12131 Several @option{-X} switches can be used simultaneously.
12132 If several @option{-X} switches specify the same
12133 @var{name}, only the last one is used.
12135 An external variable specified with a @option{-X} switch
12136 takes precedence over the value of the same name in the environment.
12139 @cindex @option{-vP} (any project-aware tool)
12140 Indicates the verbosity of the parsing of GNAT project files.
12142 @option{-vP0} means Default;
12143 @option{-vP1} means Medium;
12144 @option{-vP2} means High.
12147 The default is Default: no output for syntactically correct
12149 If several @option{-vP@emph{x}} switches are present,
12150 only the last one is used.
12153 @cindex @option{-aP} (any project-aware tool)
12154 Add directory <dir> at the beginning of the project search path, in order,
12155 after the current working directory.
12158 @cindex @option{-eL} (any project-aware tool)
12159 Follow all symbolic links when processing project files.
12161 @item --subdirs=<subdir>
12162 @cindex @option{--subdirs=} (gnatmake and gnatclean)
12163 This switch is recognized by @command{gnatmake} and @command{gnatclean}. It
12164 indicate that the real directories (except the source directories) are the
12165 subdirectories <subdir> of the directories specified in the project files.
12166 This applies in particular to object directories, library directories and
12167 exec directories. If the subdirectories do not exist, they are created
12172 @c ---------------------------------------------
12173 @node Switches and Project Files
12174 @subsection Switches and Project Files
12175 @c ---------------------------------------------
12179 For each of the packages @code{Builder}, @code{Compiler}, @code{Binder}, and
12180 @code{Linker}, you can specify a @code{Default_Switches}
12181 attribute, a @code{Switches} attribute, or both;
12182 as their names imply, these switch-related
12183 attributes affect the switches that are used for each of these GNAT
12185 @command{gnatmake} is invoked. As will be explained below, these
12186 component-specific switches precede
12187 the switches provided on the @command{gnatmake} command line.
12189 The @code{Default_Switches} attribute is an attribute
12190 indexed by language name (case insensitive) whose value is a string list.
12193 @smallexample @c projectfile
12195 @b{package} Compiler @b{is}
12196 @b{for} Default_Switches ("Ada")
12204 The @code{Switches} attribute is indexed on a file name (which may or may
12205 not be case sensitive, depending
12206 on the operating system) whose value is a string list. For example:
12208 @smallexample @c projectfile
12210 @b{package} Builder @b{is}
12211 @b{for} Switches ("main1.adb")
12213 @b{for} Switches ("main2.adb")
12220 For the @code{Builder} package, the file names must designate source files
12221 for main subprograms. For the @code{Binder} and @code{Linker} packages, the
12222 file names must designate @file{ALI} or source files for main subprograms.
12223 In each case just the file name without an explicit extension is acceptable.
12225 For each tool used in a program build (@command{gnatmake}, the compiler, the
12226 binder, and the linker), the corresponding package @dfn{contributes} a set of
12227 switches for each file on which the tool is invoked, based on the
12228 switch-related attributes defined in the package.
12229 In particular, the switches
12230 that each of these packages contributes for a given file @var{f} comprise:
12233 @item the value of attribute @code{Switches (@var{f})},
12234 if it is specified in the package for the given file,
12235 @item otherwise, the value of @code{Default_Switches ("Ada")},
12236 if it is specified in the package.
12241 If neither of these attributes is defined in the package, then the package does
12242 not contribute any switches for the given file.
12244 When @command{gnatmake} is invoked on a file, the switches comprise
12245 two sets, in the following order: those contributed for the file
12246 by the @code{Builder} package;
12247 and the switches passed on the command line.
12249 When @command{gnatmake} invokes a tool (compiler, binder, linker) on a file,
12250 the switches passed to the tool comprise three sets,
12251 in the following order:
12255 the applicable switches contributed for the file
12256 by the @code{Builder} package in the project file supplied on the command line;
12259 those contributed for the file by the package (in the relevant project file --
12260 see below) corresponding to the tool; and
12263 the applicable switches passed on the command line.
12266 The term @emph{applicable switches} reflects the fact that
12267 @command{gnatmake} switches may or may not be passed to individual
12268 tools, depending on the individual switch.
12270 @command{gnatmake} may invoke the compiler on source files from different
12271 projects. The Project Manager will use the appropriate project file to
12272 determine the @code{Compiler} package for each source file being compiled.
12273 Likewise for the @code{Binder} and @code{Linker} packages.
12275 As an example, consider the following package in a project file:
12277 @smallexample @c projectfile
12279 @b{project} Proj1 @b{is}
12280 @b{package} Compiler @b{is}
12281 @b{for} Default_Switches ("Ada")
12283 @b{for} Switches ("a.adb")
12285 @b{for} Switches ("b.adb")
12294 If @command{gnatmake} is invoked with this project file, and it needs to
12295 compile, say, the files @file{a.adb}, @file{b.adb}, and @file{c.adb}, then
12296 @file{a.adb} will be compiled with the switch
12298 @file{b.adb} with switches
12300 and @option{-gnaty},
12301 and @file{c.adb} with @option{-g}.
12303 The following example illustrates the ordering of the switches
12304 contributed by different packages:
12306 @smallexample @c projectfile
12308 @b{project} Proj2 @b{is}
12309 @b{package} Builder @b{is}
12310 @b{for} Switches ("main.adb")
12318 @b{package} Compiler @b{is}
12319 @b{for} Switches ("main.adb")
12327 If you issue the command:
12330 gnatmake -Pproj2 -O0 main
12334 then the compiler will be invoked on @file{main.adb} with the following
12335 sequence of switches
12342 with the last @option{-O}
12343 switch having precedence over the earlier ones;
12344 several other switches
12345 (such as @option{-c}) are added implicitly.
12349 and @option{-O1} are contributed by package
12350 @code{Builder}, @option{-O2} is contributed
12351 by the package @code{Compiler}
12352 and @option{-O0} comes from the command line.
12355 switch will also be passed in the invocation of
12356 @command{Gnatlink.}
12358 A final example illustrates switch contributions from packages in different
12361 @smallexample @c projectfile
12363 @b{project} Proj3 @b{is}
12364 @b{for} Source_Files @b{use} ("pack.ads", "pack.adb");
12365 @b{package} Compiler @b{is}
12366 @b{for} Default_Switches ("Ada")
12367 @b{use} ("-gnata");
12374 @b{project} Proj4 @b{is}
12375 @b{for} Source_Files @b{use} ("foo_main.adb", "bar_main.adb");
12376 @b{package} Builder @b{is}
12377 @b{for} Switches ("foo_main.adb")
12385 --@i{ Ada source file:}
12387 @b{procedure} Foo_Main @b{is}
12396 gnatmake -PProj4 foo_main.adb -cargs -gnato
12400 then the switches passed to the compiler for @file{foo_main.adb} are
12401 @option{-g} (contributed by the package @code{Proj4.Builder}) and
12402 @option{-gnato} (passed on the command line).
12403 When the imported package @code{Pack} is compiled, the switches used
12404 are @option{-g} from @code{Proj4.Builder},
12405 @option{-gnata} (contributed from package @code{Proj3.Compiler},
12406 and @option{-gnato} from the command line.
12408 When using @command{gnatmake} with project files, some switches or
12409 arguments may be expressed as relative paths. As the working directory where
12410 compilation occurs may change, these relative paths are converted to absolute
12411 paths. For the switches found in a project file, the relative paths
12412 are relative to the project file directory, for the switches on the command
12413 line, they are relative to the directory where @command{gnatmake} is invoked.
12414 The switches for which this occurs are:
12420 -aI, as well as all arguments that are not switches (arguments to
12422 -o, object files specified in package @code{Linker} or after
12423 -largs on the command line). The exception to this rule is the switch
12424 --RTS= for which a relative path argument is never converted.
12426 @c ---------------------------------------------
12427 @node Specifying Configuration Pragmas
12428 @subsection Specifying Configuration Pragmas
12429 @c ---------------------------------------------
12432 When using @command{gnatmake} with project files, if there exists a file
12433 @file{gnat.adc} that contains configuration pragmas, this file will be
12436 Configuration pragmas can be defined by means of the following attributes in
12437 project files: @code{Global_Configuration_Pragmas} in package @code{Builder}
12438 and @code{Local_Configuration_Pragmas} in package @code{Compiler}.
12440 Both these attributes are single string attributes. Their values is the path
12441 name of a file containing configuration pragmas. If a path name is relative,
12442 then it is relative to the project directory of the project file where the
12443 attribute is defined.
12445 When compiling a source, the configuration pragmas used are, in order,
12446 those listed in the file designated by attribute
12447 @code{Global_Configuration_Pragmas} in package @code{Builder} of the main
12448 project file, if it is specified, and those listed in the file designated by
12449 attribute @code{Local_Configuration_Pragmas} in package @code{Compiler} of
12450 the project file of the source, if it exists.
12452 @c ---------------------------------------------
12453 @node Project Files and Main Subprograms
12454 @subsection Project Files and Main Subprograms
12455 @c ---------------------------------------------
12458 When using a project file, you can invoke @command{gnatmake}
12459 with one or several main subprograms, by specifying their source files on the
12463 gnatmake -Pprj main1.adb main2.adb main3.adb
12467 Each of these needs to be a source file of the same project, except
12468 when the switch -u is used.
12470 When -u is not used, all the mains need to be sources of the
12471 same project, one of the project in the tree rooted at the project specified
12472 on the command line. The package @code{Builder} of this common project, the
12473 "main project" is the one that is considered by @command{gnatmake}.
12475 When -u is used, the specified source files may be in projects
12476 imported directly or indirectly by the project specified on the command line.
12477 Note that if such a source file is not part of the project specified on the
12478 command line, the switches found in package @code{Builder} of the
12479 project specified on the command line, if any, that are transmitted
12480 to the compiler will still be used, not those found in the project file of
12483 When using a project file, you can also invoke @command{gnatmake} without
12484 explicitly specifying any main, and the effect depends on whether you have
12485 defined the @code{Main} attribute. This attribute has a string list value,
12486 where each element in the list is the name of a source file (the file
12487 extension is optional) that contains a unit that can be a main subprogram.
12489 If the @code{Main} attribute is defined in a project file as a non-empty
12490 string list and the switch @option{-u} is not used on the command
12491 line, then invoking @command{gnatmake} with this project file but without any
12492 main on the command line is equivalent to invoking @command{gnatmake} with all
12493 the file names in the @code{Main} attribute on the command line.
12496 @smallexample @c projectfile
12498 @b{project} Prj @b{is}
12499 @b{for} Main @b{use} ("main1.adb", "main2.adb", "main3.adb");
12505 With this project file, @code{"gnatmake -Pprj"}
12507 @code{"gnatmake -Pprj main1.adb main2.adb main3.adb"}.
12509 When the project attribute @code{Main} is not specified, or is specified
12510 as an empty string list, or when the switch @option{-u} is used on the command
12511 line, then invoking @command{gnatmake} with no main on the command line will
12512 result in all immediate sources of the project file being checked, and
12513 potentially recompiled. Depending on the presence of the switch @option{-u},
12514 sources from other project files on which the immediate sources of the main
12515 project file depend are also checked and potentially recompiled. In other
12516 words, the @option{-u} switch is applied to all of the immediate sources of the
12519 When no main is specified on the command line and attribute @code{Main} exists
12520 and includes several mains, or when several mains are specified on the
12521 command line, the default switches in package @code{Builder} will
12522 be used for all mains, even if there are specific switches
12523 specified for one or several mains.
12525 But the switches from package @code{Binder} or @code{Linker} will be
12526 the specific switches for each main, if they are specified.
12528 @c ---------------------------------------------
12529 @node Library Project Files
12530 @subsection Library Project Files
12531 @c ---------------------------------------------
12534 When @command{gnatmake} is invoked with a main project file that is a library
12535 project file, it is not allowed to specify one or more mains on the command
12538 When a library project file is specified, switches -b and
12539 -l have special meanings.
12542 @item -b is only allowed for stand-alone libraries. It indicates
12543 to @command{gnatmake} that @command{gnatbind} should be invoked for the
12546 @item -l may be used for all library projects. It indicates
12547 to @command{gnatmake} that the binder generated file should be compiled
12548 (in the case of a stand-alone library) and that the library should be built.
12551 @c ---------------------------------------------
12552 @node The GNAT Driver and Project Files
12553 @section The GNAT Driver and Project Files
12554 @c ---------------------------------------------
12557 A number of GNAT tools, other than @command{gnatmake}
12558 can benefit from project files:
12559 (@command{gnatbind},
12560 @ifclear FSFEDITION
12561 @command{gnatcheck},
12563 @command{gnatclean},
12564 @ifclear FSFEDITION
12565 @command{gnatelim},
12567 @command{gnatfind},
12568 @command{gnatlink},
12570 @ifclear FSFEDITION
12571 @command{gnatmetric},
12573 @command{gnatstub},
12575 and @command{gnatxref}). However, none of these tools can be invoked
12576 directly with a project file switch (@option{-P}).
12577 They must be invoked through the @command{gnat} driver.
12579 The @command{gnat} driver is a wrapper that accepts a number of commands and
12580 calls the corresponding tool. It was designed initially for VMS platforms (to
12581 convert VMS qualifiers to Unix-style switches), but it is now available on all
12584 On non-VMS platforms, the @command{gnat} driver accepts the following commands
12585 (case insensitive):
12588 @item BIND to invoke @command{gnatbind}
12589 @item CHOP to invoke @command{gnatchop}
12590 @item CLEAN to invoke @command{gnatclean}
12591 @item COMP or COMPILE to invoke the compiler
12592 @ifclear FSFEDITION
12593 @item ELIM to invoke @command{gnatelim}
12595 @item FIND to invoke @command{gnatfind}
12596 @item KR or KRUNCH to invoke @command{gnatkr}
12597 @item LINK to invoke @command{gnatlink}
12598 @item LS or LIST to invoke @command{gnatls}
12599 @item MAKE to invoke @command{gnatmake}
12600 @item NAME to invoke @command{gnatname}
12601 @item PREP or PREPROCESS to invoke @command{gnatprep}
12602 @ifclear FSFEDITION
12603 @item PP or PRETTY to invoke @command{gnatpp}
12604 @item METRIC to invoke @command{gnatmetric}
12605 @item STUB to invoke @command{gnatstub}
12607 @item XREF to invoke @command{gnatxref}
12612 (note that the compiler is invoked using the command
12613 @command{gnatmake -f -u -c}).
12615 On non-VMS platforms, between @command{gnat} and the command, two
12616 special switches may be used:
12619 @item @command{-v} to display the invocation of the tool.
12620 @item @command{-dn} to prevent the @command{gnat} driver from removing
12621 the temporary files it has created. These temporary files are
12622 configuration files and temporary file list files.
12627 The command may be followed by switches and arguments for the invoked
12631 gnat bind -C main.ali
12637 Switches may also be put in text files, one switch per line, and the text
12638 files may be specified with their path name preceded by '@@'.
12641 gnat bind @@args.txt main.ali
12645 In addition, for commands BIND, COMP or COMPILE, FIND,
12646 @ifclear FSFEDITION
12650 @ifclear FSFEDITION
12655 and XREF, the project file related switches
12658 @option{-vPx}) may be used in addition to
12659 the switches of the invoking tool.
12661 @ifclear FSFEDITION
12662 When GNAT PP or GNAT PRETTY is used with a project file, but with no source
12663 specified on the command line, it invokes @command{gnatpp} with all
12664 the immediate sources of the specified project file.
12667 @ifclear FSFEDITION
12668 When GNAT METRIC is used with a project file, but with no source
12669 specified on the command line, it invokes @command{gnatmetric}
12670 with all the immediate sources of the specified project file and with
12671 @option{-d} with the parameter pointing to the object directory
12675 @ifclear FSFEDITION
12676 In addition, when GNAT PP, GNAT PRETTY or GNAT METRIC is used with
12677 a project file, no source is specified on the command line and
12678 switch -U is specified on the command line, then
12679 the underlying tool (gnatpp or
12680 gnatmetric) is invoked for all sources of all projects,
12681 not only for the immediate sources of the main project.
12682 (-U stands for Universal or Union of the project files of the project tree)
12685 For each of the following commands, there is optionally a corresponding
12686 package in the main project.
12689 @item package @code{Binder} for command BIND (invoking @code{gnatbind})
12691 @ifclear FSFEDITION
12692 @item package @code{Check} for command CHECK (invoking
12696 @item package @code{Compiler} for command COMP or COMPILE (invoking the compiler)
12698 @item package @code{Cross_Reference} for command XREF (invoking
12701 @ifclear FSFEDITION
12702 @item package @code{Eliminate} for command ELIM (invoking
12706 @item package @code{Finder} for command FIND (invoking @code{gnatfind})
12708 @item package @code{Gnatls} for command LS or LIST (invoking @code{gnatls})
12710 @ifclear FSFEDITION
12711 @item package @code{Gnatstub} for command STUB
12712 (invoking @code{gnatstub})
12715 @item package @code{Linker} for command LINK (invoking @code{gnatlink})
12717 @ifclear FSFEDITION
12718 @item package @code{Check} for command CHECK
12719 (invoking @code{gnatcheck})
12722 @ifclear FSFEDITION
12723 @item package @code{Metrics} for command METRIC
12724 (invoking @code{gnatmetric})
12727 @ifclear FSFEDITION
12728 @item package @code{Pretty_Printer} for command PP or PRETTY
12729 (invoking @code{gnatpp})
12735 Package @code{Gnatls} has a unique attribute @code{Switches},
12736 a simple variable with a string list value. It contains switches
12737 for the invocation of @code{gnatls}.
12739 @smallexample @c projectfile
12741 @b{project} Proj1 @b{is}
12742 @b{package} gnatls @b{is}
12752 All other packages have two attribute @code{Switches} and
12753 @code{Default_Switches}.
12755 @code{Switches} is an indexed attribute, indexed by the
12756 source file name, that has a string list value: the switches to be
12757 used when the tool corresponding to the package is invoked for the specific
12760 @code{Default_Switches} is an attribute,
12761 indexed by the programming language that has a string list value.
12762 @code{Default_Switches ("Ada")} contains the
12763 switches for the invocation of the tool corresponding
12764 to the package, except if a specific @code{Switches} attribute
12765 is specified for the source file.
12767 @smallexample @c projectfile
12769 @b{project} Proj @b{is}
12771 @b{for} Source_Dirs @b{use} ("**");
12773 @b{package} gnatls @b{is}
12774 @b{for} Switches @b{use}
12781 @b{package} Compiler @b{is}
12782 @b{for} Default_Switches ("Ada")
12789 @b{package} Binder @b{is}
12790 @b{for} Default_Switches ("Ada")
12797 @b{package} Linker @b{is}
12798 @b{for} Default_Switches ("Ada")
12800 @b{for} Switches ("main.adb")
12808 @b{package} Finder @b{is}
12809 @b{for} Default_Switches ("Ada")
12816 @b{package} Cross_Reference @b{is}
12817 @b{for} Default_Switches ("Ada")
12822 @b{end} Cross_Reference;
12828 With the above project file, commands such as
12831 gnat comp -Pproj main
12832 gnat ls -Pproj main
12833 gnat xref -Pproj main
12834 gnat bind -Pproj main.ali
12835 gnat link -Pproj main.ali
12839 will set up the environment properly and invoke the tool with the switches
12840 found in the package corresponding to the tool:
12841 @code{Default_Switches ("Ada")} for all tools,
12842 except @code{Switches ("main.adb")}
12843 for @code{gnatlink}.
12844 @ifclear FSFEDITION
12845 It is also possible to invoke some of the tools,
12849 on a set of project units thanks to the combination of the switches
12850 @option{-P}, @option{-U} and possibly the main unit when one is interested
12851 in its closure. For instance,
12857 will compute the metrics for all the immediate units of project
12860 gnat metric -Pproj -U
12864 will compute the metrics for all the units of the closure of projects
12865 rooted at @code{proj}.
12867 gnat metric -Pproj -U main_unit
12871 will compute the metrics for the closure of units rooted at
12872 @code{main_unit}. This last possibility relies implicitly
12873 on @command{gnatbind}'s option @option{-R}. But if the argument files for the
12874 tool invoked by the @command{gnat} driver are explicitly specified
12875 either directly or through the tool @option{-files} option, then the tool
12876 is called only for these explicitly specified files.
12879 @c *****************************************
12880 @c * Cross-referencing tools
12881 @c *****************************************
12883 @node The Cross-Referencing Tools gnatxref and gnatfind
12884 @chapter The Cross-Referencing Tools @code{gnatxref} and @code{gnatfind}
12889 The compiler generates cross-referencing information (unless
12890 you set the @samp{-gnatx} switch), which are saved in the @file{.ali} files.
12891 This information indicates where in the source each entity is declared and
12892 referenced. Note that entities in package Standard are not included, but
12893 entities in all other predefined units are included in the output.
12895 Before using any of these two tools, you need to compile successfully your
12896 application, so that GNAT gets a chance to generate the cross-referencing
12899 The two tools @code{gnatxref} and @code{gnatfind} take advantage of this
12900 information to provide the user with the capability to easily locate the
12901 declaration and references to an entity. These tools are quite similar,
12902 the difference being that @code{gnatfind} is intended for locating
12903 definitions and/or references to a specified entity or entities, whereas
12904 @code{gnatxref} is oriented to generating a full report of all
12907 To use these tools, you must not compile your application using the
12908 @option{-gnatx} switch on the @command{gnatmake} command line
12909 (@pxref{The GNAT Make Program gnatmake}). Otherwise, cross-referencing
12910 information will not be generated.
12912 Note: to invoke @code{gnatxref} or @code{gnatfind} with a project file,
12913 use the @code{gnat} driver (see @ref{The GNAT Driver and Project Files}).
12916 * Switches for gnatxref::
12917 * Switches for gnatfind::
12918 * Project Files for gnatxref and gnatfind::
12919 * Regular Expressions in gnatfind and gnatxref::
12920 * Examples of gnatxref Usage::
12921 * Examples of gnatfind Usage::
12924 @node Switches for gnatxref
12925 @section @code{gnatxref} Switches
12928 The command invocation for @code{gnatxref} is:
12930 @c $ gnatxref @ovar{switches} @var{sourcefile1} @r{[}@var{sourcefile2} @dots{}@r{]}
12931 @c Expanding @ovar macro inline (explanation in macro def comments)
12932 $ gnatxref @r{[}@var{switches}@r{]} @var{sourcefile1} @r{[}@var{sourcefile2} @dots{}@r{]}
12941 identifies the source files for which a report is to be generated. The
12942 ``with''ed units will be processed too. You must provide at least one file.
12944 These file names are considered to be regular expressions, so for instance
12945 specifying @file{source*.adb} is the same as giving every file in the current
12946 directory whose name starts with @file{source} and whose extension is
12949 You shouldn't specify any directory name, just base names. @command{gnatxref}
12950 and @command{gnatfind} will be able to locate these files by themselves using
12951 the source path. If you specify directories, no result is produced.
12956 The switches can be:
12960 @cindex @option{--version} @command{gnatxref}
12961 Display Copyright and version, then exit disregarding all other options.
12964 @cindex @option{--help} @command{gnatxref}
12965 If @option{--version} was not used, display usage, then exit disregarding
12969 @cindex @option{-a} (@command{gnatxref})
12970 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
12971 the read-only files found in the library search path. Otherwise, these files
12972 will be ignored. This option can be used to protect Gnat sources or your own
12973 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
12974 much faster, and their output much smaller. Read-only here refers to access
12975 or permissions status in the file system for the current user.
12978 @cindex @option{-aIDIR} (@command{gnatxref})
12979 When looking for source files also look in directory DIR. The order in which
12980 source file search is undertaken is the same as for @command{gnatmake}.
12983 @cindex @option{-aODIR} (@command{gnatxref})
12984 When searching for library and object files, look in directory
12985 DIR. The order in which library files are searched is the same as for
12986 @command{gnatmake}.
12989 @cindex @option{-nostdinc} (@command{gnatxref})
12990 Do not look for sources in the system default directory.
12993 @cindex @option{-nostdlib} (@command{gnatxref})
12994 Do not look for library files in the system default directory.
12996 @item --ext=@var{extension}
12997 @cindex @option{--ext} (@command{gnatxref})
12998 Specify an alternate ali file extension. The default is @code{ali} and other
12999 extensions (e.g. @code{gli} for C/C++ sources when using @option{-fdump-xref})
13000 may be specified via this switch. Note that if this switch overrides the
13001 default, which means that only the new extension will be considered.
13003 @item --RTS=@var{rts-path}
13004 @cindex @option{--RTS} (@command{gnatxref})
13005 Specifies the default location of the runtime library. Same meaning as the
13006 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
13009 @cindex @option{-d} (@command{gnatxref})
13010 If this switch is set @code{gnatxref} will output the parent type
13011 reference for each matching derived types.
13014 @cindex @option{-f} (@command{gnatxref})
13015 If this switch is set, the output file names will be preceded by their
13016 directory (if the file was found in the search path). If this switch is
13017 not set, the directory will not be printed.
13020 @cindex @option{-g} (@command{gnatxref})
13021 If this switch is set, information is output only for library-level
13022 entities, ignoring local entities. The use of this switch may accelerate
13023 @code{gnatfind} and @code{gnatxref}.
13026 @cindex @option{-IDIR} (@command{gnatxref})
13027 Equivalent to @samp{-aODIR -aIDIR}.
13030 @cindex @option{-pFILE} (@command{gnatxref})
13031 Specify a project file to use @xref{GNAT Project Manager}.
13032 If you need to use the @file{.gpr}
13033 project files, you should use gnatxref through the GNAT driver
13034 (@command{gnat xref -Pproject}).
13036 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
13037 project file in the current directory.
13039 If a project file is either specified or found by the tools, then the content
13040 of the source directory and object directory lines are added as if they
13041 had been specified respectively by @samp{-aI}
13044 Output only unused symbols. This may be really useful if you give your
13045 main compilation unit on the command line, as @code{gnatxref} will then
13046 display every unused entity and 'with'ed package.
13049 Instead of producing the default output, @code{gnatxref} will generate a
13050 @file{tags} file that can be used by vi. For examples how to use this
13051 feature, see @ref{Examples of gnatxref Usage}. The tags file is output
13052 to the standard output, thus you will have to redirect it to a file.
13057 All these switches may be in any order on the command line, and may even
13058 appear after the file names. They need not be separated by spaces, thus
13059 you can say @samp{gnatxref -ag} instead of
13060 @samp{gnatxref -a -g}.
13062 @node Switches for gnatfind
13063 @section @code{gnatfind} Switches
13066 The command line for @code{gnatfind} is:
13069 @c $ gnatfind @ovar{switches} @var{pattern}@r{[}:@var{sourcefile}@r{[}:@var{line}@r{[}:@var{column}@r{]]]}
13070 @c @r{[}@var{file1} @var{file2} @dots{}]
13071 @c Expanding @ovar macro inline (explanation in macro def comments)
13072 $ gnatfind @r{[}@var{switches}@r{]} @var{pattern}@r{[}:@var{sourcefile}@r{[}:@var{line}@r{[}:@var{column}@r{]]]}
13073 @r{[}@var{file1} @var{file2} @dots{}@r{]}
13081 An entity will be output only if it matches the regular expression found
13082 in @var{pattern}, see @ref{Regular Expressions in gnatfind and gnatxref}.
13084 Omitting the pattern is equivalent to specifying @samp{*}, which
13085 will match any entity. Note that if you do not provide a pattern, you
13086 have to provide both a sourcefile and a line.
13088 Entity names are given in Latin-1, with uppercase/lowercase equivalence
13089 for matching purposes. At the current time there is no support for
13090 8-bit codes other than Latin-1, or for wide characters in identifiers.
13093 @code{gnatfind} will look for references, bodies or declarations
13094 of symbols referenced in @file{@var{sourcefile}}, at line @var{line}
13095 and column @var{column}. See @ref{Examples of gnatfind Usage}
13096 for syntax examples.
13099 is a decimal integer identifying the line number containing
13100 the reference to the entity (or entities) to be located.
13103 is a decimal integer identifying the exact location on the
13104 line of the first character of the identifier for the
13105 entity reference. Columns are numbered from 1.
13107 @item file1 file2 @dots{}
13108 The search will be restricted to these source files. If none are given, then
13109 the search will be done for every library file in the search path.
13110 These file must appear only after the pattern or sourcefile.
13112 These file names are considered to be regular expressions, so for instance
13113 specifying @file{source*.adb} is the same as giving every file in the current
13114 directory whose name starts with @file{source} and whose extension is
13117 The location of the spec of the entity will always be displayed, even if it
13118 isn't in one of @file{@var{file1}}, @file{@var{file2}},@enddots{} The
13119 occurrences of the entity in the separate units of the ones given on the
13120 command line will also be displayed.
13122 Note that if you specify at least one file in this part, @code{gnatfind} may
13123 sometimes not be able to find the body of the subprograms.
13128 At least one of 'sourcefile' or 'pattern' has to be present on
13131 The following switches are available:
13135 @cindex @option{--version} @command{gnatfind}
13136 Display Copyright and version, then exit disregarding all other options.
13139 @cindex @option{--help} @command{gnatfind}
13140 If @option{--version} was not used, display usage, then exit disregarding
13144 @cindex @option{-a} (@command{gnatfind})
13145 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
13146 the read-only files found in the library search path. Otherwise, these files
13147 will be ignored. This option can be used to protect Gnat sources or your own
13148 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
13149 much faster, and their output much smaller. Read-only here refers to access
13150 or permission status in the file system for the current user.
13153 @cindex @option{-aIDIR} (@command{gnatfind})
13154 When looking for source files also look in directory DIR. The order in which
13155 source file search is undertaken is the same as for @command{gnatmake}.
13158 @cindex @option{-aODIR} (@command{gnatfind})
13159 When searching for library and object files, look in directory
13160 DIR. The order in which library files are searched is the same as for
13161 @command{gnatmake}.
13164 @cindex @option{-nostdinc} (@command{gnatfind})
13165 Do not look for sources in the system default directory.
13168 @cindex @option{-nostdlib} (@command{gnatfind})
13169 Do not look for library files in the system default directory.
13171 @item --ext=@var{extension}
13172 @cindex @option{--ext} (@command{gnatfind})
13173 Specify an alternate ali file extension. The default is @code{ali} and other
13174 extensions (e.g. @code{gli} for C/C++ sources when using @option{-fdump-xref})
13175 may be specified via this switch. Note that if this switch overrides the
13176 default, which means that only the new extension will be considered.
13178 @item --RTS=@var{rts-path}
13179 @cindex @option{--RTS} (@command{gnatfind})
13180 Specifies the default location of the runtime library. Same meaning as the
13181 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
13184 @cindex @option{-d} (@code{gnatfind})
13185 If this switch is set, then @code{gnatfind} will output the parent type
13186 reference for each matching derived types.
13189 @cindex @option{-e} (@command{gnatfind})
13190 By default, @code{gnatfind} accept the simple regular expression set for
13191 @samp{pattern}. If this switch is set, then the pattern will be
13192 considered as full Unix-style regular expression.
13195 @cindex @option{-f} (@command{gnatfind})
13196 If this switch is set, the output file names will be preceded by their
13197 directory (if the file was found in the search path). If this switch is
13198 not set, the directory will not be printed.
13201 @cindex @option{-g} (@command{gnatfind})
13202 If this switch is set, information is output only for library-level
13203 entities, ignoring local entities. The use of this switch may accelerate
13204 @code{gnatfind} and @code{gnatxref}.
13207 @cindex @option{-IDIR} (@command{gnatfind})
13208 Equivalent to @samp{-aODIR -aIDIR}.
13211 @cindex @option{-pFILE} (@command{gnatfind})
13212 Specify a project file (@pxref{GNAT Project Manager}) to use.
13213 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
13214 project file in the current directory.
13216 If a project file is either specified or found by the tools, then the content
13217 of the source directory and object directory lines are added as if they
13218 had been specified respectively by @samp{-aI} and
13222 @cindex @option{-r} (@command{gnatfind})
13223 By default, @code{gnatfind} will output only the information about the
13224 declaration, body or type completion of the entities. If this switch is
13225 set, the @code{gnatfind} will locate every reference to the entities in
13226 the files specified on the command line (or in every file in the search
13227 path if no file is given on the command line).
13230 @cindex @option{-s} (@command{gnatfind})
13231 If this switch is set, then @code{gnatfind} will output the content
13232 of the Ada source file lines were the entity was found.
13235 @cindex @option{-t} (@command{gnatfind})
13236 If this switch is set, then @code{gnatfind} will output the type hierarchy for
13237 the specified type. It act like -d option but recursively from parent
13238 type to parent type. When this switch is set it is not possible to
13239 specify more than one file.
13244 All these switches may be in any order on the command line, and may even
13245 appear after the file names. They need not be separated by spaces, thus
13246 you can say @samp{gnatxref -ag} instead of
13247 @samp{gnatxref -a -g}.
13249 As stated previously, gnatfind will search in every directory in the
13250 search path. You can force it to look only in the current directory if
13251 you specify @code{*} at the end of the command line.
13253 @node Project Files for gnatxref and gnatfind
13254 @section Project Files for @command{gnatxref} and @command{gnatfind}
13257 Project files allow a programmer to specify how to compile its
13258 application, where to find sources, etc. These files are used
13259 primarily by GPS, but they can also be used
13261 @code{gnatxref} and @code{gnatfind}.
13263 A project file name must end with @file{.gpr}. If a single one is
13264 present in the current directory, then @code{gnatxref} and @code{gnatfind} will
13265 extract the information from it. If multiple project files are found, none of
13266 them is read, and you have to use the @samp{-p} switch to specify the one
13269 The following lines can be included, even though most of them have default
13270 values which can be used in most cases.
13271 The lines can be entered in any order in the file.
13272 Except for @file{src_dir} and @file{obj_dir}, you can only have one instance of
13273 each line. If you have multiple instances, only the last one is taken into
13278 [default: @code{"./"}]
13279 specifies a directory where to look for source files. Multiple @code{src_dir}
13280 lines can be specified and they will be searched in the order they
13284 [default: @code{"./"}]
13285 specifies a directory where to look for object and library files. Multiple
13286 @code{obj_dir} lines can be specified, and they will be searched in the order
13289 @item comp_opt=SWITCHES
13290 [default: @code{""}]
13291 creates a variable which can be referred to subsequently by using
13292 the @code{$@{comp_opt@}} notation. This is intended to store the default
13293 switches given to @command{gnatmake} and @command{gcc}.
13295 @item bind_opt=SWITCHES
13296 [default: @code{""}]
13297 creates a variable which can be referred to subsequently by using
13298 the @samp{$@{bind_opt@}} notation. This is intended to store the default
13299 switches given to @command{gnatbind}.
13301 @item link_opt=SWITCHES
13302 [default: @code{""}]
13303 creates a variable which can be referred to subsequently by using
13304 the @samp{$@{link_opt@}} notation. This is intended to store the default
13305 switches given to @command{gnatlink}.
13307 @item main=EXECUTABLE
13308 [default: @code{""}]
13309 specifies the name of the executable for the application. This variable can
13310 be referred to in the following lines by using the @samp{$@{main@}} notation.
13312 @item comp_cmd=COMMAND
13313 [default: @code{"gcc -c -I$@{src_dir@} -g -gnatq"}]
13314 specifies the command used to compile a single file in the application.
13316 @item make_cmd=COMMAND
13317 [default: @code{"gnatmake $@{main@} -aI$@{src_dir@}
13318 -aO$@{obj_dir@} -g -gnatq -cargs $@{comp_opt@}
13319 -bargs $@{bind_opt@} -largs $@{link_opt@}"}]
13320 specifies the command used to recompile the whole application.
13322 @item run_cmd=COMMAND
13323 [default: @code{"$@{main@}"}]
13324 specifies the command used to run the application.
13326 @item debug_cmd=COMMAND
13327 [default: @code{"gdb $@{main@}"}]
13328 specifies the command used to debug the application
13333 @command{gnatxref} and @command{gnatfind} only take into account the
13334 @code{src_dir} and @code{obj_dir} lines, and ignore the others.
13336 @node Regular Expressions in gnatfind and gnatxref
13337 @section Regular Expressions in @code{gnatfind} and @code{gnatxref}
13340 As specified in the section about @command{gnatfind}, the pattern can be a
13341 regular expression. Actually, there are to set of regular expressions
13342 which are recognized by the program:
13345 @item globbing patterns
13346 These are the most usual regular expression. They are the same that you
13347 generally used in a Unix shell command line, or in a DOS session.
13349 Here is a more formal grammar:
13356 term ::= elmt -- matches elmt
13357 term ::= elmt elmt -- concatenation (elmt then elmt)
13358 term ::= * -- any string of 0 or more characters
13359 term ::= ? -- matches any character
13360 term ::= [char @{char@}] -- matches any character listed
13361 term ::= [char - char] -- matches any character in range
13365 @item full regular expression
13366 The second set of regular expressions is much more powerful. This is the
13367 type of regular expressions recognized by utilities such a @file{grep}.
13369 The following is the form of a regular expression, expressed in Ada
13370 reference manual style BNF is as follows
13377 regexp ::= term @{| term@} -- alternation (term or term @dots{})
13379 term ::= item @{item@} -- concatenation (item then item)
13381 item ::= elmt -- match elmt
13382 item ::= elmt * -- zero or more elmt's
13383 item ::= elmt + -- one or more elmt's
13384 item ::= elmt ? -- matches elmt or nothing
13387 elmt ::= nschar -- matches given character
13388 elmt ::= [nschar @{nschar@}] -- matches any character listed
13389 elmt ::= [^ nschar @{nschar@}] -- matches any character not listed
13390 elmt ::= [char - char] -- matches chars in given range
13391 elmt ::= \ char -- matches given character
13392 elmt ::= . -- matches any single character
13393 elmt ::= ( regexp ) -- parens used for grouping
13395 char ::= any character, including special characters
13396 nschar ::= any character except ()[].*+?^
13400 Following are a few examples:
13404 will match any of the two strings @samp{abcde} and @samp{fghi},
13407 will match any string like @samp{abd}, @samp{abcd}, @samp{abccd},
13408 @samp{abcccd}, and so on,
13411 will match any string which has only lowercase characters in it (and at
13412 least one character.
13417 @node Examples of gnatxref Usage
13418 @section Examples of @code{gnatxref} Usage
13420 @subsection General Usage
13423 For the following examples, we will consider the following units:
13425 @smallexample @c ada
13430 2: @b{package} Main @b{is}
13431 3: @b{procedure} Foo (B : @b{in} Integer);
13438 1: @b{package} @b{body} Main @b{is}
13439 2: @b{procedure} Foo (B : @b{in} Integer) @b{is}
13449 1: @b{package} Bar @b{is}
13450 2: @b{procedure} Print (B : Integer);
13459 The first thing to do is to recompile your application (for instance, in
13460 that case just by doing a @samp{gnatmake main}, so that GNAT generates
13461 the cross-referencing information.
13462 You can then issue any of the following commands:
13464 @item gnatxref main.adb
13465 @code{gnatxref} generates cross-reference information for main.adb
13466 and every unit 'with'ed by main.adb.
13468 The output would be:
13476 Decl: main.ads 3:20
13477 Body: main.adb 2:20
13478 Ref: main.adb 4:13 5:13 6:19
13481 Ref: main.adb 6:8 7:8
13491 Decl: main.ads 3:15
13492 Body: main.adb 2:15
13495 Body: main.adb 1:14
13498 Ref: main.adb 6:12 7:12
13502 that is the entity @code{Main} is declared in main.ads, line 2, column 9,
13503 its body is in main.adb, line 1, column 14 and is not referenced any where.
13505 The entity @code{Print} is declared in bar.ads, line 2, column 15 and it
13506 is referenced in main.adb, line 6 column 12 and line 7 column 12.
13508 @item gnatxref package1.adb package2.ads
13509 @code{gnatxref} will generates cross-reference information for
13510 package1.adb, package2.ads and any other package 'with'ed by any
13515 @subsection Using gnatxref with vi
13517 @code{gnatxref} can generate a tags file output, which can be used
13518 directly from @command{vi}. Note that the standard version of @command{vi}
13519 will not work properly with overloaded symbols. Consider using another
13520 free implementation of @command{vi}, such as @command{vim}.
13523 $ gnatxref -v gnatfind.adb > tags
13527 will generate the tags file for @code{gnatfind} itself (if the sources
13528 are in the search path!).
13530 From @command{vi}, you can then use the command @samp{:tag @var{entity}}
13531 (replacing @var{entity} by whatever you are looking for), and vi will
13532 display a new file with the corresponding declaration of entity.
13534 @node Examples of gnatfind Usage
13535 @section Examples of @code{gnatfind} Usage
13539 @item gnatfind -f xyz:main.adb
13540 Find declarations for all entities xyz referenced at least once in
13541 main.adb. The references are search in every library file in the search
13544 The directories will be printed as well (as the @samp{-f}
13547 The output will look like:
13549 directory/main.ads:106:14: xyz <= declaration
13550 directory/main.adb:24:10: xyz <= body
13551 directory/foo.ads:45:23: xyz <= declaration
13555 that is to say, one of the entities xyz found in main.adb is declared at
13556 line 12 of main.ads (and its body is in main.adb), and another one is
13557 declared at line 45 of foo.ads
13559 @item gnatfind -fs xyz:main.adb
13560 This is the same command as the previous one, instead @code{gnatfind} will
13561 display the content of the Ada source file lines.
13563 The output will look like:
13566 directory/main.ads:106:14: xyz <= declaration
13568 directory/main.adb:24:10: xyz <= body
13570 directory/foo.ads:45:23: xyz <= declaration
13575 This can make it easier to find exactly the location your are looking
13578 @item gnatfind -r "*x*":main.ads:123 foo.adb
13579 Find references to all entities containing an x that are
13580 referenced on line 123 of main.ads.
13581 The references will be searched only in main.ads and foo.adb.
13583 @item gnatfind main.ads:123
13584 Find declarations and bodies for all entities that are referenced on
13585 line 123 of main.ads.
13587 This is the same as @code{gnatfind "*":main.adb:123}.
13589 @item gnatfind mydir/main.adb:123:45
13590 Find the declaration for the entity referenced at column 45 in
13591 line 123 of file main.adb in directory mydir. Note that it
13592 is usual to omit the identifier name when the column is given,
13593 since the column position identifies a unique reference.
13595 The column has to be the beginning of the identifier, and should not
13596 point to any character in the middle of the identifier.
13600 @ifclear FSFEDITION
13601 @c *********************************
13602 @node The GNAT Pretty-Printer gnatpp
13603 @chapter The GNAT Pretty-Printer @command{gnatpp}
13605 @cindex Pretty-Printer
13608 * Switches for gnatpp::
13609 * Formatting Rules::
13613 The @command{gnatpp} tool is an ASIS-based utility
13614 for source reformatting / pretty-printing.
13615 It takes an Ada source file as input and generates a reformatted
13617 You can specify various style directives via switches; e.g.,
13618 identifier case conventions, rules of indentation, and comment layout.
13620 Note: A newly-redesigned set of formatting algorithms used by gnatpp
13622 To invoke the old formatting algorithms, use the @option{--pp-old} switch.
13623 Support for @option{--pp-old} will be removed in some future version.
13625 To produce a reformatted file, @command{gnatpp} invokes the Ada
13626 compiler and generates and uses the ASIS tree for the input source;
13627 thus the input must be legal Ada code, and the tool should have all the
13628 information needed to compile the input source. To provide this information,
13629 you may specify as a tool parameter the project file the input source belongs to
13630 (or you may call @command{gnatpp}
13631 through the @command{gnat} driver (see @ref{The GNAT Driver and
13632 Project Files}). Another possibility is to specify the source search
13633 path and needed configuration files in @option{-cargs} section of @command{gnatpp}
13634 call, see the description of the @command{gnatpp} switches below.
13636 @command{gnatpp} cannot process sources that contain
13637 preprocessing directives.
13639 The @command{gnatpp} command has the form
13642 @c $ gnatpp @ovar{switches} @var{filename}
13643 @c Expanding @ovar macro inline (explanation in macro def comments)
13644 $ gnatpp @r{[}@var{switches}@r{]} @var{filename} @r{[}-cargs @var{gcc_switches}@r{]}
13651 @var{switches} is an optional sequence of switches defining such properties as
13652 the formatting rules, the source search path, and the destination for the
13656 @var{filename} is the name (including the extension) of the source file to
13657 reformat; wildcards or several file names on the same gnatpp command are
13658 allowed. The file name may contain path information; it does not have to
13659 follow the GNAT file naming rules
13662 @samp{@var{gcc_switches}} is a list of switches for
13663 @command{gcc}. They will be passed on to all compiler invocations made by
13664 @command{gnatpp} to generate the ASIS trees. Here you can provide
13665 @option{-I} switches to form the source search path,
13666 use the @option{-gnatec} switch to set the configuration file, etc.
13669 @node Switches for gnatpp
13670 @section Switches for @command{gnatpp}
13673 The following subsections describe the various switches accepted by
13674 @command{gnatpp}, organized by category.
13676 You specify a switch by supplying a name and generally also a value.
13677 In many cases the values for a switch with a given name are incompatible with
13679 (for example the switch that controls the casing of a reserved word may have
13680 exactly one value: upper case, lower case, or
13681 mixed case) and thus exactly one such switch can be in effect for an
13682 invocation of @command{gnatpp}.
13683 If more than one is supplied, the last one is used.
13684 However, some values for the same switch are mutually compatible.
13685 You may supply several such switches to @command{gnatpp}, but then
13686 each must be specified in full, with both the name and the value.
13687 Abbreviated forms (the name appearing once, followed by each value) are
13692 * Alignment Control::
13694 * General Text Layout Control::
13695 * Other Formatting Options::
13696 * Setting the Source Search Path::
13697 * Output File Control::
13698 * Other gnatpp Switches::
13701 @node Alignment Control
13702 @subsection Alignment Control
13703 @cindex Alignment control in @command{gnatpp}
13706 Programs can be easier to read if certain constructs are vertically aligned.
13707 By default alignment of the following constructs is set ON:
13708 @code{:} in declarations, @code{:=} in initializations in declarations
13709 @code{:=} in assignment statements, @code{=>} in associations, and
13710 @code{at} keywords in the component clauses in record
13711 representation clauses.
13714 @cindex @option{-A@var{n}} (@command{gnatpp})
13717 Set alignment to OFF
13720 Set alignment to ON
13723 @node Casing Control
13724 @subsection Casing Control
13725 @cindex Casing control in @command{gnatpp}
13728 @command{gnatpp} allows you to specify the casing for reserved words,
13729 pragma names, attribute designators and identifiers.
13730 For identifiers you may define a
13731 general rule for name casing but also override this rule
13732 via a set of dictionary files.
13734 Three types of casing are supported: lower case, upper case, and mixed case.
13735 ``Mixed case'' means that the first letter, and also each letter immediately
13736 following an underscore, are converted to their uppercase forms;
13737 all the other letters are converted to their lowercase forms.
13740 @cindex @option{-a@var{x}} (@command{gnatpp})
13742 Attribute designators are lower case
13745 Attribute designators are upper case
13748 Attribute designators are mixed case (this is the default)
13750 @cindex @option{-k@var{x}} (@command{gnatpp})
13752 Keywords (technically, these are known in Ada as @emph{reserved words}) are
13753 lower case (this is the default)
13756 Keywords are upper case
13758 @cindex @option{-n@var{x}} (@command{gnatpp})
13760 Name casing for defining occurrences are as they appear in the source file
13761 (this is the default)
13764 Names are in upper case
13767 Names are in lower case
13770 Names are in mixed case
13772 @cindex @option{-ne@var{x}} (@command{gnatpp})
13774 Enumeration literal casing for defining occurrences are as they appear in the
13775 source file. Overrides -n casing setting.
13778 Enumeration literals are in upper case. Overrides -n casing
13782 Enumeration literals are in lower case. Overrides -n casing
13786 Enumeration literals are in mixed case. Overrides -n casing
13789 @cindex @option{-nt@var{x}} (@command{gnatpp})
13791 Names introduced by type and subtype declarations are always
13792 cased as they appear in the declaration in the source file.
13793 Overrides -n casing setting.
13796 Names introduced by type and subtype declarations are always in
13797 upper case. Overrides -n casing setting.
13800 Names introduced by type and subtype declarations are always in
13801 lower case. Overrides -n casing setting.
13804 Names introduced by type and subtype declarations are always in
13805 mixed case. Overrides -n casing setting.
13808 Names introduced by number declarations are always in
13809 upper case. Overrides -n casing setting.
13812 Names introduced by number declarations are always in
13813 lower case. Overrides -n casing setting.
13816 Names introduced by number declarations are always in
13817 mixed case. Overrides -n casing setting.
13819 @cindex @option{-p@var{x}} (@command{gnatpp})
13821 Pragma names are lower case
13824 Pragma names are upper case
13827 Pragma names are mixed case (this is the default)
13830 @cindex @option{-D} (@command{gnatpp})
13831 Use @var{file} as a @emph{dictionary file} that defines
13832 the casing for a set of specified names,
13833 thereby overriding the effect on these names by
13834 any explicit or implicit
13836 To supply more than one dictionary file,
13837 use several @option{-D} switches.
13840 @option{gnatpp} implicitly uses a @emph{default dictionary file}
13841 to define the casing for the Ada predefined names and
13842 the names declared in the GNAT libraries.
13845 @cindex @option{-D-} (@command{gnatpp})
13846 Do not use the default dictionary file;
13847 instead, use the casing
13848 defined by a @option{-n} switch and any explicit
13853 The structure of a dictionary file, and details on the conventions
13854 used in the default dictionary file, are defined in @ref{Name Casing}.
13856 The @option{-D-} and
13857 @option{-D@var{file}} switches are mutually
13861 This group of @command{gnatpp} switches controls the layout of comments and
13862 complex syntactic constructs. See @ref{Formatting Comments} for details
13866 @cindex @option{-c@var{n}} (@command{gnatpp})
13868 All comments remain unchanged.
13871 GNAT-style comment line indentation.
13872 This is the default.
13875 GNAT-style comment beginning.
13878 Fill comment blocks.
13881 Keep unchanged special form comments.
13882 This is the default.
13884 @item --comments-only
13885 @cindex @option{--comments-only} @command{gnatpp}
13886 Format just the comments.
13888 @cindex @option{--no-separate-is} (@command{gnatpp})
13889 @item --no-separate-is
13890 Do not place the keyword @code{is} on a separate line in a subprogram body in
13891 case if the spec occupies more than one line.
13893 @cindex @option{--separate-loop-then} (@command{gnatpp})
13894 @item --separate-loop-then
13895 Place the keyword @code{loop} in FOR and WHILE loop statements and the
13896 keyword @code{then} in IF statements on a separate line.
13898 @cindex @option{--no-separate-loop-then} (@command{gnatpp})
13899 @item --no-separate-loop-then
13900 Do not place the keyword @code{loop} in FOR and WHILE loop statements and the
13901 keyword @code{then} in IF statements on a separate line. This option is
13902 incompatible with @option{--separate-loop-then} option.
13904 @cindex @option{--use-on-new-line} (@command{gnatpp})
13905 @item --use-on-new-line
13906 Start each USE clause in a context clause from a separate line.
13908 @cindex @option{--insert-blank-lines} (@command{gnatpp})
13909 @item --insert-blank-lines
13910 Insert blank lines where appropriate (between bodies and other large
13913 @cindex @option{--preserve-blank-lines} (@command{gnatpp})
13914 @item --preserve-blank-lines
13915 Preserve blank lines in the input. By default, gnatpp will squeeze
13916 multiple blank lines down to one.
13921 The @option{-c} switches are compatible with one another, except that
13922 the @option{-c0} switch disables all other comment formatting
13926 @node General Text Layout Control
13927 @subsection General Text Layout Control
13930 These switches allow control over line length and indentation.
13934 @cindex @option{-M} (@command{gnatpp})
13935 Maximum line length, @var{nnn} from 32@dots{}256, the default value is 79
13938 @cindex @option{-i} (@command{gnatpp})
13939 Indentation level, @var{nnn} from 1@dots{}9, the default value is 3
13942 @cindex @option{-cl} (@command{gnatpp})
13943 Indentation level for continuation lines (relative to the line being
13944 continued), @var{nnn} from 1@dots{}9.
13946 value is one less than the (normal) indentation level, unless the
13947 indentation is set to 1 (in which case the default value for continuation
13948 line indentation is also 1)
13951 @node Other Formatting Options
13952 @subsection Other Formatting Options
13955 These switches control other formatting not listed above.
13958 @item --decimal-grouping=@var{n}
13959 @cindex @option{--decimal-grouping} @command{gnatpp}
13960 Put underscores in decimal literals (numeric literals without a base)
13961 every @var{n} characters. If a literal already has one or more
13962 underscores, it is not modified. For example, with
13963 @code{--decimal-grouping=3}, @code{1000000} will be changed to
13966 @item --based-grouping=@var{n}
13967 @cindex @option{--based-grouping} @command{gnatpp}
13968 Same as @code{--decimal-grouping}, but for based literals. For
13969 example, with @code{--based-grouping=4}, @code{16#0001FFFE#} will be
13970 changed to @code{16#0001_FFFE#}.
13972 @item --split-line-before-op
13973 @cindex @option{--split-line-before-op} (@command{gnatpp})
13974 If it is necessary to split a line at a binary operator, by default
13975 the line is split after the operator. With this option, it is split
13976 before the operator.
13978 @item --RM-style-spacing
13979 @cindex @option{--RM-style-spacing} (@command{gnatpp})
13980 Do not insert an extra blank before various occurrences of
13981 `(' and `:'. This also turns off alignment.
13984 @cindex @option{-ff} (@command{gnatpp})
13985 Insert a Form Feed character after a pragma Page.
13987 @item --call_threshold=@var{nnn}
13988 @cindex @option{--call_threshold} (@command{gnatpp})
13989 If the number of parameter associations is greater than @var{nnn} and if at
13990 least one association uses named notation, start each association from
13991 a new line. If @var{nnn} is 0, no check for the number of associations
13992 is made; this is the default.
13994 @item --par_threshold=@var{nnn}
13995 @cindex @option{--par_threshold} (@command{gnatpp})
13996 If the number of parameter specifications is greater than @var{nnn}
13997 (or equal to @var{nnn} in case of a function), start each specification from
13998 a new line. This feature is disabled by default.
14001 @node Setting the Source Search Path
14002 @subsection Setting the Source Search Path
14005 To define the search path for the input source file, @command{gnatpp}
14006 uses the same switches as the GNAT compiler, with the same effects:
14010 @cindex @option{-I} (@command{gnatpp})
14013 @cindex @option{-I-} (@command{gnatpp})
14015 @item -gnatec=@var{path}
14016 @cindex @option{-gnatec} (@command{gnatpp})
14020 @node Output File Control
14021 @subsection Output File Control
14024 By default the output is sent to a file whose name is obtained by appending
14025 the @file{.pp} suffix to the name of the input file.
14026 If the file with this name already exists, it is overwritten.
14027 Thus if the input file is @file{my_ada_proc.adb} then
14028 @command{gnatpp} will produce @file{my_ada_proc.adb.pp}
14030 The output may be redirected by the following switches:
14033 @item --output-dir=@var{dir}
14034 @cindex @option{--output-dir} (@command{gnatpp})
14035 Generate output file in directory @file{dir} with the same name as the input
14036 file. If @file{dir} is the same as the directory containing the input file,
14037 the input file is not processed; use @option{-rnb}
14038 if you want to update the input file in place.
14041 @cindex @option{-pipe} (@command{gnatpp})
14042 Send the output to @code{Standard_Output}
14044 @item -o @var{output_file}
14045 @cindex @option{-o} (@code{gnatpp})
14046 Write the output into @var{output_file}.
14047 If @var{output_file} already exists, @command{gnatpp} terminates without
14048 reading or processing the input file.
14050 @item -of @var{output_file}
14051 @cindex @option{-of} (@command{gnatpp})
14052 Write the output into @var{output_file}, overwriting the existing file
14053 (if one is present).
14056 @cindex @option{-r} (@command{gnatpp})
14057 Replace the input source file with the reformatted output, and copy the
14058 original input source into the file whose name is obtained by appending the
14059 @file{.npp} suffix to the name of the input file.
14060 If a file with this name already exists, @command{gnatpp} terminates without
14061 reading or processing the input file.
14064 @cindex @option{-rf} (@code{gnatpp})
14065 Like @option{-r} except that if the file with the specified name
14066 already exists, it is overwritten.
14069 @cindex @option{-rnb} (@command{gnatpp})
14070 Replace the input source file with the reformatted output without
14071 creating any backup copy of the input source.
14073 @item --eol=@var{xxx}
14074 @cindex @option{--eol} (@code{gnatpp})
14075 Specifies the line-ending style of the reformatted output file. The @var{xxx}
14076 string specified with the switch may be:
14078 @item ``@option{dos}'' MS DOS style, lines end with CR LF characters
14079 @item ``@option{crlf}''
14080 the same as @option{dos}
14081 @item ``@option{unix}'' UNIX style, lines end with LF character
14082 @item ``@option{lf}''
14083 the same as @option{unix}
14087 @cindex @option{-W} (@command{gnatpp})
14088 Specify the wide character encoding method for the input and output files.
14089 @var{e} is one of the following:
14097 Upper half encoding
14109 Brackets encoding (default value)
14115 Options @option{-o} and
14116 @option{-of} are allowed only if the call to gnatpp
14117 contains only one file to reformat.
14122 cannot be used together
14123 with @option{-pipe} option.
14125 @node Other gnatpp Switches
14126 @subsection Other @code{gnatpp} Switches
14129 The additional @command{gnatpp} switches are defined in this subsection.
14133 @cindex @option{--version} @command{gnatpp}
14134 Display copyright and version, then exit disregarding all other options.
14137 @cindex @option{--help} @command{gnatpp}
14138 Display usage, then exit disregarding all other options.
14140 @item -P @var{file}
14141 @cindex @option{-P} @command{gnatpp}
14142 Indicates the name of the project file that describes the set of sources
14143 to be processed. The exact set of argument sources depends on other options
14144 specified; see below.
14147 @cindex @option{-U} @command{gnatpp}
14148 If a project file is specified and no argument source is explicitly
14149 specified (either directly or by means of @option{-files} option), process
14150 all the units of the closure of the argument project. Otherwise this option
14153 @item -U @var{main_unit}
14154 If a project file is specified and no argument source is explicitly
14155 specified (either directly or by means of @option{-files} option), process
14156 the closure of units rooted at @var{main_unit}. Otherwise this option
14159 @item -X@var{name}=@var{value}
14160 @cindex @option{-X} @command{gnatpp}
14161 Indicates that external variable @var{name} in the argument project
14162 has the value @var{value}. Has no effect if no project is specified as
14165 @item --RTS=@var{rts-path}
14166 @cindex @option{--RTS} (@command{gnatpp})
14167 Specifies the default location of the runtime library. Same meaning as the
14168 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
14170 @item --incremental
14171 @cindex @option{--incremental} @command{gnatpp}
14172 Incremental processing on a per-file basis. Source files are only
14173 processed if they have been modified, or if files they depend on have
14174 been modified. This is similar to the way gnatmake/gprbuild only
14175 compiles files that need to be recompiled. A project file is required
14176 in this mode, and the gnat driver (as in @command{gnat pretty}) is not
14179 @item --pp-off=@var{xxx}
14180 @cindex @option{--pp-off} @command{gnatpp}
14181 Use @code{--xxx} as the command to turn off pretty printing, instead
14182 of the default @code{--!pp off}.
14184 @item --pp-on=@var{xxx}
14185 @cindex @option{--pp-on} @command{gnatpp}
14186 Use @code{--xxx} as the command to turn pretty printing back on, instead
14187 of the default @code{--!pp on}.
14190 @cindex @option{--pp-old} @command{gnatpp}
14191 Use the old formatting algorithms.
14193 @item -files @var{filename}
14194 @cindex @option{-files} (@code{gnatpp})
14195 Take the argument source files from the specified file. This file should be an
14196 ordinary text file containing file names separated by spaces or
14197 line breaks. You can use this switch more than once in the same call to
14198 @command{gnatpp}. You also can combine this switch with an explicit list of
14202 @cindex @option{-j} (@command{gnatpp})
14203 Without @option{--incremental}, use @var{n} processes to carry out the
14204 tree creations (internal representations of the argument sources). On
14205 a multiprocessor machine this speeds up processing of big sets of
14206 argument sources. If @var{n} is 0, then the maximum number of parallel
14207 tree creations is the number of core processors on the platform. This
14208 option cannot be used together with @option{-r},
14210 @option{-rnb} option.
14212 With @option{--incremental}, use @var{n} @command{gnatpp} processes to
14213 perform pretty-printing in parallel. @var{n} = 0 means the same as
14214 above. In this case, @option{-r},
14216 @option{-rnb} options are allowed.
14218 @cindex @option{-t} (@command{gnatpp})
14220 Print out execution time.
14223 @cindex @option{-v} (@command{gnatpp})
14227 @cindex @option{-q} (@command{gnatpp})
14232 If a project file is specified and no argument source is explicitly
14233 specified (either directly or by means of @option{-files} option), and no
14234 @option{-U} is specified, then the set of processed sources is
14235 all the immediate units of the argument project.
14238 @node Formatting Rules
14239 @section Formatting Rules
14242 The following subsections show how @command{gnatpp} treats white space,
14243 comments, program layout, and name casing.
14244 They provide detailed descriptions of the switches shown above.
14247 * Disabling Pretty Printing::
14248 * White Space and Empty Lines::
14249 * Formatting Comments::
14253 @node Disabling Pretty Printing
14254 @subsection Disabling Pretty Printing
14257 Pretty printing is highly heuristic in nature, and sometimes doesn't
14258 do exactly what you want. If you wish to format a certain region of
14259 code by hand, you can turn off pretty printing in that region by
14260 surrounding it with special comments that start with @code{--!pp off}
14261 and @code{--!pp on}. The text in that region will then be reproduced
14262 verbatim in the output with no formatting.
14264 To disable pretty printing for the whole file, put @code{--!pp off} at
14265 the top, with no following @code{--!pp on}.
14267 The comments must appear on a line by themselves, with nothing
14268 preceding except spaces. The initial text of the comment must be
14269 exactly @code{--!pp off} or @code{--!pp on} (case sensitive), but may
14270 be followed by arbitrary additional text. For example:
14272 @smallexample @c ada
14274 @b{package} Interrupts @b{is}
14275 --@i{!pp off -- turn off pretty printing so "Interrupt_Kind" lines up}
14276 @b{type} Interrupt_Kind @b{is}
14277 (Asynchronous_Interrupt_Kind,
14278 Synchronous_Interrupt_Kind,
14279 Green_Interrupt_Kind);
14280 --@i{!pp on -- reenable pretty printing}
14286 You can specify different comment strings using the @code{--pp-off}
14287 and @code{--pp-on} switches. For example, if you say @code{gnatpp
14288 --pp-off=' pp-' *.ad?} then gnatpp will recognize comments of the form
14289 @code{-- pp-} instead of @code{--!pp off} for disabling pretty
14290 printing. Note that the leading @code{--} of the comment is not
14291 included in the argument to these switches.
14293 @node White Space and Empty Lines
14294 @subsection White Space and Empty Lines
14297 @command{gnatpp} does not have an option to control space characters.
14298 It will add or remove spaces according to the style illustrated by the
14299 examples in the @cite{Ada Reference Manual}.
14300 The output file will contain no lines with trailing white space.
14302 By default, a sequence of one or more blank lines in the input is
14303 converted to a single blank line in the output; multiple blank lines
14304 are squeezed down to one.
14305 The @option{--preserve-blank-lines} option
14306 turns off the squeezing; each blank line in the input is copied
14308 The @option{--insert-blank-lines} option
14309 causes additional blank lines to be inserted if not already
14310 present in the input (e.g. between bodies).
14312 @node Formatting Comments
14313 @subsection Formatting Comments
14316 Comments in Ada code are of two kinds:
14319 a @emph{whole-line comment}, which appears by itself (possibly preceded by
14320 white space) on a line
14323 an @emph{end-of-line comment}, which follows some other Ada code on
14328 A whole-line comment is indented according to the surrounding code,
14329 with some exceptions.
14330 Comments that start in column 1 are kept there.
14331 If possible, comments are not moved so far to the right that the maximum
14332 line length is exceeded.
14333 The @option{-c0} option
14334 turns off comment formatting.
14335 Special-form comments such as SPARK-style @code{--#...} are left alone.
14337 For an end-of-line comment, @command{gnatpp} tries to leave the same
14338 number of spaces between the end of the preceding Ada code and the
14339 beginning of the comment as appear in the original source.
14342 The @option{-c3} switch
14343 (GNAT style comment beginning) has the following
14348 For each whole-line comment that does not end with two hyphens,
14349 @command{gnatpp} inserts spaces if necessary after the starting two hyphens
14350 to ensure that there are at least two spaces between these hyphens and the
14351 first non-blank character of the comment.
14355 The @option{-c4} switch specifies that
14356 whole-line comments that form a paragraph will be filled in typical
14357 word processor style (that is, moving words between lines to make the
14358 lines other than the last similar in length ).
14361 The @option{--comments-only} switch specifies that only the comments
14362 are formatted; the rest of the program text is left alone. The
14363 comments are formatted according to the -c3 and -c4 switches; other
14364 formatting switches are ignored. For example, @option{--comments-only
14365 -c4} means to fill comment paragraphs, and do nothing else. Likewise,
14366 @option{--comments-only -c3} ensures comments start with at least two
14367 spaces after @code{--}, and @option{--comments-only -c3 -c4} does
14368 both. If @option{--comments-only} is given without @option{-c3} or
14369 @option{-c4}, then gnatpp doesn't format anything.
14372 @subsection Name Casing
14375 @command{gnatpp} always converts the usage occurrence of a (simple) name to
14376 the same casing as the corresponding defining identifier.
14378 You control the casing for defining occurrences via the
14379 @option{-n} switch.
14380 With @option{-nD} (``as declared'', which is the default),
14381 defining occurrences appear exactly as in the source file
14382 where they are declared.
14383 The other values for this switch ---
14388 upper, lower, or mixed case, respectively.
14389 If @command{gnatpp} changes the casing of a defining
14390 occurrence, it analogously changes the casing of all the
14391 usage occurrences of this name.
14393 If the defining occurrence of a name is not in the source compilation unit
14394 currently being processed by @command{gnatpp}, the casing of each reference to
14395 this name is changed according to the value of the @option{-n}
14396 switch (subject to the dictionary file mechanism described below).
14397 Thus @command{gnatpp} acts as though the @option{-n} switch
14399 casing for the defining occurrence of the name.
14402 @option{-a@var{x}},
14403 @option{-k@var{x}},
14404 @option{-ne@var{x}},
14405 @option{-nt@var{x}},
14406 @option{-nn@var{x}}, and
14408 allow finer-grained control over casing for
14409 attributes, keywords, enumeration literals,
14410 types, named numbers and pragmas, respectively.
14411 @option{-nt@var{x}} covers subtypes and
14412 task and protected bodies as well.
14414 Some names may need to be spelled with casing conventions that are not
14415 covered by the upper-, lower-, and mixed-case transformations.
14416 You can arrange correct casing by placing such names in a
14417 @emph{dictionary file},
14418 and then supplying a @option{-D} switch.
14419 The casing of names from dictionary files overrides
14420 any @option{-n} switch.
14422 To handle the casing of Ada predefined names and the names from GNAT libraries,
14423 @command{gnatpp} assumes a default dictionary file.
14424 The name of each predefined entity is spelled with the same casing as is used
14425 for the entity in the @cite{Ada Reference Manual} (usually mixed case).
14426 The name of each entity in the GNAT libraries is spelled with the same casing
14427 as is used in the declaration of that entity.
14429 The @w{@option{-D-}} switch suppresses the use of
14430 the default dictionary file. Instead, the casing for predefined and
14431 GNAT-defined names will be established by the
14432 @option{-n} switch or explicit dictionary files. For
14433 example, by default the names @code{Ada.Text_IO} and
14434 @code{GNAT.OS_Lib} will appear as just shown, even in the presence of
14435 a @option{-nU} switch. To ensure that even
14436 such names are rendered in uppercase, additionally supply the
14437 @w{@option{-D-}} switch (or else place these names
14438 in upper case in a dictionary file).
14440 A dictionary file is a plain text file; each line in this file can be
14441 either a blank line (containing only space characters), an Ada comment
14442 line, or the specification of exactly one @emph{casing schema}.
14444 A casing schema is a string that has the following syntax:
14448 @var{casing_schema} ::= @var{identifier} | *@var{simple_identifier}*
14450 @var{simple_identifier} ::= @var{letter}@{@var{letter_or_digit}@}
14455 (See @cite{Ada Reference Manual}, Section 2.3) for the definition of the
14456 @var{identifier} lexical element and the @var{letter_or_digit} category.)
14458 The casing schema string can be followed by white space and/or an Ada-style
14459 comment; any amount of white space is allowed before the string.
14461 If a dictionary file is passed as
14462 the value of a @option{-D@var{file}} switch
14464 simple name and every identifier, @command{gnatpp} checks if the dictionary
14465 defines the casing for the name or for some of its parts (the term ``subword''
14466 is used below to denote the part of a name which is delimited by ``_'' or by
14467 the beginning or end of the word and which does not contain any ``_'' inside):
14471 if the whole name is in the dictionary, @command{gnatpp} uses for this name
14472 the casing defined by the dictionary; no subwords are checked for this word
14475 for every subword @command{gnatpp} checks if the dictionary contains the
14476 corresponding string of the form @code{*@var{simple_identifier}*},
14477 and if it does, the casing of this @var{simple_identifier} is used
14481 if the whole name does not contain any ``_'' inside, and if for this name
14482 the dictionary contains two entries - one of the form @var{identifier},
14483 and another - of the form *@var{simple_identifier}*, then the first one
14484 is applied to define the casing of this name
14487 if more than one dictionary file is passed as @command{gnatpp} switches, each
14488 dictionary adds new casing exceptions and overrides all the existing casing
14489 exceptions set by the previous dictionaries
14492 when @command{gnatpp} checks if the word or subword is in the dictionary,
14493 this check is not case sensitive
14497 For example, suppose we have the following source to reformat:
14499 @smallexample @c ada
14501 @b{procedure} test @b{is}
14502 name1 : integer := 1;
14503 name4_name3_name2 : integer := 2;
14504 name2_name3_name4 : Boolean;
14507 name2_name3_name4 := name4_name3_name2 > name1;
14513 And suppose we have two dictionaries:
14530 If @command{gnatpp} is called with the following switches:
14533 @command{gnatpp -nM -D dict1 -D dict2 test.adb}
14537 then we will get the following name casing in the @command{gnatpp} output:
14539 @smallexample @c ada
14541 @b{procedure} Test @b{is}
14542 NAME1 : Integer := 1;
14543 Name4_NAME3_Name2 : Integer := 2;
14544 Name2_NAME3_Name4 : Boolean;
14547 Name2_NAME3_Name4 := Name4_NAME3_Name2 > NAME1;
14553 @ifclear FSFEDITION
14554 @c *********************************
14555 @node The Ada-to-XML converter gnat2xml
14556 @chapter The Ada-to-XML converter @command{gnat2xml}
14558 @cindex XML generation
14561 The @command{gnat2xml} tool is an ASIS-based utility that converts
14562 Ada source code into XML.
14565 * Switches for gnat2xml::
14567 * Structure of the XML::
14568 * Generating Representation Clauses::
14571 @node Switches for gnat2xml
14572 @section Switches for @command{gnat2xml}
14575 @command{gnat2xml} takes Ada source code as input, and produces XML
14576 that conforms to the schema.
14581 gnat2xml [options] filenames [-files filename] [-cargs gcc_switches]
14588 --help -- generate usage information and quit, ignoring all other options
14589 --version -- print version and quit, ignoring all other options
14591 -P @file{file} -- indicates the name of the project file that describes
14592 the set of sources to be processed. The exact set of argument
14593 sources depends on other options specified, see below.
14595 -U -- if a project file is specified and no argument source is explicitly
14596 specified, process all the units of the closure of the argument project.
14597 Otherwise this option has no effect.
14599 -U @var{main_unit} -- if a project file is specified and no argument source
14600 is explicitly specified (either directly or by means of @option{-files}
14601 option), process the closure of units rooted at @var{main_unit}.
14602 Otherwise this option has no effect.
14604 -X@var{name}=@var{value} -- indicates that external variable @var{name} in
14605 the argument project has the value @var{value}. Has no effect if no
14606 project is specified as tool argument.
14608 --RTS=@var{rts-path} -- Specifies the default location of the runtime
14609 library. Same meaning as the equivalent @command{gnatmake} flag
14610 (@pxref{Switches for gnatmake}).
14612 --incremental -- incremental processing on a per-file basis. Source files are
14613 only processed if they have been modified, or if files they depend
14614 on have been modified. This is similar to the way gnatmake/gprbuild
14615 only compiles files that need to be recompiled. A project file
14616 is required in this mode.
14618 -j@var{n} -- In @option{--incremental} mode, use @var{n} @command{gnat2xml}
14619 processes to perform XML generation in parallel. If @var{n} is 0, then
14620 the maximum number of parallel tree creations is the number of core
14621 processors on the platform.
14623 --output-dir=@var{dir} -- generate one .xml file for each Ada source file, in
14624 directory @file{dir}. (Default is to generate the XML to standard
14628 directories to search for dependencies
14629 You can also set the ADA_INCLUDE_PATH environment variable for this.
14631 --compact -- debugging version, with interspersed source, and a more
14632 compact representation of "sloc". This version does not conform
14635 --rep-clauses -- generate representation clauses (see ``Generating
14636 Representation Clauses'' below).
14638 -files=filename - the name of a text file containing a list
14639 of Ada source files to process
14644 -cargs ... -- options to pass to gcc
14648 If a project file is specified and no argument source is explicitly
14649 specified, and no @option{-U} is specified, then the set of processed
14650 sources is all the immediate units of the argument project.
14655 gnat2xml -v -output-dir=xml-files *.ad[sb]
14659 The above will create *.xml files in the @file{xml-files} subdirectory.
14660 For example, if there is an Ada package Mumble.Dumble, whose spec and
14661 body source code lives in mumble-dumble.ads and mumble-dumble.adb,
14662 the above will produce xml-files/mumble-dumble.ads.xml and
14663 xml-files/mumble-dumble.adb.xml.
14665 @node Other Programs
14666 @section Other Programs
14669 The distribution includes two other programs that are related to
14670 @command{gnat2xml}:
14672 @command{gnat2xsd} is the schema generator, which generates the schema
14673 to standard output, based on the structure of Ada as encoded by
14674 ASIS. You don't need to run @command{gnat2xsd} in order to use
14675 @command{gnat2xml}. To generate the schema, type:
14678 gnat2xsd > ada-schema.xsd
14682 @command{gnat2xml} generates XML files that will validate against
14683 @file{ada-schema.xsd}.
14685 @command{xml2gnat} is a back-translator that translates the XML back
14686 into Ada source code. The Ada generated by @command{xml2gnat} has
14687 identical semantics to the original Ada code passed to
14688 @command{gnat2xml}. It is not textually identical, however --- for
14689 example, no attempt is made to preserve the original indentation.
14691 @node Structure of the XML
14692 @section Structure of the XML
14695 The primary documentation for the structure of the XML generated by
14696 @command{gnat2xml} is the schema (see @command{gnat2xsd} above). The
14697 following documentation gives additional details needed to understand
14698 the schema and therefore the XML.
14700 The elements listed under Defining Occurrences, Usage Occurrences, and
14701 Other Elements represent the syntactic structure of the Ada program.
14702 Element names are given in lower case, with the corresponding element
14703 type Capitalized_Like_This. The element and element type names are
14704 derived directly from the ASIS enumeration type Flat_Element_Kinds,
14705 declared in Asis.Extensions.Flat_Kinds, with the leading ``An_'' or ``A_''
14706 removed. For example, the ASIS enumeration literal
14707 An_Assignment_Statement corresponds to the XML element
14708 assignment_statement of XML type Assignment_Statement.
14710 To understand the details of the schema and the corresponding XML, it is
14711 necessary to understand the ASIS standard, as well as the GNAT-specific
14714 A defining occurrence is an identifier (or character literal or operator
14715 symbol) declared by a declaration. A usage occurrence is an identifier
14716 (or ...) that references such a declared entity. For example, in:
14719 type T is range 1..10;
14720 X, Y : constant T := 1;
14724 The first ``T'' is the defining occurrence of a type. The ``X'' is the
14725 defining occurrence of a constant, as is the ``Y'', and the second ``T'' is
14726 a usage occurrence referring to the defining occurrence of T.
14728 Each element has a 'sloc' (source location), and subelements for each
14729 syntactic subtree, reflecting the Ada grammar as implemented by ASIS.
14730 The types of subelements are as defined in the ASIS standard. For
14731 example, for the right-hand side of an assignment_statement we have
14732 the following comment in asis-statements.ads:
14735 ------------------------------------------------------------------------------
14736 -- 18.3 function Assignment_Expression
14737 ------------------------------------------------------------------------------
14739 function Assignment_Expression
14740 (Statement : Asis.Statement)
14741 return Asis.Expression;
14743 ------------------------------------------------------------------------------
14745 -- Returns the expression from the right hand side of the assignment.
14747 -- Returns Element_Kinds:
14752 The corresponding sub-element of type Assignment_Statement is:
14755 <xsd:element name="assignment_expression_q" type="Expression_Class"/>
14759 where Expression_Class is defined by an xsd:choice of all the
14760 various kinds of expression.
14762 The 'sloc' of each element indicates the starting and ending line and
14763 column numbers. Column numbers are character counts; that is, a tab
14764 counts as 1, not as however many spaces it might expand to.
14766 Subelements of type Element have names ending in ``_q'' (for ASIS
14767 ``Query''), and those of type Element_List end in ``_ql'' (``Query returning
14770 Some subelements are ``Boolean''. For example, Private_Type_Definition
14771 has has_abstract_q and has_limited_q, to indicate whether those
14772 keywords are present, as in @code{type T is abstract limited
14773 private;}. False is represented by a Nil_Element. True is represented
14774 by an element type specific to that query (for example, Abstract and
14777 The root of the tree is a Compilation_Unit, with attributes:
14781 unit_kind, unit_class, and unit_origin. These are strings that match the
14782 enumeration literals of types Unit_Kinds, Unit_Classes, and Unit_Origins
14786 unit_full_name is the full expanded name of the unit, starting from a
14787 root library unit. So for @code{package P.Q.R is ...},
14788 @code{unit_full_name="P.Q.R"}. Same for @code{separate (P.Q) package R is ...}.
14791 def_name is the same as unit_full_name for library units; for subunits,
14792 it is just the simple name.
14795 source_file is the name of the Ada source file. For example, for
14796 the spec of @code{P.Q.R}, @code{source_file="p-q-r.ads"}. This allows one to
14797 interpret the source locations --- the ``sloc'' of all elements
14798 within this Compilation_Unit refers to line and column numbers
14799 within the named file.
14803 Defining occurrences have these attributes:
14807 def_name is the simple name of the declared entity, as written in the Ada
14811 def is a unique URI of the form:
14813 ada://kind/fully/qualified/name
14817 kind indicates the kind of Ada entity being declared (see below), and
14819 fully/qualified/name, is the fully qualified name of the Ada
14820 entity, with each of ``fully'', ``qualified'', and ``name'' being
14821 mangled for uniqueness. We do not document the mangling
14822 algorithm, which is subject to change; we just guarantee that the
14823 names are unique in the face of overloading.
14826 type is the type of the declared object, or @code{null} for
14827 declarations of things other than objects.
14831 Usage occurrences have these attributes:
14835 ref_name is the same as the def_name of the corresponding defining
14836 occurrence. This attribute is not of much use, because of
14837 overloading; use ref for lookups, instead.
14840 ref is the same as the def of the corresponding defining
14845 In summary, @code{def_name} and @code{ref_name} are as in the source
14846 code of the declaration, possibly overloaded, whereas @code{def} and
14847 @code{ref} are unique-ified.
14849 Literal elements have this attribute:
14853 lit_val is the value of the literal as written in the source text,
14854 appropriately escaped (e.g. @code{"} ---> @code{"}). This applies
14855 only to numeric and string literals. Enumeration literals in Ada are
14856 not really "literals" in the usual sense; they are usage occurrences,
14857 and have ref_name and ref as described above. Note also that string
14858 literals used as operator symbols are treated as defining or usage
14859 occurrences, not as literals.
14863 Elements that can syntactically represent names and expressions (which
14864 includes usage occurrences, plus function calls and so forth) have this
14869 type. If the element represents an expression or the name of an object,
14870 'type' is the 'def' for the defining occurrence of the type of that
14871 expression or name. Names of other kinds of entities, such as package
14872 names and type names, do not have a type in Ada; these have type="null"
14877 Pragma elements have this attribute:
14881 pragma_name is the name of the pragma. For language-defined pragmas, the
14882 pragma name is redundant with the element kind (for example, an
14883 assert_pragma element necessarily has pragma_name="Assert"). However, all
14884 implementation-defined pragmas are lumped together in ASIS as a single
14885 element kind (for example, the GNAT-specific pragma Unreferenced is
14886 represented by an implementation_defined_pragma element with
14887 pragma_name="Unreferenced").
14891 Defining occurrences of formal parameters and generic formal objects have this
14896 mode indicates that the parameter is of mode 'in', 'in out', or 'out'.
14900 All elements other than Not_An_Element have this attribute:
14904 checks is a comma-separated list of run-time checks that are needed
14905 for that element. The possible checks are: do_accessibility_check,
14906 do_discriminant_check,do_division_check,do_length_check,
14907 do_overflow_check,do_range_check,do_storage_check,do_tag_check.
14911 The "kind" part of the "def" and "ref" attributes is taken from the ASIS
14912 enumeration type Flat_Declaration_Kinds, declared in
14913 Asis.Extensions.Flat_Kinds, with the leading "An_" or "A_" removed, and
14914 any trailing "_Declaration" or "_Specification" removed. Thus, the
14915 possible kinds are as follows:
14922 tagged_incomplete_type
14933 enumeration_literal
14937 generalized_iterator
14947 expression_function
14955 generic_package_renaming
14956 generic_procedure_renaming
14957 generic_function_renaming
14963 procedure_body_stub
14967 protected_body_stub
14973 package_instantiation
14974 procedure_instantiation
14975 function_instantiation
14978 formal_incomplete_type
14982 formal_package_declaration_with_box
14985 @node Generating Representation Clauses
14986 @section Generating Representation Clauses
14989 If the @option{--rep-clauses} switch is given, @command{gnat2xml} will
14990 generate representation clauses for certain types showing the
14991 representation chosen by the compiler. The information is produced by
14992 the ASIS ``Data Decomposition'' facility --- see the
14993 @code{Asis.Data_Decomposition} package for details.
14995 Not all types are supported. For example, @code{Type_Model_Kind} must
14996 be @code{A_Simple_Static_Model}. Types declared within generic units
14997 have no representation. The clauses that are generated include
14998 @code{attribute_definition_clauses} for @code{Size} and
14999 @code{Component_Size}, as well as
15000 @code{record_representation_clauses}.
15002 There is no guarantee that the generated representation clauses could
15003 have actually come from legal Ada code; Ada has some restrictions that
15004 are not necessarily obeyed by the generated clauses.
15006 The representation clauses are surrounded by comment elements to
15007 indicate that they are automatically generated, something like this:
15010 <comment text="--gen+">
15012 <attribute_definition_clause>
15014 <comment text="--gen-">
15020 @ifclear FSFEDITION
15021 @c *********************************
15022 @node The GNAT Metrics Tool gnatmetric
15023 @chapter The GNAT Metrics Tool @command{gnatmetric}
15025 @cindex Metric tool
15028 The @command{gnatmetric} tool is an ASIS-based utility
15029 for computing various program metrics.
15030 It takes an Ada source file as input and generates a file containing the
15031 metrics data as output. Various switches control which
15032 metrics are computed and output.
15035 * Switches for gnatmetric::
15038 To compute program metrics, @command{gnatmetric} invokes the Ada
15039 compiler and generates and uses the ASIS tree for the input source;
15040 thus the input must be legal Ada code, and the tool should have all the
15041 information needed to compile the input source. To provide this information,
15042 you may specify as a tool parameter the project file the input source belongs to
15043 (or you may call @command{gnatmetric}
15044 through the @command{gnat} driver (see @ref{The GNAT Driver and
15045 Project Files}). Another possibility is to specify the source search
15046 path and needed configuration files in @option{-cargs} section of @command{gnatmetric}
15047 call, see the description of the @command{gnatmetric} switches below.
15049 If the set of sources to be processed by @code{gnatmetric} contains sources with
15050 preprocessing directives
15051 then the needed options should be provided to run preprocessor as a part of
15052 the @command{gnatmetric} call, and the computed metrics
15053 will correspond to preprocessed sources.
15056 The @command{gnatmetric} command has the form
15059 @c $ gnatmetric @ovar{switches} @{@var{filename}@} @r{[}-cargs @var{gcc_switches}@r{]}
15060 @c Expanding @ovar macro inline (explanation in macro def comments)
15061 $ gnatmetric @r{[}@var{switches}@r{]} @{@var{filename}@} @r{[}-cargs @var{gcc_switches}@r{]}
15068 @var{switches} specify the metrics to compute and define the destination for
15072 Each @var{filename} is the name (including the extension) of a source
15073 file to process. ``Wildcards'' are allowed, and
15074 the file name may contain path information.
15075 If no @var{filename} is supplied, then the @var{switches} list must contain
15077 @option{-files} switch (@pxref{Other gnatmetric Switches}).
15078 Including both a @option{-files} switch and one or more
15079 @var{filename} arguments is permitted.
15082 @samp{@var{gcc_switches}} is a list of switches for
15083 @command{gcc}. They will be passed on to all compiler invocations made by
15084 @command{gnatmetric} to generate the ASIS trees. Here you can provide
15085 @option{-I} switches to form the source search path,
15086 and use the @option{-gnatec} switch to set the configuration file,
15087 use the @option{-gnat05} switch if sources should be compiled in
15091 @node Switches for gnatmetric
15092 @section Switches for @command{gnatmetric}
15095 The following subsections describe the various switches accepted by
15096 @command{gnatmetric}, organized by category.
15099 * Output Files Control::
15100 * Disable Metrics For Local Units::
15101 * Specifying a set of metrics to compute::
15102 * Other gnatmetric Switches::
15104 * Generate project-wide metrics::
15108 @node Output Files Control
15109 @subsection Output File Control
15110 @cindex Output file control in @command{gnatmetric}
15113 @command{gnatmetric} has two output formats. It can generate a
15114 textual (human-readable) form, and also XML. By default only textual
15115 output is generated.
15117 When generating the output in textual form, @command{gnatmetric} creates
15118 for each Ada source file a corresponding text file
15119 containing the computed metrics, except for the case when the set of metrics
15120 specified by gnatmetric parameters consists only of metrics that are computed
15121 for the whole set of analyzed sources, but not for each Ada source.
15122 By default, the name of the file containing metric information for a source
15123 is obtained by appending the @file{.metrix} suffix to the
15124 name of the input source file. If not otherwise specified and no project file
15125 is specified as @command{gnatmetric} option this file is placed in the same
15126 directory as where the source file is located. If @command{gnatmetric} has a
15127 project file as its parameter, it places all the generated files in the
15128 object directory of the project (or in the project source directory if the
15129 project does not define an objects directory), if @option{--subdirs} option
15130 is specified, the files are placed in the subrirectory of this directory
15131 specified by this option.
15133 All the output information generated in XML format is placed in a single
15134 file. By default the name of this file is @file{metrix.xml}.
15135 If not otherwise specified and if no project file is specified
15136 as @command{gnatmetric} option this file is placed in the
15139 Some of the computed metrics are summed over the units passed to
15140 @command{gnatmetric}; for example, the total number of lines of code.
15141 By default this information is sent to @file{stdout}, but a file
15142 can be specified with the @option{-og} switch.
15144 The following switches control the @command{gnatmetric} output:
15147 @cindex @option{-x} (@command{gnatmetric})
15149 Generate the XML output
15151 @cindex @option{-xs} (@command{gnatmetric})
15153 Generate the XML output and the XML schema file that describes the structure
15154 of the XML metric report, this schema is assigned to the XML file. The schema
15155 file has the same name as the XML output file with @file{.xml} suffix replaced
15158 @cindex @option{-nt} (@command{gnatmetric})
15160 Do not generate the output in text form (implies @option{-x})
15162 @cindex @option{-d} (@command{gnatmetric})
15163 @item -d @var{output_dir}
15164 Put text files with detailed metrics into @var{output_dir}
15166 @cindex @option{-o} (@command{gnatmetric})
15167 @item -o @var{file_suffix}
15168 Use @var{file_suffix}, instead of @file{.metrix}
15169 in the name of the output file.
15171 @cindex @option{-og} (@command{gnatmetric})
15172 @item -og @var{file_name}
15173 Put global metrics into @var{file_name}
15175 @cindex @option{-ox} (@command{gnatmetric})
15176 @item -ox @var{file_name}
15177 Put the XML output into @var{file_name} (also implies @option{-x})
15179 @cindex @option{-sfn} (@command{gnatmetric})
15181 Use ``short'' source file names in the output. (The @command{gnatmetric}
15182 output includes the name(s) of the Ada source file(s) from which the metrics
15183 are computed. By default each name includes the absolute path. The
15184 @option{-sfn} switch causes @command{gnatmetric}
15185 to exclude all directory information from the file names that are output.)
15189 @node Disable Metrics For Local Units
15190 @subsection Disable Metrics For Local Units
15191 @cindex Disable Metrics For Local Units in @command{gnatmetric}
15194 @command{gnatmetric} relies on the GNAT compilation model @minus{}
15196 unit per one source file. It computes line metrics for the whole source
15197 file, and it also computes syntax
15198 and complexity metrics for the file's outermost unit.
15200 By default, @command{gnatmetric} will also compute all metrics for certain
15201 kinds of locally declared program units:
15205 subprogram (and generic subprogram) bodies;
15208 package (and generic package) specs and bodies;
15211 task object and type specifications and bodies;
15214 protected object and type specifications and bodies.
15218 These kinds of entities will be referred to as
15219 @emph{eligible local program units}, or simply @emph{eligible local units},
15220 @cindex Eligible local unit (for @command{gnatmetric})
15221 in the discussion below.
15223 Note that a subprogram declaration, generic instantiation,
15224 or renaming declaration only receives metrics
15225 computation when it appear as the outermost entity
15228 Suppression of metrics computation for eligible local units can be
15229 obtained via the following switch:
15232 @cindex @option{-nolocal} (@command{gnatmetric})
15234 Do not compute detailed metrics for eligible local program units
15238 @node Specifying a set of metrics to compute
15239 @subsection Specifying a set of metrics to compute
15242 By default all the metrics are computed and reported. The switches
15243 described in this subsection allow you to control, on an individual
15244 basis, whether metrics are computed and
15245 reported. If at least one positive metric
15246 switch is specified (that is, a switch that defines that a given
15247 metric or set of metrics is to be computed), then only
15248 explicitly specified metrics are reported.
15251 * Line Metrics Control::
15252 * Syntax Metrics Control::
15253 * Complexity Metrics Control::
15254 * Coupling Metrics Control::
15257 @node Line Metrics Control
15258 @subsubsection Line Metrics Control
15259 @cindex Line metrics control in @command{gnatmetric}
15262 For any (legal) source file, and for each of its
15263 eligible local program units, @command{gnatmetric} computes the following
15268 the total number of lines;
15271 the total number of code lines (i.e., non-blank lines that are not comments)
15274 the number of comment lines
15277 the number of code lines containing end-of-line comments;
15280 the comment percentage: the ratio between the number of lines that contain
15281 comments and the number of all non-blank lines, expressed as a percentage;
15284 the number of empty lines and lines containing only space characters and/or
15285 format effectors (blank lines)
15288 the average number of code lines in subprogram bodies, task bodies, entry
15289 bodies and statement sequences in package bodies (this metric is only computed
15290 across the whole set of the analyzed units)
15295 @command{gnatmetric} sums the values of the line metrics for all the
15296 files being processed and then generates the cumulative results. The tool
15297 also computes for all the files being processed the average number of code
15300 You can use the following switches to select the specific line metrics
15301 to be computed and reported.
15304 @cindex @option{--lines@var{x}} (@command{gnatmetric})
15306 @cindex @option{--no-lines@var{x}}
15309 Report all the line metrics
15311 @item --no-lines-all
15312 Do not report any of line metrics
15315 Report the number of all lines
15318 Do not report the number of all lines
15321 Report the number of code lines
15323 @item --no-lines-code
15324 Do not report the number of code lines
15326 @item --lines-comment
15327 Report the number of comment lines
15329 @item --no-lines-comment
15330 Do not report the number of comment lines
15332 @item --lines-eol-comment
15333 Report the number of code lines containing
15334 end-of-line comments
15336 @item --no-lines-eol-comment
15337 Do not report the number of code lines containing
15338 end-of-line comments
15340 @item --lines-ratio
15341 Report the comment percentage in the program text
15343 @item --no-lines-ratio
15344 Do not report the comment percentage in the program text
15346 @item --lines-blank
15347 Report the number of blank lines
15349 @item --no-lines-blank
15350 Do not report the number of blank lines
15352 @item --lines-average
15353 Report the average number of code lines in subprogram bodies, task bodies,
15354 entry bodies and statement sequences in package bodies. The metric is computed
15355 and reported for the whole set of processed Ada sources only.
15357 @item --no-lines-average
15358 Do not report the average number of code lines in subprogram bodies,
15359 task bodies, entry bodies and statement sequences in package bodies.
15363 @node Syntax Metrics Control
15364 @subsubsection Syntax Metrics Control
15365 @cindex Syntax metrics control in @command{gnatmetric}
15368 @command{gnatmetric} computes various syntactic metrics for the
15369 outermost unit and for each eligible local unit:
15372 @item LSLOC (``Logical Source Lines Of Code'')
15373 The total number of declarations and the total number of statements. Note
15374 that the definition of declarations is the one given in the reference
15378 ``Each of the following is defined to be a declaration: any basic_declaration;
15379 an enumeration_literal_specification; a discriminant_specification;
15380 a component_declaration; a loop_parameter_specification; a
15381 parameter_specification; a subprogram_body; an entry_declaration;
15382 an entry_index_specification; a choice_parameter_specification;
15383 a generic_formal_parameter_declaration.''
15385 This means for example that each enumeration literal adds one to the count,
15386 as well as each subprogram parameter.
15388 Thus the results from this metric will be significantly greater than might
15389 be expected from a naive view of counting semicolons.
15391 @item Maximal static nesting level of inner program units
15393 @cite{Ada Reference Manual}, 10.1(1), ``A program unit is either a
15394 package, a task unit, a protected unit, a
15395 protected entry, a generic unit, or an explicitly declared subprogram other
15396 than an enumeration literal.''
15398 @item Maximal nesting level of composite syntactic constructs
15399 This corresponds to the notion of the
15400 maximum nesting level in the GNAT built-in style checks
15401 (@pxref{Style Checking})
15405 For the outermost unit in the file, @command{gnatmetric} additionally computes
15406 the following metrics:
15409 @item Public subprograms
15410 This metric is computed for package specs. It is the
15411 number of subprograms and generic subprograms declared in the visible
15412 part (including the visible part of nested packages, protected objects, and
15415 @item All subprograms
15416 This metric is computed for bodies and subunits. The
15417 metric is equal to a total number of subprogram bodies in the compilation
15419 Neither generic instantiations nor renamings-as-a-body nor body stubs
15420 are counted. Any subprogram body is counted, independently of its nesting
15421 level and enclosing constructs. Generic bodies and bodies of protected
15422 subprograms are counted in the same way as ``usual'' subprogram bodies.
15425 This metric is computed for package specs and
15426 generic package declarations. It is the total number of types
15427 that can be referenced from outside this compilation unit, plus the
15428 number of types from all the visible parts of all the visible generic
15429 packages. Generic formal types are not counted. Only types, not subtypes,
15433 Along with the total number of public types, the following
15434 types are counted and reported separately:
15441 Root tagged types (abstract, non-abstract, private, non-private). Type
15442 extensions are @emph{not} counted
15445 Private types (including private extensions)
15456 This metric is computed for any compilation unit. It is equal to the total
15457 number of the declarations of different types given in the compilation unit.
15458 The private and the corresponding full type declaration are counted as one
15459 type declaration. Incomplete type declarations and generic formal types
15461 No distinction is made among different kinds of types (abstract,
15462 private etc.); the total number of types is computed and reported.
15467 By default, all the syntax metrics are computed and reported. You can use the
15468 following switches to select specific syntax metrics.
15472 @cindex @option{--syntax@var{x}} (@command{gnatmetric})
15474 @cindex @option{--no-syntax@var{x}} (@command{gnatmetric})
15477 Report all the syntax metrics
15479 @item --no-syntax-all
15480 Do not report any of syntax metrics
15482 @item --declarations
15483 Report the total number of declarations
15485 @item --no-declarations
15486 Do not report the total number of declarations
15489 Report the total number of statements
15491 @item --no-statements
15492 Do not report the total number of statements
15494 @item --public-subprograms
15495 Report the number of public subprograms in a compilation unit
15497 @item --no-public-subprograms
15498 Do not report the number of public subprograms in a compilation unit
15500 @item --all-subprograms
15501 Report the number of all the subprograms in a compilation unit
15503 @item --no-all-subprograms
15504 Do not report the number of all the subprograms in a compilation unit
15506 @item --public-types
15507 Report the number of public types in a compilation unit
15509 @item --no-public-types
15510 Do not report the number of public types in a compilation unit
15513 Report the number of all the types in a compilation unit
15515 @item --no-all-types
15516 Do not report the number of all the types in a compilation unit
15518 @item --unit-nesting
15519 Report the maximal program unit nesting level
15521 @item --no-unit-nesting
15522 Do not report the maximal program unit nesting level
15524 @item --construct-nesting
15525 Report the maximal construct nesting level
15527 @item --no-construct-nesting
15528 Do not report the maximal construct nesting level
15532 @node Complexity Metrics Control
15533 @subsubsection Complexity Metrics Control
15534 @cindex Complexity metrics control in @command{gnatmetric}
15537 For a program unit that is an executable body (a subprogram body (including
15538 generic bodies), task body, entry body or a package body containing
15539 its own statement sequence) @command{gnatmetric} computes the following
15540 complexity metrics:
15544 McCabe cyclomatic complexity;
15547 McCabe essential complexity;
15550 maximal loop nesting level;
15553 extra exit points (for subprograms);
15557 The McCabe cyclomatic complexity metric is defined
15558 in @url{http://www.mccabe.com/pdf/mccabe-nist235r.pdf}
15560 According to McCabe, both control statements and short-circuit control forms
15561 should be taken into account when computing cyclomatic complexity.
15562 For Ada 2012 we have also take into account conditional expressions
15563 and quantified expressions. For each body, we compute three metric values:
15567 the complexity introduced by control
15568 statements only, without taking into account short-circuit forms
15569 (referred as @code{statement complexity} in @command{gnatmetric} output),
15572 the complexity introduced by short-circuit control forms only
15573 (referred as @code{expression complexity} in @command{gnatmetric} output), and
15577 cyclomatic complexity, which is the sum of these two values
15578 (referred as @code{cyclomatic complexity} in @command{gnatmetric} output).
15583 The cyclomatic complexity is also computed for Ada 2012 expression functions.
15584 An expression function cannot have statements as its components, so only one
15585 metric value is computed as a cyclomatic complexity of an expression function.
15587 The origin of cyclomatic complexity metric is the need to estimate the number
15588 of independent paths in the control flow graph that in turn gives the number
15589 of tests needed to satisfy paths coverage testing completeness criterion.
15590 Considered from the testing point of view, a static Ada @code{loop} (that is,
15591 the @code{loop} statement having static subtype in loop parameter
15592 specification) does not add to cyclomatic complexity. By providing
15593 @option{--no-static-loop} option a user
15594 may specify that such loops should not be counted when computing the
15595 cyclomatic complexity metric
15597 The Ada essential complexity metric is a McCabe cyclomatic complexity metric
15598 counted for the code that is reduced by excluding all the pure structural Ada
15599 control statements. An compound statement is considered as a non-structural
15600 if it contains a @code{raise} or @code{return} statement as it subcomponent,
15601 or if it contains a @code{goto} statement that transfers the control outside
15602 the operator. A selective accept statement with @code{terminate} alternative
15603 is considered as non-structural statement. When computing this metric,
15604 @code{exit} statements are treated in the same way as @code{goto}
15605 statements unless @option{-ne} option is specified.
15607 The Ada essential complexity metric defined here is intended to quantify
15608 the extent to which the software is unstructured. It is adapted from
15609 the McCabe essential complexity metric defined in
15610 @url{http://www.mccabe.com/pdf/mccabe-nist235r.pdf} but is modified to be more
15611 suitable for typical Ada usage. For example, short circuit forms
15612 are not penalized as unstructured in the Ada essential complexity metric.
15614 When computing cyclomatic and essential complexity, @command{gnatmetric} skips
15615 the code in the exception handlers and in all the nested program units. The
15616 code of assertions and predicates (that is, subprogram preconditions and
15617 postconditions, subtype predicates and type invariants) is also skipped.
15619 By default, all the complexity metrics are computed and reported.
15620 For more fine-grained control you can use
15621 the following switches:
15624 @cindex @option{-complexity@var{x}} (@command{gnatmetric})
15626 @cindex @option{--no-complexity@var{x}}
15628 @item --complexity-all
15629 Report all the complexity metrics
15631 @item --no-complexity-all
15632 Do not report any of complexity metrics
15634 @item --complexity-cyclomatic
15635 Report the McCabe Cyclomatic Complexity
15637 @item --no-complexity-cyclomatic
15638 Do not report the McCabe Cyclomatic Complexity
15640 @item --complexity-essential
15641 Report the Essential Complexity
15643 @item --no-complexity-essential
15644 Do not report the Essential Complexity
15646 @item --loop-nesting
15647 Report maximal loop nesting level
15649 @item --no-loop-nesting
15650 Do not report maximal loop nesting level
15652 @item --complexity-average
15653 Report the average McCabe Cyclomatic Complexity for all the subprogram bodies,
15654 task bodies, entry bodies and statement sequences in package bodies.
15655 The metric is computed and reported for whole set of processed Ada sources
15658 @item --no-complexity-average
15659 Do not report the average McCabe Cyclomatic Complexity for all the subprogram
15660 bodies, task bodies, entry bodies and statement sequences in package bodies
15662 @cindex @option{-ne} (@command{gnatmetric})
15664 Do not consider @code{exit} statements as @code{goto}s when
15665 computing Essential Complexity
15667 @cindex @option{--no-static-loop} (@command{gnatmetric})
15668 @item --no-static-loop
15669 Do not consider static loops when computing cyclomatic complexity
15671 @item --extra-exit-points
15672 Report the extra exit points for subprogram bodies. As an exit point, this
15673 metric counts @code{return} statements and raise statements in case when the
15674 raised exception is not handled in the same body. In case of a function this
15675 metric subtracts 1 from the number of exit points, because a function body
15676 must contain at least one @code{return} statement.
15678 @item --no-extra-exit-points
15679 Do not report the extra exit points for subprogram bodies
15683 @node Coupling Metrics Control
15684 @subsubsection Coupling Metrics Control
15685 @cindex Coupling metrics control in @command{gnatmetric}
15688 @cindex Coupling metrics (in @command{gnatmetric})
15689 Coupling metrics measure the dependencies between a given entity and other
15690 entities in the program. This information is useful since high coupling
15691 may signal potential issues with maintainability as the program evolves.
15693 @command{gnatmetric} computes the following coupling metrics:
15698 @emph{object-oriented coupling}, for classes in traditional object-oriented
15702 @emph{unit coupling}, for all the program units making up a program;
15705 @emph{control coupling}, reflecting dependencies between a unit and
15706 other units that contain subprograms.
15710 Two kinds of coupling metrics are computed:
15713 @item fan-out coupling (``efferent coupling''):
15714 @cindex fan-out coupling
15715 @cindex efferent coupling
15716 the number of entities the given entity depends upon. This metric
15717 reflects how the given entity depends on the changes in the
15718 ``external world''.
15720 @item fan-in coupling (``afferent'' coupling):
15721 @cindex fan-in coupling
15722 @cindex afferent coupling
15723 the number of entities that depend on a given entity.
15724 This metric reflects how the ``external world'' depends on the changes in a
15729 Object-oriented coupling metrics measure the dependencies
15730 between a given class (or a group of classes) and the other classes in the
15731 program. In this subsection the term ``class'' is used in its traditional
15732 object-oriented programming sense (an instantiable module that contains data
15733 and/or method members). A @emph{category} (of classes) is a group of closely
15734 related classes that are reused and/or modified together.
15736 A class @code{K}'s fan-out coupling is the number of classes
15737 that @code{K} depends upon.
15738 A category's fan-out coupling is the number of classes outside the
15739 category that the classes inside the category depend upon.
15741 A class @code{K}'s fan-in coupling is the number of classes
15742 that depend upon @code{K}.
15743 A category's fan-in coupling is the number of classes outside the
15744 category that depend on classes belonging to the category.
15746 Ada's object-oriented paradigm separates the instantiable entity
15747 (type) from the module (package), so the definition of the coupling
15748 metrics for Ada maps the class and class category notions
15749 onto Ada constructs.
15751 For the coupling metrics, several kinds of modules that define a tagged type
15752 or an interface type -- library packages, library generic packages, and
15753 library generic package instantiations -- are considered to be classes.
15754 A category consists of a library package (or
15755 a library generic package) that defines a tagged or an interface type,
15756 together with all its descendant (generic) packages that define tagged
15757 or interface types. Thus a
15758 category is an Ada hierarchy of library-level program units. Class
15759 coupling in Ada is referred to as ``tagged coupling'', and category coupling
15760 is referred to as ``hierarchy coupling''.
15762 For any package serving as a class, its body and subunits (if any) are
15763 considered together with its spec when computing dependencies, and coupling
15764 metrics are reported for spec units only. Dependencies between classes
15765 mean Ada semantic dependencies. For object-oriented coupling
15766 metrics, only dependencies on units treated as classes are
15769 Similarly, for unit and control coupling an entity is considered to be the
15770 conceptual construct consisting of the entity's specification, body, and
15771 any subunits (transitively).
15772 @command{gnatmetric} computes
15773 the dependencies of all these units as a whole, but
15774 metrics are only reported for spec
15775 units (or for a subprogram body unit in case if there is no
15776 separate spec for the given subprogram).
15778 For unit coupling, dependencies are computed between all kinds of program
15779 units. For control coupling, the dependencies of a given unit are limited to
15780 those units that define subprograms. Thus control fan-out coupling is reported
15781 for all units, but control fan-in coupling is only reported for units
15782 that define subprograms.
15784 The following simple example illustrates the difference between unit coupling
15785 and control coupling metrics:
15787 @smallexample @c ada
15789 @b{package} Lib_1 @b{is}
15790 @b{function} F_1 (I : Integer) @b{return} Integer;
15795 @b{package} Lib_2 @b{is}
15796 @b{type} T_2 @b{is} @b{new} Integer;
15801 @b{package} @b{body} Lib_1 @b{is}
15802 @b{function} F_1 (I : Integer) @b{return} Integer @b{is}
15810 @b{with} Lib_2; @b{use} Lib_2;
15811 @b{package} Pack @b{is}
15813 @b{function} Fun (I : Integer) @b{return} Integer;
15818 @b{with} Lib_1; @b{use} Lib_1;
15819 @b{package} @b{body} Pack @b{is}
15820 @b{function} Fun (I : Integer) @b{return} Integer @b{is}
15822 @b{return} F_1 (I);
15829 If we apply @command{gnatmetric} with the @option{--coupling-all} option to
15830 these units, the result will be:
15836 Unit Lib_1 (C:\customers\662\L406-007\lib_1.ads)
15837 control fan-out coupling : 0
15838 control fan-in coupling : 1
15839 unit fan-out coupling : 0
15840 unit fan-in coupling : 1
15844 Unit Pack (C:\customers\662\L406-007\pack.ads)
15845 control fan-out coupling : 1
15846 control fan-in coupling : 0
15847 unit fan-out coupling : 2
15848 unit fan-in coupling : 0
15852 Unit Lib_2 (C:\customers\662\L406-007\lib_2.ads)
15853 control fan-out coupling : 0
15854 unit fan-out coupling : 0
15855 unit fan-in coupling : 1
15860 The result does not contain values for object-oriented
15861 coupling because none of the argument units contains a tagged type and
15862 therefore none of these units can be treated as a class.
15864 The @code{Pack} package (spec and body) depends on two
15865 units -- @code{Lib_1} @code{and Lib_2} -- and so its unit fan-out coupling
15866 is 2. Since nothing depends on it, its unit fan-in coupling is 0, as
15867 is its control fan-in coupling. Only one of the units @code{Pack} depends
15868 upon defines a subprogram, so its control fan-out coupling is 1.
15870 @code{Lib_2} depends on nothing, so its fan-out metrics are 0. It does
15871 not define any subprograms, so it has no control fan-in metric.
15872 One unit (@code{Pack}) depends on it , so its unit fan-in coupling is 1.
15874 @code{Lib_1} is similar to @code{Lib_2}, but it does define a subprogram.
15875 Its control fan-in coupling is 1 (because there is one unit
15878 When computing coupling metrics, @command{gnatmetric} counts only
15879 dependencies between units that are arguments of the @command{gnatmetric}
15880 invocation. Coupling metrics are program-wide (or project-wide) metrics, so
15881 you should invoke @command{gnatmetric} for
15882 the complete set of sources comprising your program. This can be done
15883 by invoking @command{gnatmetric} with the corresponding project file
15884 and with the @option{-U} option.
15886 By default, all the coupling metrics are disabled. You can use the following
15887 switches to specify the coupling metrics to be computed and reported:
15891 @cindex @option{--tagged-coupling@var{x}} (@command{gnatmetric})
15892 @cindex @option{--hierarchy-coupling@var{x}} (@command{gnatmetric})
15893 @cindex @option{--unit-coupling@var{x}} (@command{gnatmetric})
15894 @cindex @option{--control-coupling@var{x}} (@command{gnatmetric})
15897 @item --coupling-all
15898 Report all the coupling metrics
15900 @item --tagged-coupling-out
15901 Report tagged (class) fan-out coupling
15903 @item --tagged-coupling-in
15904 Report tagged (class) fan-in coupling
15906 @item --hierarchy-coupling-out
15907 Report hierarchy (category) fan-out coupling
15909 @item --hierarchy-coupling-in
15910 Report hierarchy (category) fan-in coupling
15912 @item --unit-coupling-out
15913 Report unit fan-out coupling
15915 @item --unit-coupling-in
15916 Report unit fan-in coupling
15918 @item --control-coupling-out
15919 Report control fan-out coupling
15921 @item --control-coupling-in
15922 Report control fan-in coupling
15925 @node Other gnatmetric Switches
15926 @subsection Other @code{gnatmetric} Switches
15929 Additional @command{gnatmetric} switches are as follows:
15933 @cindex @option{--version} @command{gnatmetric}
15934 Display Copyright and version, then exit disregarding all other options.
15937 @cindex @option{--help} @command{gnatmetric}
15938 Display usage, then exit disregarding all other options.
15940 @item -P @var{file}
15941 @cindex @option{-P} @command{gnatmetric}
15942 Indicates the name of the project file that describes the set of sources
15943 to be processed. The exact set of argument sources depends on other options
15944 specified, see below.
15947 @cindex @option{-U} @command{gnatmetric}
15948 If a project file is specified and no argument source is explicitly
15949 specified (either directly or by means of @option{-files} option), process
15950 all the units of the closure of the argument project. Otherwise this option
15953 @item -U @var{main_unit}
15954 If a project file is specified and no argument source is explicitly
15955 specified (either directly or by means of @option{-files} option), process
15956 the closure of units rooted at @var{main_unit}. Otherwise this option
15959 @item -X@var{name}=@var{value}
15960 @cindex @option{-X} @command{gnatmetric}
15961 Indicates that external variable @var{name} in the argument project
15962 has the value @var{value}. Has no effect if no project is specified as
15965 @item --RTS=@var{rts-path}
15966 @cindex @option{--RTS} (@command{gnatmetric})
15967 Specifies the default location of the runtime library. Same meaning as the
15968 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
15970 @item --subdirs=@var{dir}
15971 @cindex @option{--subdirs=@var{dir}} @command{gnatmetric}
15972 Use the specified subdirectory of the project objects file (or of the
15973 project file directory if the project does not specify an object directory)
15974 for tool output files. Has no effect if no project is specified as
15975 tool argument r if @option{--no_objects_dir} is specified.
15977 @item --no_objects_dir
15978 @cindex @option{--no_objects_dir} @command{gnatmetric}
15979 Place all the result files into the current directory instead of
15980 project objects directory. This corresponds to the @command{gnatcheck}
15981 behavior when it is called with the project file from the
15982 GNAT driver. Has no effect if no project is specified.
15984 @item -files @var{filename}
15985 @cindex @option{-files} (@code{gnatmetric})
15986 Take the argument source files from the specified file. This file should be an
15987 ordinary text file containing file names separated by spaces or
15988 line breaks. You can use this switch more than once in the same call to
15989 @command{gnatmetric}. You also can combine this switch with
15990 an explicit list of files.
15993 @cindex @option{-j} (@command{gnatmetric})
15994 Use @var{n} processes to carry out the tree creations (internal representations
15995 of the argument sources). On a multiprocessor machine this speeds up processing
15996 of big sets of argument sources. If @var{n} is 0, then the maximum number of
15997 parallel tree creations is the number of core processors on the platform.
15999 @cindex @option{-t} (@command{gnatmetric})
16001 Print out execution time.
16004 @cindex @option{-v} (@command{gnatmetric})
16006 @command{gnatmetric} generates version information and then
16007 a trace of sources being processed.
16010 @cindex @option{-q} (@command{gnatmetric})
16015 If a project file is specified and no argument source is explicitly
16016 specified (either directly or by means of @option{-files} option), and no
16017 @option{-U} is specified, then the set of processed sources is
16018 all the immediate units of the argument project.
16022 @node Generate project-wide metrics
16023 @subsection Generate project-wide metrics
16025 In order to compute metrics on all units of a given project, you can use
16026 the @command{gnat} driver along with the @option{-P} option:
16032 If the project @code{proj} depends upon other projects, you can compute
16033 the metrics on the project closure using the @option{-U} option:
16035 gnat metric -Pproj -U
16039 Finally, if not all the units are relevant to a particular main
16040 program in the project closure, you can generate metrics for the set
16041 of units needed to create a given main program (unit closure) using
16042 the @option{-U} option followed by the name of the main unit:
16044 gnat metric -Pproj -U main
16050 @c ***********************************
16051 @node File Name Krunching with gnatkr
16052 @chapter File Name Krunching with @code{gnatkr}
16056 This chapter discusses the method used by the compiler to shorten
16057 the default file names chosen for Ada units so that they do not
16058 exceed the maximum length permitted. It also describes the
16059 @code{gnatkr} utility that can be used to determine the result of
16060 applying this shortening.
16064 * Krunching Method::
16065 * Examples of gnatkr Usage::
16069 @section About @code{gnatkr}
16072 The default file naming rule in GNAT
16073 is that the file name must be derived from
16074 the unit name. The exact default rule is as follows:
16077 Take the unit name and replace all dots by hyphens.
16079 If such a replacement occurs in the
16080 second character position of a name, and the first character is
16081 @samp{a}, @samp{g}, @samp{s}, or @samp{i},
16082 then replace the dot by the character
16084 instead of a minus.
16086 The reason for this exception is to avoid clashes
16087 with the standard names for children of System, Ada, Interfaces,
16088 and GNAT, which use the prefixes
16089 @samp{s-}, @samp{a-}, @samp{i-}, and @samp{g-},
16092 The @option{-gnatk@var{nn}}
16093 switch of the compiler activates a ``krunching''
16094 circuit that limits file names to nn characters (where nn is a decimal
16095 integer). For example, using OpenVMS,
16096 where the maximum file name length is
16097 39, the value of nn is usually set to 39, but if you want to generate
16098 a set of files that would be usable if ported to a system with some
16099 different maximum file length, then a different value can be specified.
16100 The default value of 39 for OpenVMS need not be specified.
16102 The @code{gnatkr} utility can be used to determine the krunched name for
16103 a given file, when krunched to a specified maximum length.
16106 @section Using @code{gnatkr}
16109 The @code{gnatkr} command has the form
16112 @c $ gnatkr @var{name} @ovar{length}
16113 @c Expanding @ovar macro inline (explanation in macro def comments)
16114 $ gnatkr @var{name} @r{[}@var{length}@r{]}
16119 @var{name} is the uncrunched file name, derived from the name of the unit
16120 in the standard manner described in the previous section (i.e., in particular
16121 all dots are replaced by hyphens). The file name may or may not have an
16122 extension (defined as a suffix of the form period followed by arbitrary
16123 characters other than period). If an extension is present then it will
16124 be preserved in the output. For example, when krunching @file{hellofile.ads}
16125 to eight characters, the result will be hellofil.ads.
16127 Note: for compatibility with previous versions of @code{gnatkr} dots may
16128 appear in the name instead of hyphens, but the last dot will always be
16129 taken as the start of an extension. So if @code{gnatkr} is given an argument
16130 such as @file{Hello.World.adb} it will be treated exactly as if the first
16131 period had been a hyphen, and for example krunching to eight characters
16132 gives the result @file{hellworl.adb}.
16134 Note that the result is always all lower case (except on OpenVMS where it is
16135 all upper case). Characters of the other case are folded as required.
16137 @var{length} represents the length of the krunched name. The default
16138 when no argument is given is 8 characters. A length of zero stands for
16139 unlimited, in other words do not chop except for system files where the
16140 implied crunching length is always eight characters.
16143 The output is the krunched name. The output has an extension only if the
16144 original argument was a file name with an extension.
16146 @node Krunching Method
16147 @section Krunching Method
16150 The initial file name is determined by the name of the unit that the file
16151 contains. The name is formed by taking the full expanded name of the
16152 unit and replacing the separating dots with hyphens and
16154 for all letters, except that a hyphen in the second character position is
16155 replaced by a tilde if the first character is
16156 @samp{a}, @samp{i}, @samp{g}, or @samp{s}.
16157 The extension is @code{.ads} for a
16158 spec and @code{.adb} for a body.
16159 Krunching does not affect the extension, but the file name is shortened to
16160 the specified length by following these rules:
16164 The name is divided into segments separated by hyphens, tildes or
16165 underscores and all hyphens, tildes, and underscores are
16166 eliminated. If this leaves the name short enough, we are done.
16169 If the name is too long, the longest segment is located (left-most
16170 if there are two of equal length), and shortened by dropping
16171 its last character. This is repeated until the name is short enough.
16173 As an example, consider the krunching of @*@file{our-strings-wide_fixed.adb}
16174 to fit the name into 8 characters as required by some operating systems.
16177 our-strings-wide_fixed 22
16178 our strings wide fixed 19
16179 our string wide fixed 18
16180 our strin wide fixed 17
16181 our stri wide fixed 16
16182 our stri wide fixe 15
16183 our str wide fixe 14
16184 our str wid fixe 13
16190 Final file name: oustwifi.adb
16194 The file names for all predefined units are always krunched to eight
16195 characters. The krunching of these predefined units uses the following
16196 special prefix replacements:
16200 replaced by @file{a-}
16203 replaced by @file{g-}
16206 replaced by @file{i-}
16209 replaced by @file{s-}
16212 These system files have a hyphen in the second character position. That
16213 is why normal user files replace such a character with a
16215 avoid confusion with system file names.
16217 As an example of this special rule, consider
16218 @*@file{ada-strings-wide_fixed.adb}, which gets krunched as follows:
16221 ada-strings-wide_fixed 22
16222 a- strings wide fixed 18
16223 a- string wide fixed 17
16224 a- strin wide fixed 16
16225 a- stri wide fixed 15
16226 a- stri wide fixe 14
16227 a- str wide fixe 13
16233 Final file name: a-stwifi.adb
16237 Of course no file shortening algorithm can guarantee uniqueness over all
16238 possible unit names, and if file name krunching is used then it is your
16239 responsibility to ensure that no name clashes occur. The utility
16240 program @code{gnatkr} is supplied for conveniently determining the
16241 krunched name of a file.
16243 @node Examples of gnatkr Usage
16244 @section Examples of @code{gnatkr} Usage
16250 $ gnatkr very_long_unit_name.ads --> velounna.ads
16251 $ gnatkr grandparent-parent-child.ads --> grparchi.ads
16252 $ gnatkr Grandparent.Parent.Child.ads --> grparchi.ads
16253 $ gnatkr grandparent-parent-child --> grparchi
16254 $ gnatkr very_long_unit_name.ads/count=6 --> vlunna.ads
16255 $ gnatkr very_long_unit_name.ads/count=0 --> very_long_unit_name.ads
16258 @node Preprocessing with gnatprep
16259 @chapter Preprocessing with @code{gnatprep}
16263 This chapter discusses how to use GNAT's @code{gnatprep} utility for simple
16265 Although designed for use with GNAT, @code{gnatprep} does not depend on any
16266 special GNAT features.
16267 For further discussion of conditional compilation in general, see
16268 @ref{Conditional Compilation}.
16271 * Preprocessing Symbols::
16273 * Switches for gnatprep::
16274 * Form of Definitions File::
16275 * Form of Input Text for gnatprep::
16278 @node Preprocessing Symbols
16279 @section Preprocessing Symbols
16282 Preprocessing symbols are defined in definition files and referred to in
16283 sources to be preprocessed. A Preprocessing symbol is an identifier, following
16284 normal Ada (case-insensitive) rules for its syntax, with the restriction that
16285 all characters need to be in the ASCII set (no accented letters).
16287 @node Using gnatprep
16288 @section Using @code{gnatprep}
16291 To call @code{gnatprep} use
16294 @c $ gnatprep @ovar{switches} @var{infile} @var{outfile} @ovar{deffile}
16295 @c Expanding @ovar macro inline (explanation in macro def comments)
16296 $ gnatprep @r{[}@var{switches}@r{]} @var{infile} @var{outfile} @r{[}@var{deffile}@r{]}
16303 is an optional sequence of switches as described in the next section.
16306 is the full name of the input file, which is an Ada source
16307 file containing preprocessor directives.
16310 is the full name of the output file, which is an Ada source
16311 in standard Ada form. When used with GNAT, this file name will
16312 normally have an ads or adb suffix.
16315 is the full name of a text file containing definitions of
16316 preprocessing symbols to be referenced by the preprocessor. This argument is
16317 optional, and can be replaced by the use of the @option{-D} switch.
16321 @node Switches for gnatprep
16322 @section Switches for @code{gnatprep}
16328 @cindex @option{-b} (@command{gnatprep})
16329 Causes both preprocessor lines and the lines deleted by
16330 preprocessing to be replaced by blank lines in the output source file,
16331 preserving line numbers in the output file.
16334 @cindex @option{-c} (@command{gnatprep})
16335 Causes both preprocessor lines and the lines deleted
16336 by preprocessing to be retained in the output source as comments marked
16337 with the special string @code{"--! "}. This option will result in line numbers
16338 being preserved in the output file.
16341 @cindex @option{-C} (@command{gnatprep})
16342 Causes comments to be scanned. Normally comments are ignored by gnatprep.
16343 If this option is specified, then comments are scanned and any $symbol
16344 substitutions performed as in program text. This is particularly useful
16345 when structured comments are used (e.g., when writing programs in the
16346 SPARK dialect of Ada). Note that this switch is not available when
16347 doing integrated preprocessing (it would be useless in this context
16348 since comments are ignored by the compiler in any case).
16350 @item -Dsymbol=value
16351 @cindex @option{-D} (@command{gnatprep})
16352 Defines a new preprocessing symbol, associated with value. If no value is given
16353 on the command line, then symbol is considered to be @code{True}. This switch
16354 can be used in place of a definition file.
16358 @cindex @option{-r} (@command{gnatprep})
16359 Causes a @code{Source_Reference} pragma to be generated that
16360 references the original input file, so that error messages will use
16361 the file name of this original file. The use of this switch implies
16362 that preprocessor lines are not to be removed from the file, so its
16363 use will force @option{-b} mode if
16365 has not been specified explicitly.
16367 Note that if the file to be preprocessed contains multiple units, then
16368 it will be necessary to @code{gnatchop} the output file from
16369 @code{gnatprep}. If a @code{Source_Reference} pragma is present
16370 in the preprocessed file, it will be respected by
16372 so that the final chopped files will correctly refer to the original
16373 input source file for @code{gnatprep}.
16376 @cindex @option{-s} (@command{gnatprep})
16377 Causes a sorted list of symbol names and values to be
16378 listed on the standard output file.
16381 @cindex @option{-u} (@command{gnatprep})
16382 Causes undefined symbols to be treated as having the value FALSE in the context
16383 of a preprocessor test. In the absence of this option, an undefined symbol in
16384 a @code{#if} or @code{#elsif} test will be treated as an error.
16389 Note: if neither @option{-b} nor @option{-c} is present,
16390 then preprocessor lines and
16391 deleted lines are completely removed from the output, unless -r is
16392 specified, in which case -b is assumed.
16394 @node Form of Definitions File
16395 @section Form of Definitions File
16398 The definitions file contains lines of the form
16405 where symbol is a preprocessing symbol, and value is one of the following:
16409 Empty, corresponding to a null substitution
16411 A string literal using normal Ada syntax
16413 Any sequence of characters from the set
16414 (letters, digits, period, underline).
16418 Comment lines may also appear in the definitions file, starting with
16419 the usual @code{--},
16420 and comments may be added to the definitions lines.
16422 @node Form of Input Text for gnatprep
16423 @section Form of Input Text for @code{gnatprep}
16426 The input text may contain preprocessor conditional inclusion lines,
16427 as well as general symbol substitution sequences.
16429 The preprocessor conditional inclusion commands have the form
16434 #if @i{expression} @r{[}then@r{]}
16436 #elsif @i{expression} @r{[}then@r{]}
16438 #elsif @i{expression} @r{[}then@r{]}
16449 In this example, @i{expression} is defined by the following grammar:
16451 @i{expression} ::= <symbol>
16452 @i{expression} ::= <symbol> = "<value>"
16453 @i{expression} ::= <symbol> = <symbol>
16454 @i{expression} ::= <symbol> = <integer>
16455 @i{expression} ::= <symbol> > <integer>
16456 @i{expression} ::= <symbol> >= <integer>
16457 @i{expression} ::= <symbol> < <integer>
16458 @i{expression} ::= <symbol> <= <integer>
16459 @i{expression} ::= <symbol> 'Defined
16460 @i{expression} ::= not @i{expression}
16461 @i{expression} ::= @i{expression} and @i{expression}
16462 @i{expression} ::= @i{expression} or @i{expression}
16463 @i{expression} ::= @i{expression} and then @i{expression}
16464 @i{expression} ::= @i{expression} or else @i{expression}
16465 @i{expression} ::= ( @i{expression} )
16468 The following restriction exists: it is not allowed to have "and" or "or"
16469 following "not" in the same expression without parentheses. For example, this
16476 This should be one of the following:
16484 For the first test (@i{expression} ::= <symbol>) the symbol must have
16485 either the value true or false, that is to say the right-hand of the
16486 symbol definition must be one of the (case-insensitive) literals
16487 @code{True} or @code{False}. If the value is true, then the
16488 corresponding lines are included, and if the value is false, they are
16491 When comparing a symbol to an integer, the integer is any non negative
16492 literal integer as defined in the Ada Reference Manual, such as 3, 16#FF# or
16493 2#11#. The symbol value must also be a non negative integer. Integer values
16494 in the range 0 .. 2**31-1 are supported.
16496 The test (@i{expression} ::= <symbol> @code{'Defined}) is true only if
16497 the symbol has been defined in the definition file or by a @option{-D}
16498 switch on the command line. Otherwise, the test is false.
16500 The equality tests are case insensitive, as are all the preprocessor lines.
16502 If the symbol referenced is not defined in the symbol definitions file,
16503 then the effect depends on whether or not switch @option{-u}
16504 is specified. If so, then the symbol is treated as if it had the value
16505 false and the test fails. If this switch is not specified, then
16506 it is an error to reference an undefined symbol. It is also an error to
16507 reference a symbol that is defined with a value other than @code{True}
16510 The use of the @code{not} operator inverts the sense of this logical test.
16511 The @code{not} operator cannot be combined with the @code{or} or @code{and}
16512 operators, without parentheses. For example, "if not X or Y then" is not
16513 allowed, but "if (not X) or Y then" and "if not (X or Y) then" are.
16515 The @code{then} keyword is optional as shown
16517 The @code{#} must be the first non-blank character on a line, but
16518 otherwise the format is free form. Spaces or tabs may appear between
16519 the @code{#} and the keyword. The keywords and the symbols are case
16520 insensitive as in normal Ada code. Comments may be used on a
16521 preprocessor line, but other than that, no other tokens may appear on a
16522 preprocessor line. Any number of @code{elsif} clauses can be present,
16523 including none at all. The @code{else} is optional, as in Ada.
16525 The @code{#} marking the start of a preprocessor line must be the first
16526 non-blank character on the line, i.e., it must be preceded only by
16527 spaces or horizontal tabs.
16529 Symbol substitution outside of preprocessor lines is obtained by using
16537 anywhere within a source line, except in a comment or within a
16538 string literal. The identifier
16539 following the @code{$} must match one of the symbols defined in the symbol
16540 definition file, and the result is to substitute the value of the
16541 symbol in place of @code{$symbol} in the output file.
16543 Note that although the substitution of strings within a string literal
16544 is not possible, it is possible to have a symbol whose defined value is
16545 a string literal. So instead of setting XYZ to @code{hello} and writing:
16548 Header : String := "$XYZ";
16552 you should set XYZ to @code{"hello"} and write:
16555 Header : String := $XYZ;
16559 and then the substitution will occur as desired.
16561 @node The GNAT Library Browser gnatls
16562 @chapter The GNAT Library Browser @code{gnatls}
16564 @cindex Library browser
16567 @code{gnatls} is a tool that outputs information about compiled
16568 units. It gives the relationship between objects, unit names and source
16569 files. It can also be used to check the source dependencies of a unit
16570 as well as various characteristics.
16572 Note: to invoke @code{gnatls} with a project file, use the @code{gnat}
16573 driver (see @ref{The GNAT Driver and Project Files}).
16577 * Switches for gnatls::
16578 * Examples of gnatls Usage::
16581 @node Running gnatls
16582 @section Running @code{gnatls}
16585 The @code{gnatls} command has the form
16588 $ gnatls switches @var{object_or_ali_file}
16592 The main argument is the list of object or @file{ali} files
16593 (@pxref{The Ada Library Information Files})
16594 for which information is requested.
16596 In normal mode, without additional option, @code{gnatls} produces a
16597 four-column listing. Each line represents information for a specific
16598 object. The first column gives the full path of the object, the second
16599 column gives the name of the principal unit in this object, the third
16600 column gives the status of the source and the fourth column gives the
16601 full path of the source representing this unit.
16602 Here is a simple example of use:
16606 ./demo1.o demo1 DIF demo1.adb
16607 ./demo2.o demo2 OK demo2.adb
16608 ./hello.o h1 OK hello.adb
16609 ./instr-child.o instr.child MOK instr-child.adb
16610 ./instr.o instr OK instr.adb
16611 ./tef.o tef DIF tef.adb
16612 ./text_io_example.o text_io_example OK text_io_example.adb
16613 ./tgef.o tgef DIF tgef.adb
16617 The first line can be interpreted as follows: the main unit which is
16619 object file @file{demo1.o} is demo1, whose main source is in
16620 @file{demo1.adb}. Furthermore, the version of the source used for the
16621 compilation of demo1 has been modified (DIF). Each source file has a status
16622 qualifier which can be:
16625 @item OK (unchanged)
16626 The version of the source file used for the compilation of the
16627 specified unit corresponds exactly to the actual source file.
16629 @item MOK (slightly modified)
16630 The version of the source file used for the compilation of the
16631 specified unit differs from the actual source file but not enough to
16632 require recompilation. If you use gnatmake with the qualifier
16633 @option{-m (minimal recompilation)}, a file marked
16634 MOK will not be recompiled.
16636 @item DIF (modified)
16637 No version of the source found on the path corresponds to the source
16638 used to build this object.
16640 @item ??? (file not found)
16641 No source file was found for this unit.
16643 @item HID (hidden, unchanged version not first on PATH)
16644 The version of the source that corresponds exactly to the source used
16645 for compilation has been found on the path but it is hidden by another
16646 version of the same source that has been modified.
16650 @node Switches for gnatls
16651 @section Switches for @code{gnatls}
16654 @code{gnatls} recognizes the following switches:
16658 @cindex @option{--version} @command{gnatls}
16659 Display Copyright and version, then exit disregarding all other options.
16662 @cindex @option{--help} @command{gnatls}
16663 If @option{--version} was not used, display usage, then exit disregarding
16667 @cindex @option{-a} (@code{gnatls})
16668 Consider all units, including those of the predefined Ada library.
16669 Especially useful with @option{-d}.
16672 @cindex @option{-d} (@code{gnatls})
16673 List sources from which specified units depend on.
16676 @cindex @option{-h} (@code{gnatls})
16677 Output the list of options.
16680 @cindex @option{-o} (@code{gnatls})
16681 Only output information about object files.
16684 @cindex @option{-s} (@code{gnatls})
16685 Only output information about source files.
16688 @cindex @option{-u} (@code{gnatls})
16689 Only output information about compilation units.
16691 @item -files=@var{file}
16692 @cindex @option{-files} (@code{gnatls})
16693 Take as arguments the files listed in text file @var{file}.
16694 Text file @var{file} may contain empty lines that are ignored.
16695 Each nonempty line should contain the name of an existing file.
16696 Several such switches may be specified simultaneously.
16699 @itemx -aI@var{dir}
16703 @cindex @option{-aO} (@code{gnatls})
16704 @cindex @option{-aI} (@code{gnatls})
16705 @cindex @option{-I} (@code{gnatls})
16706 @cindex @option{-I-} (@code{gnatls})
16707 Source path manipulation. Same meaning as the equivalent @command{gnatmake}
16708 flags (@pxref{Switches for gnatmake}).
16711 @cindex @option{-aP} (@code{gnatls})
16712 Add @var{dir} at the beginning of the project search dir.
16714 @item --RTS=@var{rts-path}
16715 @cindex @option{--RTS} (@code{gnatls})
16716 Specifies the default location of the runtime library. Same meaning as the
16717 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
16720 @cindex @option{-v} (@code{gnatls})
16721 Verbose mode. Output the complete source, object and project paths. Do not use
16722 the default column layout but instead use long format giving as much as
16723 information possible on each requested units, including special
16724 characteristics such as:
16727 @item Preelaborable
16728 The unit is preelaborable in the Ada sense.
16731 No elaboration code has been produced by the compiler for this unit.
16734 The unit is pure in the Ada sense.
16736 @item Elaborate_Body
16737 The unit contains a pragma Elaborate_Body.
16740 The unit contains a pragma Remote_Types.
16742 @item Shared_Passive
16743 The unit contains a pragma Shared_Passive.
16746 This unit is part of the predefined environment and cannot be modified
16749 @item Remote_Call_Interface
16750 The unit contains a pragma Remote_Call_Interface.
16756 @node Examples of gnatls Usage
16757 @section Example of @code{gnatls} Usage
16760 Example of using the verbose switch. Note how the source and
16761 object paths are affected by the -I switch.
16764 $ gnatls -v -I.. demo1.o
16766 GNATLS 5.03w (20041123-34)
16767 Copyright 1997-2004 Free Software Foundation, Inc.
16769 Source Search Path:
16770 <Current_Directory>
16772 /home/comar/local/adainclude/
16774 Object Search Path:
16775 <Current_Directory>
16777 /home/comar/local/lib/gcc-lib/x86-linux/3.4.3/adalib/
16779 Project Search Path:
16780 <Current_Directory>
16781 /home/comar/local/lib/gnat/
16786 Kind => subprogram body
16787 Flags => No_Elab_Code
16788 Source => demo1.adb modified
16792 The following is an example of use of the dependency list.
16793 Note the use of the -s switch
16794 which gives a straight list of source files. This can be useful for
16795 building specialized scripts.
16798 $ gnatls -d demo2.o
16799 ./demo2.o demo2 OK demo2.adb
16805 $ gnatls -d -s -a demo1.o
16807 /home/comar/local/adainclude/ada.ads
16808 /home/comar/local/adainclude/a-finali.ads
16809 /home/comar/local/adainclude/a-filico.ads
16810 /home/comar/local/adainclude/a-stream.ads
16811 /home/comar/local/adainclude/a-tags.ads
16814 /home/comar/local/adainclude/gnat.ads
16815 /home/comar/local/adainclude/g-io.ads
16817 /home/comar/local/adainclude/system.ads
16818 /home/comar/local/adainclude/s-exctab.ads
16819 /home/comar/local/adainclude/s-finimp.ads
16820 /home/comar/local/adainclude/s-finroo.ads
16821 /home/comar/local/adainclude/s-secsta.ads
16822 /home/comar/local/adainclude/s-stalib.ads
16823 /home/comar/local/adainclude/s-stoele.ads
16824 /home/comar/local/adainclude/s-stratt.ads
16825 /home/comar/local/adainclude/s-tasoli.ads
16826 /home/comar/local/adainclude/s-unstyp.ads
16827 /home/comar/local/adainclude/unchconv.ads
16831 @node Cleaning Up with gnatclean
16832 @chapter Cleaning Up with @code{gnatclean}
16834 @cindex Cleaning tool
16837 @code{gnatclean} is a tool that allows the deletion of files produced by the
16838 compiler, binder and linker, including ALI files, object files, tree files,
16839 expanded source files, library files, interface copy source files, binder
16840 generated files and executable files.
16843 * Running gnatclean::
16844 * Switches for gnatclean::
16845 @c * Examples of gnatclean Usage::
16848 @node Running gnatclean
16849 @section Running @code{gnatclean}
16852 The @code{gnatclean} command has the form:
16855 $ gnatclean switches @var{names}
16859 @var{names} is a list of source file names. Suffixes @code{.ads} and
16860 @code{adb} may be omitted. If a project file is specified using switch
16861 @code{-P}, then @var{names} may be completely omitted.
16864 In normal mode, @code{gnatclean} delete the files produced by the compiler and,
16865 if switch @code{-c} is not specified, by the binder and
16866 the linker. In informative-only mode, specified by switch
16867 @code{-n}, the list of files that would have been deleted in
16868 normal mode is listed, but no file is actually deleted.
16870 @node Switches for gnatclean
16871 @section Switches for @code{gnatclean}
16874 @code{gnatclean} recognizes the following switches:
16878 @cindex @option{--version} @command{gnatclean}
16879 Display Copyright and version, then exit disregarding all other options.
16882 @cindex @option{--help} @command{gnatclean}
16883 If @option{--version} was not used, display usage, then exit disregarding
16886 @item --subdirs=subdir
16887 Actual object directory of each project file is the subdirectory subdir of the
16888 object directory specified or defaulted in the project file.
16890 @item --unchecked-shared-lib-imports
16891 By default, shared library projects are not allowed to import static library
16892 projects. When this switch is used on the command line, this restriction is
16896 @cindex @option{-c} (@code{gnatclean})
16897 Only attempt to delete the files produced by the compiler, not those produced
16898 by the binder or the linker. The files that are not to be deleted are library
16899 files, interface copy files, binder generated files and executable files.
16902 @cindex @option{-D} (@code{gnatclean})
16903 Indicate that ALI and object files should normally be found in directory
16907 @cindex @option{-F} (@code{gnatclean})
16908 When using project files, if some errors or warnings are detected during
16909 parsing and verbose mode is not in effect (no use of switch
16910 -v), then error lines start with the full path name of the project
16911 file, rather than its simple file name.
16914 @cindex @option{-h} (@code{gnatclean})
16915 Output a message explaining the usage of @code{gnatclean}.
16918 @cindex @option{-n} (@code{gnatclean})
16919 Informative-only mode. Do not delete any files. Output the list of the files
16920 that would have been deleted if this switch was not specified.
16922 @item -P@var{project}
16923 @cindex @option{-P} (@code{gnatclean})
16924 Use project file @var{project}. Only one such switch can be used.
16925 When cleaning a project file, the files produced by the compilation of the
16926 immediate sources or inherited sources of the project files are to be
16927 deleted. This is not depending on the presence or not of executable names
16928 on the command line.
16931 @cindex @option{-q} (@code{gnatclean})
16932 Quiet output. If there are no errors, do not output anything, except in
16933 verbose mode (switch -v) or in informative-only mode
16937 @cindex @option{-r} (@code{gnatclean})
16938 When a project file is specified (using switch -P),
16939 clean all imported and extended project files, recursively. If this switch
16940 is not specified, only the files related to the main project file are to be
16941 deleted. This switch has no effect if no project file is specified.
16944 @cindex @option{-v} (@code{gnatclean})
16948 @cindex @option{-vP} (@code{gnatclean})
16949 Indicates the verbosity of the parsing of GNAT project files.
16950 @xref{Switches Related to Project Files}.
16952 @item -X@var{name=value}
16953 @cindex @option{-X} (@code{gnatclean})
16954 Indicates that external variable @var{name} has the value @var{value}.
16955 The Project Manager will use this value for occurrences of
16956 @code{external(name)} when parsing the project file.
16957 @xref{Switches Related to Project Files}.
16960 @cindex @option{-aO} (@code{gnatclean})
16961 When searching for ALI and object files, look in directory
16965 @cindex @option{-I} (@code{gnatclean})
16966 Equivalent to @option{-aO@var{dir}}.
16969 @cindex @option{-I-} (@code{gnatclean})
16970 @cindex Source files, suppressing search
16971 Do not look for ALI or object files in the directory
16972 where @code{gnatclean} was invoked.
16976 @c @node Examples of gnatclean Usage
16977 @c @section Examples of @code{gnatclean} Usage
16979 @node GNAT and Libraries
16980 @chapter GNAT and Libraries
16981 @cindex Library, building, installing, using
16984 This chapter describes how to build and use libraries with GNAT, and also shows
16985 how to recompile the GNAT run-time library. You should be familiar with the
16986 Project Manager facility (@pxref{GNAT Project Manager}) before reading this
16990 * Introduction to Libraries in GNAT::
16991 * General Ada Libraries::
16992 * Stand-alone Ada Libraries::
16993 * Rebuilding the GNAT Run-Time Library::
16996 @node Introduction to Libraries in GNAT
16997 @section Introduction to Libraries in GNAT
17000 A library is, conceptually, a collection of objects which does not have its
17001 own main thread of execution, but rather provides certain services to the
17002 applications that use it. A library can be either statically linked with the
17003 application, in which case its code is directly included in the application,
17004 or, on platforms that support it, be dynamically linked, in which case
17005 its code is shared by all applications making use of this library.
17007 GNAT supports both types of libraries.
17008 In the static case, the compiled code can be provided in different ways. The
17009 simplest approach is to provide directly the set of objects resulting from
17010 compilation of the library source files. Alternatively, you can group the
17011 objects into an archive using whatever commands are provided by the operating
17012 system. For the latter case, the objects are grouped into a shared library.
17014 In the GNAT environment, a library has three types of components:
17020 @xref{The Ada Library Information Files}.
17022 Object files, an archive or a shared library.
17026 A GNAT library may expose all its source files, which is useful for
17027 documentation purposes. Alternatively, it may expose only the units needed by
17028 an external user to make use of the library. That is to say, the specs
17029 reflecting the library services along with all the units needed to compile
17030 those specs, which can include generic bodies or any body implementing an
17031 inlined routine. In the case of @emph{stand-alone libraries} those exposed
17032 units are called @emph{interface units} (@pxref{Stand-alone Ada Libraries}).
17034 All compilation units comprising an application, including those in a library,
17035 need to be elaborated in an order partially defined by Ada's semantics. GNAT
17036 computes the elaboration order from the @file{ALI} files and this is why they
17037 constitute a mandatory part of GNAT libraries.
17038 @emph{Stand-alone libraries} are the exception to this rule because a specific
17039 library elaboration routine is produced independently of the application(s)
17042 @node General Ada Libraries
17043 @section General Ada Libraries
17046 * Building a library::
17047 * Installing a library::
17048 * Using a library::
17051 @node Building a library
17052 @subsection Building a library
17055 The easiest way to build a library is to use the Project Manager,
17056 which supports a special type of project called a @emph{Library Project}
17057 (@pxref{Library Projects}).
17059 A project is considered a library project, when two project-level attributes
17060 are defined in it: @code{Library_Name} and @code{Library_Dir}. In order to
17061 control different aspects of library configuration, additional optional
17062 project-level attributes can be specified:
17065 This attribute controls whether the library is to be static or dynamic
17067 @item Library_Version
17068 This attribute specifies the library version; this value is used
17069 during dynamic linking of shared libraries to determine if the currently
17070 installed versions of the binaries are compatible.
17072 @item Library_Options
17074 These attributes specify additional low-level options to be used during
17075 library generation, and redefine the actual application used to generate
17080 The GNAT Project Manager takes full care of the library maintenance task,
17081 including recompilation of the source files for which objects do not exist
17082 or are not up to date, assembly of the library archive, and installation of
17083 the library (i.e., copying associated source, object and @file{ALI} files
17084 to the specified location).
17086 Here is a simple library project file:
17087 @smallexample @c ada
17088 project My_Lib @b{is}
17089 @b{for} Source_Dirs @b{use} ("src1", "src2");
17090 @b{for} Object_Dir @b{use} "obj";
17091 @b{for} Library_Name @b{use} "mylib";
17092 @b{for} Library_Dir @b{use} "lib";
17093 @b{for} Library_Kind @b{use} "dynamic";
17098 and the compilation command to build and install the library:
17100 @smallexample @c ada
17101 $ gnatmake -Pmy_lib
17105 It is not entirely trivial to perform manually all the steps required to
17106 produce a library. We recommend that you use the GNAT Project Manager
17107 for this task. In special cases where this is not desired, the necessary
17108 steps are discussed below.
17110 There are various possibilities for compiling the units that make up the
17111 library: for example with a Makefile (@pxref{Using the GNU make Utility}) or
17112 with a conventional script. For simple libraries, it is also possible to create
17113 a dummy main program which depends upon all the packages that comprise the
17114 interface of the library. This dummy main program can then be given to
17115 @command{gnatmake}, which will ensure that all necessary objects are built.
17117 After this task is accomplished, you should follow the standard procedure
17118 of the underlying operating system to produce the static or shared library.
17120 Here is an example of such a dummy program:
17121 @smallexample @c ada
17123 @b{with} My_Lib.Service1;
17124 @b{with} My_Lib.Service2;
17125 @b{with} My_Lib.Service3;
17126 @b{procedure} My_Lib_Dummy @b{is}
17134 Here are the generic commands that will build an archive or a shared library.
17137 # compiling the library
17138 $ gnatmake -c my_lib_dummy.adb
17140 # we don't need the dummy object itself
17141 $ rm my_lib_dummy.o my_lib_dummy.ali
17143 # create an archive with the remaining objects
17144 $ ar rc libmy_lib.a *.o
17145 # some systems may require "ranlib" to be run as well
17147 # or create a shared library
17148 $ gcc -shared -o libmy_lib.so *.o
17149 # some systems may require the code to have been compiled with -fPIC
17151 # remove the object files that are now in the library
17154 # Make the ALI files read-only so that gnatmake will not try to
17155 # regenerate the objects that are in the library
17160 Please note that the library must have a name of the form @file{lib@var{xxx}.a}
17161 or @file{lib@var{xxx}.so} (or @file{lib@var{xxx}.dll} on Windows) in order to
17162 be accessed by the directive @option{-l@var{xxx}} at link time.
17164 @node Installing a library
17165 @subsection Installing a library
17166 @cindex @code{ADA_PROJECT_PATH}
17167 @cindex @code{GPR_PROJECT_PATH}
17170 If you use project files, library installation is part of the library build
17171 process (@pxref{Installing a library with project files}).
17173 When project files are not an option, it is also possible, but not recommended,
17174 to install the library so that the sources needed to use the library are on the
17175 Ada source path and the ALI files & libraries be on the Ada Object path (see
17176 @ref{Search Paths and the Run-Time Library (RTL)}. Alternatively, the system
17177 administrator can place general-purpose libraries in the default compiler
17178 paths, by specifying the libraries' location in the configuration files
17179 @file{ada_source_path} and @file{ada_object_path}. These configuration files
17180 must be located in the GNAT installation tree at the same place as the gcc spec
17181 file. The location of the gcc spec file can be determined as follows:
17187 The configuration files mentioned above have a simple format: each line
17188 must contain one unique directory name.
17189 Those names are added to the corresponding path
17190 in their order of appearance in the file. The names can be either absolute
17191 or relative; in the latter case, they are relative to where theses files
17194 The files @file{ada_source_path} and @file{ada_object_path} might not be
17196 GNAT installation, in which case, GNAT will look for its run-time library in
17197 the directories @file{adainclude} (for the sources) and @file{adalib} (for the
17198 objects and @file{ALI} files). When the files exist, the compiler does not
17199 look in @file{adainclude} and @file{adalib}, and thus the
17200 @file{ada_source_path} file
17201 must contain the location for the GNAT run-time sources (which can simply
17202 be @file{adainclude}). In the same way, the @file{ada_object_path} file must
17203 contain the location for the GNAT run-time objects (which can simply
17206 You can also specify a new default path to the run-time library at compilation
17207 time with the switch @option{--RTS=rts-path}. You can thus choose / change
17208 the run-time library you want your program to be compiled with. This switch is
17209 recognized by @command{gcc}, @command{gnatmake}, @command{gnatbind},
17210 @command{gnatls}, @command{gnatfind} and @command{gnatxref}.
17212 It is possible to install a library before or after the standard GNAT
17213 library, by reordering the lines in the configuration files. In general, a
17214 library must be installed before the GNAT library if it redefines
17217 @node Using a library
17218 @subsection Using a library
17220 @noindent Once again, the project facility greatly simplifies the use of
17221 libraries. In this context, using a library is just a matter of adding a
17222 @code{with} clause in the user project. For instance, to make use of the
17223 library @code{My_Lib} shown in examples in earlier sections, you can
17226 @smallexample @c projectfile
17228 @b{project} My_Proj @b{is}
17233 Even if you have a third-party, non-Ada library, you can still use GNAT's
17234 Project Manager facility to provide a wrapper for it. For example, the
17235 following project, when @code{with}ed by your main project, will link with the
17236 third-party library @file{liba.a}:
17238 @smallexample @c projectfile
17240 @b{project} Liba @b{is}
17241 @b{for} Externally_Built @b{use} "true";
17242 @b{for} Source_Files @b{use} ();
17243 @b{for} Library_Dir @b{use} "lib";
17244 @b{for} Library_Name @b{use} "a";
17245 @b{for} Library_Kind @b{use} "static";
17249 This is an alternative to the use of @code{pragma Linker_Options}. It is
17250 especially interesting in the context of systems with several interdependent
17251 static libraries where finding a proper linker order is not easy and best be
17252 left to the tools having visibility over project dependence information.
17255 In order to use an Ada library manually, you need to make sure that this
17256 library is on both your source and object path
17257 (see @ref{Search Paths and the Run-Time Library (RTL)}
17258 and @ref{Search Paths for gnatbind}). Furthermore, when the objects are grouped
17259 in an archive or a shared library, you need to specify the desired
17260 library at link time.
17262 For example, you can use the library @file{mylib} installed in
17263 @file{/dir/my_lib_src} and @file{/dir/my_lib_obj} with the following commands:
17266 $ gnatmake -aI/dir/my_lib_src -aO/dir/my_lib_obj my_appl \
17271 This can be expressed more simply:
17276 when the following conditions are met:
17279 @file{/dir/my_lib_src} has been added by the user to the environment
17280 variable @env{ADA_INCLUDE_PATH}, or by the administrator to the file
17281 @file{ada_source_path}
17283 @file{/dir/my_lib_obj} has been added by the user to the environment
17284 variable @env{ADA_OBJECTS_PATH}, or by the administrator to the file
17285 @file{ada_object_path}
17287 a pragma @code{Linker_Options} has been added to one of the sources.
17290 @smallexample @c ada
17291 @b{pragma} Linker_Options ("-lmy_lib");
17295 Note that you may also load a library dynamically at
17296 run time given its filename, as illustrated in the GNAT @file{plugins} example
17297 in the directory @file{share/examples/gnat/plugins} within the GNAT
17300 @node Stand-alone Ada Libraries
17301 @section Stand-alone Ada Libraries
17302 @cindex Stand-alone library, building, using
17305 * Introduction to Stand-alone Libraries::
17306 * Building a Stand-alone Library::
17307 * Creating a Stand-alone Library to be used in a non-Ada context::
17308 * Restrictions in Stand-alone Libraries::
17311 @node Introduction to Stand-alone Libraries
17312 @subsection Introduction to Stand-alone Libraries
17315 A Stand-alone Library (abbreviated ``SAL'') is a library that contains the
17317 elaborate the Ada units that are included in the library. In contrast with
17318 an ordinary library, which consists of all sources, objects and @file{ALI}
17320 library, a SAL may specify a restricted subset of compilation units
17321 to serve as a library interface. In this case, the fully
17322 self-sufficient set of files will normally consist of an objects
17323 archive, the sources of interface units' specs, and the @file{ALI}
17324 files of interface units.
17325 If an interface spec contains a generic unit or an inlined subprogram,
17327 source must also be provided; if the units that must be provided in the source
17328 form depend on other units, the source and @file{ALI} files of those must
17331 The main purpose of a SAL is to minimize the recompilation overhead of client
17332 applications when a new version of the library is installed. Specifically,
17333 if the interface sources have not changed, client applications do not need to
17334 be recompiled. If, furthermore, a SAL is provided in the shared form and its
17335 version, controlled by @code{Library_Version} attribute, is not changed,
17336 then the clients do not need to be relinked.
17338 SALs also allow the library providers to minimize the amount of library source
17339 text exposed to the clients. Such ``information hiding'' might be useful or
17340 necessary for various reasons.
17342 Stand-alone libraries are also well suited to be used in an executable whose
17343 main routine is not written in Ada.
17345 @node Building a Stand-alone Library
17346 @subsection Building a Stand-alone Library
17349 GNAT's Project facility provides a simple way of building and installing
17350 stand-alone libraries; see @ref{Stand-alone Library Projects}.
17351 To be a Stand-alone Library Project, in addition to the two attributes
17352 that make a project a Library Project (@code{Library_Name} and
17353 @code{Library_Dir}; see @ref{Library Projects}), the attribute
17354 @code{Library_Interface} must be defined. For example:
17356 @smallexample @c projectfile
17358 @b{for} Library_Dir @b{use} "lib_dir";
17359 @b{for} Library_Name @b{use} "dummy";
17360 @b{for} Library_Interface @b{use} ("int1", "int1.child");
17365 Attribute @code{Library_Interface} has a non-empty string list value,
17366 each string in the list designating a unit contained in an immediate source
17367 of the project file.
17369 When a Stand-alone Library is built, first the binder is invoked to build
17370 a package whose name depends on the library name
17371 (@file{b~dummy.ads/b} in the example above).
17372 This binder-generated package includes initialization and
17373 finalization procedures whose
17374 names depend on the library name (@code{dummyinit} and @code{dummyfinal}
17376 above). The object corresponding to this package is included in the library.
17378 You must ensure timely (e.g., prior to any use of interfaces in the SAL)
17379 calling of these procedures if a static SAL is built, or if a shared SAL
17381 with the project-level attribute @code{Library_Auto_Init} set to
17384 For a Stand-Alone Library, only the @file{ALI} files of the Interface Units
17385 (those that are listed in attribute @code{Library_Interface}) are copied to
17386 the Library Directory. As a consequence, only the Interface Units may be
17387 imported from Ada units outside of the library. If other units are imported,
17388 the binding phase will fail.
17391 It is also possible to build an encapsulated library where not only
17392 the code to elaborate and finalize the library is embedded but also
17393 ensuring that the library is linked only against static
17394 libraries. So an encapsulated library only depends on system
17395 libraries, all other code, including the GNAT runtime, is embedded. To
17396 build an encapsulated library the attribute
17397 @code{Library_Standalone} must be set to @code{encapsulated}:
17399 @smallexample @c projectfile
17401 @b{for} Library_Dir @b{use} "lib_dir";
17402 @b{for} Library_Name @b{use} "dummy";
17403 @b{for} Library_Kind @b{use} "dynamic";
17404 @b{for} Library_Interface @b{use} ("int1", "int1.child");
17405 @b{for} Library_Standalone @b{use} "encapsulated";
17410 The default value for this attribute is @code{standard} in which case
17411 a stand-alone library is built.
17413 The attribute @code{Library_Src_Dir} may be specified for a
17414 Stand-Alone Library. @code{Library_Src_Dir} is a simple attribute that has a
17415 single string value. Its value must be the path (absolute or relative to the
17416 project directory) of an existing directory. This directory cannot be the
17417 object directory or one of the source directories, but it can be the same as
17418 the library directory. The sources of the Interface
17419 Units of the library that are needed by an Ada client of the library will be
17420 copied to the designated directory, called the Interface Copy directory.
17421 These sources include the specs of the Interface Units, but they may also
17422 include bodies and subunits, when pragmas @code{Inline} or @code{Inline_Always}
17423 are used, or when there is a generic unit in the spec. Before the sources
17424 are copied to the Interface Copy directory, an attempt is made to delete all
17425 files in the Interface Copy directory.
17427 Building stand-alone libraries by hand is somewhat tedious, but for those
17428 occasions when it is necessary here are the steps that you need to perform:
17431 Compile all library sources.
17434 Invoke the binder with the switch @option{-n} (No Ada main program),
17435 with all the @file{ALI} files of the interfaces, and
17436 with the switch @option{-L} to give specific names to the @code{init}
17437 and @code{final} procedures. For example:
17439 gnatbind -n int1.ali int2.ali -Lsal1
17443 Compile the binder generated file:
17449 Link the dynamic library with all the necessary object files,
17450 indicating to the linker the names of the @code{init} (and possibly
17451 @code{final}) procedures for automatic initialization (and finalization).
17452 The built library should be placed in a directory different from
17453 the object directory.
17456 Copy the @code{ALI} files of the interface to the library directory,
17457 add in this copy an indication that it is an interface to a SAL
17458 (i.e., add a word @option{SL} on the line in the @file{ALI} file that starts
17459 with letter ``P'') and make the modified copy of the @file{ALI} file
17464 Using SALs is not different from using other libraries
17465 (see @ref{Using a library}).
17467 @node Creating a Stand-alone Library to be used in a non-Ada context
17468 @subsection Creating a Stand-alone Library to be used in a non-Ada context
17471 It is easy to adapt the SAL build procedure discussed above for use of a SAL in
17474 The only extra step required is to ensure that library interface subprograms
17475 are compatible with the main program, by means of @code{pragma Export}
17476 or @code{pragma Convention}.
17478 Here is an example of simple library interface for use with C main program:
17480 @smallexample @c ada
17481 @b{package} My_Package @b{is}
17483 @b{procedure} Do_Something;
17484 @b{pragma} Export (C, Do_Something, "do_something");
17486 @b{procedure} Do_Something_Else;
17487 @b{pragma} Export (C, Do_Something_Else, "do_something_else");
17489 @b{end} My_Package;
17493 On the foreign language side, you must provide a ``foreign'' view of the
17494 library interface; remember that it should contain elaboration routines in
17495 addition to interface subprograms.
17497 The example below shows the content of @code{mylib_interface.h} (note
17498 that there is no rule for the naming of this file, any name can be used)
17500 /* the library elaboration procedure */
17501 extern void mylibinit (void);
17503 /* the library finalization procedure */
17504 extern void mylibfinal (void);
17506 /* the interface exported by the library */
17507 extern void do_something (void);
17508 extern void do_something_else (void);
17512 Libraries built as explained above can be used from any program, provided
17513 that the elaboration procedures (named @code{mylibinit} in the previous
17514 example) are called before the library services are used. Any number of
17515 libraries can be used simultaneously, as long as the elaboration
17516 procedure of each library is called.
17518 Below is an example of a C program that uses the @code{mylib} library.
17521 #include "mylib_interface.h"
17526 /* First, elaborate the library before using it */
17529 /* Main program, using the library exported entities */
17531 do_something_else ();
17533 /* Library finalization at the end of the program */
17540 Note that invoking any library finalization procedure generated by
17541 @code{gnatbind} shuts down the Ada run-time environment.
17543 finalization of all Ada libraries must be performed at the end of the program.
17544 No call to these libraries or to the Ada run-time library should be made
17545 after the finalization phase.
17547 @node Restrictions in Stand-alone Libraries
17548 @subsection Restrictions in Stand-alone Libraries
17551 The pragmas listed below should be used with caution inside libraries,
17552 as they can create incompatibilities with other Ada libraries:
17554 @item pragma @code{Locking_Policy}
17555 @item pragma @code{Partition_Elaboration_Policy}
17556 @item pragma @code{Queuing_Policy}
17557 @item pragma @code{Task_Dispatching_Policy}
17558 @item pragma @code{Unreserve_All_Interrupts}
17562 When using a library that contains such pragmas, the user must make sure
17563 that all libraries use the same pragmas with the same values. Otherwise,
17564 @code{Program_Error} will
17565 be raised during the elaboration of the conflicting
17566 libraries. The usage of these pragmas and its consequences for the user
17567 should therefore be well documented.
17569 Similarly, the traceback in the exception occurrence mechanism should be
17570 enabled or disabled in a consistent manner across all libraries.
17571 Otherwise, Program_Error will be raised during the elaboration of the
17572 conflicting libraries.
17574 If the @code{Version} or @code{Body_Version}
17575 attributes are used inside a library, then you need to
17576 perform a @code{gnatbind} step that specifies all @file{ALI} files in all
17577 libraries, so that version identifiers can be properly computed.
17578 In practice these attributes are rarely used, so this is unlikely
17579 to be a consideration.
17581 @node Rebuilding the GNAT Run-Time Library
17582 @section Rebuilding the GNAT Run-Time Library
17583 @cindex GNAT Run-Time Library, rebuilding
17584 @cindex Building the GNAT Run-Time Library
17585 @cindex Rebuilding the GNAT Run-Time Library
17586 @cindex Run-Time Library, rebuilding
17589 It may be useful to recompile the GNAT library in various contexts, the
17590 most important one being the use of partition-wide configuration pragmas
17591 such as @code{Normalize_Scalars}. A special Makefile called
17592 @code{Makefile.adalib} is provided to that effect and can be found in
17593 the directory containing the GNAT library. The location of this
17594 directory depends on the way the GNAT environment has been installed and can
17595 be determined by means of the command:
17602 The last entry in the object search path usually contains the
17603 gnat library. This Makefile contains its own documentation and in
17604 particular the set of instructions needed to rebuild a new library and
17607 @node Using the GNU make Utility
17608 @chapter Using the GNU @code{make} Utility
17612 This chapter offers some examples of makefiles that solve specific
17613 problems. It does not explain how to write a makefile (@pxref{Top,, GNU
17614 make, make, GNU @code{make}}), nor does it try to replace the
17615 @command{gnatmake} utility (@pxref{The GNAT Make Program gnatmake}).
17617 All the examples in this section are specific to the GNU version of
17618 make. Although @command{make} is a standard utility, and the basic language
17619 is the same, these examples use some advanced features found only in
17623 * Using gnatmake in a Makefile::
17624 * Automatically Creating a List of Directories::
17625 * Generating the Command Line Switches::
17626 * Overcoming Command Line Length Limits::
17629 @node Using gnatmake in a Makefile
17630 @section Using gnatmake in a Makefile
17635 Complex project organizations can be handled in a very powerful way by
17636 using GNU make combined with gnatmake. For instance, here is a Makefile
17637 which allows you to build each subsystem of a big project into a separate
17638 shared library. Such a makefile allows you to significantly reduce the link
17639 time of very big applications while maintaining full coherence at
17640 each step of the build process.
17642 The list of dependencies are handled automatically by
17643 @command{gnatmake}. The Makefile is simply used to call gnatmake in each of
17644 the appropriate directories.
17646 Note that you should also read the example on how to automatically
17647 create the list of directories
17648 (@pxref{Automatically Creating a List of Directories})
17649 which might help you in case your project has a lot of subdirectories.
17654 @font@heightrm=cmr8
17657 ## This Makefile is intended to be used with the following directory
17659 ## - The sources are split into a series of csc (computer software components)
17660 ## Each of these csc is put in its own directory.
17661 ## Their name are referenced by the directory names.
17662 ## They will be compiled into shared library (although this would also work
17663 ## with static libraries
17664 ## - The main program (and possibly other packages that do not belong to any
17665 ## csc is put in the top level directory (where the Makefile is).
17666 ## toplevel_dir __ first_csc (sources) __ lib (will contain the library)
17667 ## \_ second_csc (sources) __ lib (will contain the library)
17669 ## Although this Makefile is build for shared library, it is easy to modify
17670 ## to build partial link objects instead (modify the lines with -shared and
17673 ## With this makefile, you can change any file in the system or add any new
17674 ## file, and everything will be recompiled correctly (only the relevant shared
17675 ## objects will be recompiled, and the main program will be re-linked).
17677 # The list of computer software component for your project. This might be
17678 # generated automatically.
17681 # Name of the main program (no extension)
17684 # If we need to build objects with -fPIC, uncomment the following line
17687 # The following variable should give the directory containing libgnat.so
17688 # You can get this directory through 'gnatls -v'. This is usually the last
17689 # directory in the Object_Path.
17692 # The directories for the libraries
17693 # (This macro expands the list of CSC to the list of shared libraries, you
17694 # could simply use the expanded form:
17695 # LIB_DIR=aa/lib/libaa.so bb/lib/libbb.so cc/lib/libcc.so
17696 LIB_DIR=$@{foreach dir,$@{CSC_LIST@},$@{dir@}/lib/lib$@{dir@}.so@}
17698 $@{MAIN@}: objects $@{LIB_DIR@}
17699 gnatbind $@{MAIN@} $@{CSC_LIST:%=-aO%/lib@} -shared
17700 gnatlink $@{MAIN@} $@{CSC_LIST:%=-l%@}
17703 # recompile the sources
17704 gnatmake -c -i $@{MAIN@}.adb $@{NEED_FPIC@} $@{CSC_LIST:%=-I%@}
17706 # Note: In a future version of GNAT, the following commands will be simplified
17707 # by a new tool, gnatmlib
17709 mkdir -p $@{dir $@@ @}
17710 cd $@{dir $@@ @} && gcc -shared -o $@{notdir $@@ @} ../*.o -L$@{GLIB@} -lgnat
17711 cd $@{dir $@@ @} && cp -f ../*.ali .
17713 # The dependencies for the modules
17714 # Note that we have to force the expansion of *.o, since in some cases
17715 # make won't be able to do it itself.
17716 aa/lib/libaa.so: $@{wildcard aa/*.o@}
17717 bb/lib/libbb.so: $@{wildcard bb/*.o@}
17718 cc/lib/libcc.so: $@{wildcard cc/*.o@}
17720 # Make sure all of the shared libraries are in the path before starting the
17723 LD_LIBRARY_PATH=`pwd`/aa/lib:`pwd`/bb/lib:`pwd`/cc/lib ./$@{MAIN@}
17726 $@{RM@} -rf $@{CSC_LIST:%=%/lib@}
17727 $@{RM@} $@{CSC_LIST:%=%/*.ali@}
17728 $@{RM@} $@{CSC_LIST:%=%/*.o@}
17729 $@{RM@} *.o *.ali $@{MAIN@}
17732 @node Automatically Creating a List of Directories
17733 @section Automatically Creating a List of Directories
17736 In most makefiles, you will have to specify a list of directories, and
17737 store it in a variable. For small projects, it is often easier to
17738 specify each of them by hand, since you then have full control over what
17739 is the proper order for these directories, which ones should be
17742 However, in larger projects, which might involve hundreds of
17743 subdirectories, it might be more convenient to generate this list
17746 The example below presents two methods. The first one, although less
17747 general, gives you more control over the list. It involves wildcard
17748 characters, that are automatically expanded by @command{make}. Its
17749 shortcoming is that you need to explicitly specify some of the
17750 organization of your project, such as for instance the directory tree
17751 depth, whether some directories are found in a separate tree, @enddots{}
17753 The second method is the most general one. It requires an external
17754 program, called @command{find}, which is standard on all Unix systems. All
17755 the directories found under a given root directory will be added to the
17761 @font@heightrm=cmr8
17764 # The examples below are based on the following directory hierarchy:
17765 # All the directories can contain any number of files
17766 # ROOT_DIRECTORY -> a -> aa -> aaa
17769 # -> b -> ba -> baa
17772 # This Makefile creates a variable called DIRS, that can be reused any time
17773 # you need this list (see the other examples in this section)
17775 # The root of your project's directory hierarchy
17779 # First method: specify explicitly the list of directories
17780 # This allows you to specify any subset of all the directories you need.
17783 DIRS := a/aa/ a/ab/ b/ba/
17786 # Second method: use wildcards
17787 # Note that the argument(s) to wildcard below should end with a '/'.
17788 # Since wildcards also return file names, we have to filter them out
17789 # to avoid duplicate directory names.
17790 # We thus use make's @code{dir} and @code{sort} functions.
17791 # It sets DIRs to the following value (note that the directories aaa and baa
17792 # are not given, unless you change the arguments to wildcard).
17793 # DIRS= ./a/a/ ./b/ ./a/aa/ ./a/ab/ ./a/ac/ ./b/ba/ ./b/bb/ ./b/bc/
17796 DIRS := $@{sort $@{dir $@{wildcard $@{ROOT_DIRECTORY@}/*/
17797 $@{ROOT_DIRECTORY@}/*/*/@}@}@}
17800 # Third method: use an external program
17801 # This command is much faster if run on local disks, avoiding NFS slowdowns.
17802 # This is the most complete command: it sets DIRs to the following value:
17803 # DIRS= ./a ./a/aa ./a/aa/aaa ./a/ab ./a/ac ./b ./b/ba ./b/ba/baa ./b/bb ./b/bc
17806 DIRS := $@{shell find $@{ROOT_DIRECTORY@} -type d -print@}
17810 @node Generating the Command Line Switches
17811 @section Generating the Command Line Switches
17814 Once you have created the list of directories as explained in the
17815 previous section (@pxref{Automatically Creating a List of Directories}),
17816 you can easily generate the command line arguments to pass to gnatmake.
17818 For the sake of completeness, this example assumes that the source path
17819 is not the same as the object path, and that you have two separate lists
17823 # see "Automatically creating a list of directories" to create
17828 GNATMAKE_SWITCHES := $@{patsubst %,-aI%,$@{SOURCE_DIRS@}@}
17829 GNATMAKE_SWITCHES += $@{patsubst %,-aO%,$@{OBJECT_DIRS@}@}
17832 gnatmake $@{GNATMAKE_SWITCHES@} main_unit
17835 @node Overcoming Command Line Length Limits
17836 @section Overcoming Command Line Length Limits
17839 One problem that might be encountered on big projects is that many
17840 operating systems limit the length of the command line. It is thus hard to give
17841 gnatmake the list of source and object directories.
17843 This example shows how you can set up environment variables, which will
17844 make @command{gnatmake} behave exactly as if the directories had been
17845 specified on the command line, but have a much higher length limit (or
17846 even none on most systems).
17848 It assumes that you have created a list of directories in your Makefile,
17849 using one of the methods presented in
17850 @ref{Automatically Creating a List of Directories}.
17851 For the sake of completeness, we assume that the object
17852 path (where the ALI files are found) is different from the sources patch.
17854 Note a small trick in the Makefile below: for efficiency reasons, we
17855 create two temporary variables (SOURCE_LIST and OBJECT_LIST), that are
17856 expanded immediately by @code{make}. This way we overcome the standard
17857 make behavior which is to expand the variables only when they are
17860 On Windows, if you are using the standard Windows command shell, you must
17861 replace colons with semicolons in the assignments to these variables.
17866 @font@heightrm=cmr8
17869 # In this example, we create both ADA_INCLUDE_PATH and ADA_OBJECTS_PATH.
17870 # This is the same thing as putting the -I arguments on the command line.
17871 # (the equivalent of using -aI on the command line would be to define
17872 # only ADA_INCLUDE_PATH, the equivalent of -aO is ADA_OBJECTS_PATH).
17873 # You can of course have different values for these variables.
17875 # Note also that we need to keep the previous values of these variables, since
17876 # they might have been set before running 'make' to specify where the GNAT
17877 # library is installed.
17879 # see "Automatically creating a list of directories" to create these
17885 space:=$@{empty@} $@{empty@}
17886 SOURCE_LIST := $@{subst $@{space@},:,$@{SOURCE_DIRS@}@}
17887 OBJECT_LIST := $@{subst $@{space@},:,$@{OBJECT_DIRS@}@}
17888 ADA_INCLUDE_PATH += $@{SOURCE_LIST@}
17889 ADA_OBJECTS_PATH += $@{OBJECT_LIST@}
17890 export ADA_INCLUDE_PATH
17891 export ADA_OBJECTS_PATH
17897 @node Memory Management Issues
17898 @chapter Memory Management Issues
17901 This chapter describes some useful memory pools provided in the GNAT library
17902 and in particular the GNAT Debug Pool facility, which can be used to detect
17903 incorrect uses of access values (including ``dangling references'').
17904 @ifclear FSFEDITION
17905 It also describes the @command{gnatmem} tool, which can be used to track down
17910 * Some Useful Memory Pools::
17911 * The GNAT Debug Pool Facility::
17912 @ifclear FSFEDITION
17913 * The gnatmem Tool::
17917 @node Some Useful Memory Pools
17918 @section Some Useful Memory Pools
17919 @findex Memory Pool
17920 @cindex storage, pool
17923 The @code{System.Pool_Global} package offers the Unbounded_No_Reclaim_Pool
17924 storage pool. Allocations use the standard system call @code{malloc} while
17925 deallocations use the standard system call @code{free}. No reclamation is
17926 performed when the pool goes out of scope. For performance reasons, the
17927 standard default Ada allocators/deallocators do not use any explicit storage
17928 pools but if they did, they could use this storage pool without any change in
17929 behavior. That is why this storage pool is used when the user
17930 manages to make the default implicit allocator explicit as in this example:
17931 @smallexample @c ada
17932 @b{type} T1 @b{is} @b{access} Something;
17933 --@i{ no Storage pool is defined for T2}
17934 @b{type} T2 @b{is} @b{access} Something_Else;
17935 @b{for} T2'Storage_Pool @b{use} T1'Storage_Pool;
17936 --@i{ the above is equivalent to}
17937 @b{for} T2'Storage_Pool @b{use} System.Pool_Global.Global_Pool_Object;
17941 The @code{System.Pool_Local} package offers the Unbounded_Reclaim_Pool storage
17942 pool. The allocation strategy is similar to @code{Pool_Local}'s
17943 except that the all
17944 storage allocated with this pool is reclaimed when the pool object goes out of
17945 scope. This pool provides a explicit mechanism similar to the implicit one
17946 provided by several Ada 83 compilers for allocations performed through a local
17947 access type and whose purpose was to reclaim memory when exiting the
17948 scope of a given local access. As an example, the following program does not
17949 leak memory even though it does not perform explicit deallocation:
17951 @smallexample @c ada
17952 @b{with} System.Pool_Local;
17953 @b{procedure} Pooloc1 @b{is}
17954 @b{procedure} Internal @b{is}
17955 @b{type} A @b{is} @b{access} Integer;
17956 X : System.Pool_Local.Unbounded_Reclaim_Pool;
17957 @b{for} A'Storage_Pool @b{use} X;
17960 @b{for} I @b{in} 1 .. 50 @b{loop}
17961 v := @b{new} Integer;
17965 @b{for} I @b{in} 1 .. 100 @b{loop}
17972 The @code{System.Pool_Size} package implements the Stack_Bounded_Pool used when
17973 @code{Storage_Size} is specified for an access type.
17974 The whole storage for the pool is
17975 allocated at once, usually on the stack at the point where the access type is
17976 elaborated. It is automatically reclaimed when exiting the scope where the
17977 access type is defined. This package is not intended to be used directly by the
17978 user and it is implicitly used for each such declaration:
17980 @smallexample @c ada
17981 @b{type} T1 @b{is} @b{access} Something;
17982 @b{for} T1'Storage_Size @b{use} 10_000;
17985 @node The GNAT Debug Pool Facility
17986 @section The GNAT Debug Pool Facility
17988 @cindex storage, pool, memory corruption
17991 The use of unchecked deallocation and unchecked conversion can easily
17992 lead to incorrect memory references. The problems generated by such
17993 references are usually difficult to tackle because the symptoms can be
17994 very remote from the origin of the problem. In such cases, it is
17995 very helpful to detect the problem as early as possible. This is the
17996 purpose of the Storage Pool provided by @code{GNAT.Debug_Pools}.
17998 In order to use the GNAT specific debugging pool, the user must
17999 associate a debug pool object with each of the access types that may be
18000 related to suspected memory problems. See Ada Reference Manual 13.11.
18001 @smallexample @c ada
18002 @b{type} Ptr @b{is} @b{access} Some_Type;
18003 Pool : GNAT.Debug_Pools.Debug_Pool;
18004 @b{for} Ptr'Storage_Pool @b{use} Pool;
18008 @code{GNAT.Debug_Pools} is derived from a GNAT-specific kind of
18009 pool: the @code{Checked_Pool}. Such pools, like standard Ada storage pools,
18010 allow the user to redefine allocation and deallocation strategies. They
18011 also provide a checkpoint for each dereference, through the use of
18012 the primitive operation @code{Dereference} which is implicitly called at
18013 each dereference of an access value.
18015 Once an access type has been associated with a debug pool, operations on
18016 values of the type may raise four distinct exceptions,
18017 which correspond to four potential kinds of memory corruption:
18020 @code{GNAT.Debug_Pools.Accessing_Not_Allocated_Storage}
18022 @code{GNAT.Debug_Pools.Accessing_Deallocated_Storage}
18024 @code{GNAT.Debug_Pools.Freeing_Not_Allocated_Storage}
18026 @code{GNAT.Debug_Pools.Freeing_Deallocated_Storage }
18030 For types associated with a Debug_Pool, dynamic allocation is performed using
18031 the standard GNAT allocation routine. References to all allocated chunks of
18032 memory are kept in an internal dictionary. Several deallocation strategies are
18033 provided, whereupon the user can choose to release the memory to the system,
18034 keep it allocated for further invalid access checks, or fill it with an easily
18035 recognizable pattern for debug sessions. The memory pattern is the old IBM
18036 hexadecimal convention: @code{16#DEADBEEF#}.
18038 See the documentation in the file g-debpoo.ads for more information on the
18039 various strategies.
18041 Upon each dereference, a check is made that the access value denotes a
18042 properly allocated memory location. Here is a complete example of use of
18043 @code{Debug_Pools}, that includes typical instances of memory corruption:
18044 @smallexample @c ada
18048 @b{with} Gnat.Io; @b{use} Gnat.Io;
18049 @b{with} Unchecked_Deallocation;
18050 @b{with} Unchecked_Conversion;
18051 @b{with} GNAT.Debug_Pools;
18052 @b{with} System.Storage_Elements;
18053 @b{with} Ada.Exceptions; @b{use} Ada.Exceptions;
18054 @b{procedure} Debug_Pool_Test @b{is}
18056 @b{type} T @b{is} @b{access} Integer;
18057 @b{type} U @b{is} @b{access} @b{all} T;
18059 P : GNAT.Debug_Pools.Debug_Pool;
18060 @b{for} T'Storage_Pool @b{use} P;
18062 @b{procedure} Free @b{is} @b{new} Unchecked_Deallocation (Integer, T);
18063 @b{function} UC @b{is} @b{new} Unchecked_Conversion (U, T);
18064 A, B : @b{aliased} T;
18066 @b{procedure} Info @b{is} @b{new} GNAT.Debug_Pools.Print_Info(Put_Line);
18070 A := @b{new} Integer;
18071 B := @b{new} Integer;
18076 Put_Line (Integer'Image(B.@b{all}));
18078 @b{when} E : @b{others} => Put_Line ("raised: " & Exception_Name (E));
18083 @b{when} E : @b{others} => Put_Line ("raised: " & Exception_Name (E));
18087 Put_Line (Integer'Image(B.@b{all}));
18089 @b{when} E : @b{others} => Put_Line ("raised: " & Exception_Name (E));
18094 @b{when} E : @b{others} => Put_Line ("raised: " & Exception_Name (E));
18097 @b{end} Debug_Pool_Test;
18101 The debug pool mechanism provides the following precise diagnostics on the
18102 execution of this erroneous program:
18105 Total allocated bytes : 0
18106 Total deallocated bytes : 0
18107 Current Water Mark: 0
18111 Total allocated bytes : 8
18112 Total deallocated bytes : 0
18113 Current Water Mark: 8
18116 raised: GNAT.DEBUG_POOLS.ACCESSING_DEALLOCATED_STORAGE
18117 raised: GNAT.DEBUG_POOLS.FREEING_DEALLOCATED_STORAGE
18118 raised: GNAT.DEBUG_POOLS.ACCESSING_NOT_ALLOCATED_STORAGE
18119 raised: GNAT.DEBUG_POOLS.FREEING_NOT_ALLOCATED_STORAGE
18121 Total allocated bytes : 8
18122 Total deallocated bytes : 4
18123 Current Water Mark: 4
18127 @ifclear FSFEDITION
18128 @node The gnatmem Tool
18129 @section The @command{gnatmem} Tool
18133 The @code{gnatmem} utility monitors dynamic allocation and
18134 deallocation activity in a program, and displays information about
18135 incorrect deallocations and possible sources of memory leaks.
18136 It is designed to work in association with a static runtime library
18137 only and in this context provides three types of information:
18140 General information concerning memory management, such as the total
18141 number of allocations and deallocations, the amount of allocated
18142 memory and the high water mark, i.e.@: the largest amount of allocated
18143 memory in the course of program execution.
18146 Backtraces for all incorrect deallocations, that is to say deallocations
18147 which do not correspond to a valid allocation.
18150 Information on each allocation that is potentially the origin of a memory
18155 * Running gnatmem::
18156 * Switches for gnatmem::
18157 * Example of gnatmem Usage::
18160 @node Running gnatmem
18161 @subsection Running @code{gnatmem}
18164 @code{gnatmem} makes use of the output created by the special version of
18165 allocation and deallocation routines that record call information. This allows
18166 it to obtain accurate dynamic memory usage history at a minimal cost to the
18167 execution speed. Note however, that @code{gnatmem} is not supported on all
18168 platforms (currently, it is supported on AIX, HP-UX, GNU/Linux, Solaris and
18169 Windows NT/2000/XP (x86).
18172 The @code{gnatmem} command has the form
18175 @c $ gnatmem @ovar{switches} user_program
18176 @c Expanding @ovar macro inline (explanation in macro def comments)
18177 $ gnatmem @r{[}@var{switches}@r{]} @var{user_program}
18181 The program must have been linked with the instrumented version of the
18182 allocation and deallocation routines. This is done by linking with the
18183 @file{libgmem.a} library. For correct symbolic backtrace information,
18184 the user program should be compiled with debugging options
18185 (see @ref{Switches for gcc}). For example to build @file{my_program}:
18188 $ gnatmake -g my_program -largs -lgmem
18192 As library @file{libgmem.a} contains an alternate body for package
18193 @code{System.Memory}, @file{s-memory.adb} should not be compiled and linked
18194 when an executable is linked with library @file{libgmem.a}. It is then not
18195 recommended to use @command{gnatmake} with switch @option{-a}.
18198 When @file{my_program} is executed, the file @file{gmem.out} is produced.
18199 This file contains information about all allocations and deallocations
18200 performed by the program. It is produced by the instrumented allocations and
18201 deallocations routines and will be used by @code{gnatmem}.
18203 In order to produce symbolic backtrace information for allocations and
18204 deallocations performed by the GNAT run-time library, you need to use a
18205 version of that library that has been compiled with the @option{-g} switch
18206 (see @ref{Rebuilding the GNAT Run-Time Library}).
18208 Gnatmem must be supplied with the @file{gmem.out} file and the executable to
18209 examine. If the location of @file{gmem.out} file was not explicitly supplied by
18210 @option{-i} switch, gnatmem will assume that this file can be found in the
18211 current directory. For example, after you have executed @file{my_program},
18212 @file{gmem.out} can be analyzed by @code{gnatmem} using the command:
18215 $ gnatmem my_program
18219 This will produce the output with the following format:
18221 *************** debut cc
18223 $ gnatmem my_program
18227 Total number of allocations : 45
18228 Total number of deallocations : 6
18229 Final Water Mark (non freed mem) : 11.29 Kilobytes
18230 High Water Mark : 11.40 Kilobytes
18235 Allocation Root # 2
18236 -------------------
18237 Number of non freed allocations : 11
18238 Final Water Mark (non freed mem) : 1.16 Kilobytes
18239 High Water Mark : 1.27 Kilobytes
18241 my_program.adb:23 my_program.alloc
18247 The first block of output gives general information. In this case, the
18248 Ada construct ``@code{@b{new}}'' was executed 45 times, and only 6 calls to an
18249 Unchecked_Deallocation routine occurred.
18252 Subsequent paragraphs display information on all allocation roots.
18253 An allocation root is a specific point in the execution of the program
18254 that generates some dynamic allocation, such as a ``@code{@b{new}}''
18255 construct. This root is represented by an execution backtrace (or subprogram
18256 call stack). By default the backtrace depth for allocations roots is 1, so
18257 that a root corresponds exactly to a source location. The backtrace can
18258 be made deeper, to make the root more specific.
18260 @node Switches for gnatmem
18261 @subsection Switches for @code{gnatmem}
18264 @code{gnatmem} recognizes the following switches:
18269 @cindex @option{-q} (@code{gnatmem})
18270 Quiet. Gives the minimum output needed to identify the origin of the
18271 memory leaks. Omits statistical information.
18274 @cindex @var{N} (@code{gnatmem})
18275 N is an integer literal (usually between 1 and 10) which controls the
18276 depth of the backtraces defining allocation root. The default value for
18277 N is 1. The deeper the backtrace, the more precise the localization of
18278 the root. Note that the total number of roots can depend on this
18279 parameter. This parameter must be specified @emph{before} the name of the
18280 executable to be analyzed, to avoid ambiguity.
18283 @cindex @option{-b} (@code{gnatmem})
18284 This switch has the same effect as just depth parameter.
18286 @item -i @var{file}
18287 @cindex @option{-i} (@code{gnatmem})
18288 Do the @code{gnatmem} processing starting from @file{file}, rather than
18289 @file{gmem.out} in the current directory.
18292 @cindex @option{-m} (@code{gnatmem})
18293 This switch causes @code{gnatmem} to mask the allocation roots that have less
18294 than n leaks. The default value is 1. Specifying the value of 0 will allow
18295 examination of even the roots that did not result in leaks.
18298 @cindex @option{-s} (@code{gnatmem})
18299 This switch causes @code{gnatmem} to sort the allocation roots according to the
18300 specified order of sort criteria, each identified by a single letter. The
18301 currently supported criteria are @code{n, h, w} standing respectively for
18302 number of unfreed allocations, high watermark, and final watermark
18303 corresponding to a specific root. The default order is @code{nwh}.
18306 @cindex @option{-t} (@code{gnatmem})
18307 This switch causes memory allocated size to be always output in bytes.
18308 Default @code{gnatmem} behavior is to show memory sizes less then 1 kilobyte
18309 in bytes, from 1 kilobyte till 1 megabyte in kilobytes and the rest in
18314 @node Example of gnatmem Usage
18315 @subsection Example of @code{gnatmem} Usage
18318 The following example shows the use of @code{gnatmem}
18319 on a simple memory-leaking program.
18320 Suppose that we have the following Ada program:
18322 @smallexample @c ada
18325 @b{with} Unchecked_Deallocation;
18326 @b{procedure} Test_Gm @b{is}
18328 @b{type} T @b{is} @b{array} (1..1000) @b{of} Integer;
18329 @b{type} Ptr @b{is} @b{access} T;
18330 @b{procedure} Free @b{is} @b{new} Unchecked_Deallocation (T, Ptr);
18333 @b{procedure} My_Alloc @b{is}
18338 @b{procedure} My_DeAlloc @b{is}
18342 @b{end} My_DeAlloc;
18346 @b{for} I @b{in} 1 .. 5 @b{loop}
18347 @b{for} J @b{in} I .. 5 @b{loop}
18358 The program needs to be compiled with debugging option and linked with
18359 @code{gmem} library:
18362 $ gnatmake -g test_gm -largs -lgmem
18366 Then we execute the program as usual:
18373 Then @code{gnatmem} is invoked simply with
18379 which produces the following output (result may vary on different platforms):
18384 Total number of allocations : 18
18385 Total number of deallocations : 5
18386 Final Water Mark (non freed mem) : 53.00 Kilobytes
18387 High Water Mark : 56.90 Kilobytes
18389 Allocation Root # 1
18390 -------------------
18391 Number of non freed allocations : 11
18392 Final Water Mark (non freed mem) : 42.97 Kilobytes
18393 High Water Mark : 46.88 Kilobytes
18395 test_gm.adb:11 test_gm.my_alloc
18397 Allocation Root # 2
18398 -------------------
18399 Number of non freed allocations : 1
18400 Final Water Mark (non freed mem) : 10.02 Kilobytes
18401 High Water Mark : 10.02 Kilobytes
18403 s-secsta.adb:81 system.secondary_stack.ss_init
18405 Allocation Root # 3
18406 -------------------
18407 Number of non freed allocations : 1
18408 Final Water Mark (non freed mem) : 12 Bytes
18409 High Water Mark : 12 Bytes
18411 s-secsta.adb:181 system.secondary_stack.ss_init
18415 Note that the GNAT run time contains itself a certain number of
18416 allocations that have no corresponding deallocation,
18417 as shown here for root #2 and root
18418 #3. This is a normal behavior when the number of non-freed allocations
18419 is one, it allocates dynamic data structures that the run time needs for
18420 the complete lifetime of the program. Note also that there is only one
18421 allocation root in the user program with a single line back trace:
18422 test_gm.adb:11 test_gm.my_alloc, whereas a careful analysis of the
18423 program shows that 'My_Alloc' is called at 2 different points in the
18424 source (line 21 and line 24). If those two allocation roots need to be
18425 distinguished, the backtrace depth parameter can be used:
18428 $ gnatmem 3 test_gm
18432 which will give the following output:
18437 Total number of allocations : 18
18438 Total number of deallocations : 5
18439 Final Water Mark (non freed mem) : 53.00 Kilobytes
18440 High Water Mark : 56.90 Kilobytes
18442 Allocation Root # 1
18443 -------------------
18444 Number of non freed allocations : 10
18445 Final Water Mark (non freed mem) : 39.06 Kilobytes
18446 High Water Mark : 42.97 Kilobytes
18448 test_gm.adb:11 test_gm.my_alloc
18449 test_gm.adb:24 test_gm
18450 b_test_gm.c:52 main
18452 Allocation Root # 2
18453 -------------------
18454 Number of non freed allocations : 1
18455 Final Water Mark (non freed mem) : 10.02 Kilobytes
18456 High Water Mark : 10.02 Kilobytes
18458 s-secsta.adb:81 system.secondary_stack.ss_init
18459 s-secsta.adb:283 <system__secondary_stack___elabb>
18460 b_test_gm.c:33 adainit
18462 Allocation Root # 3
18463 -------------------
18464 Number of non freed allocations : 1
18465 Final Water Mark (non freed mem) : 3.91 Kilobytes
18466 High Water Mark : 3.91 Kilobytes
18468 test_gm.adb:11 test_gm.my_alloc
18469 test_gm.adb:21 test_gm
18470 b_test_gm.c:52 main
18472 Allocation Root # 4
18473 -------------------
18474 Number of non freed allocations : 1
18475 Final Water Mark (non freed mem) : 12 Bytes
18476 High Water Mark : 12 Bytes
18478 s-secsta.adb:181 system.secondary_stack.ss_init
18479 s-secsta.adb:283 <system__secondary_stack___elabb>
18480 b_test_gm.c:33 adainit
18484 The allocation root #1 of the first example has been split in 2 roots #1
18485 and #3 thanks to the more precise associated backtrace.
18488 @node Stack Related Facilities
18489 @chapter Stack Related Facilities
18492 This chapter describes some useful tools associated with stack
18493 checking and analysis. In
18494 particular, it deals with dynamic and static stack usage measurements.
18497 * Stack Overflow Checking::
18498 * Static Stack Usage Analysis::
18499 * Dynamic Stack Usage Analysis::
18502 @node Stack Overflow Checking
18503 @section Stack Overflow Checking
18504 @cindex Stack Overflow Checking
18505 @cindex -fstack-check
18508 For most operating systems, @command{gcc} does not perform stack overflow
18509 checking by default. This means that if the main environment task or
18510 some other task exceeds the available stack space, then unpredictable
18511 behavior will occur. Most native systems offer some level of protection by
18512 adding a guard page at the end of each task stack. This mechanism is usually
18513 not enough for dealing properly with stack overflow situations because
18514 a large local variable could ``jump'' above the guard page.
18515 Furthermore, when the
18516 guard page is hit, there may not be any space left on the stack for executing
18517 the exception propagation code. Enabling stack checking avoids
18520 To activate stack checking, compile all units with the gcc option
18521 @option{-fstack-check}. For example:
18524 gcc -c -fstack-check package1.adb
18528 Units compiled with this option will generate extra instructions to check
18529 that any use of the stack (for procedure calls or for declaring local
18530 variables in declare blocks) does not exceed the available stack space.
18531 If the space is exceeded, then a @code{Storage_Error} exception is raised.
18533 For declared tasks, the stack size is controlled by the size
18534 given in an applicable @code{Storage_Size} pragma or by the value specified
18535 at bind time with @option{-d} (@pxref{Switches for gnatbind}) or is set to
18536 the default size as defined in the GNAT runtime otherwise.
18538 For the environment task, the stack size depends on
18539 system defaults and is unknown to the compiler. Stack checking
18540 may still work correctly if a fixed
18541 size stack is allocated, but this cannot be guaranteed.
18542 To ensure that a clean exception is signalled for stack
18543 overflow, set the environment variable
18544 @env{GNAT_STACK_LIMIT} to indicate the maximum
18545 stack area that can be used, as in:
18546 @cindex GNAT_STACK_LIMIT
18549 SET GNAT_STACK_LIMIT 1600
18553 The limit is given in kilobytes, so the above declaration would
18554 set the stack limit of the environment task to 1.6 megabytes.
18555 Note that the only purpose of this usage is to limit the amount
18556 of stack used by the environment task. If it is necessary to
18557 increase the amount of stack for the environment task, then this
18558 is an operating systems issue, and must be addressed with the
18559 appropriate operating systems commands.
18561 @node Static Stack Usage Analysis
18562 @section Static Stack Usage Analysis
18563 @cindex Static Stack Usage Analysis
18564 @cindex -fstack-usage
18567 A unit compiled with @option{-fstack-usage} will generate an extra file
18569 the maximum amount of stack used, on a per-function basis.
18570 The file has the same
18571 basename as the target object file with a @file{.su} extension.
18572 Each line of this file is made up of three fields:
18576 The name of the function.
18580 One or more qualifiers: @code{static}, @code{dynamic}, @code{bounded}.
18583 The second field corresponds to the size of the known part of the function
18586 The qualifier @code{static} means that the function frame size
18588 It usually means that all local variables have a static size.
18589 In this case, the second field is a reliable measure of the function stack
18592 The qualifier @code{dynamic} means that the function frame size is not static.
18593 It happens mainly when some local variables have a dynamic size. When this
18594 qualifier appears alone, the second field is not a reliable measure
18595 of the function stack analysis. When it is qualified with @code{bounded}, it
18596 means that the second field is a reliable maximum of the function stack
18599 A unit compiled with @option{-Wstack-usage} will issue a warning for each
18600 subprogram whose stack usage might be larger than the specified amount of
18601 bytes. The wording is in keeping with the qualifier documented above.
18603 @node Dynamic Stack Usage Analysis
18604 @section Dynamic Stack Usage Analysis
18607 It is possible to measure the maximum amount of stack used by a task, by
18608 adding a switch to @command{gnatbind}, as:
18611 $ gnatbind -u0 file
18615 With this option, at each task termination, its stack usage is output on
18617 It is not always convenient to output the stack usage when the program
18618 is still running. Hence, it is possible to delay this output until program
18619 termination. for a given number of tasks specified as the argument of the
18620 @option{-u} option. For instance:
18623 $ gnatbind -u100 file
18627 will buffer the stack usage information of the first 100 tasks to terminate and
18628 output this info at program termination. Results are displayed in four
18632 Index | Task Name | Stack Size | Stack Usage
18639 is a number associated with each task.
18642 is the name of the task analyzed.
18645 is the maximum size for the stack.
18648 is the measure done by the stack analyzer. In order to prevent overflow, the stack
18649 is not entirely analyzed, and it's not possible to know exactly how
18650 much has actually been used.
18655 The environment task stack, e.g., the stack that contains the main unit, is
18656 only processed when the environment variable GNAT_STACK_LIMIT is set.
18659 The package @code{GNAT.Task_Stack_Usage} provides facilities to get
18660 stack usage reports at run-time. See its body for the details.
18662 @ifclear FSFEDITION
18663 @c *********************************
18665 @c *********************************
18666 @node Verifying Properties with gnatcheck
18667 @chapter Verifying Properties with @command{gnatcheck}
18669 @cindex @command{gnatcheck}
18672 The @command{gnatcheck} tool is an ASIS-based utility that checks properties
18673 of Ada source files according to a given set of semantic rules.
18676 In order to check compliance with a given rule, @command{gnatcheck} has to
18677 semantically analyze the Ada sources.
18678 Therefore, checks can only be performed on
18679 legal Ada units. Moreover, when a unit depends semantically upon units located
18680 outside the current directory, the source search path has to be provided when
18681 calling @command{gnatcheck}, either through a specified project file or
18682 through @command{gnatcheck} switches.
18684 For full details, refer to @cite{GNATcheck Reference Manual} document.
18687 @ifclear FSFEDITION
18688 @c *********************************
18689 @node Creating Sample Bodies with gnatstub
18690 @chapter Creating Sample Bodies with @command{gnatstub}
18694 @command{gnatstub} creates empty but compilable bodies
18695 for library unit declarations and empty but compilable
18696 subunit for body stubs.
18698 To create a body or a subunit, @command{gnatstub} invokes the Ada
18699 compiler and generates and uses the ASIS tree for the input source;
18700 thus the input must be legal Ada code, and the tool should have all the
18701 information needed to compile the input source. To provide this information,
18702 you may specify as a tool parameter the project file the input source belongs to
18703 (or you may call @command{gnatstub}
18704 through the @command{gnat} driver (see @ref{The GNAT Driver and
18705 Project Files}). Another possibility is to specify the source search
18706 path and needed configuration files in @option{-cargs} section of @command{gnatstub}
18707 call, see the description of the @command{gnatstub} switches below.
18709 If the @command{gnatstub} argument source contains preprocessing directives
18710 then the needed options should be provided to run preprocessor as a part of
18711 the @command{gnatstub} call, and the generated body stub will correspond to
18712 the preprocessed source.
18714 By default, all the program unit bodies generated by @code{gnatstub}
18715 raise the predefined @code{Program_Error} exception, which will catch
18716 accidental calls of generated stubs. This behavior can be changed with
18717 option @option{--no-exception} (see below).
18720 * Running gnatstub::
18721 * Switches for gnatstub::
18724 @node Running gnatstub
18725 @section Running @command{gnatstub}
18728 @command{gnatstub} has a command-line interface of the form:
18731 @c $ gnatstub @ovar{switches} @var{filename}
18732 @c Expanding @ovar macro inline (explanation in macro def comments)
18733 $ gnatstub @r{[}@var{switches}@r{]} @var{filename} @r{[}-cargs @var{gcc_switches}@r{]}
18740 is the name of the source file that contains a library unit declaration
18741 for which a body must be created or a library unit body for which subunits
18742 must be created for the body stubs declared in this body.
18743 The file name may contain the path information.
18744 If the name does not follow GNAT file naming conventions and a set
18745 of seitches does not contain a project file that defines naming
18746 conventions, the name of the body file must
18748 explicitly as the value of the @option{-o@var{body-name}} option.
18749 If the file name follows the GNAT file naming
18750 conventions and the name of the body file is not provided,
18752 takes the naming conventions for the generated source from the
18753 project file provided as a parameter of @option{-P} switch if any,
18754 or creates the name file to generate using the standard GNAT
18755 naming conventions.
18757 @item @samp{@var{gcc_switches}} is a list of switches for
18758 @command{gcc}. They will be passed on to all compiler invocations made by
18759 @command{gnatstub} to generate the ASIS trees. Here you can provide
18760 @option{-I} switches to form the source search path,
18761 use the @option{-gnatec} switch to set the configuration file,
18762 use the @option{-gnat05} switch if sources should be compiled in
18766 is an optional sequence of switches as described in the next section
18769 @node Switches for gnatstub
18770 @section Switches for @command{gnatstub}
18776 @cindex @option{--version} @command{gnatstub}
18777 Display Copyright and version, then exit disregarding all other options.
18780 @cindex @option{--help} @command{gnatstub}
18781 Display usage, then exit disregarding all other options.
18783 @item -P @var{file}
18784 @cindex @option{-P} @command{gnatstub}
18785 Indicates the name of the project file that describes the set of sources
18788 @item -X@var{name}=@var{value}
18789 @cindex @option{-X} @command{gnatstub}
18790 Indicates that external variable @var{name} in the argument project
18791 has the value @var{value}. Has no effect if no project is specified as
18794 @item --RTS=@var{rts-path}
18795 @cindex @option{--RTS} (@command{gnatstub})
18796 Specifies the default location of the runtime library. Same meaning as the
18797 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
18800 @cindex @option{--subunits} (@command{gnatstub})
18801 Generate subunits for body stubs. If this switch is specified,
18802 @command{gnatstub} expects a library unit body as an agrument file,
18803 otherwise a library unit declaration is expected. If a body stub
18804 already has a corresponding subunit, @command{gnatstub} does not
18805 generate anything for it.
18808 @cindex @option{-f} (@command{gnatstub})
18809 If the destination directory already contains a file with the name of the
18811 for the argument spec file, replace it with the generated body stub.
18812 This switch cannot be used together with @option{--subunits}.
18815 @cindex @option{-hs} (@command{gnatstub})
18816 Put the comment header (i.e., all the comments preceding the
18817 compilation unit) from the source of the library unit declaration
18818 into the body stub.
18821 @cindex @option{-hg} (@command{gnatstub})
18822 Put a sample comment header into the body stub.
18824 @item --header-file=@var{filename}
18825 @cindex @option{--header-file} (@command{gnatstub})
18826 Use the content of the file as the comment header for a generated body stub.
18829 @cindex @option{-IDIR} (@command{gnatstub})
18831 @cindex @option{-I-} (@command{gnatstub})
18832 These switches have the same meaning as in calls to
18834 They define the source search path in the call to
18835 @command{gcc} issued
18836 by @command{gnatstub} to compile an argument source file.
18838 @item -gnatec@var{PATH}
18839 @cindex @option{-gnatec} (@command{gnatstub})
18840 This switch has the same meaning as in calls to @command{gcc}.
18841 It defines the additional configuration file to be passed to the call to
18842 @command{gcc} issued
18843 by @command{gnatstub} to compile an argument source file.
18845 @item -gnatyM@var{n}
18846 @cindex @option{-gnatyM} (@command{gnatstub})
18847 (@var{n} is a non-negative integer). Set the maximum line length that is
18848 allowed in a source file. The default is 79. The maximum value that can be
18849 specified is 32767. Note that in the special case of configuration
18850 pragma files, the maximum is always 32767 regardless of whether or
18851 not this switch appears.
18853 @item -gnaty@var{n}
18854 @cindex @option{-gnaty} (@command{gnatstub})
18855 (@var{n} is a non-negative integer from 1 to 9). Set the indentation level in
18856 the generated body sample to @var{n}.
18857 The default indentation is 3.
18860 @cindex @option{-gnatyo} (@command{gnatstub})
18861 Order local bodies alphabetically. (By default local bodies are ordered
18862 in the same way as the corresponding local specs in the argument spec file.)
18865 @cindex @option{-i} (@command{gnatstub})
18866 Same as @option{-gnaty@var{n}}
18869 @cindex @option{-k} (@command{gnatstub})
18870 Do not remove the tree file (i.e., the snapshot of the compiler internal
18871 structures used by @command{gnatstub}) after creating the body stub.
18874 @cindex @option{-l} (@command{gnatstub})
18875 Same as @option{-gnatyM@var{n}}
18877 @item --no-exception
18878 @cindex @option{--no-exception} (@command{gnatstub})
18879 Avoid raising PROGRAM_ERROR in the generated bodies of program unit stubs.
18880 This is not always possible for function stubs.
18882 @item --no-local-header
18883 @cindex @option{--no-local-header} (@command{gnatstub})
18884 Do not place local comment header with unit name before body stub for a
18887 @item -o @var{body-name}
18888 @cindex @option{-o} (@command{gnatstub})
18889 Body file name. This should be set if the argument file name does not
18891 the GNAT file naming
18892 conventions. If this switch is omitted the default name for the body will be
18894 from the argument file name according to the GNAT file naming conventions.
18896 @item --dir=@var{dir-name}
18897 @cindex @option{--dir} (@command{gnatstub})
18898 The path to the directory to place the generated files into.
18899 If this switch is not set, the generated library unit body is
18900 placed in the current directory, and generated sununits -
18901 in the directory where the argument body is located.
18904 @cindex @option{-W} (@command{gnatstub})
18905 Specify the wide character encoding method for the output body file.
18906 @var{e} is one of the following:
18914 Upper half encoding
18926 Brackets encoding (default value)
18930 @cindex @option{-q} (@command{gnatstub})
18931 Quiet mode: do not generate a confirmation when a body is
18932 successfully created, and do not generate a message when a body is not
18937 @cindex @option{-r} (@command{gnatstub})
18938 Reuse the tree file (if it exists) instead of creating it. Instead of
18939 creating the tree file for the library unit declaration, @command{gnatstub}
18940 tries to find it in the current directory and use it for creating
18941 a body. If the tree file is not found, no body is created. This option
18942 also implies @option{-k}, whether or not
18943 the latter is set explicitly.
18946 @cindex @option{-t} (@command{gnatstub})
18947 Overwrite the existing tree file. If the current directory already
18948 contains the file which, according to the GNAT file naming rules should
18949 be considered as a tree file for the argument source file,
18951 will refuse to create the tree file needed to create a sample body
18952 unless this option is set.
18955 @cindex @option{-v} (@command{gnatstub})
18956 Verbose mode: generate version information.
18961 @ifclear FSFEDITION
18962 @c *********************************
18963 @node Creating Unit Tests with gnattest
18964 @chapter Creating Unit Tests with @command{gnattest}
18968 @command{gnattest} is an ASIS-based utility that creates unit-test skeletons
18969 as well as a test driver infrastructure (harness). @command{gnattest} creates
18970 a skeleton for each visible subprogram in the packages under consideration when
18971 they do not exist already.
18973 The user can choose to generate a single test driver
18974 that will run all individual tests, or separate test drivers for each test. The
18975 second option allows much greater flexibility in test execution environment,
18976 allows to benefit from parallel tests execution to increase performance, and
18977 provides stubbing support.
18979 @command{gnattest} also has a mode of operation where it acts as the test
18980 aggregator when multiple test executables must be run, in particular when
18981 the separate test drivers were generated. In this mode it handles individual
18982 tests execution and upon completion reports the summary results of the test
18985 In order to process source files from a project, @command{gnattest} has to
18986 semantically analyze the sources. Therefore, test skeletons can only be
18987 generated for legal Ada units. If a unit is dependent on other units,
18988 those units should be among the source files of the project or of other projects
18989 imported by this one.
18991 Generated skeletons and harnesses are based on the AUnit testing framework.
18992 AUnit is an Ada adaptation of the xxxUnit testing frameworks, similar to JUnit
18993 for Java or CppUnit for C++. While it is advised that gnattest users read
18994 the AUnit manual, deep knowledge of AUnit is not necessary for using gnattest.
18995 For correct operation of @command{gnattest}, AUnit should be installed and
18996 aunit.gpr must be on the project path. This happens automatically when Aunit
18997 is installed at its default location.
19000 * Running gnattest::
19001 * Switches for gnattest in framework generation mode::
19002 * Switches for gnattest in tests execution mode::
19003 * Project Attributes for gnattest::
19005 * Setting Up and Tearing Down the Testing Environment::
19006 * Regenerating Tests::
19007 * Default Test Behavior::
19008 * Testing Primitive Operations of Tagged Types::
19009 * Testing Inheritance::
19010 * Tagged Types Substitutability Testing::
19011 * Testing with Contracts::
19012 * Additional Tests::
19013 * Individual Test Drivers::
19015 * Putting Tests under Version Control::
19016 * Support for other platforms/run-times::
19017 * Current Limitations::
19020 @node Running gnattest
19021 @section Running @command{gnattest}
19024 @b{In the framework generation mode}, @command{gnattest} has a command-line
19025 interface of the form
19028 @c $ gnattest @var{-Pprojname} @ovar{switches} @ovar{filename} @ovar{directory}
19029 @c Expanding @ovar macro inline (explanation in macro def comments)
19030 $ gnattest @var{-Pprojname} @r{[}@var{--harness-dir=dirname}@r{]} @r{[}@var{switches}@r{]} @r{[}@var{filename}@r{]} @r{[}-cargs @var{gcc_switches}@r{]}
19038 specifies the project defining the location of source files. When no
19039 file names are provided on the command line, all sources in the project
19040 are used as input. This switch is required.
19043 is the name of the source file containing the library unit package declaration
19044 for which a test package will be created. The file name may be given with a
19047 @item @samp{@var{gcc_switches}}
19048 is a list of switches for
19049 @command{gcc}. These switches will be passed on to all compiler invocations
19050 made by @command{gnattest} to generate a set of ASIS trees. Here you can provide
19051 @option{-I} switches to form the source search path,
19052 use the @option{-gnatec} switch to set the configuration file,
19053 use the @option{-gnat05} switch if sources should be compiled in
19054 Ada 2005 mode, etc.
19057 is an optional sequence of switches as described in the next section.
19061 @command{gnattest} results can be found in two different places.
19064 @item automatic harness:
19065 the harness code, which is located by default in "gnattest/harness" directory
19066 that is created in the object directory of corresponding project file. All of
19067 this code is generated completely automatically and can be destroyed and
19068 regenerated at will. It is not recommended to modify this code manually, since
19069 it could easily be overridden by mistake. The entry point in the harness code is
19070 the project file named @command{test_driver.gpr}. Tests can be compiled and run
19071 using a command such as:
19074 gnatmake -P<harness-dir>/test_driver
19078 Note that you might need to specify the necessary values of scenario variables
19079 when you are not using the AUnit defaults.
19081 @item actual unit test skeletons:
19082 a test skeleton for each visible subprogram is created in a separate file, if it
19083 doesn't exist already. By default, those separate test files are located in a
19084 "gnattest/tests" directory that is created in the object directory of
19085 corresponding project file. For example, if a source file my_unit.ads in
19086 directory src contains a visible subprogram Proc, then the corresponding unit
19087 test will be found in file src/tests/my_unit-test_data-tests.adb and will be
19088 called Test_Proc_<code>. <code> is a signature encoding used to differentiate
19089 test names in case of overloading.
19091 Note that if the project already has both my_unit.ads and my_unit-test_data.ads,
19092 this will cause a name conflict with the generated test package.
19097 @b{In the tests execution mode mode}, @command{gnattest} has a command-line
19098 interface of the form
19101 @c $ gnattest @var{-Pprojname} @ovar{switches} @ovar{filename} @ovar{directory}
19102 @c Expanding @ovar macro inline (explanation in macro def comments)
19103 $ gnattest @var{test_drivers.list} @r{[}@var{switches}@r{]}
19110 @item test_drivers.list
19111 is the name of the text file containing the list of executables to treat as
19112 test drivers. This file is automatically generated by gnattest, but can be
19113 hand-edited to add or remove tests. This switch is required.
19116 is an optional sequence of switches as described below.
19121 @node Switches for gnattest in framework generation mode
19122 @section Switches for @command{gnattest} in framework generation mode
19128 @cindex @option{-q} (@command{gnattest})
19129 Quiet mode: suppresses noncritical output messages.
19132 @cindex @option{-v} (@command{gnattest})
19133 Verbose mode: generates version information if specified by itself on the
19134 command line. If specified via GNATtest_Switches, produces output
19135 about the execution of the tool.
19138 @cindex @option{-r} (@command{gnattest})
19139 Recursively considers all sources from all projects.
19142 @item -X@var{name=value}
19143 @cindex @option{-X} (@command{gnattest})
19144 Indicate that external variable @var{name} has the value @var{value}.
19146 @item --RTS=@var{rts-path}
19147 @cindex @option{--RTS} (@command{gnattest})
19148 Specifies the default location of the runtime library. Same meaning as the
19149 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
19152 @item --additional-tests=@var{projname}
19153 @cindex @option{--additional-tests} (@command{gnattest})
19154 Sources described in @var{projname} are considered potential additional
19155 manual tests to be added to the test suite.
19157 @item --harness-only
19158 @cindex @option{--harness-only} (@command{gnattest})
19159 When this option is given, @command{gnattest} creates a harness for all
19160 sources, treating them as test packages.
19162 @item --separate-drivers
19163 @cindex @option{--separate-drivers} (@command{gnattest})
19164 Generates a separate test driver for each test, rather than a single
19165 executable incorporating all tests.
19168 @cindex @option{--stub} (@command{gnattest})
19169 Generates the testing framework that uses subsystem stubbing to isolate the
19173 @item --harness-dir=@var{dirname}
19174 @cindex @option{--harness-dir} (@command{gnattest})
19175 Specifies the directory that will hold the harness packages and project file
19176 for the test driver. If the @var{dirname} is a relative path, it is considered
19177 relative to the object directory of the project file.
19179 @item --tests-dir=@var{dirname}
19180 @cindex @option{--tests-dir} (@command{gnattest})
19181 All test packages are placed in the @var{dirname} directory.
19182 If the @var{dirname} is a relative path, it is considered relative to the object
19183 directory of the project file. When all sources from all projects are taken
19184 recursively from all projects, @var{dirname} directories are created for each
19185 project in their object directories and test packages are placed accordingly.
19187 @item --subdir=@var{dirname}
19188 @cindex @option{--subdir} (@command{gnattest})
19189 Test packages are placed in a subdirectory of the corresponding source
19190 directory, with the name @var{dirname}. Thus, each set of unit tests is located
19191 in a subdirectory of the code under test. If the sources are in separate
19192 directories, each source directory has a test subdirectory named @var{dirname}.
19194 @item --tests-root=@var{dirname}
19195 @cindex @option{--tests-root} (@command{gnattest})
19196 The hierarchy of source directories, if any, is recreated in the @var{dirname}
19197 directory, with test packages placed in directories corresponding to those
19199 If the @var{dirname} is a relative path, it is considered relative to the object
19200 directory of the project file. When projects are considered recursively,
19201 directory hierarchies of tested sources are
19202 recreated for each project in their object directories and test packages are
19203 placed accordingly.
19205 @item --stubs-dir=@var{dirname}
19206 @cindex @option{--stubs-dir} (@command{gnattest})
19207 The hierarchy of directories containing stubbed units is recreated in
19208 the @var{dirname} directory, with stubs placed in directories corresponding to
19209 projects they are derived from.
19210 If the @var{dirname} is a relative path, it is considered relative to the object
19211 directory of the project file. When projects are considered recursively,
19212 directory hierarchies of stubs are
19213 recreated for each project in their object directories and test packages are
19214 placed accordingly.
19217 @item --validate-type-extensions
19218 @cindex @option{--validate-type-extensions} (@command{gnattest})
19219 Enables substitution check: run all tests from all parents in order
19220 to check substitutability in accordance with LSP.
19222 @item --skeleton-default=@var{val}
19223 @cindex @option{--skeleton-default} (@command{gnattest})
19224 Specifies the default behavior of generated skeletons. @var{val} can be either
19225 "fail" or "pass", "fail" being the default.
19227 @item --passed-tests=@var{val}
19228 @cindex @option{--passed-tests} (@command{gnattest})
19229 Specifies whether or not passed tests should be shown. @var{val} can be either
19230 "show" or "hide", "show" being the default.
19232 @item --exit-status=@var{val}
19233 @cindex @option{--exit-status} (@command{gnattest})
19234 Specifies whether or not generated test driver should return failure exit
19235 status if at least one test fails or crashes. @var{val} can be either
19236 "on" or "off", "off" being the default.
19239 @cindex @option{--omit-sloc} (@command{gnattest})
19240 Suppresses comment line containing file name and line number of corresponding
19241 subprograms in test skeletons.
19245 @cindex @option{--separates} (@command{gnattest})
19246 Bodies of all test routines are generated as separates. Note that this mode is
19247 kept for compatibility reasons only and it is not advised to use it due to
19248 possible problems with hash in names of test skeletons when using an
19249 inconsistent casing. Separate test skeletons can be incorporated to monolith
19250 test package with improved hash being used by using @option{--transition}
19255 @cindex @option{--transition} (@command{gnattest})
19256 This allows transition from separate test routines to monolith test packages.
19257 All matching test routines are overwritten with contents of corresponding
19258 separates. Note that if separate test routines had any manually added with
19259 clauses they will be moved to the test package body as is and have to be moved
19262 @item --test-duration
19263 @cindex @option{--test-duration} (@command{gnattest})
19264 Adds time measurements for each test in generated test driver.
19268 @option{--tests_root}, @option{--subdir} and @option{--tests-dir} switches are
19269 mutually exclusive.
19272 @node Switches for gnattest in tests execution mode
19273 @section Switches for @command{gnattest} in tests execution mode
19278 @item --passed-tests=@var{val}
19279 @cindex @option{--passed-tests} (@command{gnattest})
19280 Specifies whether or not passed tests should be shown. @var{val} can be either
19281 "show" or "hide", "show" being the default.
19283 @item --queues=@var{n}, -j@var{n}
19284 @cindex @option{--queues} (@command{gnattest})
19285 @cindex @option{-j} (@command{gnattest})
19286 Runs @var{n} tests in parallel (default is 1).
19291 @node Project Attributes for gnattest
19292 @section Project Attributes for @command{gnattest}
19296 Most of the command-line options can also be passed to the tool by adding
19297 special attributes to the project file. Those attributes should be put in
19298 package gnattest. Here is the list of attributes:
19303 is used to select the same output mode as with the --tests-root option.
19304 This attribute cannot be used together with Subdir or Tests_Dir.
19307 is used to select the same output mode as with the --subdir option.
19308 This attribute cannot be used together with Tests_Root or Tests_Dir.
19311 is used to select the same output mode as with the --tests-dir option.
19312 This attribute cannot be used together with Subdir or Tests_Root.
19315 is used to specify the directory in which to place harness packages and project
19316 file for the test driver, otherwise specified by --harness-dir.
19318 @item Additional_Tests
19319 is used to specify the project file, otherwise given by
19320 --additional-tests switch.
19322 @item Skeletons_Default
19323 is used to specify the default behaviour of test skeletons, otherwise
19324 specified by --skeleton-default option. The value of this attribute
19325 should be either "pass" or "fail".
19329 Each of those attributes can be overridden from the command line if needed.
19330 Other @command{gnattest} switches can also be passed via the project
19331 file as an attribute list called GNATtest_Switches.
19333 @node Simple Example
19334 @section Simple Example
19338 Let's take a very simple example using the first @command{gnattest} example
19342 <install_prefix>/share/examples/gnattest/simple
19345 This project contains a simple package containing one subprogram. By running gnattest:
19348 $ gnattest --harness-dir=driver -Psimple.gpr
19351 a test driver is created in directory "driver". It can be compiled and run:
19355 $ gnatmake -Ptest_driver
19359 One failed test with diagnosis "test not implemented" is reported.
19360 Since no special output option was specified, the test package Simple.Tests
19364 <install_prefix>/share/examples/gnattest/simple/obj/gnattest/tests
19367 For each package containing visible subprograms, a child test package is
19368 generated. It contains one test routine per tested subprogram. Each
19369 declaration of a test subprogram has a comment specifying which tested
19370 subprogram it corresponds to. Bodies of test routines are placed in test package
19371 bodies and are surrounded by special comment sections. Those comment sections
19372 should not be removed or modified in order for gnattest to be able to regenerate
19373 test packages and keep already written tests in place.
19374 The test routine Test_Inc_5eaee3 located at simple-test_data-tests.adb contains
19375 a single statement: a call to procedure Assert. It has two arguments:
19376 the Boolean expression we want to check and the diagnosis message to display if
19377 the condition is false.
19379 That is where actual testing code should be written after a proper setup.
19380 An actual check can be performed by replacing the Assert call with:
19382 @smallexample @c ada
19383 Assert (Inc (1) = 2, "wrong incrementation");
19386 After recompiling and running the test driver, one successfully passed test
19389 @node Setting Up and Tearing Down the Testing Environment
19390 @section Setting Up and Tearing Down the Testing Environment
19394 Besides test routines themselves, each test package has a parent package
19395 Test_Data that has two procedures: Set_Up and Tear_Down. This package is never
19396 overwritten by the tool. Set_Up is called before each test routine of the
19397 package and Tear_Down is called after each test routine. Those two procedures
19398 can be used to perform necessary initialization and finalization,
19399 memory allocation, etc. Test type declared in Test_Data package is parent type
19400 for the test type of test package and can have user-defined components whose
19401 values can be set by Set_Up routine and used in test routines afterwards.
19403 @node Regenerating Tests
19404 @section Regenerating Tests
19408 Bodies of test routines and test_data packages are never overridden after they
19409 have been created once. As long as the name of the subprogram, full expanded Ada
19410 names, and the order of its parameters is the same, and comment sections are
19411 intact the old test routine will fit in its place and no test skeleton will be
19412 generated for the subprogram.
19414 This can be demonstrated with the previous example. By uncommenting declaration
19415 and body of function Dec in simple.ads and simple.adb, running
19416 @command{gnattest} on the project, and then running the test driver:
19419 gnattest --harness-dir=driver -Psimple.gpr
19421 gnatmake -Ptest_driver
19425 the old test is not replaced with a stub, nor is it lost, but a new test
19426 skeleton is created for function Dec.
19428 The only way of regenerating tests skeletons is to remove the previously created
19429 tests together with corresponding comment sections.
19431 @node Default Test Behavior
19432 @section Default Test Behavior
19436 The generated test driver can treat unimplemented tests in two ways:
19437 either count them all as failed (this is useful to see which tests are still
19438 left to implement) or as passed (to sort out unimplemented ones from those
19441 The test driver accepts a switch to specify this behavior:
19442 --skeleton-default=val, where val is either "pass" or "fail" (exactly as for
19443 @command{gnattest}).
19445 The default behavior of the test driver is set with the same switch
19446 as passed to gnattest when generating the test driver.
19448 Passing it to the driver generated on the first example:
19451 test_runner --skeleton-default=pass
19454 makes both tests pass, even the unimplemented one.
19456 @node Testing Primitive Operations of Tagged Types
19457 @section Testing Primitive Operations of Tagged Types
19461 Creation of test skeletons for primitive operations of tagged types entails
19462 a number of features. Test routines for all primitives of a given tagged type
19463 are placed in a separate child package named according to the tagged type. For
19464 example, if you have tagged type T in package P, all tests for primitives
19465 of T will be in P.T_Test_Data.T_Tests.
19467 Consider running gnattest on the second example (note: actual tests for this
19468 example already exist, so there's no need to worry if the tool reports that
19469 no new stubs were generated):
19472 cd <install_prefix>/share/examples/gnattest/tagged_rec
19473 gnattest --harness-dir=driver -Ptagged_rec.gpr
19476 Taking a closer look at the test type declared in the test package
19477 Speed1.Controller_Test_Data is necessary. It is declared in:
19480 <install_prefix>/share/examples/gnattest/tagged_rec/obj/gnattest/tests
19483 Test types are direct or indirect descendants of
19484 AUnit.Test_Fixtures.Test_Fixture type. In the case of nonprimitive tested
19485 subprograms, the user doesn't need to be concerned with them. However,
19486 when generating test packages for primitive operations, there are some things
19487 the user needs to know.
19489 Type Test_Controller has components that allow assignment of various
19490 derivations of type Controller. And if you look at the specification of
19491 package Speed2.Auto_Controller, you will see that Test_Auto_Controller
19492 actually derives from Test_Controller rather than AUnit type Test_Fixture.
19493 Thus, test types mirror the hierarchy of tested types.
19495 The Set_Up procedure of Test_Data package corresponding to a test package
19496 of primitive operations of type T assigns to Fixture a reference to an
19497 object of that exact type T. Notice, however, that if the tagged type has
19498 discriminants, the Set_Up only has a commented template for setting
19499 up the fixture, since filling the discriminant with actual value is up
19502 The knowledge of the structure of test types allows additional testing
19503 without additional effort. Those possibilities are described below.
19505 @node Testing Inheritance
19506 @section Testing Inheritance
19510 Since the test type hierarchy mimics the hierarchy of tested types, the
19511 inheritance of tests takes place. An example of such inheritance can be
19512 seen by running the test driver generated for the second example. As previously
19513 mentioned, actual tests are already written for this example.
19517 gnatmake -Ptest_driver
19521 There are 6 passed tests while there are only 5 testable subprograms. The test
19522 routine for function Speed has been inherited and run against objects of the
19525 @node Tagged Types Substitutability Testing
19526 @section Tagged Types Substitutability Testing
19530 Tagged Types Substitutability Testing is a way of verifying the global type
19531 consistency by testing. Global type consistency is a principle stating that if
19532 S is a subtype of T (in Ada, S is a derived type of tagged type T),
19533 then objects of type T may be replaced with objects of type S (that is,
19534 objects of type S may be substituted for objects of type T), without
19535 altering any of the desirable properties of the program. When the properties
19536 of the program are expressed in the form of subprogram preconditions and
19537 postconditions (let's call them pre and post), the principle is formulated as
19538 relations between the pre and post of primitive operations and the pre and post
19539 of their derived operations. The pre of a derived operation should not be
19540 stronger than the original pre, and the post of the derived operation should
19541 not be weaker than the original post. Those relations ensure that verifying if
19542 a dispatching call is safe can be done just by using the pre and post of the
19545 Verifying global type consistency by testing consists of running all the unit
19546 tests associated with the primitives of a given tagged type with objects of its
19549 In the example used in the previous section, there was clearly a violation of
19550 type consistency. The overriding primitive Adjust_Speed in package Speed2
19551 removes the functionality of the overridden primitive and thus doesn't respect
19552 the consistency principle.
19553 Gnattest has a special option to run overridden parent tests against objects
19554 of the type which have overriding primitives:
19557 gnattest --harness-dir=driver --validate-type-extensions -Ptagged_rec.gpr
19559 gnatmake -Ptest_driver
19563 While all the tests pass by themselves, the parent test for Adjust_Speed fails
19564 against objects of the derived type.
19566 Non-overridden tests are already inherited for derived test types, so the
19567 --validate-type-extensions enables the application of overriden tests to objects
19570 @node Testing with Contracts
19571 @section Testing with Contracts
19575 @command{gnattest} supports pragmas Precondition, Postcondition, and Test_Case,
19576 as well as corresponding aspects.
19577 Test routines are generated, one per each Test_Case associated with a tested
19578 subprogram. Those test routines have special wrappers for tested functions
19579 that have composition of pre- and postcondition of the subprogram with
19580 "requires" and "ensures" of the Test_Case (depending on the mode, pre and post
19581 either count for Nominal mode or do not count for Robustness mode).
19583 The third example demonstrates how this works:
19586 cd <install_prefix>/share/examples/gnattest/contracts
19587 gnattest --harness-dir=driver -Pcontracts.gpr
19590 Putting actual checks within the range of the contract does not cause any
19591 error reports. For example, for the test routine which corresponds to
19594 @smallexample @c ada
19595 Assert (Sqrt (9.0) = 3.0, "wrong sqrt");
19598 and for the test routine corresponding to test case 2:
19600 @smallexample @c ada
19601 Assert (Sqrt (-5.0) = -1.0, "wrong error indication");
19608 gnatmake -Ptest_driver
19612 However, by changing 9.0 to 25.0 and 3.0 to 5.0, for example, you can get
19613 a precondition violation for test case one. Also, by using any otherwise
19614 correct but positive pair of numbers in the second test routine, you can also
19615 get a precondition violation. Postconditions are checked and reported
19618 @node Additional Tests
19619 @section Additional Tests
19622 @command{gnattest} can add user-written tests to the main suite of the test
19623 driver. @command{gnattest} traverses the given packages and searches for test
19624 routines. All procedures with a single in out parameter of a type which is
19625 derived from AUnit.Test_Fixtures.Test_Fixture and that are declared in package
19626 specifications are added to the suites and are then executed by the test driver.
19627 (Set_Up and Tear_Down are filtered out.)
19629 An example illustrates two ways of creating test harnesses for user-written
19630 tests. Directory additional_tests contains an AUnit-based test driver written
19634 <install_prefix>/share/examples/gnattest/additional_tests/
19637 To create a test driver for already-written tests, use the --harness-only
19641 gnattest -Padditional/harness/harness.gpr --harness-dir=harness_only \
19643 gnatmake -Pharness_only/test_driver.gpr
19644 harness_only/test_runner
19647 Additional tests can also be executed together with generated tests:
19650 gnattest -Psimple.gpr --additional-tests=additional/harness/harness.gpr \
19651 --harness-dir=mixing
19652 gnatmake -Pmixing/test_driver.gpr
19657 @node Individual Test Drivers
19658 @section Individual Test Drivers
19661 By default, @command{gnattest} generates a monolithic test driver that
19662 aggregates the individual tests into a single executable. It is also possible
19663 to generate separate executables for each test, by passing the switch
19664 @option{--separate-drivers}. This approach scales better for large testing
19665 campaigns, especially involving target architectures with limited resources
19666 typical for embedded development. It can also provide a major performance
19667 benefit on multi-core systems by allowing simultaneous execution of multiple
19670 @command{gnattest} can take charge of executing the individual tests; for this,
19671 instead of passing a project file, a text file containing the list of
19672 executables can be passed. Such a file is automatically generated by gnattest
19673 under the name @option{test_drivers.list}, but it can be
19674 hand-edited to add or remove tests, or replaced. The individual tests can
19675 also be executed standalone, or from any user-defined scripted framework.
19682 Depending on the testing campaign, it is sometimes necessary to isolate the
19683 part of the algorithm under test from its dependencies. This is accomplished
19684 via @emph{stubbing}, i.e. replacing the subprograms that are called from the
19685 subprogram under test by stand-in subprograms that match the profiles of the
19686 original ones, but simply return predetermined values required by the test
19689 This mode of test harness generation is activated by the switch @option{--stub}.
19691 The implementation approach chosen by @command{gnattest} is as follows.
19692 For each package under consideration all the packages it is directly depending
19693 on are stubbed, excluding the generic packages and package instantiations.
19694 The stubs are shared for each package under test. The specs of packages to stub
19695 remain intact, while their bodies are replaced, and hide the original bodies by
19696 means of extending projects. Also, for each stubbed
19697 package, a child package with setter routines for each subprogram declaration
19698 is created. These setters are meant to be used to set the behaviour of
19699 stubbed subprograms from within test cases.
19701 Note that subprograms belonging to the same package as the subprogram under
19702 test are not stubbed. This guarantees that the sources being tested are
19703 exactly the sources used for production, which is an important property for
19704 establishing the traceability between the testing campaign and production code.
19706 Due to the nature of stubbing process, this mode implies the switch
19707 @option{--separate-drivers}, i.e. an individual test driver (with the
19708 corresponding hierarchy of extending projects) is generated for each test.
19711 Developing a stubs-based testing campaign requires
19712 good understanding of the infrastructure created by @command{gnattest} for
19713 this purpose. We recommend following the stubbing tutorials provided
19714 under @file{<install_prefix>/share/examples/gnattest/stubbing*} before
19715 attempting to use this powerful feature.
19718 @node Putting Tests under Version Control
19719 @section Putting Tests under Version Control
19722 As has been stated earlier, @command{gnattest} generates two different types
19723 of code, test skeletons and harness. The harness is generated completely
19724 automatically each time, does not require manual changes and therefore should
19725 not be put under version control.
19726 It makes sense to put under version control files containing test data packages,
19727 both specs and bodies, and files containing bodies of test packages. Note that
19728 test package specs are also generated automatically each time and should not be
19729 put under version control.
19730 Option @option{--omit-sloc} may be usefull when putting test packages under VCS.
19732 @node Support for other platforms/run-times
19733 @section Support for other platforms/run-times
19736 @command{gnattest} can be used to generate the test harness for platforms
19737 and run-time libraries others than the default native target with the
19738 default full run-time. For example, when using a limited run-time library
19739 such as Zero FootPrint (ZFP), a simplified harness is generated.
19741 Two variables are used to tell the underlying AUnit framework how to generate
19742 the test harness: @code{PLATFORM}, which identifies the target, and
19743 @code{RUNTIME}, used to determine the run-time library for which the harness
19744 is generated. Corresponding prefix should also be used when calling
19745 @command{gnattest} for non-native targets. For example, the following options
19746 are used to generate the AUnit test harness for a PowerPC ELF target using
19747 the ZFP run-time library:
19750 powerpc-elf-gnattest -Psimple.gpr -XPLATFORM=powerpc-elf -XRUNTIME=zfp
19753 @node Current Limitations
19754 @section Current Limitations
19758 The tool currently does not support following features:
19761 @item generic tests for nested generic packages and their instantiations
19762 @item tests for protected subprograms and entries
19768 @c *********************************
19769 @node Performing Dimensionality Analysis in GNAT
19770 @chapter Performing Dimensionality Analysis in GNAT
19771 @cindex Dimensionality analysis
19774 The GNAT compiler now supports dimensionality checking. The user can
19775 specify physical units for objects, and the compiler will verify that uses
19776 of these objects are compatible with their dimensions, in a fashion that is
19777 familiar to engineering practice. The dimensions of algebraic expressions
19778 (including powers with static exponents) are computed from their constituents.
19780 This feature depends on Ada 2012 aspect specifications, and is available from
19781 version 7.0.1 of GNAT onwards.
19782 The GNAT-specific aspect @code{Dimension_System}
19783 @cindex @code{Dimension_System} aspect
19784 allows you to define a system of units; the aspect @code{Dimension}
19785 @cindex @code{Dimension} aspect
19786 then allows the user to declare dimensioned quantities within a given system.
19787 (These aspects are described in the @i{Implementation Defined Aspects}
19788 chapter of the @i{GNAT Reference Manual}).
19790 The major advantage of this model is that it does not require the declaration of
19791 multiple operators for all possible combinations of types: it is only necessary
19792 to use the proper subtypes in object declarations.
19794 The simplest way to impose dimensionality checking on a computation is to make
19795 use of the package @code{System.Dim.Mks},
19796 @cindex @code{System.Dim.Mks} package (GNAT library)
19797 which is part of the GNAT library. This
19798 package defines a floating-point type @code{MKS_Type},
19799 @cindex @code{MKS_Type} type
19800 for which a sequence of
19801 dimension names are specified, together with their conventional abbreviations.
19802 The following should be read together with the full specification of the
19803 package, in file @file{s-dimmks.ads}.
19804 @cindex @file{s-dimmks.ads} file
19806 @smallexample @c ada
19808 @b{type} Mks_Type @b{is} @b{new} Long_Long_Float
19810 Dimension_System => (
19811 (Unit_Name => Meter, Unit_Symbol => 'm', Dim_Symbol => 'L'),
19812 (Unit_Name => Kilogram, Unit_Symbol => "kg", Dim_Symbol => 'M'),
19813 (Unit_Name => Second, Unit_Symbol => 's', Dim_Symbol => 'T'),
19814 (Unit_Name => Ampere, Unit_Symbol => 'A', Dim_Symbol => 'I'),
19815 (Unit_Name => Kelvin, Unit_Symbol => 'K', Dim_Symbol => "Theta"),
19816 (Unit_Name => Mole, Unit_Symbol => "mol", Dim_Symbol => 'N'),
19817 (Unit_Name => Candela, Unit_Symbol => "cd", Dim_Symbol => 'J'));
19822 The package then defines a series of subtypes that correspond to these
19823 conventional units. For example:
19825 @smallexample @c ada
19827 @b{subtype} Length @b{is} Mks_Type
19829 Dimension => (Symbol => 'm', Meter => 1, @b{others} => 0);
19834 and similarly for @code{Mass}, @code{Time}, @code{Electric_Current},
19835 @code{Thermodynamic_Temperature}, @code{Amount_Of_Substance}, and
19836 @code{Luminous_Intensity} (the standard set of units of the SI system).
19838 The package also defines conventional names for values of each unit, for
19841 @smallexample @c ada
19843 m : @b{constant} Length := 1.0;
19844 kg : @b{constant} Mass := 1.0;
19845 s : @b{constant} Time := 1.0;
19846 A : @b{constant} Electric_Current := 1.0;
19851 as well as useful multiples of these units:
19853 @smallexample @c ada
19855 cm : @b{constant} Length := 1.0E-02;
19856 g : @b{constant} Mass := 1.0E-03;
19857 min : @b{constant} Time := 60.0;
19858 day : @b{constant} Time := 60.0 * 24.0 * min;
19864 Using this package, you can then define a derived unit by
19865 providing the aspect that
19866 specifies its dimensions within the MKS system, as well as the string to
19867 be used for output of a value of that unit:
19869 @smallexample @c ada
19871 @b{subtype} Acceleration @b{is} Mks_Type
19872 @b{with} Dimension => ("m/sec^2",
19880 Here is a complete example of use:
19882 @smallexample @c ada
19884 @b{with} System.Dim.MKS; @b{use} System.Dim.Mks;
19885 @b{with} System.Dim.Mks_IO; @b{use} System.Dim.Mks_IO;
19886 @b{with} Text_IO; @b{use} Text_IO;
19887 @b{procedure} Free_Fall @b{is}
19888 @b{subtype} Acceleration @b{is} Mks_Type
19889 @b{with} Dimension => ("m/sec^2", 1, 0, -2, @b{others} => 0);
19890 G : @b{constant} acceleration := 9.81 * m / (s ** 2);
19891 T : Time := 10.0*s;
19896 Put ("Gravitational constant: ");
19897 Put (G, Aft => 2, Exp => 0); Put_Line ("");
19898 Distance := 0.5 * G * T ** 2;
19899 Put ("distance travelled in 10 seconds of free fall ");
19900 Put (Distance, Aft => 2, Exp => 0);
19907 Execution of this program yields:
19910 Gravitational constant: 9.81 m/sec^2
19911 distance travelled in 10 seconds of free fall 490.50 m
19916 However, incorrect assignments such as:
19918 @smallexample @c ada
19921 Distance := 5.0 * kg:
19926 are rejected with the following diagnoses:
19931 >>> dimensions mismatch in assignment
19932 >>> left-hand side has dimension [L]
19933 >>> right-hand side is dimensionless
19937 Distance := 5.0 * kg:
19938 >>> dimensions mismatch in assignment
19939 >>> left-hand side has dimension [L]
19940 >>> right-hand side has dimension [M]
19945 The dimensions of an expression are properly displayed, even if there is
19946 no explicit subtype for it. If we add to the program:
19948 @smallexample @c ada
19950 Put ("Final velocity: ");
19951 Put (G * T, Aft =>2, Exp =>0);
19957 then the output includes:
19959 Final velocity: 98.10 m.s**(-1)
19963 @c *********************************
19964 @node Generating Ada Bindings for C and C++ headers
19965 @chapter Generating Ada Bindings for C and C++ headers
19969 GNAT now comes with a binding generator for C and C++ headers which is
19970 intended to do 95% of the tedious work of generating Ada specs from C
19971 or C++ header files.
19973 Note that this capability is not intended to generate 100% correct Ada specs,
19974 and will is some cases require manual adjustments, although it can often
19975 be used out of the box in practice.
19977 Some of the known limitations include:
19980 @item only very simple character constant macros are translated into Ada
19981 constants. Function macros (macros with arguments) are partially translated
19982 as comments, to be completed manually if needed.
19983 @item some extensions (e.g. vector types) are not supported
19984 @item pointers to pointers or complex structures are mapped to System.Address
19985 @item identifiers with identical name (except casing) will generate compilation
19986 errors (e.g. @code{shm_get} vs @code{SHM_GET}).
19989 The code generated is using the Ada 2005 syntax, which makes it
19990 easier to interface with other languages than previous versions of Ada.
19993 * Running the binding generator::
19994 * Generating bindings for C++ headers::
19998 @node Running the binding generator
19999 @section Running the binding generator
20002 The binding generator is part of the @command{gcc} compiler and can be
20003 invoked via the @option{-fdump-ada-spec} switch, which will generate Ada
20004 spec files for the header files specified on the command line, and all
20005 header files needed by these files transitively. For example:
20008 $ g++ -c -fdump-ada-spec -C /usr/include/time.h
20009 $ gcc -c -gnat05 *.ads
20012 will generate, under GNU/Linux, the following files: @file{time_h.ads},
20013 @file{bits_time_h.ads}, @file{stddef_h.ads}, @file{bits_types_h.ads} which
20014 correspond to the files @file{/usr/include/time.h},
20015 @file{/usr/include/bits/time.h}, etc@dots{}, and will then compile in Ada 2005
20016 mode these Ada specs.
20018 The @code{-C} switch tells @command{gcc} to extract comments from headers,
20019 and will attempt to generate corresponding Ada comments.
20021 If you want to generate a single Ada file and not the transitive closure, you
20022 can use instead the @option{-fdump-ada-spec-slim} switch.
20024 You can optionally specify a parent unit, of which all generated units will
20025 be children, using @code{-fada-spec-parent=}@var{unit}.
20027 Note that we recommend when possible to use the @command{g++} driver to
20028 generate bindings, even for most C headers, since this will in general
20029 generate better Ada specs. For generating bindings for C++ headers, it is
20030 mandatory to use the @command{g++} command, or @command{gcc -x c++} which
20031 is equivalent in this case. If @command{g++} cannot work on your C headers
20032 because of incompatibilities between C and C++, then you can fallback to
20033 @command{gcc} instead.
20035 For an example of better bindings generated from the C++ front-end,
20036 the name of the parameters (when available) are actually ignored by the C
20037 front-end. Consider the following C header:
20040 extern void foo (int variable);
20043 with the C front-end, @code{variable} is ignored, and the above is handled as:
20046 extern void foo (int);
20049 generating a generic:
20052 procedure foo (param1 : int);
20055 with the C++ front-end, the name is available, and we generate:
20058 procedure foo (variable : int);
20061 In some cases, the generated bindings will be more complete or more meaningful
20062 when defining some macros, which you can do via the @option{-D} switch. This
20063 is for example the case with @file{Xlib.h} under GNU/Linux:
20066 g++ -c -fdump-ada-spec -DXLIB_ILLEGAL_ACCESS -C /usr/include/X11/Xlib.h
20069 The above will generate more complete bindings than a straight call without
20070 the @option{-DXLIB_ILLEGAL_ACCESS} switch.
20072 In other cases, it is not possible to parse a header file in a stand-alone
20073 manner, because other include files need to be included first. In this
20074 case, the solution is to create a small header file including the needed
20075 @code{#include} and possible @code{#define} directives. For example, to
20076 generate Ada bindings for @file{readline/readline.h}, you need to first
20077 include @file{stdio.h}, so you can create a file with the following two
20078 lines in e.g. @file{readline1.h}:
20082 #include <readline/readline.h>
20085 and then generate Ada bindings from this file:
20088 $ g++ -c -fdump-ada-spec readline1.h
20091 @node Generating bindings for C++ headers
20092 @section Generating bindings for C++ headers
20095 Generating bindings for C++ headers is done using the same options, always
20096 with the @command{g++} compiler.
20098 In this mode, C++ classes will be mapped to Ada tagged types, constructors
20099 will be mapped using the @code{CPP_Constructor} pragma, and when possible,
20100 multiple inheritance of abstract classes will be mapped to Ada interfaces
20101 (@xref{Interfacing to C++,,,gnat_rm, GNAT Reference Manual}, for additional
20102 information on interfacing to C++).
20104 For example, given the following C++ header file:
20111 virtual int Number_Of_Teeth () = 0;
20116 virtual void Set_Owner (char* Name) = 0;
20122 virtual void Set_Age (int New_Age);
20125 class Dog : Animal, Carnivore, Domestic @{
20130 virtual int Number_Of_Teeth ();
20131 virtual void Set_Owner (char* Name);
20139 The corresponding Ada code is generated:
20141 @smallexample @c ada
20144 @b{package} Class_Carnivore @b{is}
20145 @b{type} Carnivore @b{is} @b{limited} interface;
20146 @b{pragma} Import (CPP, Carnivore);
20148 @b{function} Number_Of_Teeth (this : @b{access} Carnivore) @b{return} int @b{is} @b{abstract};
20150 @b{use} Class_Carnivore;
20152 @b{package} Class_Domestic @b{is}
20153 @b{type} Domestic @b{is} @b{limited} interface;
20154 @b{pragma} Import (CPP, Domestic);
20156 @b{procedure} Set_Owner
20157 (this : @b{access} Domestic;
20158 Name : Interfaces.C.Strings.chars_ptr) @b{is} @b{abstract};
20160 @b{use} Class_Domestic;
20162 @b{package} Class_Animal @b{is}
20163 @b{type} Animal @b{is} @b{tagged} @b{limited} @b{record}
20164 Age_Count : @b{aliased} int;
20165 @b{end} @b{record};
20166 @b{pragma} Import (CPP, Animal);
20168 @b{procedure} Set_Age (this : @b{access} Animal; New_Age : int);
20169 @b{pragma} Import (CPP, Set_Age, "_ZN6Animal7Set_AgeEi");
20171 @b{use} Class_Animal;
20173 @b{package} Class_Dog @b{is}
20174 @b{type} Dog @b{is} @b{new} Animal @b{and} Carnivore @b{and} Domestic @b{with} @b{record}
20175 Tooth_Count : @b{aliased} int;
20176 Owner : Interfaces.C.Strings.chars_ptr;
20177 @b{end} @b{record};
20178 @b{pragma} Import (CPP, Dog);
20180 @b{function} Number_Of_Teeth (this : @b{access} Dog) @b{return} int;
20181 @b{pragma} Import (CPP, Number_Of_Teeth, "_ZN3Dog15Number_Of_TeethEv");
20183 @b{procedure} Set_Owner
20184 (this : @b{access} Dog; Name : Interfaces.C.Strings.chars_ptr);
20185 @b{pragma} Import (CPP, Set_Owner, "_ZN3Dog9Set_OwnerEPc");
20187 @b{function} New_Dog @b{return} Dog;
20188 @b{pragma} CPP_Constructor (New_Dog);
20189 @b{pragma} Import (CPP, New_Dog, "_ZN3DogC1Ev");
20200 @item -fdump-ada-spec
20201 @cindex @option{-fdump-ada-spec} (@command{gcc})
20202 Generate Ada spec files for the given header files transitively (including
20203 all header files that these headers depend upon).
20205 @item -fdump-ada-spec-slim
20206 @cindex @option{-fdump-ada-spec-slim} (@command{gcc})
20207 Generate Ada spec files for the header files specified on the command line
20210 @item -fada-spec-parent=@var{unit}
20211 @cindex -fada-spec-parent (@command{gcc})
20212 Specifies that all files generated by @option{-fdump-ada-spec*} are
20213 to be child units of the specified parent unit.
20216 @cindex @option{-C} (@command{gcc})
20217 Extract comments from headers and generate Ada comments in the Ada spec files.
20220 @node Other Utility Programs
20221 @chapter Other Utility Programs
20224 This chapter discusses some other utility programs available in the Ada
20228 * Using Other Utility Programs with GNAT::
20229 * The External Symbol Naming Scheme of GNAT::
20230 * Converting Ada Files to html with gnathtml::
20231 * Installing gnathtml::
20234 @node Using Other Utility Programs with GNAT
20235 @section Using Other Utility Programs with GNAT
20238 The object files generated by GNAT are in standard system format and in
20239 particular the debugging information uses this format. This means
20240 programs generated by GNAT can be used with existing utilities that
20241 depend on these formats.
20243 In general, any utility program that works with C will also often work with
20244 Ada programs generated by GNAT. This includes software utilities such as
20245 gprof (a profiling program), @code{gdb} (the FSF debugger), and utilities such
20248 @node The External Symbol Naming Scheme of GNAT
20249 @section The External Symbol Naming Scheme of GNAT
20252 In order to interpret the output from GNAT, when using tools that are
20253 originally intended for use with other languages, it is useful to
20254 understand the conventions used to generate link names from the Ada
20257 All link names are in all lowercase letters. With the exception of library
20258 procedure names, the mechanism used is simply to use the full expanded
20259 Ada name with dots replaced by double underscores. For example, suppose
20260 we have the following package spec:
20262 @smallexample @c ada
20265 @b{package} QRS @b{is}
20273 The variable @code{MN} has a full expanded Ada name of @code{QRS.MN}, so
20274 the corresponding link name is @code{qrs__mn}.
20276 Of course if a @code{pragma Export} is used this may be overridden:
20278 @smallexample @c ada
20281 @b{package} Exports @b{is}
20283 @b{pragma} Export (Var1, C, External_Name => "var1_name");
20285 @b{pragma} Export (Var2, C, Link_Name => "var2_link_name");
20292 In this case, the link name for @var{Var1} is whatever link name the
20293 C compiler would assign for the C function @var{var1_name}. This typically
20294 would be either @var{var1_name} or @var{_var1_name}, depending on operating
20295 system conventions, but other possibilities exist. The link name for
20296 @var{Var2} is @var{var2_link_name}, and this is not operating system
20300 One exception occurs for library level procedures. A potential ambiguity
20301 arises between the required name @code{_main} for the C main program,
20302 and the name we would otherwise assign to an Ada library level procedure
20303 called @code{Main} (which might well not be the main program).
20305 To avoid this ambiguity, we attach the prefix @code{_ada_} to such
20306 names. So if we have a library level procedure such as
20308 @smallexample @c ada
20311 @b{procedure} Hello (S : String);
20317 the external name of this procedure will be @var{_ada_hello}.
20320 @node Converting Ada Files to html with gnathtml
20321 @section Converting Ada Files to HTML with @code{gnathtml}
20324 This @code{Perl} script allows Ada source files to be browsed using
20325 standard Web browsers. For installation procedure, see the section
20326 @xref{Installing gnathtml}.
20328 Ada reserved keywords are highlighted in a bold font and Ada comments in
20329 a blue font. Unless your program was compiled with the gcc @option{-gnatx}
20330 switch to suppress the generation of cross-referencing information, user
20331 defined variables and types will appear in a different color; you will
20332 be able to click on any identifier and go to its declaration.
20334 The command line is as follow:
20336 @c $ perl gnathtml.pl @ovar{switches} @var{ada-files}
20337 @c Expanding @ovar macro inline (explanation in macro def comments)
20338 $ perl gnathtml.pl @r{[}@var{switches}@r{]} @var{ada-files}
20342 You can pass it as many Ada files as you want. @code{gnathtml} will generate
20343 an html file for every ada file, and a global file called @file{index.htm}.
20344 This file is an index of every identifier defined in the files.
20346 The available switches are the following ones:
20350 @cindex @option{-83} (@code{gnathtml})
20351 Only the Ada 83 subset of keywords will be highlighted.
20353 @item -cc @var{color}
20354 @cindex @option{-cc} (@code{gnathtml})
20355 This option allows you to change the color used for comments. The default
20356 value is green. The color argument can be any name accepted by html.
20359 @cindex @option{-d} (@code{gnathtml})
20360 If the Ada files depend on some other files (for instance through
20361 @code{with} clauses, the latter files will also be converted to html.
20362 Only the files in the user project will be converted to html, not the files
20363 in the run-time library itself.
20366 @cindex @option{-D} (@code{gnathtml})
20367 This command is the same as @option{-d} above, but @command{gnathtml} will
20368 also look for files in the run-time library, and generate html files for them.
20370 @item -ext @var{extension}
20371 @cindex @option{-ext} (@code{gnathtml})
20372 This option allows you to change the extension of the generated HTML files.
20373 If you do not specify an extension, it will default to @file{htm}.
20376 @cindex @option{-f} (@code{gnathtml})
20377 By default, gnathtml will generate html links only for global entities
20378 ('with'ed units, global variables and types,@dots{}). If you specify
20379 @option{-f} on the command line, then links will be generated for local
20382 @item -l @var{number}
20383 @cindex @option{-l} (@code{gnathtml})
20384 If this switch is provided and @var{number} is not 0, then
20385 @code{gnathtml} will number the html files every @var{number} line.
20388 @cindex @option{-I} (@code{gnathtml})
20389 Specify a directory to search for library files (@file{.ALI} files) and
20390 source files. You can provide several -I switches on the command line,
20391 and the directories will be parsed in the order of the command line.
20394 @cindex @option{-o} (@code{gnathtml})
20395 Specify the output directory for html files. By default, gnathtml will
20396 saved the generated html files in a subdirectory named @file{html/}.
20398 @item -p @var{file}
20399 @cindex @option{-p} (@code{gnathtml})
20400 If you are using Emacs and the most recent Emacs Ada mode, which provides
20401 a full Integrated Development Environment for compiling, checking,
20402 running and debugging applications, you may use @file{.gpr} files
20403 to give the directories where Emacs can find sources and object files.
20405 Using this switch, you can tell gnathtml to use these files.
20406 This allows you to get an html version of your application, even if it
20407 is spread over multiple directories.
20409 @item -sc @var{color}
20410 @cindex @option{-sc} (@code{gnathtml})
20411 This switch allows you to change the color used for symbol
20413 The default value is red. The color argument can be any name accepted by html.
20415 @item -t @var{file}
20416 @cindex @option{-t} (@code{gnathtml})
20417 This switch provides the name of a file. This file contains a list of
20418 file names to be converted, and the effect is exactly as though they had
20419 appeared explicitly on the command line. This
20420 is the recommended way to work around the command line length limit on some
20425 @node Installing gnathtml
20426 @section Installing @code{gnathtml}
20429 @code{Perl} needs to be installed on your machine to run this script.
20430 @code{Perl} is freely available for almost every architecture and
20431 Operating System via the Internet.
20433 On Unix systems, you may want to modify the first line of the script
20434 @code{gnathtml}, to explicitly tell the Operating system where Perl
20435 is. The syntax of this line is:
20437 #!full_path_name_to_perl
20441 Alternatively, you may run the script using the following command line:
20444 @c $ perl gnathtml.pl @ovar{switches} @var{files}
20445 @c Expanding @ovar macro inline (explanation in macro def comments)
20446 $ perl gnathtml.pl @r{[}@var{switches}@r{]} @var{files}
20450 @c ******************************
20451 @node Code Coverage and Profiling
20452 @chapter Code Coverage and Profiling
20453 @cindex Code Coverage
20457 This chapter describes how to use @code{gcov} - coverage testing tool - and
20458 @code{gprof} - profiler tool - on your Ada programs.
20461 * Code Coverage of Ada Programs with gcov::
20462 * Profiling an Ada Program with gprof::
20465 @node Code Coverage of Ada Programs with gcov
20466 @section Code Coverage of Ada Programs with gcov
20468 @cindex -fprofile-arcs
20469 @cindex -ftest-coverage
20471 @cindex Code Coverage
20474 @code{gcov} is a test coverage program: it analyzes the execution of a given
20475 program on selected tests, to help you determine the portions of the program
20476 that are still untested.
20478 @code{gcov} is part of the GCC suite, and is described in detail in the GCC
20479 User's Guide. You can refer to this documentation for a more complete
20482 This chapter provides a quick startup guide, and
20483 details some Gnat-specific features.
20486 * Quick startup guide::
20490 @node Quick startup guide
20491 @subsection Quick startup guide
20493 In order to perform coverage analysis of a program using @code{gcov}, 3
20498 Code instrumentation during the compilation process
20500 Execution of the instrumented program
20502 Execution of the @code{gcov} tool to generate the result.
20505 The code instrumentation needed by gcov is created at the object level:
20506 The source code is not modified in any way, because the instrumentation code is
20507 inserted by gcc during the compilation process. To compile your code with code
20508 coverage activated, you need to recompile your whole project using the
20510 @code{-fprofile-arcs} and @code{-ftest-coverage}, and link it using
20511 @code{-fprofile-arcs}.
20514 $ gnatmake -P my_project.gpr -f -cargs -fprofile-arcs -ftest-coverage \
20515 -largs -fprofile-arcs
20518 This compilation process will create @file{.gcno} files together with
20519 the usual object files.
20521 Once the program is compiled with coverage instrumentation, you can
20522 run it as many times as needed - on portions of a test suite for
20523 example. The first execution will produce @file{.gcda} files at the
20524 same location as the @file{.gcno} files. The following executions
20525 will update those files, so that a cumulative result of the covered
20526 portions of the program is generated.
20528 Finally, you need to call the @code{gcov} tool. The different options of
20529 @code{gcov} are available in the GCC User's Guide, section 'Invoking gcov'.
20531 This will create annotated source files with a @file{.gcov} extension:
20532 @file{my_main.adb} file will be analysed in @file{my_main.adb.gcov}.
20534 @node Gnat specifics
20535 @subsection Gnat specifics
20537 Because Ada semantics, portions of the source code may be shared among
20538 several object files. This is the case for example when generics are
20539 involved, when inlining is active or when declarations generate initialisation
20540 calls. In order to take
20541 into account this shared code, you need to call @code{gcov} on all
20542 source files of the tested program at once.
20544 The list of source files might exceed the system's maximum command line
20545 length. In order to bypass this limitation, a new mechanism has been
20546 implemented in @code{gcov}: you can now list all your project's files into a
20547 text file, and provide this file to gcov as a parameter, preceded by a @@
20548 (e.g. @samp{gcov @@mysrclist.txt}).
20550 Note that on AIX compiling a static library with @code{-fprofile-arcs} is
20551 not supported as there can be unresolved symbols during the final link.
20553 @node Profiling an Ada Program with gprof
20554 @section Profiling an Ada Program with gprof
20560 This section is not meant to be an exhaustive documentation of @code{gprof}.
20561 Full documentation for it can be found in the GNU Profiler User's Guide
20562 documentation that is part of this GNAT distribution.
20564 Profiling a program helps determine the parts of a program that are executed
20565 most often, and are therefore the most time-consuming.
20567 @code{gprof} is the standard GNU profiling tool; it has been enhanced to
20568 better handle Ada programs and multitasking.
20569 It is currently supported on the following platforms
20574 solaris sparc/sparc64/x86
20580 In order to profile a program using @code{gprof}, 3 steps are needed:
20584 Code instrumentation, requiring a full recompilation of the project with the
20587 Execution of the program under the analysis conditions, i.e. with the desired
20590 Analysis of the results using the @code{gprof} tool.
20594 The following sections detail the different steps, and indicate how
20595 to interpret the results:
20597 * Compilation for profiling::
20598 * Program execution::
20600 * Interpretation of profiling results::
20603 @node Compilation for profiling
20604 @subsection Compilation for profiling
20608 In order to profile a program the first step is to tell the compiler
20609 to generate the necessary profiling information. The compiler switch to be used
20610 is @code{-pg}, which must be added to other compilation switches. This
20611 switch needs to be specified both during compilation and link stages, and can
20612 be specified once when using gnatmake:
20615 gnatmake -f -pg -P my_project
20619 Note that only the objects that were compiled with the @samp{-pg} switch will
20620 be profiled; if you need to profile your whole project, use the @samp{-f}
20621 gnatmake switch to force full recompilation.
20623 @node Program execution
20624 @subsection Program execution
20627 Once the program has been compiled for profiling, you can run it as usual.
20629 The only constraint imposed by profiling is that the program must terminate
20630 normally. An interrupted program (via a Ctrl-C, kill, etc.) will not be
20633 Once the program completes execution, a data file called @file{gmon.out} is
20634 generated in the directory where the program was launched from. If this file
20635 already exists, it will be overwritten.
20637 @node Running gprof
20638 @subsection Running gprof
20641 The @code{gprof} tool is called as follow:
20644 gprof my_prog gmon.out
20655 The complete form of the gprof command line is the following:
20658 gprof [switches] [executable [data-file]]
20662 @code{gprof} supports numerous switch. The order of these
20663 switch does not matter. The full list of options can be found in
20664 the GNU Profiler User's Guide documentation that comes with this documentation.
20666 The following is the subset of those switches that is most relevant:
20670 @item --demangle[=@var{style}]
20671 @itemx --no-demangle
20672 @cindex @option{--demangle} (@code{gprof})
20673 These options control whether symbol names should be demangled when
20674 printing output. The default is to demangle C++ symbols. The
20675 @code{--no-demangle} option may be used to turn off demangling. Different
20676 compilers have different mangling styles. The optional demangling style
20677 argument can be used to choose an appropriate demangling style for your
20678 compiler, in particular Ada symbols generated by GNAT can be demangled using
20679 @code{--demangle=gnat}.
20681 @item -e @var{function_name}
20682 @cindex @option{-e} (@code{gprof})
20683 The @samp{-e @var{function}} option tells @code{gprof} not to print
20684 information about the function @var{function_name} (and its
20685 children@dots{}) in the call graph. The function will still be listed
20686 as a child of any functions that call it, but its index number will be
20687 shown as @samp{[not printed]}. More than one @samp{-e} option may be
20688 given; only one @var{function_name} may be indicated with each @samp{-e}
20691 @item -E @var{function_name}
20692 @cindex @option{-E} (@code{gprof})
20693 The @code{-E @var{function}} option works like the @code{-e} option, but
20694 execution time spent in the function (and children who were not called from
20695 anywhere else), will not be used to compute the percentages-of-time for
20696 the call graph. More than one @samp{-E} option may be given; only one
20697 @var{function_name} may be indicated with each @samp{-E} option.
20699 @item -f @var{function_name}
20700 @cindex @option{-f} (@code{gprof})
20701 The @samp{-f @var{function}} option causes @code{gprof} to limit the
20702 call graph to the function @var{function_name} and its children (and
20703 their children@dots{}). More than one @samp{-f} option may be given;
20704 only one @var{function_name} may be indicated with each @samp{-f}
20707 @item -F @var{function_name}
20708 @cindex @option{-F} (@code{gprof})
20709 The @samp{-F @var{function}} option works like the @code{-f} option, but
20710 only time spent in the function and its children (and their
20711 children@dots{}) will be used to determine total-time and
20712 percentages-of-time for the call graph. More than one @samp{-F} option
20713 may be given; only one @var{function_name} may be indicated with each
20714 @samp{-F} option. The @samp{-F} option overrides the @samp{-E} option.
20718 @node Interpretation of profiling results
20719 @subsection Interpretation of profiling results
20723 The results of the profiling analysis are represented by two arrays: the
20724 'flat profile' and the 'call graph'. Full documentation of those outputs
20725 can be found in the GNU Profiler User's Guide.
20727 The flat profile shows the time spent in each function of the program, and how
20728 many time it has been called. This allows you to locate easily the most
20729 time-consuming functions.
20731 The call graph shows, for each subprogram, the subprograms that call it,
20732 and the subprograms that it calls. It also provides an estimate of the time
20733 spent in each of those callers/called subprograms.
20735 @c ******************************
20736 @node Running and Debugging Ada Programs
20737 @chapter Running and Debugging Ada Programs
20741 This chapter discusses how to debug Ada programs.
20743 An incorrect Ada program may be handled in three ways by the GNAT compiler:
20747 The illegality may be a violation of the static semantics of Ada. In
20748 that case GNAT diagnoses the constructs in the program that are illegal.
20749 It is then a straightforward matter for the user to modify those parts of
20753 The illegality may be a violation of the dynamic semantics of Ada. In
20754 that case the program compiles and executes, but may generate incorrect
20755 results, or may terminate abnormally with some exception.
20758 When presented with a program that contains convoluted errors, GNAT
20759 itself may terminate abnormally without providing full diagnostics on
20760 the incorrect user program.
20764 * The GNAT Debugger GDB::
20766 * Introduction to GDB Commands::
20767 * Using Ada Expressions::
20768 * Calling User-Defined Subprograms::
20769 * Using the Next Command in a Function::
20772 * Debugging Generic Units::
20773 * Remote Debugging with gdbserver::
20774 * GNAT Abnormal Termination or Failure to Terminate::
20775 * Naming Conventions for GNAT Source Files::
20776 * Getting Internal Debugging Information::
20777 * Stack Traceback::
20783 @node The GNAT Debugger GDB
20784 @section The GNAT Debugger GDB
20787 @code{GDB} is a general purpose, platform-independent debugger that
20788 can be used to debug mixed-language programs compiled with @command{gcc},
20789 and in particular is capable of debugging Ada programs compiled with
20790 GNAT. The latest versions of @code{GDB} are Ada-aware and can handle
20791 complex Ada data structures.
20793 @xref{Top,, Debugging with GDB, gdb, Debugging with GDB},
20794 for full details on the usage of @code{GDB}, including a section on
20795 its usage on programs. This manual should be consulted for full
20796 details. The section that follows is a brief introduction to the
20797 philosophy and use of @code{GDB}.
20799 When GNAT programs are compiled, the compiler optionally writes debugging
20800 information into the generated object file, including information on
20801 line numbers, and on declared types and variables. This information is
20802 separate from the generated code. It makes the object files considerably
20803 larger, but it does not add to the size of the actual executable that
20804 will be loaded into memory, and has no impact on run-time performance. The
20805 generation of debug information is triggered by the use of the
20806 -g switch in the @command{gcc} or @command{gnatmake} command
20807 used to carry out the compilations. It is important to emphasize that
20808 the use of these options does not change the generated code.
20810 The debugging information is written in standard system formats that
20811 are used by many tools, including debuggers and profilers. The format
20812 of the information is typically designed to describe C types and
20813 semantics, but GNAT implements a translation scheme which allows full
20814 details about Ada types and variables to be encoded into these
20815 standard C formats. Details of this encoding scheme may be found in
20816 the file exp_dbug.ads in the GNAT source distribution. However, the
20817 details of this encoding are, in general, of no interest to a user,
20818 since @code{GDB} automatically performs the necessary decoding.
20820 When a program is bound and linked, the debugging information is
20821 collected from the object files, and stored in the executable image of
20822 the program. Again, this process significantly increases the size of
20823 the generated executable file, but it does not increase the size of
20824 the executable program itself. Furthermore, if this program is run in
20825 the normal manner, it runs exactly as if the debug information were
20826 not present, and takes no more actual memory.
20828 However, if the program is run under control of @code{GDB}, the
20829 debugger is activated. The image of the program is loaded, at which
20830 point it is ready to run. If a run command is given, then the program
20831 will run exactly as it would have if @code{GDB} were not present. This
20832 is a crucial part of the @code{GDB} design philosophy. @code{GDB} is
20833 entirely non-intrusive until a breakpoint is encountered. If no
20834 breakpoint is ever hit, the program will run exactly as it would if no
20835 debugger were present. When a breakpoint is hit, @code{GDB} accesses
20836 the debugging information and can respond to user commands to inspect
20837 variables, and more generally to report on the state of execution.
20841 @section Running GDB
20844 This section describes how to initiate the debugger.
20845 @c The above sentence is really just filler, but it was otherwise
20846 @c clumsy to get the first paragraph nonindented given the conditional
20847 @c nature of the description
20849 The debugger can be launched from a @code{GPS} menu or
20850 directly from the command line. The description below covers the latter use.
20851 All the commands shown can be used in the @code{GPS} debug console window,
20852 but there are usually more GUI-based ways to achieve the same effect.
20854 The command to run @code{GDB} is
20861 where @code{program} is the name of the executable file. This
20862 activates the debugger and results in a prompt for debugger commands.
20863 The simplest command is simply @code{run}, which causes the program to run
20864 exactly as if the debugger were not present. The following section
20865 describes some of the additional commands that can be given to @code{GDB}.
20867 @c *******************************
20868 @node Introduction to GDB Commands
20869 @section Introduction to GDB Commands
20872 @code{GDB} contains a large repertoire of commands. @xref{Top,,
20873 Debugging with GDB, gdb, Debugging with GDB},
20874 for extensive documentation on the use
20875 of these commands, together with examples of their use. Furthermore,
20876 the command @command{help} invoked from within GDB activates a simple help
20877 facility which summarizes the available commands and their options.
20878 In this section we summarize a few of the most commonly
20879 used commands to give an idea of what @code{GDB} is about. You should create
20880 a simple program with debugging information and experiment with the use of
20881 these @code{GDB} commands on the program as you read through the
20885 @item set args @var{arguments}
20886 The @var{arguments} list above is a list of arguments to be passed to
20887 the program on a subsequent run command, just as though the arguments
20888 had been entered on a normal invocation of the program. The @code{set args}
20889 command is not needed if the program does not require arguments.
20892 The @code{run} command causes execution of the program to start from
20893 the beginning. If the program is already running, that is to say if
20894 you are currently positioned at a breakpoint, then a prompt will ask
20895 for confirmation that you want to abandon the current execution and
20898 @item breakpoint @var{location}
20899 The breakpoint command sets a breakpoint, that is to say a point at which
20900 execution will halt and @code{GDB} will await further
20901 commands. @var{location} is
20902 either a line number within a file, given in the format @code{file:linenumber},
20903 or it is the name of a subprogram. If you request that a breakpoint be set on
20904 a subprogram that is overloaded, a prompt will ask you to specify on which of
20905 those subprograms you want to breakpoint. You can also
20906 specify that all of them should be breakpointed. If the program is run
20907 and execution encounters the breakpoint, then the program
20908 stops and @code{GDB} signals that the breakpoint was encountered by
20909 printing the line of code before which the program is halted.
20911 @item catch exception @var{name}
20912 This command causes the program execution to stop whenever exception
20913 @var{name} is raised. If @var{name} is omitted, then the execution is
20914 suspended when any exception is raised.
20916 @item print @var{expression}
20917 This will print the value of the given expression. Most simple
20918 Ada expression formats are properly handled by @code{GDB}, so the expression
20919 can contain function calls, variables, operators, and attribute references.
20922 Continues execution following a breakpoint, until the next breakpoint or the
20923 termination of the program.
20926 Executes a single line after a breakpoint. If the next statement
20927 is a subprogram call, execution continues into (the first statement of)
20928 the called subprogram.
20931 Executes a single line. If this line is a subprogram call, executes and
20932 returns from the call.
20935 Lists a few lines around the current source location. In practice, it
20936 is usually more convenient to have a separate edit window open with the
20937 relevant source file displayed. Successive applications of this command
20938 print subsequent lines. The command can be given an argument which is a
20939 line number, in which case it displays a few lines around the specified one.
20942 Displays a backtrace of the call chain. This command is typically
20943 used after a breakpoint has occurred, to examine the sequence of calls that
20944 leads to the current breakpoint. The display includes one line for each
20945 activation record (frame) corresponding to an active subprogram.
20948 At a breakpoint, @code{GDB} can display the values of variables local
20949 to the current frame. The command @code{up} can be used to
20950 examine the contents of other active frames, by moving the focus up
20951 the stack, that is to say from callee to caller, one frame at a time.
20954 Moves the focus of @code{GDB} down from the frame currently being
20955 examined to the frame of its callee (the reverse of the previous command),
20957 @item frame @var{n}
20958 Inspect the frame with the given number. The value 0 denotes the frame
20959 of the current breakpoint, that is to say the top of the call stack.
20962 Kills the child process in which the program is running under GDB.
20963 This may be useful for several purposes:
20966 It allows you to recompile and relink your program, since on many systems
20967 you cannot regenerate an executable file while it is running in a process.
20969 You can run your program outside the debugger, on systems that do not
20970 permit executing a program outside GDB while breakpoints are set
20973 It allows you to debug a core dump rather than a running process.
20978 The above list is a very short introduction to the commands that
20979 @code{GDB} provides. Important additional capabilities, including conditional
20980 breakpoints, the ability to execute command sequences on a breakpoint,
20981 the ability to debug at the machine instruction level and many other
20982 features are described in detail in @ref{Top,, Debugging with GDB, gdb,
20983 Debugging with GDB}. Note that most commands can be abbreviated
20984 (for example, c for continue, bt for backtrace).
20986 @node Using Ada Expressions
20987 @section Using Ada Expressions
20988 @cindex Ada expressions
20991 @code{GDB} supports a fairly large subset of Ada expression syntax, with some
20992 extensions. The philosophy behind the design of this subset is
20996 That @code{GDB} should provide basic literals and access to operations for
20997 arithmetic, dereferencing, field selection, indexing, and subprogram calls,
20998 leaving more sophisticated computations to subprograms written into the
20999 program (which therefore may be called from @code{GDB}).
21002 That type safety and strict adherence to Ada language restrictions
21003 are not particularly important to the @code{GDB} user.
21006 That brevity is important to the @code{GDB} user.
21010 Thus, for brevity, the debugger acts as if there were
21011 implicit @code{with} and @code{use} clauses in effect for all user-written
21012 packages, thus making it unnecessary to fully qualify most names with
21013 their packages, regardless of context. Where this causes ambiguity,
21014 @code{GDB} asks the user's intent.
21016 For details on the supported Ada syntax, see @ref{Top,, Debugging with
21017 GDB, gdb, Debugging with GDB}.
21019 @node Calling User-Defined Subprograms
21020 @section Calling User-Defined Subprograms
21023 An important capability of @code{GDB} is the ability to call user-defined
21024 subprograms while debugging. This is achieved simply by entering
21025 a subprogram call statement in the form:
21028 call subprogram-name (parameters)
21032 The keyword @code{call} can be omitted in the normal case where the
21033 @code{subprogram-name} does not coincide with any of the predefined
21034 @code{GDB} commands.
21036 The effect is to invoke the given subprogram, passing it the
21037 list of parameters that is supplied. The parameters can be expressions and
21038 can include variables from the program being debugged. The
21039 subprogram must be defined
21040 at the library level within your program, and @code{GDB} will call the
21041 subprogram within the environment of your program execution (which
21042 means that the subprogram is free to access or even modify variables
21043 within your program).
21045 The most important use of this facility is in allowing the inclusion of
21046 debugging routines that are tailored to particular data structures
21047 in your program. Such debugging routines can be written to provide a suitably
21048 high-level description of an abstract type, rather than a low-level dump
21049 of its physical layout. After all, the standard
21050 @code{GDB print} command only knows the physical layout of your
21051 types, not their abstract meaning. Debugging routines can provide information
21052 at the desired semantic level and are thus enormously useful.
21054 For example, when debugging GNAT itself, it is crucial to have access to
21055 the contents of the tree nodes used to represent the program internally.
21056 But tree nodes are represented simply by an integer value (which in turn
21057 is an index into a table of nodes).
21058 Using the @code{print} command on a tree node would simply print this integer
21059 value, which is not very useful. But the PN routine (defined in file
21060 treepr.adb in the GNAT sources) takes a tree node as input, and displays
21061 a useful high level representation of the tree node, which includes the
21062 syntactic category of the node, its position in the source, the integers
21063 that denote descendant nodes and parent node, as well as varied
21064 semantic information. To study this example in more detail, you might want to
21065 look at the body of the PN procedure in the stated file.
21067 Another useful application of this capability is to deal with situations of
21068 complex data which are not handled suitably by GDB. For example, if you specify
21069 Convention Fortran for a multi-dimensional array, GDB does not know that
21070 the ordering of array elements has been switched and will not properly
21071 address the array elements. In such a case, instead of trying to print the
21072 elements directly from GDB, you can write a callable procedure that prints
21073 the elements in the desired format.
21075 @node Using the Next Command in a Function
21076 @section Using the Next Command in a Function
21079 When you use the @code{next} command in a function, the current source
21080 location will advance to the next statement as usual. A special case
21081 arises in the case of a @code{return} statement.
21083 Part of the code for a return statement is the ``epilogue'' of the function.
21084 This is the code that returns to the caller. There is only one copy of
21085 this epilogue code, and it is typically associated with the last return
21086 statement in the function if there is more than one return. In some
21087 implementations, this epilogue is associated with the first statement
21090 The result is that if you use the @code{next} command from a return
21091 statement that is not the last return statement of the function you
21092 may see a strange apparent jump to the last return statement or to
21093 the start of the function. You should simply ignore this odd jump.
21094 The value returned is always that from the first return statement
21095 that was stepped through.
21097 @node Ada Exceptions
21098 @section Stopping when Ada Exceptions are Raised
21102 You can set catchpoints that stop the program execution when your program
21103 raises selected exceptions.
21106 @item catch exception
21107 Set a catchpoint that stops execution whenever (any task in the) program
21108 raises any exception.
21110 @item catch exception @var{name}
21111 Set a catchpoint that stops execution whenever (any task in the) program
21112 raises the exception @var{name}.
21114 @item catch exception unhandled
21115 Set a catchpoint that stops executing whenever (any task in the) program
21116 raises an exception for which there is no handler.
21118 @item info exceptions
21119 @itemx info exceptions @var{regexp}
21120 The @code{info exceptions} command permits the user to examine all defined
21121 exceptions within Ada programs. With a regular expression, @var{regexp}, as
21122 argument, prints out only those exceptions whose name matches @var{regexp}.
21130 @code{GDB} allows the following task-related commands:
21134 This command shows a list of current Ada tasks, as in the following example:
21141 ID TID P-ID Thread Pri State Name
21142 1 8088000 0 807e000 15 Child Activation Wait main_task
21143 2 80a4000 1 80ae000 15 Accept/Select Wait b
21144 3 809a800 1 80a4800 15 Child Activation Wait a
21145 * 4 80ae800 3 80b8000 15 Running c
21149 In this listing, the asterisk before the first task indicates it to be the
21150 currently running task. The first column lists the task ID that is used
21151 to refer to tasks in the following commands.
21153 @item break @var{linespec} task @var{taskid}
21154 @itemx break @var{linespec} task @var{taskid} if @dots{}
21155 @cindex Breakpoints and tasks
21156 These commands are like the @code{break @dots{} thread @dots{}}.
21157 @var{linespec} specifies source lines.
21159 Use the qualifier @samp{task @var{taskid}} with a breakpoint command
21160 to specify that you only want @code{GDB} to stop the program when a
21161 particular Ada task reaches this breakpoint. @var{taskid} is one of the
21162 numeric task identifiers assigned by @code{GDB}, shown in the first
21163 column of the @samp{info tasks} display.
21165 If you do not specify @samp{task @var{taskid}} when you set a
21166 breakpoint, the breakpoint applies to @emph{all} tasks of your
21169 You can use the @code{task} qualifier on conditional breakpoints as
21170 well; in this case, place @samp{task @var{taskid}} before the
21171 breakpoint condition (before the @code{if}).
21173 @item task @var{taskno}
21174 @cindex Task switching
21176 This command allows switching to the task referred by @var{taskno}. In
21177 particular, this allows browsing of the backtrace of the specified
21178 task. It is advisable to switch back to the original task before
21179 continuing execution otherwise the scheduling of the program may be
21184 For more detailed information on the tasking support,
21185 see @ref{Top,, Debugging with GDB, gdb, Debugging with GDB}.
21187 @node Debugging Generic Units
21188 @section Debugging Generic Units
21189 @cindex Debugging Generic Units
21193 GNAT always uses code expansion for generic instantiation. This means that
21194 each time an instantiation occurs, a complete copy of the original code is
21195 made, with appropriate substitutions of formals by actuals.
21197 It is not possible to refer to the original generic entities in
21198 @code{GDB}, but it is always possible to debug a particular instance of
21199 a generic, by using the appropriate expanded names. For example, if we have
21201 @smallexample @c ada
21204 @b{procedure} g @b{is}
21206 @b{generic} @b{package} k @b{is}
21207 @b{procedure} kp (v1 : @b{in} @b{out} integer);
21210 @b{package} @b{body} k @b{is}
21211 @b{procedure} kp (v1 : @b{in} @b{out} integer) @b{is}
21217 @b{package} k1 @b{is} @b{new} k;
21218 @b{package} k2 @b{is} @b{new} k;
21220 var : integer := 1;
21233 Then to break on a call to procedure kp in the k2 instance, simply
21237 (gdb) break g.k2.kp
21241 When the breakpoint occurs, you can step through the code of the
21242 instance in the normal manner and examine the values of local variables, as for
21245 @node Remote Debugging with gdbserver
21246 @section Remote Debugging with gdbserver
21247 @cindex Remote Debugging with gdbserver
21250 On platforms where gdbserver is supported, it is possible to use this tool
21251 to debug your application remotely. This can be useful in situations
21252 where the program needs to be run on a target host that is different
21253 from the host used for development, particularly when the target has
21254 a limited amount of resources (either CPU and/or memory).
21256 To do so, start your program using gdbserver on the target machine.
21257 gdbserver then automatically suspends the execution of your program
21258 at its entry point, waiting for a debugger to connect to it. The
21259 following commands starts an application and tells gdbserver to
21260 wait for a connection with the debugger on localhost port 4444.
21263 $ gdbserver localhost:4444 program
21264 Process program created; pid = 5685
21265 Listening on port 4444
21268 Once gdbserver has started listening, we can tell the debugger to establish
21269 a connection with this gdbserver, and then start the same debugging session
21270 as if the program was being debugged on the same host, directly under
21271 the control of GDB.
21275 (gdb) target remote targethost:4444
21276 Remote debugging using targethost:4444
21277 0x00007f29936d0af0 in ?? () from /lib64/ld-linux-x86-64.so.
21279 Breakpoint 1 at 0x401f0c: file foo.adb, line 3.
21283 Breakpoint 1, foo () at foo.adb:4
21287 It is also possible to use gdbserver to attach to an already running
21288 program, in which case the execution of that program is simply suspended
21289 until the connection between the debugger and gdbserver is established.
21291 For more information on how to use gdbserver, @ref{Top, Server, Using
21292 the gdbserver Program, gdb, Debugging with GDB}. @value{EDITION} provides support
21293 for gdbserver on x86-linux, x86-windows and x86_64-linux.
21295 @node GNAT Abnormal Termination or Failure to Terminate
21296 @section GNAT Abnormal Termination or Failure to Terminate
21297 @cindex GNAT Abnormal Termination or Failure to Terminate
21300 When presented with programs that contain serious errors in syntax
21302 GNAT may on rare occasions experience problems in operation, such
21304 segmentation fault or illegal memory access, raising an internal
21305 exception, terminating abnormally, or failing to terminate at all.
21306 In such cases, you can activate
21307 various features of GNAT that can help you pinpoint the construct in your
21308 program that is the likely source of the problem.
21310 The following strategies are presented in increasing order of
21311 difficulty, corresponding to your experience in using GNAT and your
21312 familiarity with compiler internals.
21316 Run @command{gcc} with the @option{-gnatf}. This first
21317 switch causes all errors on a given line to be reported. In its absence,
21318 only the first error on a line is displayed.
21320 The @option{-gnatdO} switch causes errors to be displayed as soon as they
21321 are encountered, rather than after compilation is terminated. If GNAT
21322 terminates prematurely or goes into an infinite loop, the last error
21323 message displayed may help to pinpoint the culprit.
21326 Run @command{gcc} with the @option{-v (verbose)} switch. In this
21327 mode, @command{gcc} produces ongoing information about the progress of the
21328 compilation and provides the name of each procedure as code is
21329 generated. This switch allows you to find which Ada procedure was being
21330 compiled when it encountered a code generation problem.
21333 @cindex @option{-gnatdc} switch
21334 Run @command{gcc} with the @option{-gnatdc} switch. This is a GNAT specific
21335 switch that does for the front-end what @option{-v} does
21336 for the back end. The system prints the name of each unit,
21337 either a compilation unit or nested unit, as it is being analyzed.
21339 Finally, you can start
21340 @code{gdb} directly on the @code{gnat1} executable. @code{gnat1} is the
21341 front-end of GNAT, and can be run independently (normally it is just
21342 called from @command{gcc}). You can use @code{gdb} on @code{gnat1} as you
21343 would on a C program (but @pxref{The GNAT Debugger GDB} for caveats). The
21344 @code{where} command is the first line of attack; the variable
21345 @code{lineno} (seen by @code{print lineno}), used by the second phase of
21346 @code{gnat1} and by the @command{gcc} backend, indicates the source line at
21347 which the execution stopped, and @code{input_file name} indicates the name of
21351 @node Naming Conventions for GNAT Source Files
21352 @section Naming Conventions for GNAT Source Files
21355 In order to examine the workings of the GNAT system, the following
21356 brief description of its organization may be helpful:
21360 Files with prefix @file{sc} contain the lexical scanner.
21363 All files prefixed with @file{par} are components of the parser. The
21364 numbers correspond to chapters of the Ada Reference Manual. For example,
21365 parsing of select statements can be found in @file{par-ch9.adb}.
21368 All files prefixed with @file{sem} perform semantic analysis. The
21369 numbers correspond to chapters of the Ada standard. For example, all
21370 issues involving context clauses can be found in @file{sem_ch10.adb}. In
21371 addition, some features of the language require sufficient special processing
21372 to justify their own semantic files: sem_aggr for aggregates, sem_disp for
21373 dynamic dispatching, etc.
21376 All files prefixed with @file{exp} perform normalization and
21377 expansion of the intermediate representation (abstract syntax tree, or AST).
21378 these files use the same numbering scheme as the parser and semantics files.
21379 For example, the construction of record initialization procedures is done in
21380 @file{exp_ch3.adb}.
21383 The files prefixed with @file{bind} implement the binder, which
21384 verifies the consistency of the compilation, determines an order of
21385 elaboration, and generates the bind file.
21388 The files @file{atree.ads} and @file{atree.adb} detail the low-level
21389 data structures used by the front-end.
21392 The files @file{sinfo.ads} and @file{sinfo.adb} detail the structure of
21393 the abstract syntax tree as produced by the parser.
21396 The files @file{einfo.ads} and @file{einfo.adb} detail the attributes of
21397 all entities, computed during semantic analysis.
21400 Library management issues are dealt with in files with prefix
21406 Ada files with the prefix @file{a-} are children of @code{Ada}, as
21407 defined in Annex A.
21412 Files with prefix @file{i-} are children of @code{Interfaces}, as
21413 defined in Annex B.
21417 Files with prefix @file{s-} are children of @code{System}. This includes
21418 both language-defined children and GNAT run-time routines.
21422 Files with prefix @file{g-} are children of @code{GNAT}. These are useful
21423 general-purpose packages, fully documented in their specs. All
21424 the other @file{.c} files are modifications of common @command{gcc} files.
21427 @node Getting Internal Debugging Information
21428 @section Getting Internal Debugging Information
21431 Most compilers have internal debugging switches and modes. GNAT
21432 does also, except GNAT internal debugging switches and modes are not
21433 secret. A summary and full description of all the compiler and binder
21434 debug flags are in the file @file{debug.adb}. You must obtain the
21435 sources of the compiler to see the full detailed effects of these flags.
21437 The switches that print the source of the program (reconstructed from
21438 the internal tree) are of general interest for user programs, as are the
21440 the full internal tree, and the entity table (the symbol table
21441 information). The reconstructed source provides a readable version of the
21442 program after the front-end has completed analysis and expansion,
21443 and is useful when studying the performance of specific constructs.
21444 For example, constraint checks are indicated, complex aggregates
21445 are replaced with loops and assignments, and tasking primitives
21446 are replaced with run-time calls.
21448 @node Stack Traceback
21449 @section Stack Traceback
21451 @cindex stack traceback
21452 @cindex stack unwinding
21455 Traceback is a mechanism to display the sequence of subprogram calls that
21456 leads to a specified execution point in a program. Often (but not always)
21457 the execution point is an instruction at which an exception has been raised.
21458 This mechanism is also known as @i{stack unwinding} because it obtains
21459 its information by scanning the run-time stack and recovering the activation
21460 records of all active subprograms. Stack unwinding is one of the most
21461 important tools for program debugging.
21463 The first entry stored in traceback corresponds to the deepest calling level,
21464 that is to say the subprogram currently executing the instruction
21465 from which we want to obtain the traceback.
21467 Note that there is no runtime performance penalty when stack traceback
21468 is enabled, and no exception is raised during program execution.
21471 * Non-Symbolic Traceback::
21472 * Symbolic Traceback::
21475 @node Non-Symbolic Traceback
21476 @subsection Non-Symbolic Traceback
21477 @cindex traceback, non-symbolic
21480 Note: this feature is not supported on all platforms. See
21481 @file{GNAT.Traceback spec in g-traceb.ads} for a complete list of supported
21485 * Tracebacks From an Unhandled Exception::
21486 * Tracebacks From Exception Occurrences (non-symbolic)::
21487 * Tracebacks From Anywhere in a Program (non-symbolic)::
21490 @node Tracebacks From an Unhandled Exception
21491 @subsubsection Tracebacks From an Unhandled Exception
21494 A runtime non-symbolic traceback is a list of addresses of call instructions.
21495 To enable this feature you must use the @option{-E}
21496 @code{gnatbind}'s option. With this option a stack traceback is stored as part
21497 of exception information. You can retrieve this information using the
21498 @code{addr2line} tool.
21500 Here is a simple example:
21502 @smallexample @c ada
21504 @b{procedure} STB @b{is}
21506 @b{procedure} P1 @b{is}
21508 @b{raise} Constraint_Error;
21511 @b{procedure} P2 @b{is}
21523 $ gnatmake stb -bargs -E
21526 Execution terminated by unhandled exception
21527 Exception name: CONSTRAINT_ERROR
21529 Call stack traceback locations:
21530 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
21534 As we see the traceback lists a sequence of addresses for the unhandled
21535 exception @code{CONSTRAINT_ERROR} raised in procedure P1. It is easy to
21536 guess that this exception come from procedure P1. To translate these
21537 addresses into the source lines where the calls appear, the
21538 @code{addr2line} tool, described below, is invaluable. The use of this tool
21539 requires the program to be compiled with debug information.
21542 $ gnatmake -g stb -bargs -E
21545 Execution terminated by unhandled exception
21546 Exception name: CONSTRAINT_ERROR
21548 Call stack traceback locations:
21549 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
21551 $ addr2line --exe=stb 0x401373 0x40138b 0x40139c 0x401335 0x4011c4
21552 0x4011f1 0x77e892a4
21554 00401373 at d:/stb/stb.adb:5
21555 0040138B at d:/stb/stb.adb:10
21556 0040139C at d:/stb/stb.adb:14
21557 00401335 at d:/stb/b~stb.adb:104
21558 004011C4 at /build/@dots{}/crt1.c:200
21559 004011F1 at /build/@dots{}/crt1.c:222
21560 77E892A4 in ?? at ??:0
21564 The @code{addr2line} tool has several other useful options:
21568 to get the function name corresponding to any location
21570 @item --demangle=gnat
21571 to use the gnat decoding mode for the function names. Note that
21572 for binutils version 2.9.x the option is simply @option{--demangle}.
21576 $ addr2line --exe=stb --functions --demangle=gnat 0x401373 0x40138b
21577 0x40139c 0x401335 0x4011c4 0x4011f1
21579 00401373 in stb.p1 at d:/stb/stb.adb:5
21580 0040138B in stb.p2 at d:/stb/stb.adb:10
21581 0040139C in stb at d:/stb/stb.adb:14
21582 00401335 in main at d:/stb/b~stb.adb:104
21583 004011C4 in <__mingw_CRTStartup> at /build/@dots{}/crt1.c:200
21584 004011F1 in <mainCRTStartup> at /build/@dots{}/crt1.c:222
21588 From this traceback we can see that the exception was raised in
21589 @file{stb.adb} at line 5, which was reached from a procedure call in
21590 @file{stb.adb} at line 10, and so on. The @file{b~std.adb} is the binder file,
21591 which contains the call to the main program.
21592 @xref{Running gnatbind}. The remaining entries are assorted runtime routines,
21593 and the output will vary from platform to platform.
21595 It is also possible to use @code{GDB} with these traceback addresses to debug
21596 the program. For example, we can break at a given code location, as reported
21597 in the stack traceback:
21602 Furthermore, this feature is not implemented inside Windows DLL. Only
21603 the non-symbolic traceback is reported in this case.
21605 (gdb) break *0x401373
21606 Breakpoint 1 at 0x401373: file stb.adb, line 5.
21610 It is important to note that the stack traceback addresses
21611 do not change when debug information is included. This is particularly useful
21612 because it makes it possible to release software without debug information (to
21613 minimize object size), get a field report that includes a stack traceback
21614 whenever an internal bug occurs, and then be able to retrieve the sequence
21615 of calls with the same program compiled with debug information.
21617 @node Tracebacks From Exception Occurrences (non-symbolic)
21618 @subsubsection Tracebacks From Exception Occurrences
21621 Non-symbolic tracebacks are obtained by using the @option{-E} binder argument.
21622 The stack traceback is attached to the exception information string, and can
21623 be retrieved in an exception handler within the Ada program, by means of the
21624 Ada facilities defined in @code{Ada.Exceptions}. Here is a simple example:
21626 @smallexample @c ada
21627 @b{with} Ada.Text_IO;
21628 @b{with} Ada.Exceptions;
21630 @b{procedure} STB @b{is}
21633 @b{use} Ada.Exceptions;
21635 @b{procedure} P1 @b{is}
21640 @b{when} E : @b{others} =>
21641 Text_IO.Put_Line (Exception_Information (E));
21644 @b{procedure} P2 @b{is}
21655 This program will output:
21660 Exception name: CONSTRAINT_ERROR
21661 Message: stb.adb:12
21662 Call stack traceback locations:
21663 0x4015e4 0x401633 0x401644 0x401461 0x4011c4 0x4011f1 0x77e892a4
21666 @node Tracebacks From Anywhere in a Program (non-symbolic)
21667 @subsubsection Tracebacks From Anywhere in a Program
21670 It is also possible to retrieve a stack traceback from anywhere in a
21671 program. For this you need to
21672 use the @code{GNAT.Traceback} API. This package includes a procedure called
21673 @code{Call_Chain} that computes a complete stack traceback, as well as useful
21674 display procedures described below. It is not necessary to use the
21675 @option{-E gnatbind} option in this case, because the stack traceback mechanism
21676 is invoked explicitly.
21679 In the following example we compute a traceback at a specific location in
21680 the program, and we display it using @code{GNAT.Debug_Utilities.Image} to
21681 convert addresses to strings:
21683 @smallexample @c ada
21684 @b{with} Ada.Text_IO;
21685 @b{with} GNAT.Traceback;
21686 @b{with} GNAT.Debug_Utilities;
21688 @b{procedure} STB @b{is}
21692 @b{use} GNAT.Traceback;
21694 @b{procedure} P1 @b{is}
21695 TB : Tracebacks_Array (1 .. 10);
21696 --@i{ We are asking for a maximum of 10 stack frames.}
21698 --@i{ Len will receive the actual number of stack frames returned.}
21700 Call_Chain (TB, Len);
21702 Text_IO.Put ("In STB.P1 : ");
21704 @b{for} K @b{in} 1 .. Len @b{loop}
21705 Text_IO.Put (Debug_Utilities.Image (TB (K)));
21712 @b{procedure} P2 @b{is}
21726 In STB.P1 : 16#0040_F1E4# 16#0040_14F2# 16#0040_170B# 16#0040_171C#
21727 16#0040_1461# 16#0040_11C4# 16#0040_11F1# 16#77E8_92A4#
21731 You can then get further information by invoking the @code{addr2line}
21732 tool as described earlier (note that the hexadecimal addresses
21733 need to be specified in C format, with a leading ``0x'').
21735 @node Symbolic Traceback
21736 @subsection Symbolic Traceback
21737 @cindex traceback, symbolic
21740 A symbolic traceback is a stack traceback in which procedure names are
21741 associated with each code location.
21744 Note that this feature is not supported on all platforms. See
21745 @file{GNAT.Traceback.Symbolic spec in g-trasym.ads} for a complete
21746 list of currently supported platforms.
21749 Note that the symbolic traceback requires that the program be compiled
21750 with debug information. If it is not compiled with debug information
21751 only the non-symbolic information will be valid.
21754 * Tracebacks From Exception Occurrences (symbolic)::
21755 * Tracebacks From Anywhere in a Program (symbolic)::
21758 @node Tracebacks From Exception Occurrences (symbolic)
21759 @subsubsection Tracebacks From Exception Occurrences
21761 @smallexample @c ada
21762 @b{with} Ada.Text_IO;
21763 @b{with} GNAT.Traceback.Symbolic;
21765 @b{procedure} STB @b{is}
21767 @b{procedure} P1 @b{is}
21769 @b{raise} Constraint_Error;
21772 @b{procedure} P2 @b{is}
21777 @b{procedure} P3 @b{is}
21785 @b{when} E : @b{others} =>
21786 Ada.Text_IO.Put_Line (GNAT.Traceback.Symbolic.Symbolic_Traceback (E));
21791 $ gnatmake -g .\stb -bargs -E
21794 0040149F in stb.p1 at stb.adb:8
21795 004014B7 in stb.p2 at stb.adb:13
21796 004014CF in stb.p3 at stb.adb:18
21797 004015DD in ada.stb at stb.adb:22
21798 00401461 in main at b~stb.adb:168
21799 004011C4 in __mingw_CRTStartup at crt1.c:200
21800 004011F1 in mainCRTStartup at crt1.c:222
21801 77E892A4 in ?? at ??:0
21805 In the above example the ``.\'' syntax in the @command{gnatmake} command
21806 is currently required by @command{addr2line} for files that are in
21807 the current working directory.
21808 Moreover, the exact sequence of linker options may vary from platform
21810 The above @option{-largs} section is for Windows platforms. By contrast,
21811 under Unix there is no need for the @option{-largs} section.
21812 Differences across platforms are due to details of linker implementation.
21814 @node Tracebacks From Anywhere in a Program (symbolic)
21815 @subsubsection Tracebacks From Anywhere in a Program
21818 It is possible to get a symbolic stack traceback
21819 from anywhere in a program, just as for non-symbolic tracebacks.
21820 The first step is to obtain a non-symbolic
21821 traceback, and then call @code{Symbolic_Traceback} to compute the symbolic
21822 information. Here is an example:
21824 @smallexample @c ada
21825 @b{with} Ada.Text_IO;
21826 @b{with} GNAT.Traceback;
21827 @b{with} GNAT.Traceback.Symbolic;
21829 @b{procedure} STB @b{is}
21832 @b{use} GNAT.Traceback;
21833 @b{use} GNAT.Traceback.Symbolic;
21835 @b{procedure} P1 @b{is}
21836 TB : Tracebacks_Array (1 .. 10);
21837 --@i{ We are asking for a maximum of 10 stack frames.}
21839 --@i{ Len will receive the actual number of stack frames returned.}
21841 Call_Chain (TB, Len);
21842 Text_IO.Put_Line (Symbolic_Traceback (TB (1 .. Len)));
21845 @b{procedure} P2 @b{is}
21855 @c ******************************
21857 @c **************************************
21858 @node Platform-Specific Information for the Run-Time Libraries
21859 @appendix Platform-Specific Information for the Run-Time Libraries
21860 @cindex Tasking and threads libraries
21861 @cindex Threads libraries and tasking
21862 @cindex Run-time libraries (platform-specific information)
21865 The GNAT run-time implementation may vary with respect to both the
21866 underlying threads library and the exception handling scheme.
21867 For threads support, one or more of the following are supplied:
21869 @item @b{native threads library}, a binding to the thread package from
21870 the underlying operating system
21872 @item @b{pthreads library} (Sparc Solaris only), a binding to the Solaris
21873 POSIX thread package
21877 For exception handling, either or both of two models are supplied:
21879 @item @b{Zero-Cost Exceptions} (``ZCX''),@footnote{
21880 Most programs should experience a substantial speed improvement by
21881 being compiled with a ZCX run-time.
21882 This is especially true for
21883 tasking applications or applications with many exception handlers.}
21884 @cindex Zero-Cost Exceptions
21885 @cindex ZCX (Zero-Cost Exceptions)
21886 which uses binder-generated tables that
21887 are interrogated at run time to locate a handler
21889 @item @b{setjmp / longjmp} (``SJLJ''),
21890 @cindex setjmp/longjmp Exception Model
21891 @cindex SJLJ (setjmp/longjmp Exception Model)
21892 which uses dynamically-set data to establish
21893 the set of handlers
21897 This appendix summarizes which combinations of threads and exception support
21898 are supplied on various GNAT platforms.
21899 It then shows how to select a particular library either
21900 permanently or temporarily,
21901 explains the properties of (and tradeoffs among) the various threads
21902 libraries, and provides some additional
21903 information about several specific platforms.
21906 * Summary of Run-Time Configurations::
21907 * Specifying a Run-Time Library::
21908 * Choosing the Scheduling Policy::
21909 * Solaris-Specific Considerations::
21910 * Linux-Specific Considerations::
21911 * AIX-Specific Considerations::
21912 * RTX-Specific Considerations::
21913 * HP-UX-Specific Considerations::
21916 @node Summary of Run-Time Configurations
21917 @section Summary of Run-Time Configurations
21919 @multitable @columnfractions .30 .70
21920 @item @b{alpha-openvms}
21921 @item @code{@ @ }@i{rts-native (default)}
21922 @item @code{@ @ @ @ }Tasking @tab native VMS threads
21923 @item @code{@ @ @ @ }Exceptions @tab ZCX
21925 @item @code{@ @ }@i{rts-sjlj}
21926 @item @code{@ @ @ @ }Tasking @tab native TRU64 threads
21927 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21929 @item @b{ia64-hp_linux}
21930 @item @code{@ @ }@i{rts-native (default)}
21931 @item @code{@ @ @ @ }Tasking @tab pthread library
21932 @item @code{@ @ @ @ }Exceptions @tab ZCX
21934 @item @b{ia64-hpux}
21935 @item @code{@ @ }@i{rts-native (default)}
21936 @item @code{@ @ @ @ }Tasking @tab native HP-UX threads
21937 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21939 @item @b{ia64-openvms}
21940 @item @code{@ @ }@i{rts-native (default)}
21941 @item @code{@ @ @ @ }Tasking @tab native VMS threads
21942 @item @code{@ @ @ @ }Exceptions @tab ZCX
21944 @item @b{ia64-sgi_linux}
21945 @item @code{@ @ }@i{rts-native (default)}
21946 @item @code{@ @ @ @ }Tasking @tab pthread library
21947 @item @code{@ @ @ @ }Exceptions @tab ZCX
21950 @item @code{@ @ }@i{rts-native (default)}
21951 @item @code{@ @ @ @ }Tasking @tab native HP-UX threads
21952 @item @code{@ @ @ @ }Exceptions @tab ZCX
21954 @item @code{@ @ }@i{rts-sjlj}
21955 @item @code{@ @ @ @ }Tasking @tab native HP-UX threads
21956 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21959 @item @code{@ @ }@i{rts-native (default)}
21960 @item @code{@ @ @ @ }Tasking @tab native AIX threads
21961 @item @code{@ @ @ @ }Exceptions @tab ZCX
21963 @item @code{@ @ }@i{rts-sjlj}
21964 @item @code{@ @ @ @ }Tasking @tab native AIX threads
21965 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21967 @item @b{ppc-darwin}
21968 @item @code{@ @ }@i{rts-native (default)}
21969 @item @code{@ @ @ @ }Tasking @tab native MacOS threads
21970 @item @code{@ @ @ @ }Exceptions @tab ZCX
21972 @item @b{sparc-solaris} @tab
21973 @item @code{@ @ }@i{rts-native (default)}
21974 @item @code{@ @ @ @ }Tasking @tab native Solaris threads library
21975 @item @code{@ @ @ @ }Exceptions @tab ZCX
21977 @item @code{@ @ }@i{rts-pthread}
21978 @item @code{@ @ @ @ }Tasking @tab pthread library
21979 @item @code{@ @ @ @ }Exceptions @tab ZCX
21981 @item @code{@ @ }@i{rts-sjlj}
21982 @item @code{@ @ @ @ }Tasking @tab native Solaris threads library
21983 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21985 @item @b{sparc64-solaris} @tab
21986 @item @code{@ @ }@i{rts-native (default)}
21987 @item @code{@ @ @ @ }Tasking @tab native Solaris threads library
21988 @item @code{@ @ @ @ }Exceptions @tab ZCX
21990 @item @b{x86-linux}
21991 @item @code{@ @ }@i{rts-native (default)}
21992 @item @code{@ @ @ @ }Tasking @tab pthread library
21993 @item @code{@ @ @ @ }Exceptions @tab ZCX
21995 @item @code{@ @ }@i{rts-sjlj}
21996 @item @code{@ @ @ @ }Tasking @tab pthread library
21997 @item @code{@ @ @ @ }Exceptions @tab SJLJ
22000 @item @code{@ @ }@i{rts-native (default)}
22001 @item @code{@ @ @ @ }Tasking @tab native LynxOS threads
22002 @item @code{@ @ @ @ }Exceptions @tab SJLJ
22004 @item @b{x86-solaris}
22005 @item @code{@ @ }@i{rts-native (default)}
22006 @item @code{@ @ @ @ }Tasking @tab native Solaris threads
22007 @item @code{@ @ @ @ }Exceptions @tab ZCX
22009 @item @code{@ @ }@i{rts-sjlj}
22010 @item @code{@ @ @ @ }Tasking @tab native Solaris threads library
22011 @item @code{@ @ @ @ }Exceptions @tab SJLJ
22013 @item @b{x86-windows}
22014 @item @code{@ @ }@i{rts-native (default)}
22015 @item @code{@ @ @ @ }Tasking @tab native Win32 threads
22016 @item @code{@ @ @ @ }Exceptions @tab ZCX
22018 @item @code{@ @ }@i{rts-sjlj}
22019 @item @code{@ @ @ @ }Tasking @tab native Win32 threads
22020 @item @code{@ @ @ @ }Exceptions @tab SJLJ
22022 @item @b{x86-windows-rtx}
22023 @item @code{@ @ }@i{rts-rtx-rtss (default)}
22024 @item @code{@ @ @ @ }Tasking @tab RTX real-time subsystem RTSS threads (kernel mode)
22025 @item @code{@ @ @ @ }Exceptions @tab SJLJ
22027 @item @code{@ @ }@i{rts-rtx-w32}
22028 @item @code{@ @ @ @ }Tasking @tab RTX Win32 threads (user mode)
22029 @item @code{@ @ @ @ }Exceptions @tab ZCX
22031 @item @b{x86_64-linux}
22032 @item @code{@ @ }@i{rts-native (default)}
22033 @item @code{@ @ @ @ }Tasking @tab pthread library
22034 @item @code{@ @ @ @ }Exceptions @tab ZCX
22036 @item @code{@ @ }@i{rts-sjlj}
22037 @item @code{@ @ @ @ }Tasking @tab pthread library
22038 @item @code{@ @ @ @ }Exceptions @tab SJLJ
22042 @node Specifying a Run-Time Library
22043 @section Specifying a Run-Time Library
22046 The @file{adainclude} subdirectory containing the sources of the GNAT
22047 run-time library, and the @file{adalib} subdirectory containing the
22048 @file{ALI} files and the static and/or shared GNAT library, are located
22049 in the gcc target-dependent area:
22052 target=$prefix/lib/gcc/gcc-@i{dumpmachine}/gcc-@i{dumpversion}/
22056 As indicated above, on some platforms several run-time libraries are supplied.
22057 These libraries are installed in the target dependent area and
22058 contain a complete source and binary subdirectory. The detailed description
22059 below explains the differences between the different libraries in terms of
22060 their thread support.
22062 The default run-time library (when GNAT is installed) is @emph{rts-native}.
22063 This default run time is selected by the means of soft links.
22064 For example on x86-linux:
22070 +--- adainclude----------+
22072 +--- adalib-----------+ |
22074 +--- rts-native | |
22076 | +--- adainclude <---+
22078 | +--- adalib <----+
22089 If the @i{rts-sjlj} library is to be selected on a permanent basis,
22090 these soft links can be modified with the following commands:
22094 $ rm -f adainclude adalib
22095 $ ln -s rts-sjlj/adainclude adainclude
22096 $ ln -s rts-sjlj/adalib adalib
22100 Alternatively, you can specify @file{rts-sjlj/adainclude} in the file
22101 @file{$target/ada_source_path} and @file{rts-sjlj/adalib} in
22102 @file{$target/ada_object_path}.
22104 Selecting another run-time library temporarily can be
22105 achieved by using the @option{--RTS} switch, e.g., @option{--RTS=sjlj}
22106 @cindex @option{--RTS} option
22108 @node Choosing the Scheduling Policy
22109 @section Choosing the Scheduling Policy
22112 When using a POSIX threads implementation, you have a choice of several
22113 scheduling policies: @code{SCHED_FIFO},
22114 @cindex @code{SCHED_FIFO} scheduling policy
22116 @cindex @code{SCHED_RR} scheduling policy
22117 and @code{SCHED_OTHER}.
22118 @cindex @code{SCHED_OTHER} scheduling policy
22119 Typically, the default is @code{SCHED_OTHER}, while using @code{SCHED_FIFO}
22120 or @code{SCHED_RR} requires special (e.g., root) privileges.
22122 By default, GNAT uses the @code{SCHED_OTHER} policy. To specify
22124 @cindex @code{SCHED_FIFO} scheduling policy
22125 you can use one of the following:
22129 @code{pragma Time_Slice (0.0)}
22130 @cindex pragma Time_Slice
22132 the corresponding binder option @option{-T0}
22133 @cindex @option{-T0} option
22135 @code{pragma Task_Dispatching_Policy (FIFO_Within_Priorities)}
22136 @cindex pragma Task_Dispatching_Policy
22140 To specify @code{SCHED_RR},
22141 @cindex @code{SCHED_RR} scheduling policy
22142 you should use @code{pragma Time_Slice} with a
22143 value greater than @code{0.0}, or else use the corresponding @option{-T}
22146 @node Solaris-Specific Considerations
22147 @section Solaris-Specific Considerations
22148 @cindex Solaris Sparc threads libraries
22151 This section addresses some topics related to the various threads libraries
22155 * Solaris Threads Issues::
22158 @node Solaris Threads Issues
22159 @subsection Solaris Threads Issues
22162 GNAT under Solaris/Sparc 32 bits comes with an alternate tasking run-time
22163 library based on POSIX threads --- @emph{rts-pthread}.
22164 @cindex rts-pthread threads library
22165 This run-time library has the advantage of being mostly shared across all
22166 POSIX-compliant thread implementations, and it also provides under
22167 @w{Solaris 8} the @code{PTHREAD_PRIO_INHERIT}
22168 @cindex @code{PTHREAD_PRIO_INHERIT} policy (under rts-pthread)
22169 and @code{PTHREAD_PRIO_PROTECT}
22170 @cindex @code{PTHREAD_PRIO_PROTECT} policy (under rts-pthread)
22171 semantics that can be selected using the predefined pragma
22172 @code{Locking_Policy}
22173 @cindex pragma Locking_Policy (under rts-pthread)
22175 @code{Inheritance_Locking} and @code{Ceiling_Locking} as the policy.
22176 @cindex @code{Inheritance_Locking} (under rts-pthread)
22177 @cindex @code{Ceiling_Locking} (under rts-pthread)
22179 As explained above, the native run-time library is based on the Solaris thread
22180 library (@code{libthread}) and is the default library.
22182 When the Solaris threads library is used (this is the default), programs
22183 compiled with GNAT can automatically take advantage of
22184 and can thus execute on multiple processors.
22185 The user can alternatively specify a processor on which the program should run
22186 to emulate a single-processor system. The multiprocessor / uniprocessor choice
22188 setting the environment variable @env{GNAT_PROCESSOR}
22189 @cindex @env{GNAT_PROCESSOR} environment variable (on Sparc Solaris)
22190 to one of the following:
22194 Use the default configuration (run the program on all
22195 available processors) - this is the same as having @code{GNAT_PROCESSOR}
22199 Let the run-time implementation choose one processor and run the program on
22202 @item 0 .. Last_Proc
22203 Run the program on the specified processor.
22204 @code{Last_Proc} is equal to @code{_SC_NPROCESSORS_CONF - 1}
22205 (where @code{_SC_NPROCESSORS_CONF} is a system variable).
22208 @node Linux-Specific Considerations
22209 @section Linux-Specific Considerations
22210 @cindex Linux threads libraries
22213 On GNU/Linux without NPTL support (usually system with GNU C Library
22214 older than 2.3), the signal model is not POSIX compliant, which means
22215 that to send a signal to the process, you need to send the signal to all
22216 threads, e.g.@: by using @code{killpg()}.
22218 @node AIX-Specific Considerations
22219 @section AIX-Specific Considerations
22220 @cindex AIX resolver library
22223 On AIX, the resolver library initializes some internal structure on
22224 the first call to @code{get*by*} functions, which are used to implement
22225 @code{GNAT.Sockets.Get_Host_By_Name} and
22226 @code{GNAT.Sockets.Get_Host_By_Address}.
22227 If such initialization occurs within an Ada task, and the stack size for
22228 the task is the default size, a stack overflow may occur.
22230 To avoid this overflow, the user should either ensure that the first call
22231 to @code{GNAT.Sockets.Get_Host_By_Name} or
22232 @code{GNAT.Sockets.Get_Host_By_Addrss}
22233 occurs in the environment task, or use @code{pragma Storage_Size} to
22234 specify a sufficiently large size for the stack of the task that contains
22237 @node RTX-Specific Considerations
22238 @section RTX-Specific Considerations
22239 @cindex RTX libraries
22242 The Real-time Extension (RTX) to Windows is based on the Windows Win32
22243 API. Applications can be built to work in two different modes:
22247 Windows executables that run in Ring 3 to utilize memory protection
22248 (@emph{rts-rtx-w32}).
22251 Real-time subsystem (RTSS) executables that run in Ring 0, where
22252 performance can be optimized with RTSS applications taking precedent
22253 over all Windows applications (@emph{rts-rtx-rtss}). This mode requires
22254 the Microsoft linker to handle RTSS libraries.
22258 @node HP-UX-Specific Considerations
22259 @section HP-UX-Specific Considerations
22260 @cindex HP-UX Scheduling
22263 On HP-UX, appropriate privileges are required to change the scheduling
22264 parameters of a task. The calling process must have appropriate
22265 privileges or be a member of a group having @code{PRIV_RTSCHED} access to
22266 successfully change the scheduling parameters.
22268 By default, GNAT uses the @code{SCHED_HPUX} policy. To have access to the
22269 priority range 0-31 either the @code{FIFO_Within_Priorities} or the
22270 @code{Round_Robin_Within_Priorities} scheduling policies need to be set.
22272 To specify the @code{FIFO_Within_Priorities} scheduling policy you can use
22273 one of the following:
22277 @code{pragma Time_Slice (0.0)}
22278 @cindex pragma Time_Slice
22280 the corresponding binder option @option{-T0}
22281 @cindex @option{-T0} option
22283 @code{pragma Task_Dispatching_Policy (FIFO_Within_Priorities)}
22284 @cindex pragma Task_Dispatching_Policy
22288 To specify the @code{Round_Robin_Within_Priorities}, scheduling policy
22289 you should use @code{pragma Time_Slice} with a
22290 value greater than @code{0.0}, or use the corresponding @option{-T}
22291 binder option, or set the @code{pragma Task_Dispatching_Policy
22292 (Round_Robin_Within_Priorities)}.
22294 @c *******************************
22295 @node Example of Binder Output File
22296 @appendix Example of Binder Output File
22299 This Appendix displays the source code for @command{gnatbind}'s output
22300 file generated for a simple ``Hello World'' program.
22301 Comments have been added for clarification purposes.
22303 @smallexample @c adanocomment
22307 -- The package is called Ada_Main unless this name is actually used
22308 -- as a unit name in the partition, in which case some other unique
22312 @b{package} ada_main @b{is}
22314 Elab_Final_Code : Integer;
22315 @b{pragma} Import (C, Elab_Final_Code, "__gnat_inside_elab_final_code");
22317 -- The main program saves the parameters (argument count,
22318 -- argument values, environment pointer) in global variables
22319 -- for later access by other units including
22320 -- Ada.Command_Line.
22322 gnat_argc : Integer;
22323 gnat_argv : System.Address;
22324 gnat_envp : System.Address;
22326 -- The actual variables are stored in a library routine. This
22327 -- is useful for some shared library situations, where there
22328 -- are problems if variables are not in the library.
22330 @b{pragma} Import (C, gnat_argc);
22331 @b{pragma} Import (C, gnat_argv);
22332 @b{pragma} Import (C, gnat_envp);
22334 -- The exit status is similarly an external location
22336 gnat_exit_status : Integer;
22337 @b{pragma} Import (C, gnat_exit_status);
22339 GNAT_Version : @b{constant} String :=
22340 "GNAT Version: 6.0.0w (20061115)";
22341 @b{pragma} Export (C, GNAT_Version, "__gnat_version");
22343 -- This is the generated adafinal routine that performs
22344 -- finalization at the end of execution. In the case where
22345 -- Ada is the main program, this main program makes a call
22346 -- to adafinal at program termination.
22348 @b{procedure} adafinal;
22349 @b{pragma} Export (C, adafinal, "adafinal");
22351 -- This is the generated adainit routine that performs
22352 -- initialization at the start of execution. In the case
22353 -- where Ada is the main program, this main program makes
22354 -- a call to adainit at program startup.
22356 @b{procedure} adainit;
22357 @b{pragma} Export (C, adainit, "adainit");
22359 -- This routine is called at the start of execution. It is
22360 -- a dummy routine that is used by the debugger to breakpoint
22361 -- at the start of execution.
22363 @b{procedure} Break_Start;
22364 @b{pragma} Import (C, Break_Start, "__gnat_break_start");
22366 -- This is the actual generated main program (it would be
22367 -- suppressed if the no main program switch were used). As
22368 -- required by standard system conventions, this program has
22369 -- the external name main.
22373 argv : System.Address;
22374 envp : System.Address)
22375 @b{return} Integer;
22376 @b{pragma} Export (C, main, "main");
22378 -- The following set of constants give the version
22379 -- identification values for every unit in the bound
22380 -- partition. This identification is computed from all
22381 -- dependent semantic units, and corresponds to the
22382 -- string that would be returned by use of the
22383 -- Body_Version or Version attributes.
22385 @b{type} Version_32 @b{is} @b{mod} 2 ** 32;
22386 u00001 : @b{constant} Version_32 := 16#7880BEB3#;
22387 u00002 : @b{constant} Version_32 := 16#0D24CBD0#;
22388 u00003 : @b{constant} Version_32 := 16#3283DBEB#;
22389 u00004 : @b{constant} Version_32 := 16#2359F9ED#;
22390 u00005 : @b{constant} Version_32 := 16#664FB847#;
22391 u00006 : @b{constant} Version_32 := 16#68E803DF#;
22392 u00007 : @b{constant} Version_32 := 16#5572E604#;
22393 u00008 : @b{constant} Version_32 := 16#46B173D8#;
22394 u00009 : @b{constant} Version_32 := 16#156A40CF#;
22395 u00010 : @b{constant} Version_32 := 16#033DABE0#;
22396 u00011 : @b{constant} Version_32 := 16#6AB38FEA#;
22397 u00012 : @b{constant} Version_32 := 16#22B6217D#;
22398 u00013 : @b{constant} Version_32 := 16#68A22947#;
22399 u00014 : @b{constant} Version_32 := 16#18CC4A56#;
22400 u00015 : @b{constant} Version_32 := 16#08258E1B#;
22401 u00016 : @b{constant} Version_32 := 16#367D5222#;
22402 u00017 : @b{constant} Version_32 := 16#20C9ECA4#;
22403 u00018 : @b{constant} Version_32 := 16#50D32CB6#;
22404 u00019 : @b{constant} Version_32 := 16#39A8BB77#;
22405 u00020 : @b{constant} Version_32 := 16#5CF8FA2B#;
22406 u00021 : @b{constant} Version_32 := 16#2F1EB794#;
22407 u00022 : @b{constant} Version_32 := 16#31AB6444#;
22408 u00023 : @b{constant} Version_32 := 16#1574B6E9#;
22409 u00024 : @b{constant} Version_32 := 16#5109C189#;
22410 u00025 : @b{constant} Version_32 := 16#56D770CD#;
22411 u00026 : @b{constant} Version_32 := 16#02F9DE3D#;
22412 u00027 : @b{constant} Version_32 := 16#08AB6B2C#;
22413 u00028 : @b{constant} Version_32 := 16#3FA37670#;
22414 u00029 : @b{constant} Version_32 := 16#476457A0#;
22415 u00030 : @b{constant} Version_32 := 16#731E1B6E#;
22416 u00031 : @b{constant} Version_32 := 16#23C2E789#;
22417 u00032 : @b{constant} Version_32 := 16#0F1BD6A1#;
22418 u00033 : @b{constant} Version_32 := 16#7C25DE96#;
22419 u00034 : @b{constant} Version_32 := 16#39ADFFA2#;
22420 u00035 : @b{constant} Version_32 := 16#571DE3E7#;
22421 u00036 : @b{constant} Version_32 := 16#5EB646AB#;
22422 u00037 : @b{constant} Version_32 := 16#4249379B#;
22423 u00038 : @b{constant} Version_32 := 16#0357E00A#;
22424 u00039 : @b{constant} Version_32 := 16#3784FB72#;
22425 u00040 : @b{constant} Version_32 := 16#2E723019#;
22426 u00041 : @b{constant} Version_32 := 16#623358EA#;
22427 u00042 : @b{constant} Version_32 := 16#107F9465#;
22428 u00043 : @b{constant} Version_32 := 16#6843F68A#;
22429 u00044 : @b{constant} Version_32 := 16#63305874#;
22430 u00045 : @b{constant} Version_32 := 16#31E56CE1#;
22431 u00046 : @b{constant} Version_32 := 16#02917970#;
22432 u00047 : @b{constant} Version_32 := 16#6CCBA70E#;
22433 u00048 : @b{constant} Version_32 := 16#41CD4204#;
22434 u00049 : @b{constant} Version_32 := 16#572E3F58#;
22435 u00050 : @b{constant} Version_32 := 16#20729FF5#;
22436 u00051 : @b{constant} Version_32 := 16#1D4F93E8#;
22437 u00052 : @b{constant} Version_32 := 16#30B2EC3D#;
22438 u00053 : @b{constant} Version_32 := 16#34054F96#;
22439 u00054 : @b{constant} Version_32 := 16#5A199860#;
22440 u00055 : @b{constant} Version_32 := 16#0E7F912B#;
22441 u00056 : @b{constant} Version_32 := 16#5760634A#;
22442 u00057 : @b{constant} Version_32 := 16#5D851835#;
22444 -- The following Export pragmas export the version numbers
22445 -- with symbolic names ending in B (for body) or S
22446 -- (for spec) so that they can be located in a link. The
22447 -- information provided here is sufficient to track down
22448 -- the exact versions of units used in a given build.
22450 @b{pragma} Export (C, u00001, "helloB");
22451 @b{pragma} Export (C, u00002, "system__standard_libraryB");
22452 @b{pragma} Export (C, u00003, "system__standard_libraryS");
22453 @b{pragma} Export (C, u00004, "adaS");
22454 @b{pragma} Export (C, u00005, "ada__text_ioB");
22455 @b{pragma} Export (C, u00006, "ada__text_ioS");
22456 @b{pragma} Export (C, u00007, "ada__exceptionsB");
22457 @b{pragma} Export (C, u00008, "ada__exceptionsS");
22458 @b{pragma} Export (C, u00009, "gnatS");
22459 @b{pragma} Export (C, u00010, "gnat__heap_sort_aB");
22460 @b{pragma} Export (C, u00011, "gnat__heap_sort_aS");
22461 @b{pragma} Export (C, u00012, "systemS");
22462 @b{pragma} Export (C, u00013, "system__exception_tableB");
22463 @b{pragma} Export (C, u00014, "system__exception_tableS");
22464 @b{pragma} Export (C, u00015, "gnat__htableB");
22465 @b{pragma} Export (C, u00016, "gnat__htableS");
22466 @b{pragma} Export (C, u00017, "system__exceptionsS");
22467 @b{pragma} Export (C, u00018, "system__machine_state_operationsB");
22468 @b{pragma} Export (C, u00019, "system__machine_state_operationsS");
22469 @b{pragma} Export (C, u00020, "system__machine_codeS");
22470 @b{pragma} Export (C, u00021, "system__storage_elementsB");
22471 @b{pragma} Export (C, u00022, "system__storage_elementsS");
22472 @b{pragma} Export (C, u00023, "system__secondary_stackB");
22473 @b{pragma} Export (C, u00024, "system__secondary_stackS");
22474 @b{pragma} Export (C, u00025, "system__parametersB");
22475 @b{pragma} Export (C, u00026, "system__parametersS");
22476 @b{pragma} Export (C, u00027, "system__soft_linksB");
22477 @b{pragma} Export (C, u00028, "system__soft_linksS");
22478 @b{pragma} Export (C, u00029, "system__stack_checkingB");
22479 @b{pragma} Export (C, u00030, "system__stack_checkingS");
22480 @b{pragma} Export (C, u00031, "system__tracebackB");
22481 @b{pragma} Export (C, u00032, "system__tracebackS");
22482 @b{pragma} Export (C, u00033, "ada__streamsS");
22483 @b{pragma} Export (C, u00034, "ada__tagsB");
22484 @b{pragma} Export (C, u00035, "ada__tagsS");
22485 @b{pragma} Export (C, u00036, "system__string_opsB");
22486 @b{pragma} Export (C, u00037, "system__string_opsS");
22487 @b{pragma} Export (C, u00038, "interfacesS");
22488 @b{pragma} Export (C, u00039, "interfaces__c_streamsB");
22489 @b{pragma} Export (C, u00040, "interfaces__c_streamsS");
22490 @b{pragma} Export (C, u00041, "system__file_ioB");
22491 @b{pragma} Export (C, u00042, "system__file_ioS");
22492 @b{pragma} Export (C, u00043, "ada__finalizationB");
22493 @b{pragma} Export (C, u00044, "ada__finalizationS");
22494 @b{pragma} Export (C, u00045, "system__finalization_rootB");
22495 @b{pragma} Export (C, u00046, "system__finalization_rootS");
22496 @b{pragma} Export (C, u00047, "system__finalization_implementationB");
22497 @b{pragma} Export (C, u00048, "system__finalization_implementationS");
22498 @b{pragma} Export (C, u00049, "system__string_ops_concat_3B");
22499 @b{pragma} Export (C, u00050, "system__string_ops_concat_3S");
22500 @b{pragma} Export (C, u00051, "system__stream_attributesB");
22501 @b{pragma} Export (C, u00052, "system__stream_attributesS");
22502 @b{pragma} Export (C, u00053, "ada__io_exceptionsS");
22503 @b{pragma} Export (C, u00054, "system__unsigned_typesS");
22504 @b{pragma} Export (C, u00055, "system__file_control_blockS");
22505 @b{pragma} Export (C, u00056, "ada__finalization__list_controllerB");
22506 @b{pragma} Export (C, u00057, "ada__finalization__list_controllerS");
22508 -- BEGIN ELABORATION ORDER
22511 -- gnat.heap_sort_a (spec)
22512 -- gnat.heap_sort_a (body)
22513 -- gnat.htable (spec)
22514 -- gnat.htable (body)
22515 -- interfaces (spec)
22517 -- system.machine_code (spec)
22518 -- system.parameters (spec)
22519 -- system.parameters (body)
22520 -- interfaces.c_streams (spec)
22521 -- interfaces.c_streams (body)
22522 -- system.standard_library (spec)
22523 -- ada.exceptions (spec)
22524 -- system.exception_table (spec)
22525 -- system.exception_table (body)
22526 -- ada.io_exceptions (spec)
22527 -- system.exceptions (spec)
22528 -- system.storage_elements (spec)
22529 -- system.storage_elements (body)
22530 -- system.machine_state_operations (spec)
22531 -- system.machine_state_operations (body)
22532 -- system.secondary_stack (spec)
22533 -- system.stack_checking (spec)
22534 -- system.soft_links (spec)
22535 -- system.soft_links (body)
22536 -- system.stack_checking (body)
22537 -- system.secondary_stack (body)
22538 -- system.standard_library (body)
22539 -- system.string_ops (spec)
22540 -- system.string_ops (body)
22543 -- ada.streams (spec)
22544 -- system.finalization_root (spec)
22545 -- system.finalization_root (body)
22546 -- system.string_ops_concat_3 (spec)
22547 -- system.string_ops_concat_3 (body)
22548 -- system.traceback (spec)
22549 -- system.traceback (body)
22550 -- ada.exceptions (body)
22551 -- system.unsigned_types (spec)
22552 -- system.stream_attributes (spec)
22553 -- system.stream_attributes (body)
22554 -- system.finalization_implementation (spec)
22555 -- system.finalization_implementation (body)
22556 -- ada.finalization (spec)
22557 -- ada.finalization (body)
22558 -- ada.finalization.list_controller (spec)
22559 -- ada.finalization.list_controller (body)
22560 -- system.file_control_block (spec)
22561 -- system.file_io (spec)
22562 -- system.file_io (body)
22563 -- ada.text_io (spec)
22564 -- ada.text_io (body)
22566 -- END ELABORATION ORDER
22570 -- The following source file name pragmas allow the generated file
22571 -- names to be unique for different main programs. They are needed
22572 -- since the package name will always be Ada_Main.
22574 @b{pragma} Source_File_Name (ada_main, Spec_File_Name => "b~hello.ads");
22575 @b{pragma} Source_File_Name (ada_main, Body_File_Name => "b~hello.adb");
22577 -- Generated package body for Ada_Main starts here
22579 @b{package} @b{body} ada_main @b{is}
22581 -- The actual finalization is performed by calling the
22582 -- library routine in System.Standard_Library.Adafinal
22584 @b{procedure} Do_Finalize;
22585 @b{pragma} Import (C, Do_Finalize, "system__standard_library__adafinal");
22592 @b{procedure} adainit @b{is}
22594 -- These booleans are set to True once the associated unit has
22595 -- been elaborated. It is also used to avoid elaborating the
22596 -- same unit twice.
22599 @b{pragma} Import (Ada, E040, "interfaces__c_streams_E");
22602 @b{pragma} Import (Ada, E008, "ada__exceptions_E");
22605 @b{pragma} Import (Ada, E014, "system__exception_table_E");
22608 @b{pragma} Import (Ada, E053, "ada__io_exceptions_E");
22611 @b{pragma} Import (Ada, E017, "system__exceptions_E");
22614 @b{pragma} Import (Ada, E024, "system__secondary_stack_E");
22617 @b{pragma} Import (Ada, E030, "system__stack_checking_E");
22620 @b{pragma} Import (Ada, E028, "system__soft_links_E");
22623 @b{pragma} Import (Ada, E035, "ada__tags_E");
22626 @b{pragma} Import (Ada, E033, "ada__streams_E");
22629 @b{pragma} Import (Ada, E046, "system__finalization_root_E");
22632 @b{pragma} Import (Ada, E048, "system__finalization_implementation_E");
22635 @b{pragma} Import (Ada, E044, "ada__finalization_E");
22638 @b{pragma} Import (Ada, E057, "ada__finalization__list_controller_E");
22641 @b{pragma} Import (Ada, E055, "system__file_control_block_E");
22644 @b{pragma} Import (Ada, E042, "system__file_io_E");
22647 @b{pragma} Import (Ada, E006, "ada__text_io_E");
22649 -- Set_Globals is a library routine that stores away the
22650 -- value of the indicated set of global values in global
22651 -- variables within the library.
22653 @b{procedure} Set_Globals
22654 (Main_Priority : Integer;
22655 Time_Slice_Value : Integer;
22656 WC_Encoding : Character;
22657 Locking_Policy : Character;
22658 Queuing_Policy : Character;
22659 Task_Dispatching_Policy : Character;
22660 Adafinal : System.Address;
22661 Unreserve_All_Interrupts : Integer;
22662 Exception_Tracebacks : Integer);
22663 @findex __gnat_set_globals
22664 @b{pragma} Import (C, Set_Globals, "__gnat_set_globals");
22666 -- SDP_Table_Build is a library routine used to build the
22667 -- exception tables. See unit Ada.Exceptions in files
22668 -- a-except.ads/adb for full details of how zero cost
22669 -- exception handling works. This procedure, the call to
22670 -- it, and the two following tables are all omitted if the
22671 -- build is in longjmp/setjmp exception mode.
22673 @findex SDP_Table_Build
22674 @findex Zero Cost Exceptions
22675 @b{procedure} SDP_Table_Build
22676 (SDP_Addresses : System.Address;
22677 SDP_Count : Natural;
22678 Elab_Addresses : System.Address;
22679 Elab_Addr_Count : Natural);
22680 @b{pragma} Import (C, SDP_Table_Build, "__gnat_SDP_Table_Build");
22682 -- Table of Unit_Exception_Table addresses. Used for zero
22683 -- cost exception handling to build the top level table.
22685 ST : @b{aliased} @b{constant} @b{array} (1 .. 23) @b{of} System.Address := (
22687 Ada.Text_Io'UET_Address,
22688 Ada.Exceptions'UET_Address,
22689 Gnat.Heap_Sort_A'UET_Address,
22690 System.Exception_Table'UET_Address,
22691 System.Machine_State_Operations'UET_Address,
22692 System.Secondary_Stack'UET_Address,
22693 System.Parameters'UET_Address,
22694 System.Soft_Links'UET_Address,
22695 System.Stack_Checking'UET_Address,
22696 System.Traceback'UET_Address,
22697 Ada.Streams'UET_Address,
22698 Ada.Tags'UET_Address,
22699 System.String_Ops'UET_Address,
22700 Interfaces.C_Streams'UET_Address,
22701 System.File_Io'UET_Address,
22702 Ada.Finalization'UET_Address,
22703 System.Finalization_Root'UET_Address,
22704 System.Finalization_Implementation'UET_Address,
22705 System.String_Ops_Concat_3'UET_Address,
22706 System.Stream_Attributes'UET_Address,
22707 System.File_Control_Block'UET_Address,
22708 Ada.Finalization.List_Controller'UET_Address);
22710 -- Table of addresses of elaboration routines. Used for
22711 -- zero cost exception handling to make sure these
22712 -- addresses are included in the top level procedure
22715 EA : @b{aliased} @b{constant} @b{array} (1 .. 23) @b{of} System.Address := (
22716 adainit'Code_Address,
22717 Do_Finalize'Code_Address,
22718 Ada.Exceptions'Elab_Spec'Address,
22719 System.Exceptions'Elab_Spec'Address,
22720 Interfaces.C_Streams'Elab_Spec'Address,
22721 System.Exception_Table'Elab_Body'Address,
22722 Ada.Io_Exceptions'Elab_Spec'Address,
22723 System.Stack_Checking'Elab_Spec'Address,
22724 System.Soft_Links'Elab_Body'Address,
22725 System.Secondary_Stack'Elab_Body'Address,
22726 Ada.Tags'Elab_Spec'Address,
22727 Ada.Tags'Elab_Body'Address,
22728 Ada.Streams'Elab_Spec'Address,
22729 System.Finalization_Root'Elab_Spec'Address,
22730 Ada.Exceptions'Elab_Body'Address,
22731 System.Finalization_Implementation'Elab_Spec'Address,
22732 System.Finalization_Implementation'Elab_Body'Address,
22733 Ada.Finalization'Elab_Spec'Address,
22734 Ada.Finalization.List_Controller'Elab_Spec'Address,
22735 System.File_Control_Block'Elab_Spec'Address,
22736 System.File_Io'Elab_Body'Address,
22737 Ada.Text_Io'Elab_Spec'Address,
22738 Ada.Text_Io'Elab_Body'Address);
22740 -- Start of processing for adainit
22744 -- Call SDP_Table_Build to build the top level procedure
22745 -- table for zero cost exception handling (omitted in
22746 -- longjmp/setjmp mode).
22748 SDP_Table_Build (ST'Address, 23, EA'Address, 23);
22750 -- Call Set_Globals to record various information for
22751 -- this partition. The values are derived by the binder
22752 -- from information stored in the ali files by the compiler.
22754 @findex __gnat_set_globals
22756 (Main_Priority => -1,
22757 -- Priority of main program, -1 if no pragma Priority used
22759 Time_Slice_Value => -1,
22760 -- Time slice from Time_Slice pragma, -1 if none used
22762 WC_Encoding => 'b',
22763 -- Wide_Character encoding used, default is brackets
22765 Locking_Policy => ' ',
22766 -- Locking_Policy used, default of space means not
22767 -- specified, otherwise it is the first character of
22768 -- the policy name.
22770 Queuing_Policy => ' ',
22771 -- Queuing_Policy used, default of space means not
22772 -- specified, otherwise it is the first character of
22773 -- the policy name.
22775 Task_Dispatching_Policy => ' ',
22776 -- Task_Dispatching_Policy used, default of space means
22777 -- not specified, otherwise first character of the
22780 Adafinal => System.Null_Address,
22781 -- Address of Adafinal routine, not used anymore
22783 Unreserve_All_Interrupts => 0,
22784 -- Set true if pragma Unreserve_All_Interrupts was used
22786 Exception_Tracebacks => 0);
22787 -- Indicates if exception tracebacks are enabled
22789 Elab_Final_Code := 1;
22791 -- Now we have the elaboration calls for all units in the partition.
22792 -- The Elab_Spec and Elab_Body attributes generate references to the
22793 -- implicit elaboration procedures generated by the compiler for
22794 -- each unit that requires elaboration.
22796 @b{if} @b{not} E040 @b{then}
22797 Interfaces.C_Streams'Elab_Spec;
22800 @b{if} @b{not} E008 @b{then}
22801 Ada.Exceptions'Elab_Spec;
22803 @b{if} @b{not} E014 @b{then}
22804 System.Exception_Table'Elab_Body;
22807 @b{if} @b{not} E053 @b{then}
22808 Ada.Io_Exceptions'Elab_Spec;
22811 @b{if} @b{not} E017 @b{then}
22812 System.Exceptions'Elab_Spec;
22815 @b{if} @b{not} E030 @b{then}
22816 System.Stack_Checking'Elab_Spec;
22818 @b{if} @b{not} E028 @b{then}
22819 System.Soft_Links'Elab_Body;
22823 @b{if} @b{not} E024 @b{then}
22824 System.Secondary_Stack'Elab_Body;
22827 @b{if} @b{not} E035 @b{then}
22828 Ada.Tags'Elab_Spec;
22830 @b{if} @b{not} E035 @b{then}
22831 Ada.Tags'Elab_Body;
22834 @b{if} @b{not} E033 @b{then}
22835 Ada.Streams'Elab_Spec;
22838 @b{if} @b{not} E046 @b{then}
22839 System.Finalization_Root'Elab_Spec;
22842 @b{if} @b{not} E008 @b{then}
22843 Ada.Exceptions'Elab_Body;
22846 @b{if} @b{not} E048 @b{then}
22847 System.Finalization_Implementation'Elab_Spec;
22849 @b{if} @b{not} E048 @b{then}
22850 System.Finalization_Implementation'Elab_Body;
22853 @b{if} @b{not} E044 @b{then}
22854 Ada.Finalization'Elab_Spec;
22857 @b{if} @b{not} E057 @b{then}
22858 Ada.Finalization.List_Controller'Elab_Spec;
22861 @b{if} @b{not} E055 @b{then}
22862 System.File_Control_Block'Elab_Spec;
22865 @b{if} @b{not} E042 @b{then}
22866 System.File_Io'Elab_Body;
22869 @b{if} @b{not} E006 @b{then}
22870 Ada.Text_Io'Elab_Spec;
22872 @b{if} @b{not} E006 @b{then}
22873 Ada.Text_Io'Elab_Body;
22877 Elab_Final_Code := 0;
22885 @b{procedure} adafinal @b{is}
22894 -- main is actually a function, as in the ANSI C standard,
22895 -- defined to return the exit status. The three parameters
22896 -- are the argument count, argument values and environment
22899 @findex Main Program
22902 argv : System.Address;
22903 envp : System.Address)
22906 -- The initialize routine performs low level system
22907 -- initialization using a standard library routine which
22908 -- sets up signal handling and performs any other
22909 -- required setup. The routine can be found in file
22912 @findex __gnat_initialize
22913 @b{procedure} initialize;
22914 @b{pragma} Import (C, initialize, "__gnat_initialize");
22916 -- The finalize routine performs low level system
22917 -- finalization using a standard library routine. The
22918 -- routine is found in file a-final.c and in the standard
22919 -- distribution is a dummy routine that does nothing, so
22920 -- really this is a hook for special user finalization.
22922 @findex __gnat_finalize
22923 @b{procedure} finalize;
22924 @b{pragma} Import (C, finalize, "__gnat_finalize");
22926 -- We get to the main program of the partition by using
22927 -- pragma Import because if we try to with the unit and
22928 -- call it Ada style, then not only do we waste time
22929 -- recompiling it, but also, we don't really know the right
22930 -- switches (e.g.@: identifier character set) to be used
22933 @b{procedure} Ada_Main_Program;
22934 @b{pragma} Import (Ada, Ada_Main_Program, "_ada_hello");
22936 -- Start of processing for main
22939 -- Save global variables
22945 -- Call low level system initialization
22949 -- Call our generated Ada initialization routine
22953 -- This is the point at which we want the debugger to get
22958 -- Now we call the main program of the partition
22962 -- Perform Ada finalization
22966 -- Perform low level system finalization
22970 -- Return the proper exit status
22971 @b{return} (gnat_exit_status);
22974 -- This section is entirely comments, so it has no effect on the
22975 -- compilation of the Ada_Main package. It provides the list of
22976 -- object files and linker options, as well as some standard
22977 -- libraries needed for the link. The gnatlink utility parses
22978 -- this b~hello.adb file to read these comment lines to generate
22979 -- the appropriate command line arguments for the call to the
22980 -- system linker. The BEGIN/END lines are used for sentinels for
22981 -- this parsing operation.
22983 -- The exact file names will of course depend on the environment,
22984 -- host/target and location of files on the host system.
22986 @findex Object file list
22987 -- BEGIN Object file/option list
22990 -- -L/usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/
22991 -- /usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/libgnat.a
22992 -- END Object file/option list
22998 The Ada code in the above example is exactly what is generated by the
22999 binder. We have added comments to more clearly indicate the function
23000 of each part of the generated @code{Ada_Main} package.
23002 The code is standard Ada in all respects, and can be processed by any
23003 tools that handle Ada. In particular, it is possible to use the debugger
23004 in Ada mode to debug the generated @code{Ada_Main} package. For example,
23005 suppose that for reasons that you do not understand, your program is crashing
23006 during elaboration of the body of @code{Ada.Text_IO}. To locate this bug,
23007 you can place a breakpoint on the call:
23009 @smallexample @c ada
23010 Ada.Text_Io'Elab_Body;
23014 and trace the elaboration routine for this package to find out where
23015 the problem might be (more usually of course you would be debugging
23016 elaboration code in your own application).
23018 @node Elaboration Order Handling in GNAT
23019 @appendix Elaboration Order Handling in GNAT
23020 @cindex Order of elaboration
23021 @cindex Elaboration control
23024 * Elaboration Code::
23025 * Checking the Elaboration Order::
23026 * Controlling the Elaboration Order::
23027 * Controlling Elaboration in GNAT - Internal Calls::
23028 * Controlling Elaboration in GNAT - External Calls::
23029 * Default Behavior in GNAT - Ensuring Safety::
23030 * Treatment of Pragma Elaborate::
23031 * Elaboration Issues for Library Tasks::
23032 * Mixing Elaboration Models::
23033 * What to Do If the Default Elaboration Behavior Fails::
23034 * Elaboration for Indirect Calls::
23035 * Summary of Procedures for Elaboration Control::
23036 * Other Elaboration Order Considerations::
23037 * Determining the Chosen Elaboration Order::
23041 This chapter describes the handling of elaboration code in Ada and
23042 in GNAT, and discusses how the order of elaboration of program units can
23043 be controlled in GNAT, either automatically or with explicit programming
23046 @node Elaboration Code
23047 @section Elaboration Code
23050 Ada provides rather general mechanisms for executing code at elaboration
23051 time, that is to say before the main program starts executing. Such code arises
23055 @item Initializers for variables.
23056 Variables declared at the library level, in package specs or bodies, can
23057 require initialization that is performed at elaboration time, as in:
23058 @smallexample @c ada
23060 Sqrt_Half : Float := Sqrt (0.5);
23064 @item Package initialization code
23065 Code in a @code{BEGIN-END} section at the outer level of a package body is
23066 executed as part of the package body elaboration code.
23068 @item Library level task allocators
23069 Tasks that are declared using task allocators at the library level
23070 start executing immediately and hence can execute at elaboration time.
23074 Subprogram calls are possible in any of these contexts, which means that
23075 any arbitrary part of the program may be executed as part of the elaboration
23076 code. It is even possible to write a program which does all its work at
23077 elaboration time, with a null main program, although stylistically this
23078 would usually be considered an inappropriate way to structure
23081 An important concern arises in the context of elaboration code:
23082 we have to be sure that it is executed in an appropriate order. What we
23083 have is a series of elaboration code sections, potentially one section
23084 for each unit in the program. It is important that these execute
23085 in the correct order. Correctness here means that, taking the above
23086 example of the declaration of @code{Sqrt_Half},
23087 if some other piece of
23088 elaboration code references @code{Sqrt_Half},
23089 then it must run after the
23090 section of elaboration code that contains the declaration of
23093 There would never be any order of elaboration problem if we made a rule
23094 that whenever you @code{with} a unit, you must elaborate both the spec and body
23095 of that unit before elaborating the unit doing the @code{with}'ing:
23097 @smallexample @c ada
23101 @b{package} Unit_2 @b{is} @dots{}
23107 would require that both the body and spec of @code{Unit_1} be elaborated
23108 before the spec of @code{Unit_2}. However, a rule like that would be far too
23109 restrictive. In particular, it would make it impossible to have routines
23110 in separate packages that were mutually recursive.
23112 You might think that a clever enough compiler could look at the actual
23113 elaboration code and determine an appropriate correct order of elaboration,
23114 but in the general case, this is not possible. Consider the following
23117 In the body of @code{Unit_1}, we have a procedure @code{Func_1}
23119 the variable @code{Sqrt_1}, which is declared in the elaboration code
23120 of the body of @code{Unit_1}:
23122 @smallexample @c ada
23124 Sqrt_1 : Float := Sqrt (0.1);
23129 The elaboration code of the body of @code{Unit_1} also contains:
23131 @smallexample @c ada
23134 @b{if} expression_1 = 1 @b{then}
23135 Q := Unit_2.Func_2;
23142 @code{Unit_2} is exactly parallel,
23143 it has a procedure @code{Func_2} that references
23144 the variable @code{Sqrt_2}, which is declared in the elaboration code of
23145 the body @code{Unit_2}:
23147 @smallexample @c ada
23149 Sqrt_2 : Float := Sqrt (0.1);
23154 The elaboration code of the body of @code{Unit_2} also contains:
23156 @smallexample @c ada
23159 @b{if} expression_2 = 2 @b{then}
23160 Q := Unit_1.Func_1;
23167 Now the question is, which of the following orders of elaboration is
23192 If you carefully analyze the flow here, you will see that you cannot tell
23193 at compile time the answer to this question.
23194 If @code{expression_1} is not equal to 1,
23195 and @code{expression_2} is not equal to 2,
23196 then either order is acceptable, because neither of the function calls is
23197 executed. If both tests evaluate to true, then neither order is acceptable
23198 and in fact there is no correct order.
23200 If one of the two expressions is true, and the other is false, then one
23201 of the above orders is correct, and the other is incorrect. For example,
23202 if @code{expression_1} /= 1 and @code{expression_2} = 2,
23203 then the call to @code{Func_1}
23204 will occur, but not the call to @code{Func_2.}
23205 This means that it is essential
23206 to elaborate the body of @code{Unit_1} before
23207 the body of @code{Unit_2}, so the first
23208 order of elaboration is correct and the second is wrong.
23210 By making @code{expression_1} and @code{expression_2}
23211 depend on input data, or perhaps
23212 the time of day, we can make it impossible for the compiler or binder
23213 to figure out which of these expressions will be true, and hence it
23214 is impossible to guarantee a safe order of elaboration at run time.
23216 @node Checking the Elaboration Order
23217 @section Checking the Elaboration Order
23220 In some languages that involve the same kind of elaboration problems,
23221 e.g.@: Java and C++, the programmer is expected to worry about these
23222 ordering problems himself, and it is common to
23223 write a program in which an incorrect elaboration order gives
23224 surprising results, because it references variables before they
23226 Ada is designed to be a safe language, and a programmer-beware approach is
23227 clearly not sufficient. Consequently, the language provides three lines
23231 @item Standard rules
23232 Some standard rules restrict the possible choice of elaboration
23233 order. In particular, if you @code{with} a unit, then its spec is always
23234 elaborated before the unit doing the @code{with}. Similarly, a parent
23235 spec is always elaborated before the child spec, and finally
23236 a spec is always elaborated before its corresponding body.
23238 @item Dynamic elaboration checks
23239 @cindex Elaboration checks
23240 @cindex Checks, elaboration
23241 Dynamic checks are made at run time, so that if some entity is accessed
23242 before it is elaborated (typically by means of a subprogram call)
23243 then the exception (@code{Program_Error}) is raised.
23245 @item Elaboration control
23246 Facilities are provided for the programmer to specify the desired order
23250 Let's look at these facilities in more detail. First, the rules for
23251 dynamic checking. One possible rule would be simply to say that the
23252 exception is raised if you access a variable which has not yet been
23253 elaborated. The trouble with this approach is that it could require
23254 expensive checks on every variable reference. Instead Ada has two
23255 rules which are a little more restrictive, but easier to check, and
23259 @item Restrictions on calls
23260 A subprogram can only be called at elaboration time if its body
23261 has been elaborated. The rules for elaboration given above guarantee
23262 that the spec of the subprogram has been elaborated before the
23263 call, but not the body. If this rule is violated, then the
23264 exception @code{Program_Error} is raised.
23266 @item Restrictions on instantiations
23267 A generic unit can only be instantiated if the body of the generic
23268 unit has been elaborated. Again, the rules for elaboration given above
23269 guarantee that the spec of the generic unit has been elaborated
23270 before the instantiation, but not the body. If this rule is
23271 violated, then the exception @code{Program_Error} is raised.
23275 The idea is that if the body has been elaborated, then any variables
23276 it references must have been elaborated; by checking for the body being
23277 elaborated we guarantee that none of its references causes any
23278 trouble. As we noted above, this is a little too restrictive, because a
23279 subprogram that has no non-local references in its body may in fact be safe
23280 to call. However, it really would be unsafe to rely on this, because
23281 it would mean that the caller was aware of details of the implementation
23282 in the body. This goes against the basic tenets of Ada.
23284 A plausible implementation can be described as follows.
23285 A Boolean variable is associated with each subprogram
23286 and each generic unit. This variable is initialized to False, and is set to
23287 True at the point body is elaborated. Every call or instantiation checks the
23288 variable, and raises @code{Program_Error} if the variable is False.
23290 Note that one might think that it would be good enough to have one Boolean
23291 variable for each package, but that would not deal with cases of trying
23292 to call a body in the same package as the call
23293 that has not been elaborated yet.
23294 Of course a compiler may be able to do enough analysis to optimize away
23295 some of the Boolean variables as unnecessary, and @code{GNAT} indeed
23296 does such optimizations, but still the easiest conceptual model is to
23297 think of there being one variable per subprogram.
23299 @node Controlling the Elaboration Order
23300 @section Controlling the Elaboration Order
23303 In the previous section we discussed the rules in Ada which ensure
23304 that @code{Program_Error} is raised if an incorrect elaboration order is
23305 chosen. This prevents erroneous executions, but we need mechanisms to
23306 specify a correct execution and avoid the exception altogether.
23307 To achieve this, Ada provides a number of features for controlling
23308 the order of elaboration. We discuss these features in this section.
23310 First, there are several ways of indicating to the compiler that a given
23311 unit has no elaboration problems:
23314 @item packages that do not require a body
23315 A library package that does not require a body does not permit
23316 a body (this rule was introduced in Ada 95).
23317 Thus if we have a such a package, as in:
23319 @smallexample @c ada
23322 @b{package} Definitions @b{is}
23324 @b{type} m @b{is} @b{new} integer;
23325 @b{package} Subp @b{is}
23326 @b{type} a @b{is} @b{array} (1 .. 10) @b{of} m;
23327 @b{type} b @b{is} @b{array} (1 .. 20) @b{of} m;
23329 @b{end} Definitions;
23335 A package that @code{with}'s @code{Definitions} may safely instantiate
23336 @code{Definitions.Subp} because the compiler can determine that there
23337 definitely is no package body to worry about in this case
23340 @cindex pragma Pure
23342 Places sufficient restrictions on a unit to guarantee that
23343 no call to any subprogram in the unit can result in an
23344 elaboration problem. This means that the compiler does not need
23345 to worry about the point of elaboration of such units, and in
23346 particular, does not need to check any calls to any subprograms
23349 @item pragma Preelaborate
23350 @findex Preelaborate
23351 @cindex pragma Preelaborate
23352 This pragma places slightly less stringent restrictions on a unit than
23354 but these restrictions are still sufficient to ensure that there
23355 are no elaboration problems with any calls to the unit.
23357 @item pragma Elaborate_Body
23358 @findex Elaborate_Body
23359 @cindex pragma Elaborate_Body
23360 This pragma requires that the body of a unit be elaborated immediately
23361 after its spec. Suppose a unit @code{A} has such a pragma,
23362 and unit @code{B} does
23363 a @code{with} of unit @code{A}. Recall that the standard rules require
23364 the spec of unit @code{A}
23365 to be elaborated before the @code{with}'ing unit; given the pragma in
23366 @code{A}, we also know that the body of @code{A}
23367 will be elaborated before @code{B}, so
23368 that calls to @code{A} are safe and do not need a check.
23373 unlike pragma @code{Pure} and pragma @code{Preelaborate},
23375 @code{Elaborate_Body} does not guarantee that the program is
23376 free of elaboration problems, because it may not be possible
23377 to satisfy the requested elaboration order.
23378 Let's go back to the example with @code{Unit_1} and @code{Unit_2}.
23380 marks @code{Unit_1} as @code{Elaborate_Body},
23381 and not @code{Unit_2,} then the order of
23382 elaboration will be:
23394 Now that means that the call to @code{Func_1} in @code{Unit_2}
23395 need not be checked,
23396 it must be safe. But the call to @code{Func_2} in
23397 @code{Unit_1} may still fail if
23398 @code{Expression_1} is equal to 1,
23399 and the programmer must still take
23400 responsibility for this not being the case.
23402 If all units carry a pragma @code{Elaborate_Body}, then all problems are
23403 eliminated, except for calls entirely within a body, which are
23404 in any case fully under programmer control. However, using the pragma
23405 everywhere is not always possible.
23406 In particular, for our @code{Unit_1}/@code{Unit_2} example, if
23407 we marked both of them as having pragma @code{Elaborate_Body}, then
23408 clearly there would be no possible elaboration order.
23410 The above pragmas allow a server to guarantee safe use by clients, and
23411 clearly this is the preferable approach. Consequently a good rule
23412 is to mark units as @code{Pure} or @code{Preelaborate} if possible,
23413 and if this is not possible,
23414 mark them as @code{Elaborate_Body} if possible.
23415 As we have seen, there are situations where neither of these
23416 three pragmas can be used.
23417 So we also provide methods for clients to control the
23418 order of elaboration of the servers on which they depend:
23421 @item pragma Elaborate (unit)
23423 @cindex pragma Elaborate
23424 This pragma is placed in the context clause, after a @code{with} clause,
23425 and it requires that the body of the named unit be elaborated before
23426 the unit in which the pragma occurs. The idea is to use this pragma
23427 if the current unit calls at elaboration time, directly or indirectly,
23428 some subprogram in the named unit.
23430 @item pragma Elaborate_All (unit)
23431 @findex Elaborate_All
23432 @cindex pragma Elaborate_All
23433 This is a stronger version of the Elaborate pragma. Consider the
23437 Unit A @code{with}'s unit B and calls B.Func in elab code
23438 Unit B @code{with}'s unit C, and B.Func calls C.Func
23442 Now if we put a pragma @code{Elaborate (B)}
23443 in unit @code{A}, this ensures that the
23444 body of @code{B} is elaborated before the call, but not the
23445 body of @code{C}, so
23446 the call to @code{C.Func} could still cause @code{Program_Error} to
23449 The effect of a pragma @code{Elaborate_All} is stronger, it requires
23450 not only that the body of the named unit be elaborated before the
23451 unit doing the @code{with}, but also the bodies of all units that the
23452 named unit uses, following @code{with} links transitively. For example,
23453 if we put a pragma @code{Elaborate_All (B)} in unit @code{A},
23455 not only that the body of @code{B} be elaborated before @code{A},
23457 body of @code{C}, because @code{B} @code{with}'s @code{C}.
23461 We are now in a position to give a usage rule in Ada for avoiding
23462 elaboration problems, at least if dynamic dispatching and access to
23463 subprogram values are not used. We will handle these cases separately
23466 The rule is simple. If a unit has elaboration code that can directly or
23467 indirectly make a call to a subprogram in a @code{with}'ed unit, or instantiate
23468 a generic package in a @code{with}'ed unit,
23469 then if the @code{with}'ed unit does not have
23470 pragma @code{Pure} or @code{Preelaborate}, then the client should have
23471 a pragma @code{Elaborate_All}
23472 for the @code{with}'ed unit. By following this rule a client is
23473 assured that calls can be made without risk of an exception.
23475 For generic subprogram instantiations, the rule can be relaxed to
23476 require only a pragma @code{Elaborate} since elaborating the body
23477 of a subprogram cannot cause any transitive elaboration (we are
23478 not calling the subprogram in this case, just elaborating its
23481 If this rule is not followed, then a program may be in one of four
23485 @item No order exists
23486 No order of elaboration exists which follows the rules, taking into
23487 account any @code{Elaborate}, @code{Elaborate_All},
23488 or @code{Elaborate_Body} pragmas. In
23489 this case, an Ada compiler must diagnose the situation at bind
23490 time, and refuse to build an executable program.
23492 @item One or more orders exist, all incorrect
23493 One or more acceptable elaboration orders exist, and all of them
23494 generate an elaboration order problem. In this case, the binder
23495 can build an executable program, but @code{Program_Error} will be raised
23496 when the program is run.
23498 @item Several orders exist, some right, some incorrect
23499 One or more acceptable elaboration orders exists, and some of them
23500 work, and some do not. The programmer has not controlled
23501 the order of elaboration, so the binder may or may not pick one of
23502 the correct orders, and the program may or may not raise an
23503 exception when it is run. This is the worst case, because it means
23504 that the program may fail when moved to another compiler, or even
23505 another version of the same compiler.
23507 @item One or more orders exists, all correct
23508 One ore more acceptable elaboration orders exist, and all of them
23509 work. In this case the program runs successfully. This state of
23510 affairs can be guaranteed by following the rule we gave above, but
23511 may be true even if the rule is not followed.
23515 Note that one additional advantage of following our rules on the use
23516 of @code{Elaborate} and @code{Elaborate_All}
23517 is that the program continues to stay in the ideal (all orders OK) state
23518 even if maintenance
23519 changes some bodies of some units. Conversely, if a program that does
23520 not follow this rule happens to be safe at some point, this state of affairs
23521 may deteriorate silently as a result of maintenance changes.
23523 You may have noticed that the above discussion did not mention
23524 the use of @code{Elaborate_Body}. This was a deliberate omission. If you
23525 @code{with} an @code{Elaborate_Body} unit, it still may be the case that
23526 code in the body makes calls to some other unit, so it is still necessary
23527 to use @code{Elaborate_All} on such units.
23529 @node Controlling Elaboration in GNAT - Internal Calls
23530 @section Controlling Elaboration in GNAT - Internal Calls
23533 In the case of internal calls, i.e., calls within a single package, the
23534 programmer has full control over the order of elaboration, and it is up
23535 to the programmer to elaborate declarations in an appropriate order. For
23538 @smallexample @c ada
23541 @b{function} One @b{return} Float;
23545 @b{function} One @b{return} Float @b{is}
23554 will obviously raise @code{Program_Error} at run time, because function
23555 One will be called before its body is elaborated. In this case GNAT will
23556 generate a warning that the call will raise @code{Program_Error}:
23562 2. function One return Float;
23564 4. Q : Float := One;
23566 >>> warning: cannot call "One" before body is elaborated
23567 >>> warning: Program_Error will be raised at run time
23570 6. function One return Float is
23583 Note that in this particular case, it is likely that the call is safe, because
23584 the function @code{One} does not access any global variables.
23585 Nevertheless in Ada, we do not want the validity of the check to depend on
23586 the contents of the body (think about the separate compilation case), so this
23587 is still wrong, as we discussed in the previous sections.
23589 The error is easily corrected by rearranging the declarations so that the
23590 body of @code{One} appears before the declaration containing the call
23591 (note that in Ada 95 and Ada 2005,
23592 declarations can appear in any order, so there is no restriction that
23593 would prevent this reordering, and if we write:
23595 @smallexample @c ada
23598 @b{function} One @b{return} Float;
23600 @b{function} One @b{return} Float @b{is}
23611 then all is well, no warning is generated, and no
23612 @code{Program_Error} exception
23614 Things are more complicated when a chain of subprograms is executed:
23616 @smallexample @c ada
23619 @b{function} A @b{return} Integer;
23620 @b{function} B @b{return} Integer;
23621 @b{function} C @b{return} Integer;
23623 @b{function} B @b{return} Integer @b{is} @b{begin} @b{return} A; @b{end};
23624 @b{function} C @b{return} Integer @b{is} @b{begin} @b{return} B; @b{end};
23628 @b{function} A @b{return} Integer @b{is} @b{begin} @b{return} 1; @b{end};
23634 Now the call to @code{C}
23635 at elaboration time in the declaration of @code{X} is correct, because
23636 the body of @code{C} is already elaborated,
23637 and the call to @code{B} within the body of
23638 @code{C} is correct, but the call
23639 to @code{A} within the body of @code{B} is incorrect, because the body
23640 of @code{A} has not been elaborated, so @code{Program_Error}
23641 will be raised on the call to @code{A}.
23642 In this case GNAT will generate a
23643 warning that @code{Program_Error} may be
23644 raised at the point of the call. Let's look at the warning:
23650 2. function A return Integer;
23651 3. function B return Integer;
23652 4. function C return Integer;
23654 6. function B return Integer is begin return A; end;
23656 >>> warning: call to "A" before body is elaborated may
23657 raise Program_Error
23658 >>> warning: "B" called at line 7
23659 >>> warning: "C" called at line 9
23661 7. function C return Integer is begin return B; end;
23663 9. X : Integer := C;
23665 11. function A return Integer is begin return 1; end;
23675 Note that the message here says ``may raise'', instead of the direct case,
23676 where the message says ``will be raised''. That's because whether
23678 actually called depends in general on run-time flow of control.
23679 For example, if the body of @code{B} said
23681 @smallexample @c ada
23684 @b{function} B @b{return} Integer @b{is}
23686 @b{if} some-condition-depending-on-input-data @b{then}
23697 then we could not know until run time whether the incorrect call to A would
23698 actually occur, so @code{Program_Error} might
23699 or might not be raised. It is possible for a compiler to
23700 do a better job of analyzing bodies, to
23701 determine whether or not @code{Program_Error}
23702 might be raised, but it certainly
23703 couldn't do a perfect job (that would require solving the halting problem
23704 and is provably impossible), and because this is a warning anyway, it does
23705 not seem worth the effort to do the analysis. Cases in which it
23706 would be relevant are rare.
23708 In practice, warnings of either of the forms given
23709 above will usually correspond to
23710 real errors, and should be examined carefully and eliminated.
23711 In the rare case where a warning is bogus, it can be suppressed by any of
23712 the following methods:
23716 Compile with the @option{-gnatws} switch set
23719 Suppress @code{Elaboration_Check} for the called subprogram
23722 Use pragma @code{Warnings_Off} to turn warnings off for the call
23726 For the internal elaboration check case,
23727 GNAT by default generates the
23728 necessary run-time checks to ensure
23729 that @code{Program_Error} is raised if any
23730 call fails an elaboration check. Of course this can only happen if a
23731 warning has been issued as described above. The use of pragma
23732 @code{Suppress (Elaboration_Check)} may (but is not guaranteed to) suppress
23733 some of these checks, meaning that it may be possible (but is not
23734 guaranteed) for a program to be able to call a subprogram whose body
23735 is not yet elaborated, without raising a @code{Program_Error} exception.
23737 @node Controlling Elaboration in GNAT - External Calls
23738 @section Controlling Elaboration in GNAT - External Calls
23741 The previous section discussed the case in which the execution of a
23742 particular thread of elaboration code occurred entirely within a
23743 single unit. This is the easy case to handle, because a programmer
23744 has direct and total control over the order of elaboration, and
23745 furthermore, checks need only be generated in cases which are rare
23746 and which the compiler can easily detect.
23747 The situation is more complex when separate compilation is taken into account.
23748 Consider the following:
23750 @smallexample @c ada
23753 @b{package} Math @b{is}
23754 @b{function} Sqrt (Arg : Float) @b{return} Float;
23757 @b{package} @b{body} Math @b{is}
23758 @b{function} Sqrt (Arg : Float) @b{return} Float @b{is}
23766 @b{package} Stuff @b{is}
23767 X : Float := Math.Sqrt (0.5);
23771 @b{procedure} Main @b{is}
23780 where @code{Main} is the main program. When this program is executed, the
23781 elaboration code must first be executed, and one of the jobs of the
23782 binder is to determine the order in which the units of a program are
23783 to be elaborated. In this case we have four units: the spec and body
23785 the spec of @code{Stuff} and the body of @code{Main}).
23786 In what order should the four separate sections of elaboration code
23789 There are some restrictions in the order of elaboration that the binder
23790 can choose. In particular, if unit U has a @code{with}
23791 for a package @code{X}, then you
23792 are assured that the spec of @code{X}
23793 is elaborated before U , but you are
23794 not assured that the body of @code{X}
23795 is elaborated before U.
23796 This means that in the above case, the binder is allowed to choose the
23807 but that's not good, because now the call to @code{Math.Sqrt}
23808 that happens during
23809 the elaboration of the @code{Stuff}
23810 spec happens before the body of @code{Math.Sqrt} is
23811 elaborated, and hence causes @code{Program_Error} exception to be raised.
23812 At first glance, one might say that the binder is misbehaving, because
23813 obviously you want to elaborate the body of something you @code{with}
23815 that is not a general rule that can be followed in all cases. Consider
23817 @smallexample @c ada
23820 @b{package} X @b{is} @dots{}
23822 @b{package} Y @b{is} @dots{}
23825 @b{package} @b{body} Y @b{is} @dots{}
23828 @b{package} @b{body} X @b{is} @dots{}
23834 This is a common arrangement, and, apart from the order of elaboration
23835 problems that might arise in connection with elaboration code, this works fine.
23836 A rule that says that you must first elaborate the body of anything you
23837 @code{with} cannot work in this case:
23838 the body of @code{X} @code{with}'s @code{Y},
23839 which means you would have to
23840 elaborate the body of @code{Y} first, but that @code{with}'s @code{X},
23842 you have to elaborate the body of @code{X} first, but @dots{} and we have a
23843 loop that cannot be broken.
23845 It is true that the binder can in many cases guess an order of elaboration
23846 that is unlikely to cause a @code{Program_Error}
23847 exception to be raised, and it tries to do so (in the
23848 above example of @code{Math/Stuff/Spec}, the GNAT binder will
23850 elaborate the body of @code{Math} right after its spec, so all will be well).
23852 However, a program that blindly relies on the binder to be helpful can
23853 get into trouble, as we discussed in the previous sections, so
23855 provides a number of facilities for assisting the programmer in
23856 developing programs that are robust with respect to elaboration order.
23858 @node Default Behavior in GNAT - Ensuring Safety
23859 @section Default Behavior in GNAT - Ensuring Safety
23862 The default behavior in GNAT ensures elaboration safety. In its
23863 default mode GNAT implements the
23864 rule we previously described as the right approach. Let's restate it:
23868 @emph{If a unit has elaboration code that can directly or indirectly make a
23869 call to a subprogram in a @code{with}'ed unit, or instantiate a generic
23870 package in a @code{with}'ed unit, then if the @code{with}'ed unit
23871 does not have pragma @code{Pure} or
23872 @code{Preelaborate}, then the client should have an
23873 @code{Elaborate_All} pragma for the @code{with}'ed unit.}
23875 @emph{In the case of instantiating a generic subprogram, it is always
23876 sufficient to have only an @code{Elaborate} pragma for the
23877 @code{with}'ed unit.}
23881 By following this rule a client is assured that calls and instantiations
23882 can be made without risk of an exception.
23884 In this mode GNAT traces all calls that are potentially made from
23885 elaboration code, and puts in any missing implicit @code{Elaborate}
23886 and @code{Elaborate_All} pragmas.
23887 The advantage of this approach is that no elaboration problems
23888 are possible if the binder can find an elaboration order that is
23889 consistent with these implicit @code{Elaborate} and
23890 @code{Elaborate_All} pragmas. The
23891 disadvantage of this approach is that no such order may exist.
23893 If the binder does not generate any diagnostics, then it means that it has
23894 found an elaboration order that is guaranteed to be safe. However, the binder
23895 may still be relying on implicitly generated @code{Elaborate} and
23896 @code{Elaborate_All} pragmas so portability to other compilers than GNAT is not
23899 If it is important to guarantee portability, then the compilations should
23902 (info messages for elaboration prag mas) switch. This will cause info messages
23903 to be generated indicating the missing @code{Elaborate} and
23904 @code{Elaborate_All} pragmas.
23905 Consider the following source program:
23907 @smallexample @c ada
23911 @b{package} j @b{is}
23912 m : integer := k.r;
23919 where it is clear that there
23920 should be a pragma @code{Elaborate_All}
23921 for unit @code{k}. An implicit pragma will be generated, and it is
23922 likely that the binder will be able to honor it. However, if you want
23923 to port this program to some other Ada compiler than GNAT.
23924 it is safer to include the pragma explicitly in the source. If this
23925 unit is compiled with the
23927 switch, then the compiler outputs an information message:
23934 3. m : integer := k.r;
23936 >>> info: call to "r" may raise Program_Error
23937 >>> info: missing pragma Elaborate_All for "k"
23945 and these messages can be used as a guide for supplying manually
23946 the missing pragmas. It is usually a bad idea to use this
23947 option during development. That's because it will tell you when
23948 you need to put in a pragma, but cannot tell you when it is time
23949 to take it out. So the use of pragma @code{Elaborate_All} may lead to
23950 unnecessary dependencies and even false circularities.
23952 This default mode is more restrictive than the Ada Reference
23953 Manual, and it is possible to construct programs which will compile
23954 using the dynamic model described there, but will run into a
23955 circularity using the safer static model we have described.
23957 Of course any Ada compiler must be able to operate in a mode
23958 consistent with the requirements of the Ada Reference Manual,
23959 and in particular must have the capability of implementing the
23960 standard dynamic model of elaboration with run-time checks.
23962 In GNAT, this standard mode can be achieved either by the use of
23963 the @option{-gnatE} switch on the compiler (@command{gcc} or
23964 @command{gnatmake}) command, or by the use of the configuration pragma:
23966 @smallexample @c ada
23967 @b{pragma} Elaboration_Checks (DYNAMIC);
23971 Either approach will cause the unit affected to be compiled using the
23972 standard dynamic run-time elaboration checks described in the Ada
23973 Reference Manual. The static model is generally preferable, since it
23974 is clearly safer to rely on compile and link time checks rather than
23975 run-time checks. However, in the case of legacy code, it may be
23976 difficult to meet the requirements of the static model. This
23977 issue is further discussed in
23978 @ref{What to Do If the Default Elaboration Behavior Fails}.
23980 Note that the static model provides a strict subset of the allowed
23981 behavior and programs of the Ada Reference Manual, so if you do
23982 adhere to the static model and no circularities exist,
23983 then you are assured that your program will
23984 work using the dynamic model, providing that you remove any
23985 pragma Elaborate statements from the source.
23987 @node Treatment of Pragma Elaborate
23988 @section Treatment of Pragma Elaborate
23989 @cindex Pragma Elaborate
23992 The use of @code{pragma Elaborate}
23993 should generally be avoided in Ada 95 and Ada 2005 programs,
23994 since there is no guarantee that transitive calls
23995 will be properly handled. Indeed at one point, this pragma was placed
23996 in Annex J (Obsolescent Features), on the grounds that it is never useful.
23998 Now that's a bit restrictive. In practice, the case in which
23999 @code{pragma Elaborate} is useful is when the caller knows that there
24000 are no transitive calls, or that the called unit contains all necessary
24001 transitive @code{pragma Elaborate} statements, and legacy code often
24002 contains such uses.
24004 Strictly speaking the static mode in GNAT should ignore such pragmas,
24005 since there is no assurance at compile time that the necessary safety
24006 conditions are met. In practice, this would cause GNAT to be incompatible
24007 with correctly written Ada 83 code that had all necessary
24008 @code{pragma Elaborate} statements in place. Consequently, we made the
24009 decision that GNAT in its default mode will believe that if it encounters
24010 a @code{pragma Elaborate} then the programmer knows what they are doing,
24011 and it will trust that no elaboration errors can occur.
24013 The result of this decision is two-fold. First to be safe using the
24014 static mode, you should remove all @code{pragma Elaborate} statements.
24015 Second, when fixing circularities in existing code, you can selectively
24016 use @code{pragma Elaborate} statements to convince the static mode of
24017 GNAT that it need not generate an implicit @code{pragma Elaborate_All}
24020 When using the static mode with @option{-gnatwl}, any use of
24021 @code{pragma Elaborate} will generate a warning about possible
24024 @node Elaboration Issues for Library Tasks
24025 @section Elaboration Issues for Library Tasks
24026 @cindex Library tasks, elaboration issues
24027 @cindex Elaboration of library tasks
24030 In this section we examine special elaboration issues that arise for
24031 programs that declare library level tasks.
24033 Generally the model of execution of an Ada program is that all units are
24034 elaborated, and then execution of the program starts. However, the
24035 declaration of library tasks definitely does not fit this model. The
24036 reason for this is that library tasks start as soon as they are declared
24037 (more precisely, as soon as the statement part of the enclosing package
24038 body is reached), that is to say before elaboration
24039 of the program is complete. This means that if such a task calls a
24040 subprogram, or an entry in another task, the callee may or may not be
24041 elaborated yet, and in the standard
24042 Reference Manual model of dynamic elaboration checks, you can even
24043 get timing dependent Program_Error exceptions, since there can be
24044 a race between the elaboration code and the task code.
24046 The static model of elaboration in GNAT seeks to avoid all such
24047 dynamic behavior, by being conservative, and the conservative
24048 approach in this particular case is to assume that all the code
24049 in a task body is potentially executed at elaboration time if
24050 a task is declared at the library level.
24052 This can definitely result in unexpected circularities. Consider
24053 the following example
24055 @smallexample @c ada
24056 @b{package} Decls @b{is}
24057 @b{task} Lib_Task @b{is}
24061 @b{type} My_Int @b{is} @b{new} Integer;
24063 @b{function} Ident (M : My_Int) @b{return} My_Int;
24067 @b{package} @b{body} Decls @b{is}
24068 @b{task} @b{body} Lib_Task @b{is}
24074 @b{function} Ident (M : My_Int) @b{return} My_Int @b{is}
24081 @b{package} Utils @b{is}
24082 @b{procedure} Put_Val (Arg : Decls.My_Int);
24086 @b{package} @b{body} Utils @b{is}
24087 @b{procedure} Put_Val (Arg : Decls.My_Int) @b{is}
24089 Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
24094 @b{procedure} Main @b{is}
24096 Decls.Lib_Task.Start;
24101 If the above example is compiled in the default static elaboration
24102 mode, then a circularity occurs. The circularity comes from the call
24103 @code{Utils.Put_Val} in the task body of @code{Decls.Lib_Task}. Since
24104 this call occurs in elaboration code, we need an implicit pragma
24105 @code{Elaborate_All} for @code{Utils}. This means that not only must
24106 the spec and body of @code{Utils} be elaborated before the body
24107 of @code{Decls}, but also the spec and body of any unit that is
24108 @code{with'ed} by the body of @code{Utils} must also be elaborated before
24109 the body of @code{Decls}. This is the transitive implication of
24110 pragma @code{Elaborate_All} and it makes sense, because in general
24111 the body of @code{Put_Val} might have a call to something in a
24112 @code{with'ed} unit.
24114 In this case, the body of Utils (actually its spec) @code{with's}
24115 @code{Decls}. Unfortunately this means that the body of @code{Decls}
24116 must be elaborated before itself, in case there is a call from the
24117 body of @code{Utils}.
24119 Here is the exact chain of events we are worrying about:
24123 In the body of @code{Decls} a call is made from within the body of a library
24124 task to a subprogram in the package @code{Utils}. Since this call may
24125 occur at elaboration time (given that the task is activated at elaboration
24126 time), we have to assume the worst, i.e., that the
24127 call does happen at elaboration time.
24130 This means that the body and spec of @code{Util} must be elaborated before
24131 the body of @code{Decls} so that this call does not cause an access before
24135 Within the body of @code{Util}, specifically within the body of
24136 @code{Util.Put_Val} there may be calls to any unit @code{with}'ed
24140 One such @code{with}'ed package is package @code{Decls}, so there
24141 might be a call to a subprogram in @code{Decls} in @code{Put_Val}.
24142 In fact there is such a call in this example, but we would have to
24143 assume that there was such a call even if it were not there, since
24144 we are not supposed to write the body of @code{Decls} knowing what
24145 is in the body of @code{Utils}; certainly in the case of the
24146 static elaboration model, the compiler does not know what is in
24147 other bodies and must assume the worst.
24150 This means that the spec and body of @code{Decls} must also be
24151 elaborated before we elaborate the unit containing the call, but
24152 that unit is @code{Decls}! This means that the body of @code{Decls}
24153 must be elaborated before itself, and that's a circularity.
24157 Indeed, if you add an explicit pragma @code{Elaborate_All} for @code{Utils} in
24158 the body of @code{Decls} you will get a true Ada Reference Manual
24159 circularity that makes the program illegal.
24161 In practice, we have found that problems with the static model of
24162 elaboration in existing code often arise from library tasks, so
24163 we must address this particular situation.
24165 Note that if we compile and run the program above, using the dynamic model of
24166 elaboration (that is to say use the @option{-gnatE} switch),
24167 then it compiles, binds,
24168 links, and runs, printing the expected result of 2. Therefore in some sense
24169 the circularity here is only apparent, and we need to capture
24170 the properties of this program that distinguish it from other library-level
24171 tasks that have real elaboration problems.
24173 We have four possible answers to this question:
24178 Use the dynamic model of elaboration.
24180 If we use the @option{-gnatE} switch, then as noted above, the program works.
24181 Why is this? If we examine the task body, it is apparent that the task cannot
24183 @code{accept} statement until after elaboration has been completed, because
24184 the corresponding entry call comes from the main program, not earlier.
24185 This is why the dynamic model works here. But that's really giving
24186 up on a precise analysis, and we prefer to take this approach only if we cannot
24188 problem in any other manner. So let us examine two ways to reorganize
24189 the program to avoid the potential elaboration problem.
24192 Split library tasks into separate packages.
24194 Write separate packages, so that library tasks are isolated from
24195 other declarations as much as possible. Let us look at a variation on
24198 @smallexample @c ada
24199 @b{package} Decls1 @b{is}
24200 @b{task} Lib_Task @b{is}
24206 @b{package} @b{body} Decls1 @b{is}
24207 @b{task} @b{body} Lib_Task @b{is}
24214 @b{package} Decls2 @b{is}
24215 @b{type} My_Int @b{is} @b{new} Integer;
24216 @b{function} Ident (M : My_Int) @b{return} My_Int;
24220 @b{package} @b{body} Decls2 @b{is}
24221 @b{function} Ident (M : My_Int) @b{return} My_Int @b{is}
24228 @b{package} Utils @b{is}
24229 @b{procedure} Put_Val (Arg : Decls2.My_Int);
24233 @b{package} @b{body} Utils @b{is}
24234 @b{procedure} Put_Val (Arg : Decls2.My_Int) @b{is}
24236 Text_IO.Put_Line (Decls2.My_Int'Image (Decls2.Ident (Arg)));
24241 @b{procedure} Main @b{is}
24243 Decls1.Lib_Task.Start;
24248 All we have done is to split @code{Decls} into two packages, one
24249 containing the library task, and one containing everything else. Now
24250 there is no cycle, and the program compiles, binds, links and executes
24251 using the default static model of elaboration.
24254 Declare separate task types.
24256 A significant part of the problem arises because of the use of the
24257 single task declaration form. This means that the elaboration of
24258 the task type, and the elaboration of the task itself (i.e.@: the
24259 creation of the task) happen at the same time. A good rule
24260 of style in Ada is to always create explicit task types. By
24261 following the additional step of placing task objects in separate
24262 packages from the task type declaration, many elaboration problems
24263 are avoided. Here is another modified example of the example program:
24265 @smallexample @c ada
24266 @b{package} Decls @b{is}
24267 @b{task} @b{type} Lib_Task_Type @b{is}
24269 @b{end} Lib_Task_Type;
24271 @b{type} My_Int @b{is} @b{new} Integer;
24273 @b{function} Ident (M : My_Int) @b{return} My_Int;
24277 @b{package} @b{body} Decls @b{is}
24278 @b{task} @b{body} Lib_Task_Type @b{is}
24282 @b{end} Lib_Task_Type;
24284 @b{function} Ident (M : My_Int) @b{return} My_Int @b{is}
24291 @b{package} Utils @b{is}
24292 @b{procedure} Put_Val (Arg : Decls.My_Int);
24296 @b{package} @b{body} Utils @b{is}
24297 @b{procedure} Put_Val (Arg : Decls.My_Int) @b{is}
24299 Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
24304 @b{package} Declst @b{is}
24305 Lib_Task : Decls.Lib_Task_Type;
24309 @b{procedure} Main @b{is}
24311 Declst.Lib_Task.Start;
24316 What we have done here is to replace the @code{task} declaration in
24317 package @code{Decls} with a @code{task type} declaration. Then we
24318 introduce a separate package @code{Declst} to contain the actual
24319 task object. This separates the elaboration issues for
24320 the @code{task type}
24321 declaration, which causes no trouble, from the elaboration issues
24322 of the task object, which is also unproblematic, since it is now independent
24323 of the elaboration of @code{Utils}.
24324 This separation of concerns also corresponds to
24325 a generally sound engineering principle of separating declarations
24326 from instances. This version of the program also compiles, binds, links,
24327 and executes, generating the expected output.
24330 Use No_Entry_Calls_In_Elaboration_Code restriction.
24331 @cindex No_Entry_Calls_In_Elaboration_Code
24333 The previous two approaches described how a program can be restructured
24334 to avoid the special problems caused by library task bodies. in practice,
24335 however, such restructuring may be difficult to apply to existing legacy code,
24336 so we must consider solutions that do not require massive rewriting.
24338 Let us consider more carefully why our original sample program works
24339 under the dynamic model of elaboration. The reason is that the code
24340 in the task body blocks immediately on the @code{accept}
24341 statement. Now of course there is nothing to prohibit elaboration
24342 code from making entry calls (for example from another library level task),
24343 so we cannot tell in isolation that
24344 the task will not execute the accept statement during elaboration.
24346 However, in practice it is very unusual to see elaboration code
24347 make any entry calls, and the pattern of tasks starting
24348 at elaboration time and then immediately blocking on @code{accept} or
24349 @code{select} statements is very common. What this means is that
24350 the compiler is being too pessimistic when it analyzes the
24351 whole package body as though it might be executed at elaboration
24354 If we know that the elaboration code contains no entry calls, (a very safe
24355 assumption most of the time, that could almost be made the default
24356 behavior), then we can compile all units of the program under control
24357 of the following configuration pragma:
24360 pragma Restrictions (No_Entry_Calls_In_Elaboration_Code);
24364 This pragma can be placed in the @file{gnat.adc} file in the usual
24365 manner. If we take our original unmodified program and compile it
24366 in the presence of a @file{gnat.adc} containing the above pragma,
24367 then once again, we can compile, bind, link, and execute, obtaining
24368 the expected result. In the presence of this pragma, the compiler does
24369 not trace calls in a task body, that appear after the first @code{accept}
24370 or @code{select} statement, and therefore does not report a potential
24371 circularity in the original program.
24373 The compiler will check to the extent it can that the above
24374 restriction is not violated, but it is not always possible to do a
24375 complete check at compile time, so it is important to use this
24376 pragma only if the stated restriction is in fact met, that is to say
24377 no task receives an entry call before elaboration of all units is completed.
24381 @node Mixing Elaboration Models
24382 @section Mixing Elaboration Models
24384 So far, we have assumed that the entire program is either compiled
24385 using the dynamic model or static model, ensuring consistency. It
24386 is possible to mix the two models, but rules have to be followed
24387 if this mixing is done to ensure that elaboration checks are not
24390 The basic rule is that @emph{a unit compiled with the static model cannot
24391 be @code{with'ed} by a unit compiled with the dynamic model}. The
24392 reason for this is that in the static model, a unit assumes that
24393 its clients guarantee to use (the equivalent of) pragma
24394 @code{Elaborate_All} so that no elaboration checks are required
24395 in inner subprograms, and this assumption is violated if the
24396 client is compiled with dynamic checks.
24398 The precise rule is as follows. A unit that is compiled with dynamic
24399 checks can only @code{with} a unit that meets at least one of the
24400 following criteria:
24405 The @code{with'ed} unit is itself compiled with dynamic elaboration
24406 checks (that is with the @option{-gnatE} switch.
24409 The @code{with'ed} unit is an internal GNAT implementation unit from
24410 the System, Interfaces, Ada, or GNAT hierarchies.
24413 The @code{with'ed} unit has pragma Preelaborate or pragma Pure.
24416 The @code{with'ing} unit (that is the client) has an explicit pragma
24417 @code{Elaborate_All} for the @code{with'ed} unit.
24422 If this rule is violated, that is if a unit with dynamic elaboration
24423 checks @code{with's} a unit that does not meet one of the above four
24424 criteria, then the binder (@code{gnatbind}) will issue a warning
24425 similar to that in the following example:
24428 warning: "x.ads" has dynamic elaboration checks and with's
24429 warning: "y.ads" which has static elaboration checks
24433 These warnings indicate that the rule has been violated, and that as a result
24434 elaboration checks may be missed in the resulting executable file.
24435 This warning may be suppressed using the @option{-ws} binder switch
24436 in the usual manner.
24438 One useful application of this mixing rule is in the case of a subsystem
24439 which does not itself @code{with} units from the remainder of the
24440 application. In this case, the entire subsystem can be compiled with
24441 dynamic checks to resolve a circularity in the subsystem, while
24442 allowing the main application that uses this subsystem to be compiled
24443 using the more reliable default static model.
24445 @node What to Do If the Default Elaboration Behavior Fails
24446 @section What to Do If the Default Elaboration Behavior Fails
24449 If the binder cannot find an acceptable order, it outputs detailed
24450 diagnostics. For example:
24456 error: elaboration circularity detected
24457 info: "proc (body)" must be elaborated before "pack (body)"
24458 info: reason: Elaborate_All probably needed in unit "pack (body)"
24459 info: recompile "pack (body)" with -gnatel
24460 info: for full details
24461 info: "proc (body)"
24462 info: is needed by its spec:
24463 info: "proc (spec)"
24464 info: which is withed by:
24465 info: "pack (body)"
24466 info: "pack (body)" must be elaborated before "proc (body)"
24467 info: reason: pragma Elaborate in unit "proc (body)"
24473 In this case we have a cycle that the binder cannot break. On the one
24474 hand, there is an explicit pragma Elaborate in @code{proc} for
24475 @code{pack}. This means that the body of @code{pack} must be elaborated
24476 before the body of @code{proc}. On the other hand, there is elaboration
24477 code in @code{pack} that calls a subprogram in @code{proc}. This means
24478 that for maximum safety, there should really be a pragma
24479 Elaborate_All in @code{pack} for @code{proc} which would require that
24480 the body of @code{proc} be elaborated before the body of
24481 @code{pack}. Clearly both requirements cannot be satisfied.
24482 Faced with a circularity of this kind, you have three different options.
24485 @item Fix the program
24486 The most desirable option from the point of view of long-term maintenance
24487 is to rearrange the program so that the elaboration problems are avoided.
24488 One useful technique is to place the elaboration code into separate
24489 child packages. Another is to move some of the initialization code to
24490 explicitly called subprograms, where the program controls the order
24491 of initialization explicitly. Although this is the most desirable option,
24492 it may be impractical and involve too much modification, especially in
24493 the case of complex legacy code.
24495 @item Perform dynamic checks
24496 If the compilations are done using the
24498 (dynamic elaboration check) switch, then GNAT behaves in a quite different
24499 manner. Dynamic checks are generated for all calls that could possibly result
24500 in raising an exception. With this switch, the compiler does not generate
24501 implicit @code{Elaborate} or @code{Elaborate_All} pragmas. The behavior then is
24502 exactly as specified in the @cite{Ada Reference Manual}.
24503 The binder will generate
24504 an executable program that may or may not raise @code{Program_Error}, and then
24505 it is the programmer's job to ensure that it does not raise an exception. Note
24506 that it is important to compile all units with the switch, it cannot be used
24509 @item Suppress checks
24510 The drawback of dynamic checks is that they generate a
24511 significant overhead at run time, both in space and time. If you
24512 are absolutely sure that your program cannot raise any elaboration
24513 exceptions, and you still want to use the dynamic elaboration model,
24514 then you can use the configuration pragma
24515 @code{Suppress (Elaboration_Check)} to suppress all such checks. For
24516 example this pragma could be placed in the @file{gnat.adc} file.
24518 @item Suppress checks selectively
24519 When you know that certain calls or instantiations in elaboration code cannot
24520 possibly lead to an elaboration error, and the binder nevertheless complains
24521 about implicit @code{Elaborate} and @code{Elaborate_All} pragmas that lead to
24522 elaboration circularities, it is possible to remove those warnings locally and
24523 obtain a program that will bind. Clearly this can be unsafe, and it is the
24524 responsibility of the programmer to make sure that the resulting program has no
24525 elaboration anomalies. The pragma @code{Suppress (Elaboration_Check)} can be
24526 used with different granularity to suppress warnings and break elaboration
24531 Place the pragma that names the called subprogram in the declarative part
24532 that contains the call.
24535 Place the pragma in the declarative part, without naming an entity. This
24536 disables warnings on all calls in the corresponding declarative region.
24539 Place the pragma in the package spec that declares the called subprogram,
24540 and name the subprogram. This disables warnings on all elaboration calls to
24544 Place the pragma in the package spec that declares the called subprogram,
24545 without naming any entity. This disables warnings on all elaboration calls to
24546 all subprograms declared in this spec.
24548 @item Use Pragma Elaborate
24549 As previously described in section @xref{Treatment of Pragma Elaborate},
24550 GNAT in static mode assumes that a @code{pragma} Elaborate indicates correctly
24551 that no elaboration checks are required on calls to the designated unit.
24552 There may be cases in which the caller knows that no transitive calls
24553 can occur, so that a @code{pragma Elaborate} will be sufficient in a
24554 case where @code{pragma Elaborate_All} would cause a circularity.
24558 These five cases are listed in order of decreasing safety, and therefore
24559 require increasing programmer care in their application. Consider the
24562 @smallexample @c adanocomment
24563 @b{package} Pack1 @b{is}
24564 @b{function} F1 @b{return} Integer;
24568 @b{package} Pack2 @b{is}
24569 @b{function} F2 @b{return} Integer;
24570 @b{function} Pure (x : integer) @b{return} integer;
24571 -- pragma Suppress (Elaboration_Check, On => Pure); -- (3)
24572 -- pragma Suppress (Elaboration_Check); -- (4)
24576 @b{package} @b{body} Pack1 @b{is}
24577 @b{function} F1 @b{return} Integer @b{is}
24581 Val : integer := Pack2.Pure (11); -- Elab. call (1)
24584 -- pragma Suppress(Elaboration_Check, Pack2.F2); -- (1)
24585 -- pragma Suppress(Elaboration_Check); -- (2)
24587 X1 := Pack2.F2 + 1; -- Elab. call (2)
24592 @b{package} @b{body} Pack2 @b{is}
24593 @b{function} F2 @b{return} Integer @b{is}
24595 @b{return} Pack1.F1;
24597 @b{function} Pure (x : integer) @b{return} integer @b{is}
24599 @b{return} x ** 3 - 3 * x;
24603 @b{with} Pack1, Ada.Text_IO;
24604 @b{procedure} Proc3 @b{is}
24606 Ada.Text_IO.Put_Line(Pack1.X1'Img); -- 101
24609 In the absence of any pragmas, an attempt to bind this program produces
24610 the following diagnostics:
24616 error: elaboration circularity detected
24617 info: "pack1 (body)" must be elaborated before "pack1 (body)"
24618 info: reason: Elaborate_All probably needed in unit "pack1 (body)"
24619 info: recompile "pack1 (body)" with -gnatel for full details
24620 info: "pack1 (body)"
24621 info: must be elaborated along with its spec:
24622 info: "pack1 (spec)"
24623 info: which is withed by:
24624 info: "pack2 (body)"
24625 info: which must be elaborated along with its spec:
24626 info: "pack2 (spec)"
24627 info: which is withed by:
24628 info: "pack1 (body)"
24631 The sources of the circularity are the two calls to @code{Pack2.Pure} and
24632 @code{Pack2.F2} in the body of @code{Pack1}. We can see that the call to
24633 F2 is safe, even though F2 calls F1, because the call appears after the
24634 elaboration of the body of F1. Therefore the pragma (1) is safe, and will
24635 remove the warning on the call. It is also possible to use pragma (2)
24636 because there are no other potentially unsafe calls in the block.
24639 The call to @code{Pure} is safe because this function does not depend on the
24640 state of @code{Pack2}. Therefore any call to this function is safe, and it
24641 is correct to place pragma (3) in the corresponding package spec.
24644 Finally, we could place pragma (4) in the spec of @code{Pack2} to disable
24645 warnings on all calls to functions declared therein. Note that this is not
24646 necessarily safe, and requires more detailed examination of the subprogram
24647 bodies involved. In particular, a call to @code{F2} requires that @code{F1}
24648 be already elaborated.
24652 It is hard to generalize on which of these four approaches should be
24653 taken. Obviously if it is possible to fix the program so that the default
24654 treatment works, this is preferable, but this may not always be practical.
24655 It is certainly simple enough to use
24657 but the danger in this case is that, even if the GNAT binder
24658 finds a correct elaboration order, it may not always do so,
24659 and certainly a binder from another Ada compiler might not. A
24660 combination of testing and analysis (for which the
24661 information messages generated with the
24663 switch can be useful) must be used to ensure that the program is free
24664 of errors. One switch that is useful in this testing is the
24665 @option{-p (pessimistic elaboration order)}
24668 Normally the binder tries to find an order that has the best chance
24669 of avoiding elaboration problems. However, if this switch is used, the binder
24670 plays a devil's advocate role, and tries to choose the order that
24671 has the best chance of failing. If your program works even with this
24672 switch, then it has a better chance of being error free, but this is still
24675 For an example of this approach in action, consider the C-tests (executable
24676 tests) from the ACVC suite. If these are compiled and run with the default
24677 treatment, then all but one of them succeed without generating any error
24678 diagnostics from the binder. However, there is one test that fails, and
24679 this is not surprising, because the whole point of this test is to ensure
24680 that the compiler can handle cases where it is impossible to determine
24681 a correct order statically, and it checks that an exception is indeed
24682 raised at run time.
24684 This one test must be compiled and run using the
24686 switch, and then it passes. Alternatively, the entire suite can
24687 be run using this switch. It is never wrong to run with the dynamic
24688 elaboration switch if your code is correct, and we assume that the
24689 C-tests are indeed correct (it is less efficient, but efficiency is
24690 not a factor in running the ACVC tests.)
24692 @node Elaboration for Indirect Calls
24693 @section Elaboration for Indirect Calls
24694 @cindex Dispatching calls
24695 @cindex Indirect calls
24698 In rare cases, the static elaboration model fails to prevent
24699 dispatching calls to not-yet-elaborated subprograms. In such cases, we
24700 fall back to run-time checks; premature calls to any primitive
24701 operation of a tagged type before the body of the operation has been
24702 elaborated will raise @code{Program_Error}.
24704 Access-to-subprogram types, however, are handled conservatively, and
24705 do not require run-time checks. This was not true in earlier versions
24706 of the compiler; you can use the @option{-gnatd.U} debug switch to
24707 revert to the old behavior if the new conservative behavior causes
24708 elaboration cycles. Here, ``conservative'' means that if you do
24709 @code{P'Access} during elaboration, the compiler will assume that you
24710 might call @code{P} indirectly during elaboration, so it adds an
24711 implicit @code{pragma Elaborate_All} on the library unit containing
24712 @code{P}. The @option{-gnatd.U} switch is safe if you know there are
24713 no such calls. If the program worked before, it will continue to work
24714 with @option{-gnatd.U}. But beware that code modifications such as
24715 adding an indirect call can cause erroneous behavior in the presence
24716 of @option{-gnatd.U}.
24718 @node Summary of Procedures for Elaboration Control
24719 @section Summary of Procedures for Elaboration Control
24720 @cindex Elaboration control
24723 First, compile your program with the default options, using none of
24724 the special elaboration control switches. If the binder successfully
24725 binds your program, then you can be confident that, apart from issues
24726 raised by the use of access-to-subprogram types and dynamic dispatching,
24727 the program is free of elaboration errors. If it is important that the
24728 program be portable to other compilers than GNAT, then use the
24730 switch to generate messages about missing @code{Elaborate} or
24731 @code{Elaborate_All} pragmas, and supply the missing pragmas.
24733 If the program fails to bind using the default static elaboration
24734 handling, then you can fix the program to eliminate the binder
24735 message, or recompile the entire program with the
24736 @option{-gnatE} switch to generate dynamic elaboration checks,
24737 and, if you are sure there really are no elaboration problems,
24738 use a global pragma @code{Suppress (Elaboration_Check)}.
24740 @node Other Elaboration Order Considerations
24741 @section Other Elaboration Order Considerations
24743 This section has been entirely concerned with the issue of finding a valid
24744 elaboration order, as defined by the Ada Reference Manual. In a case
24745 where several elaboration orders are valid, the task is to find one
24746 of the possible valid elaboration orders (and the static model in GNAT
24747 will ensure that this is achieved).
24749 The purpose of the elaboration rules in the Ada Reference Manual is to
24750 make sure that no entity is accessed before it has been elaborated. For
24751 a subprogram, this means that the spec and body must have been elaborated
24752 before the subprogram is called. For an object, this means that the object
24753 must have been elaborated before its value is read or written. A violation
24754 of either of these two requirements is an access before elaboration order,
24755 and this section has been all about avoiding such errors.
24757 In the case where more than one order of elaboration is possible, in the
24758 sense that access before elaboration errors are avoided, then any one of
24759 the orders is ``correct'' in the sense that it meets the requirements of
24760 the Ada Reference Manual, and no such error occurs.
24762 However, it may be the case for a given program, that there are
24763 constraints on the order of elaboration that come not from consideration
24764 of avoiding elaboration errors, but rather from extra-lingual logic
24765 requirements. Consider this example:
24767 @smallexample @c ada
24768 @b{with} Init_Constants;
24769 @b{package} Constants @b{is}
24774 @b{package} Init_Constants @b{is}
24775 @b{procedure} P; --@i{ require a body}
24776 @b{end} Init_Constants;
24778 @b{with} Constants;
24779 @b{package} @b{body} Init_Constants @b{is}
24780 @b{procedure} P @b{is} @b{begin} @b{null}; @b{end};
24784 @b{end} Init_Constants;
24786 @b{with} Constants;
24787 @b{package} Calc @b{is}
24788 Z : Integer := Constants.X + Constants.Y;
24792 @b{with} Text_IO; @b{use} Text_IO;
24793 @b{procedure} Main @b{is}
24795 Put_Line (Calc.Z'Img);
24800 In this example, there is more than one valid order of elaboration. For
24801 example both the following are correct orders:
24804 Init_Constants spec
24807 Init_Constants body
24812 Init_Constants spec
24813 Init_Constants body
24820 There is no language rule to prefer one or the other, both are correct
24821 from an order of elaboration point of view. But the programmatic effects
24822 of the two orders are very different. In the first, the elaboration routine
24823 of @code{Calc} initializes @code{Z} to zero, and then the main program
24824 runs with this value of zero. But in the second order, the elaboration
24825 routine of @code{Calc} runs after the body of Init_Constants has set
24826 @code{X} and @code{Y} and thus @code{Z} is set to 7 before @code{Main}
24829 One could perhaps by applying pretty clever non-artificial intelligence
24830 to the situation guess that it is more likely that the second order of
24831 elaboration is the one desired, but there is no formal linguistic reason
24832 to prefer one over the other. In fact in this particular case, GNAT will
24833 prefer the second order, because of the rule that bodies are elaborated
24834 as soon as possible, but it's just luck that this is what was wanted
24835 (if indeed the second order was preferred).
24837 If the program cares about the order of elaboration routines in a case like
24838 this, it is important to specify the order required. In this particular
24839 case, that could have been achieved by adding to the spec of Calc:
24841 @smallexample @c ada
24842 @b{pragma} Elaborate_All (Constants);
24846 which requires that the body (if any) and spec of @code{Constants},
24847 as well as the body and spec of any unit @code{with}'ed by
24848 @code{Constants} be elaborated before @code{Calc} is elaborated.
24850 Clearly no automatic method can always guess which alternative you require,
24851 and if you are working with legacy code that had constraints of this kind
24852 which were not properly specified by adding @code{Elaborate} or
24853 @code{Elaborate_All} pragmas, then indeed it is possible that two different
24854 compilers can choose different orders.
24856 However, GNAT does attempt to diagnose the common situation where there
24857 are uninitialized variables in the visible part of a package spec, and the
24858 corresponding package body has an elaboration block that directly or
24859 indirectly initialized one or more of these variables. This is the situation
24860 in which a pragma Elaborate_Body is usually desirable, and GNAT will generate
24861 a warning that suggests this addition if it detects this situation.
24863 The @code{gnatbind}
24864 @option{-p} switch may be useful in smoking
24865 out problems. This switch causes bodies to be elaborated as late as possible
24866 instead of as early as possible. In the example above, it would have forced
24867 the choice of the first elaboration order. If you get different results
24868 when using this switch, and particularly if one set of results is right,
24869 and one is wrong as far as you are concerned, it shows that you have some
24870 missing @code{Elaborate} pragmas. For the example above, we have the
24874 gnatmake -f -q main
24877 gnatmake -f -q main -bargs -p
24883 It is of course quite unlikely that both these results are correct, so
24884 it is up to you in a case like this to investigate the source of the
24885 difference, by looking at the two elaboration orders that are chosen,
24886 and figuring out which is correct, and then adding the necessary
24887 @code{Elaborate} or @code{Elaborate_All} pragmas to ensure the desired order.
24889 @node Determining the Chosen Elaboration Order
24890 @section Determining the Chosen Elaboration Order
24893 To see the elaboration order that the binder chooses, you can look at
24894 the last part of the b~xxx.adb binder output file. Here is an example:
24896 @smallexample @c ada
24897 System.Soft_Links'Elab_Body;
24899 System.Secondary_Stack'Elab_Body;
24901 System.Exception_Table'Elab_Body;
24903 Ada.Io_Exceptions'Elab_Spec;
24905 Ada.Tags'Elab_Spec;
24906 Ada.Streams'Elab_Spec;
24908 Interfaces.C'Elab_Spec;
24910 System.Finalization_Root'Elab_Spec;
24912 System.Os_Lib'Elab_Body;
24914 System.Finalization_Implementation'Elab_Spec;
24915 System.Finalization_Implementation'Elab_Body;
24917 Ada.Finalization'Elab_Spec;
24919 Ada.Finalization.List_Controller'Elab_Spec;
24921 System.File_Control_Block'Elab_Spec;
24923 System.File_Io'Elab_Body;
24925 Ada.Tags'Elab_Body;
24927 Ada.Text_Io'Elab_Spec;
24928 Ada.Text_Io'Elab_Body;
24933 Here Elab_Spec elaborates the spec
24934 and Elab_Body elaborates the body. The assignments to the Exx flags
24935 flag that the corresponding body is now elaborated.
24937 You can also ask the binder to generate a more
24938 readable list of the elaboration order using the
24939 @code{-l} switch when invoking the binder. Here is
24940 an example of the output generated by this switch:
24946 system.case_util (spec)
24947 system.case_util (body)
24948 system.concat_2 (spec)
24949 system.concat_2 (body)
24950 system.concat_3 (spec)
24951 system.concat_3 (body)
24952 system.htable (spec)
24953 system.parameters (spec)
24954 system.parameters (body)
24956 interfaces.c_streams (spec)
24957 interfaces.c_streams (body)
24958 system.restrictions (spec)
24959 system.restrictions (body)
24960 system.standard_library (spec)
24961 system.exceptions (spec)
24962 system.exceptions (body)
24963 system.storage_elements (spec)
24964 system.storage_elements (body)
24965 system.secondary_stack (spec)
24966 system.stack_checking (spec)
24967 system.stack_checking (body)
24968 system.string_hash (spec)
24969 system.string_hash (body)
24970 system.htable (body)
24971 system.strings (spec)
24972 system.strings (body)
24973 system.traceback (spec)
24974 system.traceback (body)
24975 system.traceback_entries (spec)
24976 system.traceback_entries (body)
24977 ada.exceptions (spec)
24978 ada.exceptions.last_chance_handler (spec)
24979 system.soft_links (spec)
24980 system.soft_links (body)
24981 ada.exceptions.last_chance_handler (body)
24982 system.secondary_stack (body)
24983 system.exception_table (spec)
24984 system.exception_table (body)
24985 ada.io_exceptions (spec)
24988 interfaces.c (spec)
24989 interfaces.c (body)
24990 system.finalization_root (spec)
24991 system.finalization_root (body)
24992 system.memory (spec)
24993 system.memory (body)
24994 system.standard_library (body)
24995 system.os_lib (spec)
24996 system.os_lib (body)
24997 system.unsigned_types (spec)
24998 system.stream_attributes (spec)
24999 system.stream_attributes (body)
25000 system.finalization_implementation (spec)
25001 system.finalization_implementation (body)
25002 ada.finalization (spec)
25003 ada.finalization (body)
25004 ada.finalization.list_controller (spec)
25005 ada.finalization.list_controller (body)
25006 system.file_control_block (spec)
25007 system.file_io (spec)
25008 system.file_io (body)
25009 system.val_uns (spec)
25010 system.val_util (spec)
25011 system.val_util (body)
25012 system.val_uns (body)
25013 system.wch_con (spec)
25014 system.wch_con (body)
25015 system.wch_cnv (spec)
25016 system.wch_jis (spec)
25017 system.wch_jis (body)
25018 system.wch_cnv (body)
25019 system.wch_stw (spec)
25020 system.wch_stw (body)
25022 ada.exceptions (body)
25029 @c **********************************
25030 @node Overflow Check Handling in GNAT
25031 @appendix Overflow Check Handling in GNAT
25032 @cindex Overflow checks
25033 @cindex Checks (overflow)
25034 @c **********************************
25038 * Overflow Checking Modes in GNAT::
25039 * Specifying the Desired Mode::
25040 * Default Settings::
25041 * Implementation Notes::
25046 @section Background
25049 Overflow checks are checks that the compiler may make to ensure
25050 that intermediate results are not out of range. For example:
25052 @smallexample @c ada
25059 if @code{A} has the value @code{Integer'Last}, then the addition may cause
25060 overflow since the result is out of range of the type @code{Integer}.
25061 In this case @code{Constraint_Error} will be raised if checks are
25064 A trickier situation arises in examples like the following:
25066 @smallexample @c ada
25073 where @code{A} is @code{Integer'Last} and @code{C} is @code{-1}.
25074 Now the final result of the expression on the right hand side is
25075 @code{Integer'Last} which is in range, but the question arises whether the
25076 intermediate addition of @code{(A + 1)} raises an overflow error.
25078 The (perhaps surprising) answer is that the Ada language
25079 definition does not answer this question. Instead it leaves
25080 it up to the implementation to do one of two things if overflow
25081 checks are enabled.
25085 raise an exception (@code{Constraint_Error}), or
25088 yield the correct mathematical result which is then used in
25089 subsequent operations.
25093 If the compiler chooses the first approach, then the assignment of this
25094 example will indeed raise @code{Constraint_Error} if overflow checking is
25095 enabled, or result in erroneous execution if overflow checks are suppressed.
25097 But if the compiler
25098 chooses the second approach, then it can perform both additions yielding
25099 the correct mathematical result, which is in range, so no exception
25100 will be raised, and the right result is obtained, regardless of whether
25101 overflow checks are suppressed.
25103 Note that in the first example an
25104 exception will be raised in either case, since if the compiler
25105 gives the correct mathematical result for the addition, it will
25106 be out of range of the target type of the assignment, and thus
25107 fails the range check.
25109 This lack of specified behavior in the handling of overflow for
25110 intermediate results is a source of non-portability, and can thus
25111 be problematic when programs are ported. Most typically this arises
25112 in a situation where the original compiler did not raise an exception,
25113 and then the application is moved to a compiler where the check is
25114 performed on the intermediate result and an unexpected exception is
25117 Furthermore, when using Ada 2012's preconditions and other
25118 assertion forms, another issue arises. Consider:
25120 @smallexample @c ada
25121 @b{procedure} P (A, B : Integer) @b{with}
25122 Pre => A + B <= Integer'Last;
25126 One often wants to regard arithmetic in a context like this from
25127 a mathematical point of view. So for example, if the two actual parameters
25128 for a call to @code{P} are both @code{Integer'Last}, then
25129 the precondition should be regarded as False. If we are executing
25130 in a mode with run-time checks enabled for preconditions, then we would
25131 like this precondition to fail, rather than raising an exception
25132 because of the intermediate overflow.
25134 However, the language definition leaves the specification of
25135 whether the above condition fails (raising @code{Assert_Error}) or
25136 causes an intermediate overflow (raising @code{Constraint_Error})
25137 up to the implementation.
25139 The situation is worse in a case such as the following:
25141 @smallexample @c ada
25142 @b{procedure} Q (A, B, C : Integer) @b{with}
25143 Pre => A + B + C <= Integer'Last;
25149 @smallexample @c ada
25150 Q (A => Integer'Last, B => 1, C => -1);
25154 From a mathematical point of view the precondition
25155 is True, but at run time we may (but are not guaranteed to) get an
25156 exception raised because of the intermediate overflow (and we really
25157 would prefer this precondition to be considered True at run time).
25159 @node Overflow Checking Modes in GNAT
25160 @section Overflow Checking Modes in GNAT
25163 To deal with the portability issue, and with the problem of
25164 mathematical versus run-time interpretation of the expressions in
25165 assertions, GNAT provides comprehensive control over the handling
25166 of intermediate overflow. GNAT can operate in three modes, and
25167 furthemore, permits separate selection of operating modes for
25168 the expressions within assertions (here the term ``assertions''
25169 is used in the technical sense, which includes preconditions and so forth)
25170 and for expressions appearing outside assertions.
25172 The three modes are:
25175 @item @i{Use base type for intermediate operations} (@code{STRICT})
25177 In this mode, all intermediate results for predefined arithmetic
25178 operators are computed using the base type, and the result must
25179 be in range of the base type. If this is not the
25180 case then either an exception is raised (if overflow checks are
25181 enabled) or the execution is erroneous (if overflow checks are suppressed).
25182 This is the normal default mode.
25184 @item @i{Most intermediate overflows avoided} (@code{MINIMIZED})
25186 In this mode, the compiler attempts to avoid intermediate overflows by
25187 using a larger integer type, typically @code{Long_Long_Integer},
25188 as the type in which arithmetic is
25189 performed for predefined arithmetic operators. This may be slightly more
25191 run time (compared to suppressing intermediate overflow checks), though
25192 the cost is negligible on modern 64-bit machines. For the examples given
25193 earlier, no intermediate overflows would have resulted in exceptions,
25194 since the intermediate results are all in the range of
25195 @code{Long_Long_Integer} (typically 64-bits on nearly all implementations
25196 of GNAT). In addition, if checks are enabled, this reduces the number of
25197 checks that must be made, so this choice may actually result in an
25198 improvement in space and time behavior.
25200 However, there are cases where @code{Long_Long_Integer} is not large
25201 enough, consider the following example:
25203 @smallexample @c ada
25204 @b{procedure} R (A, B, C, D : Integer) @b{with}
25205 Pre => (A**2 * B**2) / (C**2 * D**2) <= 10;
25208 where @code{A} = @code{B} = @code{C} = @code{D} = @code{Integer'Last}.
25209 Now the intermediate results are
25210 out of the range of @code{Long_Long_Integer} even though the final result
25211 is in range and the precondition is True (from a mathematical point
25212 of view). In such a case, operating in this mode, an overflow occurs
25213 for the intermediate computation (which is why this mode
25214 says @i{most} intermediate overflows are avoided). In this case,
25215 an exception is raised if overflow checks are enabled, and the
25216 execution is erroneous if overflow checks are suppressed.
25218 @item @i{All intermediate overflows avoided} (@code{ELIMINATED})
25220 In this mode, the compiler avoids all intermediate overflows
25221 by using arbitrary precision arithmetic as required. In this
25222 mode, the above example with @code{A**2 * B**2} would
25223 not cause intermediate overflow, because the intermediate result
25224 would be evaluated using sufficient precision, and the result
25225 of evaluating the precondition would be True.
25227 This mode has the advantage of avoiding any intermediate
25228 overflows, but at the expense of significant run-time overhead,
25229 including the use of a library (included automatically in this
25230 mode) for multiple-precision arithmetic.
25232 This mode provides cleaner semantics for assertions, since now
25233 the run-time behavior emulates true arithmetic behavior for the
25234 predefined arithmetic operators, meaning that there is never a
25235 conflict between the mathematical view of the assertion, and its
25238 Note that in this mode, the behavior is unaffected by whether or
25239 not overflow checks are suppressed, since overflow does not occur.
25240 It is possible for gigantic intermediate expressions to raise
25241 @code{Storage_Error} as a result of attempting to compute the
25242 results of such expressions (e.g. @code{Integer'Last ** Integer'Last})
25243 but overflow is impossible.
25249 Note that these modes apply only to the evaluation of predefined
25250 arithmetic, membership, and comparison operators for signed integer
25253 For fixed-point arithmetic, checks can be suppressed. But if checks
25255 then fixed-point values are always checked for overflow against the
25256 base type for intermediate expressions (that is such checks always
25257 operate in the equivalent of @code{STRICT} mode).
25259 For floating-point, on nearly all architectures, @code{Machine_Overflows}
25260 is False, and IEEE infinities are generated, so overflow exceptions
25261 are never raised. If you want to avoid infinities, and check that
25262 final results of expressions are in range, then you can declare a
25263 constrained floating-point type, and range checks will be carried
25264 out in the normal manner (with infinite values always failing all
25268 @c -------------------------
25269 @node Specifying the Desired Mode
25270 @section Specifying the Desired Mode
25273 The desired mode of for handling intermediate overflow can be specified using
25274 either the @code{Overflow_Mode} pragma or an equivalent compiler switch.
25275 The pragma has the form
25276 @cindex pragma @code{Overflow_Mode}
25278 @smallexample @c ada
25279 @b{pragma} Overflow_Mode ([General =>] MODE [, [Assertions =>] MODE]);
25283 where @code{MODE} is one of
25286 @item @code{STRICT}: intermediate overflows checked (using base type)
25287 @item @code{MINIMIZED}: minimize intermediate overflows
25288 @item @code{ELIMINATED}: eliminate intermediate overflows
25292 The case is ignored, so @code{MINIMIZED}, @code{Minimized} and
25293 @code{minimized} all have the same effect.
25295 If only the @code{General} parameter is present, then the given @code{MODE}
25297 to expressions both within and outside assertions. If both arguments
25298 are present, then @code{General} applies to expressions outside assertions,
25299 and @code{Assertions} applies to expressions within assertions. For example:
25301 @smallexample @c ada
25302 @b{pragma} Overflow_Mode
25303 (General => Minimized, Assertions => Eliminated);
25307 specifies that general expressions outside assertions be evaluated
25308 in ``minimize intermediate overflows'' mode, and expressions within
25309 assertions be evaluated in ``eliminate intermediate overflows'' mode.
25310 This is often a reasonable choice, avoiding excessive overhead
25311 outside assertions, but assuring a high degree of portability
25312 when importing code from another compiler, while incurring
25313 the extra overhead for assertion expressions to ensure that
25314 the behavior at run time matches the expected mathematical
25317 The @code{Overflow_Mode} pragma has the same scoping and placement
25318 rules as pragma @code{Suppress}, so it can occur either as a
25319 configuration pragma, specifying a default for the whole
25320 program, or in a declarative scope, where it applies to the
25321 remaining declarations and statements in that scope.
25323 Note that pragma @code{Overflow_Mode} does not affect whether
25324 overflow checks are enabled or suppressed. It only controls the
25325 method used to compute intermediate values. To control whether
25326 overflow checking is enabled or suppressed, use pragma @code{Suppress}
25327 or @code{Unsuppress} in the usual manner
25329 Additionally, a compiler switch @option{-gnato?} or @option{-gnato??}
25330 can be used to control the checking mode default (which can be subsequently
25331 overridden using pragmas).
25332 @cindex @option{-gnato?} (gcc)
25333 @cindex @option{-gnato??} (gcc)
25335 Here `@code{?}' is one of the digits `@code{1}' through `@code{3}':
25339 use base type for intermediate operations (@code{STRICT})
25341 minimize intermediate overflows (@code{MINIMIZED})
25343 eliminate intermediate overflows (@code{ELIMINATED})
25347 As with the pragma, if only one digit appears then it applies to all
25348 cases; if two digits are given, then the first applies outside
25349 assertions, and the second within assertions. Thus the equivalent
25350 of the example pragma above would be
25353 If no digits follow the @option{-gnato}, then it is equivalent to
25355 causing all intermediate operations to be computed using the base
25356 type (@code{STRICT} mode).
25358 In addition to setting the mode used for computation of intermediate
25359 results, the @code{-gnato} switch also enables overflow checking (which
25360 is suppressed by default). It thus combines the effect of using
25361 a pragma @code{Overflow_Mode} and pragma @code{Unsuppress}.
25364 @c -------------------------
25365 @node Default Settings
25366 @section Default Settings
25368 The default mode for overflow checks is
25375 which causes all computations both inside and outside assertions to use
25376 the base type. In addition overflow checks are suppressed.
25378 This retains compatibility with previous versions of
25379 GNAT which suppressed overflow checks by default and always
25380 used the base type for computation of intermediate results.
25382 The switch @option{-gnato} (with no digits following) is equivalent to
25383 @cindex @option{-gnato} (gcc)
25390 which causes overflow checking of all intermediate overflows
25391 both inside and outside assertions against the base type.
25392 This provides compatibility
25393 with this switch as implemented in previous versions of GNAT.
25395 The pragma @code{Suppress (Overflow_Check)} disables overflow
25396 checking, but it has no effect on the method used for computing
25397 intermediate results.
25399 The pragma @code{Unsuppress (Overflow_Check)} enables overflow
25400 checking, but it has no effect on the method used for computing
25401 intermediate results.
25403 @c -------------------------
25404 @node Implementation Notes
25405 @section Implementation Notes
25407 In practice on typical 64-bit machines, the @code{MINIMIZED} mode is
25408 reasonably efficient, and can be generally used. It also helps
25409 to ensure compatibility with code imported from some other
25412 Setting all intermediate overflows checking (@code{CHECKED} mode)
25413 makes sense if you want to
25414 make sure that your code is compatible with any other possible
25415 Ada implementation. This may be useful in ensuring portability
25416 for code that is to be exported to some other compiler than GNAT.
25419 The Ada standard allows the reassociation of expressions at
25420 the same precedence level if no parentheses are present. For
25421 example, @w{@code{A+B+C}} parses as though it were @w{@code{(A+B)+C}}, but
25422 the compiler can reintepret this as @w{@code{A+(B+C)}}, possibly
25423 introducing or eliminating an overflow exception. The GNAT
25424 compiler never takes advantage of this freedom, and the
25425 expression @w{@code{A+B+C}} will be evaluated as @w{@code{(A+B)+C}}.
25426 If you need the other order, you can write the parentheses
25427 explicitly @w{@code{A+(B+C)}} and GNAT will respect this order.
25429 The use of @code{ELIMINATED} mode will cause the compiler to
25430 automatically include an appropriate arbitrary precision
25431 integer arithmetic package. The compiler will make calls
25432 to this package, though only in cases where it cannot be
25433 sure that @code{Long_Long_Integer} is sufficient to guard against
25434 intermediate overflows. This package does not use dynamic
25435 alllocation, but it does use the secondary stack, so an
25436 appropriate secondary stack package must be present (this
25437 is always true for standard full Ada, but may require
25438 specific steps for restricted run times such as ZFP).
25440 Although @code{ELIMINATED} mode causes expressions to use arbitrary
25441 precision arithmetic, avoiding overflow, the final result
25442 must be in an appropriate range. This is true even if the
25443 final result is of type @code{[Long_[Long_]]Integer'Base}, which
25444 still has the same bounds as its associated constrained
25447 Currently, the @code{ELIMINATED} mode is only available on target
25448 platforms for which @code{Long_Long_Integer} is 64-bits (nearly all GNAT
25451 @c *******************************
25452 @node Conditional Compilation
25453 @appendix Conditional Compilation
25454 @c *******************************
25455 @cindex Conditional compilation
25458 It is often necessary to arrange for a single source program
25459 to serve multiple purposes, where it is compiled in different
25460 ways to achieve these different goals. Some examples of the
25461 need for this feature are
25464 @item Adapting a program to a different hardware environment
25465 @item Adapting a program to a different target architecture
25466 @item Turning debugging features on and off
25467 @item Arranging for a program to compile with different compilers
25471 In C, or C++, the typical approach would be to use the preprocessor
25472 that is defined as part of the language. The Ada language does not
25473 contain such a feature. This is not an oversight, but rather a very
25474 deliberate design decision, based on the experience that overuse of
25475 the preprocessing features in C and C++ can result in programs that
25476 are extremely difficult to maintain. For example, if we have ten
25477 switches that can be on or off, this means that there are a thousand
25478 separate programs, any one of which might not even be syntactically
25479 correct, and even if syntactically correct, the resulting program
25480 might not work correctly. Testing all combinations can quickly become
25483 Nevertheless, the need to tailor programs certainly exists, and in
25484 this Appendix we will discuss how this can
25485 be achieved using Ada in general, and GNAT in particular.
25488 * Use of Boolean Constants::
25489 * Debugging - A Special Case::
25490 * Conditionalizing Declarations::
25491 * Use of Alternative Implementations::
25495 @node Use of Boolean Constants
25496 @section Use of Boolean Constants
25499 In the case where the difference is simply which code
25500 sequence is executed, the cleanest solution is to use Boolean
25501 constants to control which code is executed.
25503 @smallexample @c ada
25505 FP_Initialize_Required : @b{constant} Boolean := True;
25507 @b{if} FP_Initialize_Required @b{then}
25514 Not only will the code inside the @code{if} statement not be executed if
25515 the constant Boolean is @code{False}, but it will also be completely
25516 deleted from the program.
25517 However, the code is only deleted after the @code{if} statement
25518 has been checked for syntactic and semantic correctness.
25519 (In contrast, with preprocessors the code is deleted before the
25520 compiler ever gets to see it, so it is not checked until the switch
25522 @cindex Preprocessors (contrasted with conditional compilation)
25524 Typically the Boolean constants will be in a separate package,
25527 @smallexample @c ada
25529 @b{package} Config @b{is}
25530 FP_Initialize_Required : @b{constant} Boolean := True;
25531 Reset_Available : @b{constant} Boolean := False;
25538 The @code{Config} package exists in multiple forms for the various targets,
25539 with an appropriate script selecting the version of @code{Config} needed.
25540 Then any other unit requiring conditional compilation can do a @code{with}
25541 of @code{Config} to make the constants visible.
25544 @node Debugging - A Special Case
25545 @section Debugging - A Special Case
25548 A common use of conditional code is to execute statements (for example
25549 dynamic checks, or output of intermediate results) under control of a
25550 debug switch, so that the debugging behavior can be turned on and off.
25551 This can be done using a Boolean constant to control whether the code
25554 @smallexample @c ada
25556 @b{if} Debugging @b{then}
25557 Put_Line ("got to the first stage!");
25565 @smallexample @c ada
25567 @b{if} Debugging @b{and} @b{then} Temperature > 999.0 @b{then}
25568 @b{raise} Temperature_Crazy;
25574 Since this is a common case, there are special features to deal with
25575 this in a convenient manner. For the case of tests, Ada 2005 has added
25576 a pragma @code{Assert} that can be used for such tests. This pragma is modeled
25577 @cindex pragma @code{Assert}
25578 on the @code{Assert} pragma that has always been available in GNAT, so this
25579 feature may be used with GNAT even if you are not using Ada 2005 features.
25580 The use of pragma @code{Assert} is described in
25581 @ref{Pragma Assert,,, gnat_rm, GNAT Reference Manual}, but as an
25582 example, the last test could be written:
25584 @smallexample @c ada
25585 @b{pragma} Assert (Temperature <= 999.0, "Temperature Crazy");
25591 @smallexample @c ada
25592 @b{pragma} Assert (Temperature <= 999.0);
25596 In both cases, if assertions are active and the temperature is excessive,
25597 the exception @code{Assert_Failure} will be raised, with the given string in
25598 the first case or a string indicating the location of the pragma in the second
25599 case used as the exception message.
25601 You can turn assertions on and off by using the @code{Assertion_Policy}
25603 @cindex pragma @code{Assertion_Policy}
25604 This is an Ada 2005 pragma which is implemented in all modes by
25605 GNAT, but only in the latest versions of GNAT which include Ada 2005
25606 capability. Alternatively, you can use the @option{-gnata} switch
25607 @cindex @option{-gnata} switch
25608 to enable assertions from the command line (this is recognized by all versions
25611 For the example above with the @code{Put_Line}, the GNAT-specific pragma
25612 @code{Debug} can be used:
25613 @cindex pragma @code{Debug}
25615 @smallexample @c ada
25616 @b{pragma} Debug (Put_Line ("got to the first stage!"));
25620 If debug pragmas are enabled, the argument, which must be of the form of
25621 a procedure call, is executed (in this case, @code{Put_Line} will be called).
25622 Only one call can be present, but of course a special debugging procedure
25623 containing any code you like can be included in the program and then
25624 called in a pragma @code{Debug} argument as needed.
25626 One advantage of pragma @code{Debug} over the @code{if Debugging then}
25627 construct is that pragma @code{Debug} can appear in declarative contexts,
25628 such as at the very beginning of a procedure, before local declarations have
25631 Debug pragmas are enabled using either the @option{-gnata} switch that also
25632 controls assertions, or with a separate Debug_Policy pragma.
25633 @cindex pragma @code{Debug_Policy}
25634 The latter pragma is new in the Ada 2005 versions of GNAT (but it can be used
25635 in Ada 95 and Ada 83 programs as well), and is analogous to
25636 pragma @code{Assertion_Policy} to control assertions.
25638 @code{Assertion_Policy} and @code{Debug_Policy} are configuration pragmas,
25639 and thus they can appear in @file{gnat.adc} if you are not using a
25640 project file, or in the file designated to contain configuration pragmas
25642 They then apply to all subsequent compilations. In practice the use of
25643 the @option{-gnata} switch is often the most convenient method of controlling
25644 the status of these pragmas.
25646 Note that a pragma is not a statement, so in contexts where a statement
25647 sequence is required, you can't just write a pragma on its own. You have
25648 to add a @code{null} statement.
25650 @smallexample @c ada
25652 @b{if} @dots{} @b{then}
25653 @dots{} -- some statements
25655 @b{pragma} Assert (Num_Cases < 10);
25662 @node Conditionalizing Declarations
25663 @section Conditionalizing Declarations
25666 In some cases, it may be necessary to conditionalize declarations to meet
25667 different requirements. For example we might want a bit string whose length
25668 is set to meet some hardware message requirement.
25670 In some cases, it may be possible to do this using declare blocks controlled
25671 by conditional constants:
25673 @smallexample @c ada
25675 @b{if} Small_Machine @b{then}
25677 X : Bit_String (1 .. 10);
25683 X : Large_Bit_String (1 .. 1000);
25692 Note that in this approach, both declarations are analyzed by the
25693 compiler so this can only be used where both declarations are legal,
25694 even though one of them will not be used.
25696 Another approach is to define integer constants, e.g.@: @code{Bits_Per_Word},
25697 or Boolean constants, e.g.@: @code{Little_Endian}, and then write declarations
25698 that are parameterized by these constants. For example
25700 @smallexample @c ada
25702 @b{for} Rec @b{use}
25703 Field1 @b{at} 0 @b{range} Boolean'Pos (Little_Endian) * 10 .. Bits_Per_Word;
25704 @b{end} @b{record};
25709 If @code{Bits_Per_Word} is set to 32, this generates either
25711 @smallexample @c ada
25713 @b{for} Rec @b{use}
25714 Field1 @b{at} 0 @b{range} 0 .. 32;
25715 @b{end} @b{record};
25720 for the big endian case, or
25722 @smallexample @c ada
25724 @b{for} Rec @b{use} @b{record}
25725 Field1 @b{at} 0 @b{range} 10 .. 32;
25726 @b{end} @b{record};
25731 for the little endian case. Since a powerful subset of Ada expression
25732 notation is usable for creating static constants, clever use of this
25733 feature can often solve quite difficult problems in conditionalizing
25734 compilation (note incidentally that in Ada 95, the little endian
25735 constant was introduced as @code{System.Default_Bit_Order}, so you do not
25736 need to define this one yourself).
25739 @node Use of Alternative Implementations
25740 @section Use of Alternative Implementations
25743 In some cases, none of the approaches described above are adequate. This
25744 can occur for example if the set of declarations required is radically
25745 different for two different configurations.
25747 In this situation, the official Ada way of dealing with conditionalizing
25748 such code is to write separate units for the different cases. As long as
25749 this does not result in excessive duplication of code, this can be done
25750 without creating maintenance problems. The approach is to share common
25751 code as far as possible, and then isolate the code and declarations
25752 that are different. Subunits are often a convenient method for breaking
25753 out a piece of a unit that is to be conditionalized, with separate files
25754 for different versions of the subunit for different targets, where the
25755 build script selects the right one to give to the compiler.
25756 @cindex Subunits (and conditional compilation)
25758 As an example, consider a situation where a new feature in Ada 2005
25759 allows something to be done in a really nice way. But your code must be able
25760 to compile with an Ada 95 compiler. Conceptually you want to say:
25762 @smallexample @c ada
25764 @b{if} Ada_2005 @b{then}
25765 @dots{} neat Ada 2005 code
25767 @dots{} not quite as neat Ada 95 code
25773 where @code{Ada_2005} is a Boolean constant.
25775 But this won't work when @code{Ada_2005} is set to @code{False},
25776 since the @code{then} clause will be illegal for an Ada 95 compiler.
25777 (Recall that although such unreachable code would eventually be deleted
25778 by the compiler, it still needs to be legal. If it uses features
25779 introduced in Ada 2005, it will be illegal in Ada 95.)
25781 So instead we write
25783 @smallexample @c ada
25784 @b{procedure} Insert @b{is} @b{separate};
25788 Then we have two files for the subunit @code{Insert}, with the two sets of
25790 If the package containing this is called @code{File_Queries}, then we might
25794 @item @file{file_queries-insert-2005.adb}
25795 @item @file{file_queries-insert-95.adb}
25799 and the build script renames the appropriate file to
25802 file_queries-insert.adb
25806 and then carries out the compilation.
25808 This can also be done with project files' naming schemes. For example:
25810 @smallexample @c project
25811 For Body ("File_Queries.Insert") use "file_queries-insert-2005.ada";
25815 Note also that with project files it is desirable to use a different extension
25816 than @file{ads} / @file{adb} for alternative versions. Otherwise a naming
25817 conflict may arise through another commonly used feature: to declare as part
25818 of the project a set of directories containing all the sources obeying the
25819 default naming scheme.
25821 The use of alternative units is certainly feasible in all situations,
25822 and for example the Ada part of the GNAT run-time is conditionalized
25823 based on the target architecture using this approach. As a specific example,
25824 consider the implementation of the AST feature in VMS. There is one
25832 which is the same for all architectures, and three bodies:
25836 used for all non-VMS operating systems
25837 @item s-asthan-vms-alpha.adb
25838 used for VMS on the Alpha
25839 @item s-asthan-vms-ia64.adb
25840 used for VMS on the ia64
25844 The dummy version @file{s-asthan.adb} simply raises exceptions noting that
25845 this operating system feature is not available, and the two remaining
25846 versions interface with the corresponding versions of VMS to provide
25847 VMS-compatible AST handling. The GNAT build script knows the architecture
25848 and operating system, and automatically selects the right version,
25849 renaming it if necessary to @file{s-asthan.adb} before the run-time build.
25851 Another style for arranging alternative implementations is through Ada's
25852 access-to-subprogram facility.
25853 In case some functionality is to be conditionally included,
25854 you can declare an access-to-procedure variable @code{Ref} that is initialized
25855 to designate a ``do nothing'' procedure, and then invoke @code{Ref.all}
25857 In some library package, set @code{Ref} to @code{Proc'Access} for some
25858 procedure @code{Proc} that performs the relevant processing.
25859 The initialization only occurs if the library package is included in the
25861 The same idea can also be implemented using tagged types and dispatching
25865 @node Preprocessing
25866 @section Preprocessing
25867 @cindex Preprocessing
25870 Although it is quite possible to conditionalize code without the use of
25871 C-style preprocessing, as described earlier in this section, it is
25872 nevertheless convenient in some cases to use the C approach. Moreover,
25873 older Ada compilers have often provided some preprocessing capability,
25874 so legacy code may depend on this approach, even though it is not
25877 To accommodate such use, GNAT provides a preprocessor (modeled to a large
25878 extent on the various preprocessors that have been used
25879 with legacy code on other compilers, to enable easier transition).
25881 The preprocessor may be used in two separate modes. It can be used quite
25882 separately from the compiler, to generate a separate output source file
25883 that is then fed to the compiler as a separate step. This is the
25884 @code{gnatprep} utility, whose use is fully described in
25885 @ref{Preprocessing with gnatprep}.
25886 @cindex @code{gnatprep}
25888 The preprocessing language allows such constructs as
25892 #if DEBUG or else (PRIORITY > 4) then
25893 bunch of declarations
25895 completely different bunch of declarations
25901 The values of the symbols @code{DEBUG} and @code{PRIORITY} can be
25902 defined either on the command line or in a separate file.
25904 The other way of running the preprocessor is even closer to the C style and
25905 often more convenient. In this approach the preprocessing is integrated into
25906 the compilation process. The compiler is fed the preprocessor input which
25907 includes @code{#if} lines etc, and then the compiler carries out the
25908 preprocessing internally and processes the resulting output.
25909 For more details on this approach, see @ref{Integrated Preprocessing}.
25912 @c *******************************
25913 @node Inline Assembler
25914 @appendix Inline Assembler
25915 @c *******************************
25918 If you need to write low-level software that interacts directly
25919 with the hardware, Ada provides two ways to incorporate assembly
25920 language code into your program. First, you can import and invoke
25921 external routines written in assembly language, an Ada feature fully
25922 supported by GNAT@. However, for small sections of code it may be simpler
25923 or more efficient to include assembly language statements directly
25924 in your Ada source program, using the facilities of the implementation-defined
25925 package @code{System.Machine_Code}, which incorporates the gcc
25926 Inline Assembler. The Inline Assembler approach offers a number of advantages,
25927 including the following:
25930 @item No need to use non-Ada tools
25931 @item Consistent interface over different targets
25932 @item Automatic usage of the proper calling conventions
25933 @item Access to Ada constants and variables
25934 @item Definition of intrinsic routines
25935 @item Possibility of inlining a subprogram comprising assembler code
25936 @item Code optimizer can take Inline Assembler code into account
25939 This chapter presents a series of examples to show you how to use
25940 the Inline Assembler. Although it focuses on the Intel x86,
25941 the general approach applies also to other processors.
25942 It is assumed that you are familiar with Ada
25943 and with assembly language programming.
25946 * Basic Assembler Syntax::
25947 * A Simple Example of Inline Assembler::
25948 * Output Variables in Inline Assembler::
25949 * Input Variables in Inline Assembler::
25950 * Inlining Inline Assembler Code::
25951 * Other Asm Functionality::
25954 @c ---------------------------------------------------------------------------
25955 @node Basic Assembler Syntax
25956 @section Basic Assembler Syntax
25959 The assembler used by GNAT and gcc is based not on the Intel assembly
25960 language, but rather on a language that descends from the AT&T Unix
25961 assembler @emph{as} (and which is often referred to as ``AT&T syntax'').
25962 The following table summarizes the main features of @emph{as} syntax
25963 and points out the differences from the Intel conventions.
25964 See the gcc @emph{as} and @emph{gas} (an @emph{as} macro
25965 pre-processor) documentation for further information.
25968 @item Register names
25969 gcc / @emph{as}: Prefix with ``%''; for example @code{%eax}
25971 Intel: No extra punctuation; for example @code{eax}
25973 @item Immediate operand
25974 gcc / @emph{as}: Prefix with ``$''; for example @code{$4}
25976 Intel: No extra punctuation; for example @code{4}
25979 gcc / @emph{as}: Prefix with ``$''; for example @code{$loc}
25981 Intel: No extra punctuation; for example @code{loc}
25983 @item Memory contents
25984 gcc / @emph{as}: No extra punctuation; for example @code{loc}
25986 Intel: Square brackets; for example @code{[loc]}
25988 @item Register contents
25989 gcc / @emph{as}: Parentheses; for example @code{(%eax)}
25991 Intel: Square brackets; for example @code{[eax]}
25993 @item Hexadecimal numbers
25994 gcc / @emph{as}: Leading ``0x'' (C language syntax); for example @code{0xA0}
25996 Intel: Trailing ``h''; for example @code{A0h}
25999 gcc / @emph{as}: Explicit in op code; for example @code{movw} to move
26002 Intel: Implicit, deduced by assembler; for example @code{mov}
26004 @item Instruction repetition
26005 gcc / @emph{as}: Split into two lines; for example
26011 Intel: Keep on one line; for example @code{rep stosl}
26013 @item Order of operands
26014 gcc / @emph{as}: Source first; for example @code{movw $4, %eax}
26016 Intel: Destination first; for example @code{mov eax, 4}
26019 @c ---------------------------------------------------------------------------
26020 @node A Simple Example of Inline Assembler
26021 @section A Simple Example of Inline Assembler
26024 The following example will generate a single assembly language statement,
26025 @code{nop}, which does nothing. Despite its lack of run-time effect,
26026 the example will be useful in illustrating the basics of
26027 the Inline Assembler facility.
26029 @smallexample @c ada
26031 @b{with} System.Machine_Code; @b{use} System.Machine_Code;
26032 @b{procedure} Nothing @b{is}
26039 @code{Asm} is a procedure declared in package @code{System.Machine_Code};
26040 here it takes one parameter, a @emph{template string} that must be a static
26041 expression and that will form the generated instruction.
26042 @code{Asm} may be regarded as a compile-time procedure that parses
26043 the template string and additional parameters (none here),
26044 from which it generates a sequence of assembly language instructions.
26046 The examples in this chapter will illustrate several of the forms
26047 for invoking @code{Asm}; a complete specification of the syntax
26048 is found in @ref{Machine Code Insertions,,, gnat_rm, GNAT Reference
26051 Under the standard GNAT conventions, the @code{Nothing} procedure
26052 should be in a file named @file{nothing.adb}.
26053 You can build the executable in the usual way:
26057 However, the interesting aspect of this example is not its run-time behavior
26058 but rather the generated assembly code.
26059 To see this output, invoke the compiler as follows:
26061 gcc -c -S -fomit-frame-pointer -gnatp @file{nothing.adb}
26063 where the options are:
26067 compile only (no bind or link)
26069 generate assembler listing
26070 @item -fomit-frame-pointer
26071 do not set up separate stack frames
26073 do not add runtime checks
26076 This gives a human-readable assembler version of the code. The resulting
26077 file will have the same name as the Ada source file, but with a @code{.s}
26078 extension. In our example, the file @file{nothing.s} has the following
26083 .file "nothing.adb"
26085 ___gnu_compiled_ada:
26088 .globl __ada_nothing
26100 The assembly code you included is clearly indicated by
26101 the compiler, between the @code{#APP} and @code{#NO_APP}
26102 delimiters. The character before the 'APP' and 'NOAPP'
26103 can differ on different targets. For example, GNU/Linux uses '#APP' while
26104 on NT you will see '/APP'.
26106 If you make a mistake in your assembler code (such as using the
26107 wrong size modifier, or using a wrong operand for the instruction) GNAT
26108 will report this error in a temporary file, which will be deleted when
26109 the compilation is finished. Generating an assembler file will help
26110 in such cases, since you can assemble this file separately using the
26111 @emph{as} assembler that comes with gcc.
26113 Assembling the file using the command
26116 as @file{nothing.s}
26119 will give you error messages whose lines correspond to the assembler
26120 input file, so you can easily find and correct any mistakes you made.
26121 If there are no errors, @emph{as} will generate an object file
26122 @file{nothing.out}.
26124 @c ---------------------------------------------------------------------------
26125 @node Output Variables in Inline Assembler
26126 @section Output Variables in Inline Assembler
26129 The examples in this section, showing how to access the processor flags,
26130 illustrate how to specify the destination operands for assembly language
26133 @smallexample @c ada
26135 @b{with} Interfaces; @b{use} Interfaces;
26136 @b{with} Ada.Text_IO; @b{use} Ada.Text_IO;
26137 @b{with} System.Machine_Code; @b{use} System.Machine_Code;
26138 @b{procedure} Get_Flags @b{is}
26139 Flags : Unsigned_32;
26142 Asm ("pushfl" & LF & HT & --@i{ push flags on stack}
26143 "popl %%eax" & LF & HT & --@i{ load eax with flags}
26144 "movl %%eax, %0", --@i{ store flags in variable}
26145 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
26146 Put_Line ("Flags register:" & Flags'Img);
26151 In order to have a nicely aligned assembly listing, we have separated
26152 multiple assembler statements in the Asm template string with linefeed
26153 (ASCII.LF) and horizontal tab (ASCII.HT) characters.
26154 The resulting section of the assembly output file is:
26161 movl %eax, -40(%ebp)
26166 It would have been legal to write the Asm invocation as:
26169 Asm ("pushfl popl %%eax movl %%eax, %0")
26172 but in the generated assembler file, this would come out as:
26176 pushfl popl %eax movl %eax, -40(%ebp)
26180 which is not so convenient for the human reader.
26182 We use Ada comments
26183 at the end of each line to explain what the assembler instructions
26184 actually do. This is a useful convention.
26186 When writing Inline Assembler instructions, you need to precede each register
26187 and variable name with a percent sign. Since the assembler already requires
26188 a percent sign at the beginning of a register name, you need two consecutive
26189 percent signs for such names in the Asm template string, thus @code{%%eax}.
26190 In the generated assembly code, one of the percent signs will be stripped off.
26192 Names such as @code{%0}, @code{%1}, @code{%2}, etc., denote input or output
26193 variables: operands you later define using @code{Input} or @code{Output}
26194 parameters to @code{Asm}.
26195 An output variable is illustrated in
26196 the third statement in the Asm template string:
26200 The intent is to store the contents of the eax register in a variable that can
26201 be accessed in Ada. Simply writing @code{movl %%eax, Flags} would not
26202 necessarily work, since the compiler might optimize by using a register
26203 to hold Flags, and the expansion of the @code{movl} instruction would not be
26204 aware of this optimization. The solution is not to store the result directly
26205 but rather to advise the compiler to choose the correct operand form;
26206 that is the purpose of the @code{%0} output variable.
26208 Information about the output variable is supplied in the @code{Outputs}
26209 parameter to @code{Asm}:
26211 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
26214 The output is defined by the @code{Asm_Output} attribute of the target type;
26215 the general format is
26217 Type'Asm_Output (constraint_string, variable_name)
26220 The constraint string directs the compiler how
26221 to store/access the associated variable. In the example
26223 Unsigned_32'Asm_Output ("=m", Flags);
26225 the @code{"m"} (memory) constraint tells the compiler that the variable
26226 @code{Flags} should be stored in a memory variable, thus preventing
26227 the optimizer from keeping it in a register. In contrast,
26229 Unsigned_32'Asm_Output ("=r", Flags);
26231 uses the @code{"r"} (register) constraint, telling the compiler to
26232 store the variable in a register.
26234 If the constraint is preceded by the equal character (@strong{=}), it tells
26235 the compiler that the variable will be used to store data into it.
26237 In the @code{Get_Flags} example, we used the @code{"g"} (global) constraint,
26238 allowing the optimizer to choose whatever it deems best.
26240 There are a fairly large number of constraints, but the ones that are
26241 most useful (for the Intel x86 processor) are the following:
26247 global (i.e.@: can be stored anywhere)
26265 use one of eax, ebx, ecx or edx
26267 use one of eax, ebx, ecx, edx, esi or edi
26270 The full set of constraints is described in the gcc and @emph{as}
26271 documentation; note that it is possible to combine certain constraints
26272 in one constraint string.
26274 You specify the association of an output variable with an assembler operand
26275 through the @code{%}@emph{n} notation, where @emph{n} is a non-negative
26277 @smallexample @c ada
26279 Asm ("pushfl" & LF & HT & --@i{ push flags on stack}
26280 "popl %%eax" & LF & HT & --@i{ load eax with flags}
26281 "movl %%eax, %0", --@i{ store flags in variable}
26282 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
26286 @code{%0} will be replaced in the expanded code by the appropriate operand,
26288 the compiler decided for the @code{Flags} variable.
26290 In general, you may have any number of output variables:
26293 Count the operands starting at 0; thus @code{%0}, @code{%1}, etc.
26295 Specify the @code{Outputs} parameter as a parenthesized comma-separated list
26296 of @code{Asm_Output} attributes
26300 @smallexample @c ada
26302 Asm ("movl %%eax, %0" & LF & HT &
26303 "movl %%ebx, %1" & LF & HT &
26305 Outputs => (Unsigned_32'Asm_Output ("=g", Var_A), --@i{ %0 = Var_A}
26306 Unsigned_32'Asm_Output ("=g", Var_B), --@i{ %1 = Var_B}
26307 Unsigned_32'Asm_Output ("=g", Var_C))); --@i{ %2 = Var_C}
26311 where @code{Var_A}, @code{Var_B}, and @code{Var_C} are variables
26312 in the Ada program.
26314 As a variation on the @code{Get_Flags} example, we can use the constraints
26315 string to direct the compiler to store the eax register into the @code{Flags}
26316 variable, instead of including the store instruction explicitly in the
26317 @code{Asm} template string:
26319 @smallexample @c ada
26321 @b{with} Interfaces; @b{use} Interfaces;
26322 @b{with} Ada.Text_IO; @b{use} Ada.Text_IO;
26323 @b{with} System.Machine_Code; @b{use} System.Machine_Code;
26324 @b{procedure} Get_Flags_2 @b{is}
26325 Flags : Unsigned_32;
26328 Asm ("pushfl" & LF & HT & --@i{ push flags on stack}
26329 "popl %%eax", --@i{ save flags in eax}
26330 Outputs => Unsigned_32'Asm_Output ("=a", Flags));
26331 Put_Line ("Flags register:" & Flags'Img);
26332 @b{end} Get_Flags_2;
26337 The @code{"a"} constraint tells the compiler that the @code{Flags}
26338 variable will come from the eax register. Here is the resulting code:
26346 movl %eax,-40(%ebp)
26351 The compiler generated the store of eax into Flags after
26352 expanding the assembler code.
26354 Actually, there was no need to pop the flags into the eax register;
26355 more simply, we could just pop the flags directly into the program variable:
26357 @smallexample @c ada
26359 @b{with} Interfaces; @b{use} Interfaces;
26360 @b{with} Ada.Text_IO; @b{use} Ada.Text_IO;
26361 @b{with} System.Machine_Code; @b{use} System.Machine_Code;
26362 @b{procedure} Get_Flags_3 @b{is}
26363 Flags : Unsigned_32;
26366 Asm ("pushfl" & LF & HT & --@i{ push flags on stack}
26367 "pop %0", --@i{ save flags in Flags}
26368 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
26369 Put_Line ("Flags register:" & Flags'Img);
26370 @b{end} Get_Flags_3;
26374 @c ---------------------------------------------------------------------------
26375 @node Input Variables in Inline Assembler
26376 @section Input Variables in Inline Assembler
26379 The example in this section illustrates how to specify the source operands
26380 for assembly language statements.
26381 The program simply increments its input value by 1:
26383 @smallexample @c ada
26385 @b{with} Interfaces; @b{use} Interfaces;
26386 @b{with} Ada.Text_IO; @b{use} Ada.Text_IO;
26387 @b{with} System.Machine_Code; @b{use} System.Machine_Code;
26388 @b{procedure} Increment @b{is}
26390 @b{function} Incr (Value : Unsigned_32) @b{return} Unsigned_32 @b{is}
26391 Result : Unsigned_32;
26394 Outputs => Unsigned_32'Asm_Output ("=a", Result),
26395 Inputs => Unsigned_32'Asm_Input ("a", Value));
26399 Value : Unsigned_32;
26403 Put_Line ("Value before is" & Value'Img);
26404 Value := Incr (Value);
26405 Put_Line ("Value after is" & Value'Img);
26410 The @code{Outputs} parameter to @code{Asm} specifies
26411 that the result will be in the eax register and that it is to be stored
26412 in the @code{Result} variable.
26414 The @code{Inputs} parameter looks much like the @code{Outputs} parameter,
26415 but with an @code{Asm_Input} attribute.
26416 The @code{"="} constraint, indicating an output value, is not present.
26418 You can have multiple input variables, in the same way that you can have more
26419 than one output variable.
26421 The parameter count (%0, %1) etc, still starts at the first output statement,
26422 and continues with the input statements.
26424 Just as the @code{Outputs} parameter causes the register to be stored into the
26425 target variable after execution of the assembler statements, so does the
26426 @code{Inputs} parameter cause its variable to be loaded into the register
26427 before execution of the assembler statements.
26429 Thus the effect of the @code{Asm} invocation is:
26431 @item load the 32-bit value of @code{Value} into eax
26432 @item execute the @code{incl %eax} instruction
26433 @item store the contents of eax into the @code{Result} variable
26436 The resulting assembler file (with @option{-O2} optimization) contains:
26439 _increment__incr.1:
26452 @c ---------------------------------------------------------------------------
26453 @node Inlining Inline Assembler Code
26454 @section Inlining Inline Assembler Code
26457 For a short subprogram such as the @code{Incr} function in the previous
26458 section, the overhead of the call and return (creating / deleting the stack
26459 frame) can be significant, compared to the amount of code in the subprogram
26460 body. A solution is to apply Ada's @code{Inline} pragma to the subprogram,
26461 which directs the compiler to expand invocations of the subprogram at the
26462 point(s) of call, instead of setting up a stack frame for out-of-line calls.
26463 Here is the resulting program:
26465 @smallexample @c ada
26467 @b{with} Interfaces; @b{use} Interfaces;
26468 @b{with} Ada.Text_IO; @b{use} Ada.Text_IO;
26469 @b{with} System.Machine_Code; @b{use} System.Machine_Code;
26470 @b{procedure} Increment_2 @b{is}
26472 @b{function} Incr (Value : Unsigned_32) @b{return} Unsigned_32 @b{is}
26473 Result : Unsigned_32;
26476 Outputs => Unsigned_32'Asm_Output ("=a", Result),
26477 Inputs => Unsigned_32'Asm_Input ("a", Value));
26480 @b{pragma} Inline (Increment);
26482 Value : Unsigned_32;
26486 Put_Line ("Value before is" & Value'Img);
26487 Value := Increment (Value);
26488 Put_Line ("Value after is" & Value'Img);
26489 @b{end} Increment_2;
26493 Compile the program with both optimization (@option{-O2}) and inlining
26494 (@option{-gnatn}) enabled.
26496 The @code{Incr} function is still compiled as usual, but at the
26497 point in @code{Increment} where our function used to be called:
26502 call _increment__incr.1
26507 the code for the function body directly appears:
26520 thus saving the overhead of stack frame setup and an out-of-line call.
26522 @c ---------------------------------------------------------------------------
26523 @node Other Asm Functionality
26524 @section Other @code{Asm} Functionality
26527 This section describes two important parameters to the @code{Asm}
26528 procedure: @code{Clobber}, which identifies register usage;
26529 and @code{Volatile}, which inhibits unwanted optimizations.
26532 * The Clobber Parameter::
26533 * The Volatile Parameter::
26536 @c ---------------------------------------------------------------------------
26537 @node The Clobber Parameter
26538 @subsection The @code{Clobber} Parameter
26541 One of the dangers of intermixing assembly language and a compiled language
26542 such as Ada is that the compiler needs to be aware of which registers are
26543 being used by the assembly code. In some cases, such as the earlier examples,
26544 the constraint string is sufficient to indicate register usage (e.g.,
26546 the eax register). But more generally, the compiler needs an explicit
26547 identification of the registers that are used by the Inline Assembly
26550 Using a register that the compiler doesn't know about
26551 could be a side effect of an instruction (like @code{mull}
26552 storing its result in both eax and edx).
26553 It can also arise from explicit register usage in your
26554 assembly code; for example:
26557 Asm ("movl %0, %%ebx" & LF & HT &
26559 Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
26560 Inputs => Unsigned_32'Asm_Input ("g", Var_In));
26564 where the compiler (since it does not analyze the @code{Asm} template string)
26565 does not know you are using the ebx register.
26567 In such cases you need to supply the @code{Clobber} parameter to @code{Asm},
26568 to identify the registers that will be used by your assembly code:
26572 Asm ("movl %0, %%ebx" & LF & HT &
26574 Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
26575 Inputs => Unsigned_32'Asm_Input ("g", Var_In),
26580 The Clobber parameter is a static string expression specifying the
26581 register(s) you are using. Note that register names are @emph{not} prefixed
26582 by a percent sign. Also, if more than one register is used then their names
26583 are separated by commas; e.g., @code{"eax, ebx"}
26585 The @code{Clobber} parameter has several additional uses:
26587 @item Use ``register'' name @code{cc} to indicate that flags might have changed
26588 @item Use ``register'' name @code{memory} if you changed a memory location
26591 @c ---------------------------------------------------------------------------
26592 @node The Volatile Parameter
26593 @subsection The @code{Volatile} Parameter
26594 @cindex Volatile parameter
26597 Compiler optimizations in the presence of Inline Assembler may sometimes have
26598 unwanted effects. For example, when an @code{Asm} invocation with an input
26599 variable is inside a loop, the compiler might move the loading of the input
26600 variable outside the loop, regarding it as a one-time initialization.
26602 If this effect is not desired, you can disable such optimizations by setting
26603 the @code{Volatile} parameter to @code{True}; for example:
26605 @smallexample @c ada
26607 Asm ("movl %0, %%ebx" & LF & HT &
26609 Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
26610 Inputs => Unsigned_32'Asm_Input ("g", Var_In),
26616 By default, @code{Volatile} is set to @code{False} unless there is no
26617 @code{Outputs} parameter.
26619 Although setting @code{Volatile} to @code{True} prevents unwanted
26620 optimizations, it will also disable other optimizations that might be
26621 important for efficiency. In general, you should set @code{Volatile}
26622 to @code{True} only if the compiler's optimizations have created
26624 @c END OF INLINE ASSEMBLER CHAPTER
26625 @c ===============================
26628 @c *****************************************
26629 @c Writing Portable Fixed-Point Declarations
26630 @c *****************************************
26631 @node Writing Portable Fixed-Point Declarations
26632 @appendix Writing Portable Fixed-Point Declarations
26633 @cindex Fixed-point types (writing portable declarations)
26636 The Ada Reference Manual gives an implementation freedom to choose bounds
26637 that are narrower by @code{Small} from the given bounds.
26638 For example, if we write
26640 @smallexample @c ada
26641 type F1 is delta 1.0 range -128.0 .. +128.0;
26645 then the implementation is allowed to choose -128.0 .. +127.0 if it
26646 likes, but is not required to do so.
26648 This leads to possible portability problems, so let's have a closer
26649 look at this, and figure out how to avoid these problems.
26651 First, why does this freedom exist, and why would an implementation
26652 take advantage of it? To answer this, take a closer look at the type
26653 declaration for @code{F1} above. If the compiler uses the given bounds,
26654 it would need 9 bits to hold the largest positive value (and typically
26655 that means 16 bits on all machines). But if the implementation chooses
26656 the +127.0 bound then it can fit values of the type in 8 bits.
26658 Why not make the user write +127.0 if that's what is wanted?
26659 The rationale is that if you are thinking of fixed point
26660 as a kind of ``poor man's floating-point'', then you don't want
26661 to be thinking about the scaled integers that are used in its
26662 representation. Let's take another example:
26664 @smallexample @c ada
26665 type F2 is delta 2.0**(-15) range -1.0 .. +1.0;
26669 Looking at this declaration, it seems casually as though
26670 it should fit in 16 bits, but again that extra positive value
26671 +1.0 has the scaled integer equivalent of 2**15 which is one too
26672 big for signed 16 bits. The implementation can treat this as:
26674 @smallexample @c ada
26675 type F2 is delta 2.0**(-15) range -1.0 .. +1.0-(2.0**(-15));
26679 and the Ada language design team felt that this was too annoying
26680 to require. We don't need to debate this decision at this point,
26681 since it is well established (the rule about narrowing the ranges
26684 But the important point is that an implementation is not required
26685 to do this narrowing, so we have a potential portability problem.
26686 We could imagine three types of implementation:
26690 those that narrow the range automatically if they can figure
26691 out that the narrower range will allow storage in a smaller machine unit,
26694 those that will narrow only if forced to by a @code{'Size} clause, and
26697 those that will never narrow.
26701 Now if we are language theoreticians, we can imagine a fourth
26702 approach: is to narrow all the time, e.g. to treat
26704 @smallexample @c ada
26705 type F3 is delta 1.0 range -10.0 .. +23.0;
26709 as though it had been written:
26711 @smallexample @c ada
26712 type F3 is delta 1.0 range -9.0 .. +22.0;
26716 But although technically allowed, such a behavior would be hostile and silly,
26717 and no real compiler would do this. All real compilers will fall into one of
26718 the categories (a), (b) or (c) above.
26720 So, how do you get the compiler to do what you want? The answer is give the
26721 actual bounds you want, and then use a @code{'Small} clause and a
26722 @code{'Size} clause to absolutely pin down what the compiler does.
26723 E.g., for @code{F2} above, we will write:
26725 @smallexample @c ada
26727 My_Small : constant := 2.0**(-15);
26728 My_First : constant := -1.0;
26729 My_Last : constant := +1.0 - My_Small;
26731 type F2 is delta My_Small range My_First .. My_Last;
26738 @smallexample @c ada
26740 for F2'Small use my_Small;
26741 for F2'Size use 16;
26746 In practice all compilers will do the same thing here and will give you
26747 what you want, so the above declarations are fully portable. If you really
26748 want to play language lawyer and guard against ludicrous behavior by the
26749 compiler you could add
26751 @smallexample @c ada
26753 Test1 : constant := 1 / Boolean'Pos (F2'First = My_First);
26754 Test2 : constant := 1 / Boolean'Pos (F2'Last = My_Last);
26759 One or other or both are allowed to be illegal if the compiler is
26760 behaving in a silly manner, but at least the silly compiler will not
26761 get away with silently messing with your (very clear) intentions.
26763 If you follow this scheme you will be guaranteed that your fixed-point
26764 types will be portable.
26767 @c ***********************************
26768 @c * Compatibility and Porting Guide *
26769 @c ***********************************
26770 @node Compatibility and Porting Guide
26771 @appendix Compatibility and Porting Guide
26774 This chapter describes the compatibility issues that may arise between
26775 GNAT and other Ada compilation systems (including those for Ada 83),
26776 and shows how GNAT can expedite porting
26777 applications developed in other Ada environments.
26780 * Compatibility with Ada 83::
26781 * Compatibility between Ada 95 and Ada 2005::
26782 * Implementation-dependent characteristics::
26783 * Compatibility with Other Ada Systems::
26784 * Representation Clauses::
26785 @c Brief section is only in non-VMS version
26786 @c Full chapter is in VMS version
26787 * Compatibility with HP Ada 83::
26790 @node Compatibility with Ada 83
26791 @section Compatibility with Ada 83
26792 @cindex Compatibility (between Ada 83 and Ada 95 / Ada 2005)
26795 Ada 95 and Ada 2005 are highly upwards compatible with Ada 83. In
26796 particular, the design intention was that the difficulties associated
26797 with moving from Ada 83 to Ada 95 or Ada 2005 should be no greater than those
26798 that occur when moving from one Ada 83 system to another.
26800 However, there are a number of points at which there are minor
26801 incompatibilities. The @cite{Ada 95 Annotated Reference Manual} contains
26802 full details of these issues,
26803 and should be consulted for a complete treatment.
26805 following subsections treat the most likely issues to be encountered.
26808 * Legal Ada 83 programs that are illegal in Ada 95::
26809 * More deterministic semantics::
26810 * Changed semantics::
26811 * Other language compatibility issues::
26814 @node Legal Ada 83 programs that are illegal in Ada 95
26815 @subsection Legal Ada 83 programs that are illegal in Ada 95
26817 Some legal Ada 83 programs are illegal (i.e., they will fail to compile) in
26818 Ada 95 and thus also in Ada 2005:
26821 @item Character literals
26822 Some uses of character literals are ambiguous. Since Ada 95 has introduced
26823 @code{Wide_Character} as a new predefined character type, some uses of
26824 character literals that were legal in Ada 83 are illegal in Ada 95.
26826 @smallexample @c ada
26827 @b{for} Char @b{in} 'A' .. 'Z' @b{loop} @dots{} @b{end} @b{loop};
26831 The problem is that @code{'A'} and @code{'Z'} could be from either
26832 @code{Character} or @code{Wide_Character}. The simplest correction
26833 is to make the type explicit; e.g.:
26834 @smallexample @c ada
26835 @b{for} Char @b{in} Character @b{range} 'A' .. 'Z' @b{loop} @dots{} @b{end} @b{loop};
26838 @item New reserved words
26839 The identifiers @code{abstract}, @code{aliased}, @code{protected},
26840 @code{requeue}, @code{tagged}, and @code{until} are reserved in Ada 95.
26841 Existing Ada 83 code using any of these identifiers must be edited to
26842 use some alternative name.
26844 @item Freezing rules
26845 The rules in Ada 95 are slightly different with regard to the point at
26846 which entities are frozen, and representation pragmas and clauses are
26847 not permitted past the freeze point. This shows up most typically in
26848 the form of an error message complaining that a representation item
26849 appears too late, and the appropriate corrective action is to move
26850 the item nearer to the declaration of the entity to which it refers.
26852 A particular case is that representation pragmas
26853 cannot be applied to a subprogram body. If necessary, a separate subprogram
26854 declaration must be introduced to which the pragma can be applied.
26856 @item Optional bodies for library packages
26857 In Ada 83, a package that did not require a package body was nevertheless
26858 allowed to have one. This lead to certain surprises in compiling large
26859 systems (situations in which the body could be unexpectedly ignored by the
26860 binder). In Ada 95, if a package does not require a body then it is not
26861 permitted to have a body. To fix this problem, simply remove a redundant
26862 body if it is empty, or, if it is non-empty, introduce a dummy declaration
26863 into the spec that makes the body required. One approach is to add a private
26864 part to the package declaration (if necessary), and define a parameterless
26865 procedure called @code{Requires_Body}, which must then be given a dummy
26866 procedure body in the package body, which then becomes required.
26867 Another approach (assuming that this does not introduce elaboration
26868 circularities) is to add an @code{Elaborate_Body} pragma to the package spec,
26869 since one effect of this pragma is to require the presence of a package body.
26871 @item @code{Numeric_Error} is now the same as @code{Constraint_Error}
26872 In Ada 95, the exception @code{Numeric_Error} is a renaming of
26873 @code{Constraint_Error}.
26874 This means that it is illegal to have separate exception handlers for
26875 the two exceptions. The fix is simply to remove the handler for the
26876 @code{Numeric_Error} case (since even in Ada 83, a compiler was free to raise
26877 @code{Constraint_Error} in place of @code{Numeric_Error} in all cases).
26879 @item Indefinite subtypes in generics
26880 In Ada 83, it was permissible to pass an indefinite type (e.g.@: @code{String})
26881 as the actual for a generic formal private type, but then the instantiation
26882 would be illegal if there were any instances of declarations of variables
26883 of this type in the generic body. In Ada 95, to avoid this clear violation
26884 of the methodological principle known as the ``contract model'',
26885 the generic declaration explicitly indicates whether
26886 or not such instantiations are permitted. If a generic formal parameter
26887 has explicit unknown discriminants, indicated by using @code{(<>)} after the
26888 subtype name, then it can be instantiated with indefinite types, but no
26889 stand-alone variables can be declared of this type. Any attempt to declare
26890 such a variable will result in an illegality at the time the generic is
26891 declared. If the @code{(<>)} notation is not used, then it is illegal
26892 to instantiate the generic with an indefinite type.
26893 This is the potential incompatibility issue when porting Ada 83 code to Ada 95.
26894 It will show up as a compile time error, and
26895 the fix is usually simply to add the @code{(<>)} to the generic declaration.
26898 @node More deterministic semantics
26899 @subsection More deterministic semantics
26903 Conversions from real types to integer types round away from 0. In Ada 83
26904 the conversion Integer(2.5) could deliver either 2 or 3 as its value. This
26905 implementation freedom was intended to support unbiased rounding in
26906 statistical applications, but in practice it interfered with portability.
26907 In Ada 95 the conversion semantics are unambiguous, and rounding away from 0
26908 is required. Numeric code may be affected by this change in semantics.
26909 Note, though, that this issue is no worse than already existed in Ada 83
26910 when porting code from one vendor to another.
26913 The Real-Time Annex introduces a set of policies that define the behavior of
26914 features that were implementation dependent in Ada 83, such as the order in
26915 which open select branches are executed.
26918 @node Changed semantics
26919 @subsection Changed semantics
26922 The worst kind of incompatibility is one where a program that is legal in
26923 Ada 83 is also legal in Ada 95 but can have an effect in Ada 95 that was not
26924 possible in Ada 83. Fortunately this is extremely rare, but the one
26925 situation that you should be alert to is the change in the predefined type
26926 @code{Character} from 7-bit ASCII to 8-bit Latin-1.
26929 @item Range of type @code{Character}
26930 The range of @code{Standard.Character} is now the full 256 characters
26931 of Latin-1, whereas in most Ada 83 implementations it was restricted
26932 to 128 characters. Although some of the effects of
26933 this change will be manifest in compile-time rejection of legal
26934 Ada 83 programs it is possible for a working Ada 83 program to have
26935 a different effect in Ada 95, one that was not permitted in Ada 83.
26936 As an example, the expression
26937 @code{Character'Pos(Character'Last)} returned @code{127} in Ada 83 and now
26938 delivers @code{255} as its value.
26939 In general, you should look at the logic of any
26940 character-processing Ada 83 program and see whether it needs to be adapted
26941 to work correctly with Latin-1. Note that the predefined Ada 95 API has a
26942 character handling package that may be relevant if code needs to be adapted
26943 to account for the additional Latin-1 elements.
26944 The desirable fix is to
26945 modify the program to accommodate the full character set, but in some cases
26946 it may be convenient to define a subtype or derived type of Character that
26947 covers only the restricted range.
26951 @node Other language compatibility issues
26952 @subsection Other language compatibility issues
26955 @item @option{-gnat83} switch
26956 All implementations of GNAT provide a switch that causes GNAT to operate
26957 in Ada 83 mode. In this mode, some but not all compatibility problems
26958 of the type described above are handled automatically. For example, the
26959 new reserved words introduced in Ada 95 and Ada 2005 are treated simply
26960 as identifiers as in Ada 83.
26962 in practice, it is usually advisable to make the necessary modifications
26963 to the program to remove the need for using this switch.
26964 See @ref{Compiling Different Versions of Ada}.
26966 @item Support for removed Ada 83 pragmas and attributes
26967 A number of pragmas and attributes from Ada 83 were removed from Ada 95,
26968 generally because they were replaced by other mechanisms. Ada 95 and Ada 2005
26969 compilers are allowed, but not required, to implement these missing
26970 elements. In contrast with some other compilers, GNAT implements all
26971 such pragmas and attributes, eliminating this compatibility concern. These
26972 include @code{pragma Interface} and the floating point type attributes
26973 (@code{Emax}, @code{Mantissa}, etc.), among other items.
26977 @node Compatibility between Ada 95 and Ada 2005
26978 @section Compatibility between Ada 95 and Ada 2005
26979 @cindex Compatibility between Ada 95 and Ada 2005
26982 Although Ada 2005 was designed to be upwards compatible with Ada 95, there are
26983 a number of incompatibilities. Several are enumerated below;
26984 for a complete description please see the
26985 Annotated Ada 2005 Reference Manual, or section 9.1.1 in
26986 @cite{Rationale for Ada 2005}.
26989 @item New reserved words.
26990 The words @code{interface}, @code{overriding} and @code{synchronized} are
26991 reserved in Ada 2005.
26992 A pre-Ada 2005 program that uses any of these as an identifier will be
26995 @item New declarations in predefined packages.
26996 A number of packages in the predefined environment contain new declarations:
26997 @code{Ada.Exceptions}, @code{Ada.Real_Time}, @code{Ada.Strings},
26998 @code{Ada.Strings.Fixed}, @code{Ada.Strings.Bounded},
26999 @code{Ada.Strings.Unbounded}, @code{Ada.Strings.Wide_Fixed},
27000 @code{Ada.Strings.Wide_Bounded}, @code{Ada.Strings.Wide_Unbounded},
27001 @code{Ada.Tags}, @code{Ada.Text_IO}, and @code{Interfaces.C}.
27002 If an Ada 95 program does a @code{with} and @code{use} of any of these
27003 packages, the new declarations may cause name clashes.
27005 @item Access parameters.
27006 A nondispatching subprogram with an access parameter cannot be renamed
27007 as a dispatching operation. This was permitted in Ada 95.
27009 @item Access types, discriminants, and constraints.
27010 Rule changes in this area have led to some incompatibilities; for example,
27011 constrained subtypes of some access types are not permitted in Ada 2005.
27013 @item Aggregates for limited types.
27014 The allowance of aggregates for limited types in Ada 2005 raises the
27015 possibility of ambiguities in legal Ada 95 programs, since additional types
27016 now need to be considered in expression resolution.
27018 @item Fixed-point multiplication and division.
27019 Certain expressions involving ``*'' or ``/'' for a fixed-point type, which
27020 were legal in Ada 95 and invoked the predefined versions of these operations,
27022 The ambiguity may be resolved either by applying a type conversion to the
27023 expression, or by explicitly invoking the operation from package
27026 @item Return-by-reference types.
27027 The Ada 95 return-by-reference mechanism has been removed. Instead, the user
27028 can declare a function returning a value from an anonymous access type.
27032 @node Implementation-dependent characteristics
27033 @section Implementation-dependent characteristics
27035 Although the Ada language defines the semantics of each construct as
27036 precisely as practical, in some situations (for example for reasons of
27037 efficiency, or where the effect is heavily dependent on the host or target
27038 platform) the implementation is allowed some freedom. In porting Ada 83
27039 code to GNAT, you need to be aware of whether / how the existing code
27040 exercised such implementation dependencies. Such characteristics fall into
27041 several categories, and GNAT offers specific support in assisting the
27042 transition from certain Ada 83 compilers.
27045 * Implementation-defined pragmas::
27046 * Implementation-defined attributes::
27048 * Elaboration order::
27049 * Target-specific aspects::
27052 @node Implementation-defined pragmas
27053 @subsection Implementation-defined pragmas
27056 Ada compilers are allowed to supplement the language-defined pragmas, and
27057 these are a potential source of non-portability. All GNAT-defined pragmas
27058 are described in @ref{Implementation Defined Pragmas,,, gnat_rm, GNAT
27059 Reference Manual}, and these include several that are specifically
27060 intended to correspond to other vendors' Ada 83 pragmas.
27061 For migrating from VADS, the pragma @code{Use_VADS_Size} may be useful.
27062 For compatibility with HP Ada 83, GNAT supplies the pragmas
27063 @code{Extend_System}, @code{Ident}, @code{Inline_Generic},
27064 @code{Interface_Name}, @code{Passive}, @code{Suppress_All},
27065 and @code{Volatile}.
27066 Other relevant pragmas include @code{External} and @code{Link_With}.
27067 Some vendor-specific
27068 Ada 83 pragmas (@code{Share_Generic}, @code{Subtitle}, and @code{Title}) are
27070 avoiding compiler rejection of units that contain such pragmas; they are not
27071 relevant in a GNAT context and hence are not otherwise implemented.
27073 @node Implementation-defined attributes
27074 @subsection Implementation-defined attributes
27076 Analogous to pragmas, the set of attributes may be extended by an
27077 implementation. All GNAT-defined attributes are described in
27078 @ref{Implementation Defined Attributes,,, gnat_rm, GNAT Reference
27079 Manual}, and these include several that are specifically intended
27080 to correspond to other vendors' Ada 83 attributes. For migrating from VADS,
27081 the attribute @code{VADS_Size} may be useful. For compatibility with HP
27082 Ada 83, GNAT supplies the attributes @code{Bit}, @code{Machine_Size} and
27086 @subsection Libraries
27088 Vendors may supply libraries to supplement the standard Ada API. If Ada 83
27089 code uses vendor-specific libraries then there are several ways to manage
27090 this in Ada 95 or Ada 2005:
27093 If the source code for the libraries (specs and bodies) are
27094 available, then the libraries can be migrated in the same way as the
27097 If the source code for the specs but not the bodies are
27098 available, then you can reimplement the bodies.
27100 Some features introduced by Ada 95 obviate the need for library support. For
27101 example most Ada 83 vendors supplied a package for unsigned integers. The
27102 Ada 95 modular type feature is the preferred way to handle this need, so
27103 instead of migrating or reimplementing the unsigned integer package it may
27104 be preferable to retrofit the application using modular types.
27107 @node Elaboration order
27108 @subsection Elaboration order
27110 The implementation can choose any elaboration order consistent with the unit
27111 dependency relationship. This freedom means that some orders can result in
27112 Program_Error being raised due to an ``Access Before Elaboration'': an attempt
27113 to invoke a subprogram its body has been elaborated, or to instantiate a
27114 generic before the generic body has been elaborated. By default GNAT
27115 attempts to choose a safe order (one that will not encounter access before
27116 elaboration problems) by implicitly inserting @code{Elaborate} or
27117 @code{Elaborate_All} pragmas where
27118 needed. However, this can lead to the creation of elaboration circularities
27119 and a resulting rejection of the program by gnatbind. This issue is
27120 thoroughly described in @ref{Elaboration Order Handling in GNAT}.
27121 In brief, there are several
27122 ways to deal with this situation:
27126 Modify the program to eliminate the circularities, e.g.@: by moving
27127 elaboration-time code into explicitly-invoked procedures
27129 Constrain the elaboration order by including explicit @code{Elaborate_Body} or
27130 @code{Elaborate} pragmas, and then inhibit the generation of implicit
27131 @code{Elaborate_All}
27132 pragmas either globally (as an effect of the @option{-gnatE} switch) or locally
27133 (by selectively suppressing elaboration checks via pragma
27134 @code{Suppress(Elaboration_Check)} when it is safe to do so).
27137 @node Target-specific aspects
27138 @subsection Target-specific aspects
27140 Low-level applications need to deal with machine addresses, data
27141 representations, interfacing with assembler code, and similar issues. If
27142 such an Ada 83 application is being ported to different target hardware (for
27143 example where the byte endianness has changed) then you will need to
27144 carefully examine the program logic; the porting effort will heavily depend
27145 on the robustness of the original design. Moreover, Ada 95 (and thus
27146 Ada 2005) are sometimes
27147 incompatible with typical Ada 83 compiler practices regarding implicit
27148 packing, the meaning of the Size attribute, and the size of access values.
27149 GNAT's approach to these issues is described in @ref{Representation Clauses}.
27151 @node Compatibility with Other Ada Systems
27152 @section Compatibility with Other Ada Systems
27155 If programs avoid the use of implementation dependent and
27156 implementation defined features, as documented in the @cite{Ada
27157 Reference Manual}, there should be a high degree of portability between
27158 GNAT and other Ada systems. The following are specific items which
27159 have proved troublesome in moving Ada 95 programs from GNAT to other Ada 95
27160 compilers, but do not affect porting code to GNAT@.
27161 (As of @value{NOW}, GNAT is the only compiler available for Ada 2005;
27162 the following issues may or may not arise for Ada 2005 programs
27163 when other compilers appear.)
27166 @item Ada 83 Pragmas and Attributes
27167 Ada 95 compilers are allowed, but not required, to implement the missing
27168 Ada 83 pragmas and attributes that are no longer defined in Ada 95.
27169 GNAT implements all such pragmas and attributes, eliminating this as
27170 a compatibility concern, but some other Ada 95 compilers reject these
27171 pragmas and attributes.
27173 @item Specialized Needs Annexes
27174 GNAT implements the full set of special needs annexes. At the
27175 current time, it is the only Ada 95 compiler to do so. This means that
27176 programs making use of these features may not be portable to other Ada
27177 95 compilation systems.
27179 @item Representation Clauses
27180 Some other Ada 95 compilers implement only the minimal set of
27181 representation clauses required by the Ada 95 reference manual. GNAT goes
27182 far beyond this minimal set, as described in the next section.
27185 @node Representation Clauses
27186 @section Representation Clauses
27189 The Ada 83 reference manual was quite vague in describing both the minimal
27190 required implementation of representation clauses, and also their precise
27191 effects. Ada 95 (and thus also Ada 2005) are much more explicit, but the
27192 minimal set of capabilities required is still quite limited.
27194 GNAT implements the full required set of capabilities in
27195 Ada 95 and Ada 2005, but also goes much further, and in particular
27196 an effort has been made to be compatible with existing Ada 83 usage to the
27197 greatest extent possible.
27199 A few cases exist in which Ada 83 compiler behavior is incompatible with
27200 the requirements in Ada 95 (and thus also Ada 2005). These are instances of
27201 intentional or accidental dependence on specific implementation dependent
27202 characteristics of these Ada 83 compilers. The following is a list of
27203 the cases most likely to arise in existing Ada 83 code.
27206 @item Implicit Packing
27207 Some Ada 83 compilers allowed a Size specification to cause implicit
27208 packing of an array or record. This could cause expensive implicit
27209 conversions for change of representation in the presence of derived
27210 types, and the Ada design intends to avoid this possibility.
27211 Subsequent AI's were issued to make it clear that such implicit
27212 change of representation in response to a Size clause is inadvisable,
27213 and this recommendation is represented explicitly in the Ada 95 (and Ada 2005)
27214 Reference Manuals as implementation advice that is followed by GNAT@.
27215 The problem will show up as an error
27216 message rejecting the size clause. The fix is simply to provide
27217 the explicit pragma @code{Pack}, or for more fine tuned control, provide
27218 a Component_Size clause.
27220 @item Meaning of Size Attribute
27221 The Size attribute in Ada 95 (and Ada 2005) for discrete types is defined as
27222 the minimal number of bits required to hold values of the type. For example,
27223 on a 32-bit machine, the size of @code{Natural} will typically be 31 and not
27224 32 (since no sign bit is required). Some Ada 83 compilers gave 31, and
27225 some 32 in this situation. This problem will usually show up as a compile
27226 time error, but not always. It is a good idea to check all uses of the
27227 'Size attribute when porting Ada 83 code. The GNAT specific attribute
27228 Object_Size can provide a useful way of duplicating the behavior of
27229 some Ada 83 compiler systems.
27231 @item Size of Access Types
27232 A common assumption in Ada 83 code is that an access type is in fact a pointer,
27233 and that therefore it will be the same size as a System.Address value. This
27234 assumption is true for GNAT in most cases with one exception. For the case of
27235 a pointer to an unconstrained array type (where the bounds may vary from one
27236 value of the access type to another), the default is to use a ``fat pointer'',
27237 which is represented as two separate pointers, one to the bounds, and one to
27238 the array. This representation has a number of advantages, including improved
27239 efficiency. However, it may cause some difficulties in porting existing Ada 83
27240 code which makes the assumption that, for example, pointers fit in 32 bits on
27241 a machine with 32-bit addressing.
27243 To get around this problem, GNAT also permits the use of ``thin pointers'' for
27244 access types in this case (where the designated type is an unconstrained array
27245 type). These thin pointers are indeed the same size as a System.Address value.
27246 To specify a thin pointer, use a size clause for the type, for example:
27248 @smallexample @c ada
27249 @b{type} X @b{is} @b{access} @b{all} String;
27250 @b{for} X'Size @b{use} Standard'Address_Size;
27254 which will cause the type X to be represented using a single pointer.
27255 When using this representation, the bounds are right behind the array.
27256 This representation is slightly less efficient, and does not allow quite
27257 such flexibility in the use of foreign pointers or in using the
27258 Unrestricted_Access attribute to create pointers to non-aliased objects.
27259 But for any standard portable use of the access type it will work in
27260 a functionally correct manner and allow porting of existing code.
27261 Note that another way of forcing a thin pointer representation
27262 is to use a component size clause for the element size in an array,
27263 or a record representation clause for an access field in a record.
27265 See the documentation of Unrestricted_Access in the GNAT RM for a
27266 full discussion of possible problems using this attribute in conjunction
27267 with thin pointers.
27270 @c This brief section is only in the non-VMS version
27271 @c The complete chapter on HP Ada is in the VMS version
27272 @node Compatibility with HP Ada 83
27273 @section Compatibility with HP Ada 83
27276 The VMS version of GNAT fully implements all the pragmas and attributes
27277 provided by HP Ada 83, as well as providing the standard HP Ada 83
27278 libraries, including Starlet. In addition, data layouts and parameter
27279 passing conventions are highly compatible. This means that porting
27280 existing HP Ada 83 code to GNAT in VMS systems should be easier than
27281 most other porting efforts. The following are some of the most
27282 significant differences between GNAT and HP Ada 83.
27285 @item Default floating-point representation
27286 In GNAT, the default floating-point format is IEEE, whereas in HP Ada 83,
27287 it is VMS format. GNAT does implement the necessary pragmas
27288 (Long_Float, Float_Representation) for changing this default.
27291 The package System in GNAT exactly corresponds to the definition in the
27292 Ada 95 reference manual, which means that it excludes many of the
27293 HP Ada 83 extensions. However, a separate package Aux_DEC is provided
27294 that contains the additional definitions, and a special pragma,
27295 Extend_System allows this package to be treated transparently as an
27296 extension of package System.
27299 The definitions provided by Aux_DEC are exactly compatible with those
27300 in the HP Ada 83 version of System, with one exception.
27301 HP Ada provides the following declarations:
27303 @smallexample @c ada
27304 TO_ADDRESS (INTEGER)
27305 TO_ADDRESS (UNSIGNED_LONGWORD)
27306 TO_ADDRESS (@i{universal_integer})
27310 The version of TO_ADDRESS taking a @i{universal integer} argument is in fact
27311 an extension to Ada 83 not strictly compatible with the reference manual.
27312 In GNAT, we are constrained to be exactly compatible with the standard,
27313 and this means we cannot provide this capability. In HP Ada 83, the
27314 point of this definition is to deal with a call like:
27316 @smallexample @c ada
27317 TO_ADDRESS (16#12777#);
27321 Normally, according to the Ada 83 standard, one would expect this to be
27322 ambiguous, since it matches both the INTEGER and UNSIGNED_LONGWORD forms
27323 of TO_ADDRESS@. However, in HP Ada 83, there is no ambiguity, since the
27324 definition using @i{universal_integer} takes precedence.
27326 In GNAT, since the version with @i{universal_integer} cannot be supplied, it
27327 is not possible to be 100% compatible. Since there are many programs using
27328 numeric constants for the argument to TO_ADDRESS, the decision in GNAT was
27329 to change the name of the function in the UNSIGNED_LONGWORD case, so the
27330 declarations provided in the GNAT version of AUX_Dec are:
27332 @smallexample @c ada
27333 @b{function} To_Address (X : Integer) @b{return} Address;
27334 @b{pragma} Pure_Function (To_Address);
27336 @b{function} To_Address_Long (X : Unsigned_Longword)
27337 @b{return} Address;
27338 @b{pragma} Pure_Function (To_Address_Long);
27342 This means that programs using TO_ADDRESS for UNSIGNED_LONGWORD must
27343 change the name to TO_ADDRESS_LONG@.
27345 @item Task_Id values
27346 The Task_Id values assigned will be different in the two systems, and GNAT
27347 does not provide a specified value for the Task_Id of the environment task,
27348 which in GNAT is treated like any other declared task.
27352 For full details on these and other less significant compatibility issues,
27353 see appendix E of the HP publication entitled @cite{HP Ada, Technical
27354 Overview and Comparison on HP Platforms}.
27356 For GNAT running on other than VMS systems, all the HP Ada 83 pragmas and
27357 attributes are recognized, although only a subset of them can sensibly
27358 be implemented. The description of pragmas in @ref{Implementation
27359 Defined Pragmas,,, gnat_rm, GNAT Reference Manual}
27360 indicates whether or not they are applicable to non-VMS systems.
27363 @c ************************************************
27364 @node Microsoft Windows Topics
27365 @appendix Microsoft Windows Topics
27371 This chapter describes topics that are specific to the Microsoft Windows
27372 platforms (NT, 2000, and XP Professional).
27375 @ifclear FSFEDITION
27376 * Installing from the Command Line::
27378 * Using GNAT on Windows::
27379 * Using a network installation of GNAT::
27380 * CONSOLE and WINDOWS subsystems::
27381 * Temporary Files::
27382 * Mixed-Language Programming on Windows::
27383 * Windows Calling Conventions::
27384 * Introduction to Dynamic Link Libraries (DLLs)::
27385 * Using DLLs with GNAT::
27386 * Building DLLs with GNAT Project files::
27387 * Building DLLs with GNAT::
27388 * Building DLLs with gnatdll::
27389 * GNAT and Windows Resources::
27390 * Debugging a DLL::
27391 * Setting Stack Size from gnatlink::
27392 * Setting Heap Size from gnatlink::
27395 @ifclear FSFEDITION
27396 @node Installing from the Command Line
27397 @section Installing from the Command Line
27398 @cindex Batch installation
27399 @cindex Silent installation
27400 @cindex Unassisted installation
27403 By default the @value{EDITION} installers display a GUI that prompts the user
27404 to enter installation path and similar information, and guide him through the
27405 installation process. It is also possible to perform silent installations
27406 using the command-line interface.
27408 In order to install one of the @value{EDITION} installers from the command
27409 line you should pass parameter @code{/S} (and, optionally,
27410 @code{/D=<directory>}) as command-line arguments.
27413 For example, for an unattended installation of
27414 @value{EDITION} 7.0.2 into the default directory
27415 @code{C:\GNATPRO\7.0.2} you would run:
27418 gnatpro-7.0.2-i686-pc-mingw32-bin.exe /S
27421 To install into a custom directory, say, @code{C:\TOOLS\GNATPRO\7.0.2}:
27424 gnatpro-7.0.2-i686-pc-mingw32-bin /S /D=C:\TOOLS\GNATPRO\7.0.2
27429 For example, for an unattended installation of
27430 @value{EDITION} 2012 into @code{C:\GNAT\2012}:
27433 gnat-gpl-2012-i686-pc-mingw32-bin /S /D=C:\GNAT\2012
27437 You can use the same syntax for all installers.
27439 Note that unattended installations don't modify system path, nor create file
27440 associations, so such activities need to be done by hand.
27443 @node Using GNAT on Windows
27444 @section Using GNAT on Windows
27447 One of the strengths of the GNAT technology is that its tool set
27448 (@command{gcc}, @command{gnatbind}, @command{gnatlink}, @command{gnatmake}, the
27449 @code{gdb} debugger, etc.) is used in the same way regardless of the
27452 On Windows this tool set is complemented by a number of Microsoft-specific
27453 tools that have been provided to facilitate interoperability with Windows
27454 when this is required. With these tools:
27459 You can build applications using the @code{CONSOLE} or @code{WINDOWS}
27463 You can use any Dynamically Linked Library (DLL) in your Ada code (both
27464 relocatable and non-relocatable DLLs are supported).
27467 You can build Ada DLLs for use in other applications. These applications
27468 can be written in a language other than Ada (e.g., C, C++, etc). Again both
27469 relocatable and non-relocatable Ada DLLs are supported.
27472 You can include Windows resources in your Ada application.
27475 You can use or create COM/DCOM objects.
27479 Immediately below are listed all known general GNAT-for-Windows restrictions.
27480 Other restrictions about specific features like Windows Resources and DLLs
27481 are listed in separate sections below.
27486 It is not possible to use @code{GetLastError} and @code{SetLastError}
27487 when tasking, protected records, or exceptions are used. In these
27488 cases, in order to implement Ada semantics, the GNAT run-time system
27489 calls certain Win32 routines that set the last error variable to 0 upon
27490 success. It should be possible to use @code{GetLastError} and
27491 @code{SetLastError} when tasking, protected record, and exception
27492 features are not used, but it is not guaranteed to work.
27495 It is not possible to link against Microsoft C++ libraries except for
27496 import libraries. Interfacing must be done by the mean of DLLs.
27499 It is possible to link against Microsoft C libraries. Yet the preferred
27500 solution is to use C/C++ compiler that comes with @value{EDITION}, since it
27501 doesn't require having two different development environments and makes the
27502 inter-language debugging experience smoother.
27505 When the compilation environment is located on FAT32 drives, users may
27506 experience recompilations of the source files that have not changed if
27507 Daylight Saving Time (DST) state has changed since the last time files
27508 were compiled. NTFS drives do not have this problem.
27511 No components of the GNAT toolset use any entries in the Windows
27512 registry. The only entries that can be created are file associations and
27513 PATH settings, provided the user has chosen to create them at installation
27514 time, as well as some minimal book-keeping information needed to correctly
27515 uninstall or integrate different GNAT products.
27518 @node Using a network installation of GNAT
27519 @section Using a network installation of GNAT
27522 Make sure the system on which GNAT is installed is accessible from the
27523 current machine, i.e., the install location is shared over the network.
27524 Shared resources are accessed on Windows by means of UNC paths, which
27525 have the format @code{\\server\sharename\path}
27527 In order to use such a network installation, simply add the UNC path of the
27528 @file{bin} directory of your GNAT installation in front of your PATH. For
27529 example, if GNAT is installed in @file{\GNAT} directory of a share location
27530 called @file{c-drive} on a machine @file{LOKI}, the following command will
27533 @code{@ @ @ path \\loki\c-drive\gnat\bin;%path%}
27535 Be aware that every compilation using the network installation results in the
27536 transfer of large amounts of data across the network and will likely cause
27537 serious performance penalty.
27539 @node CONSOLE and WINDOWS subsystems
27540 @section CONSOLE and WINDOWS subsystems
27541 @cindex CONSOLE Subsystem
27542 @cindex WINDOWS Subsystem
27546 There are two main subsystems under Windows. The @code{CONSOLE} subsystem
27547 (which is the default subsystem) will always create a console when
27548 launching the application. This is not something desirable when the
27549 application has a Windows GUI. To get rid of this console the
27550 application must be using the @code{WINDOWS} subsystem. To do so
27551 the @option{-mwindows} linker option must be specified.
27554 $ gnatmake winprog -largs -mwindows
27557 @node Temporary Files
27558 @section Temporary Files
27559 @cindex Temporary files
27562 It is possible to control where temporary files gets created by setting
27563 the @env{TMP} environment variable. The file will be created:
27566 @item Under the directory pointed to by the @env{TMP} environment variable if
27567 this directory exists.
27569 @item Under @file{c:\temp}, if the @env{TMP} environment variable is not
27570 set (or not pointing to a directory) and if this directory exists.
27572 @item Under the current working directory otherwise.
27576 This allows you to determine exactly where the temporary
27577 file will be created. This is particularly useful in networked
27578 environments where you may not have write access to some
27581 @node Mixed-Language Programming on Windows
27582 @section Mixed-Language Programming on Windows
27585 Developing pure Ada applications on Windows is no different than on
27586 other GNAT-supported platforms. However, when developing or porting an
27587 application that contains a mix of Ada and C/C++, the choice of your
27588 Windows C/C++ development environment conditions your overall
27589 interoperability strategy.
27591 If you use @command{gcc} or Microsoft C to compile the non-Ada part of
27592 your application, there are no Windows-specific restrictions that
27593 affect the overall interoperability with your Ada code. If you do want
27594 to use the Microsoft tools for your C++ code, you have two choices:
27598 Encapsulate your C++ code in a DLL to be linked with your Ada
27599 application. In this case, use the Microsoft or whatever environment to
27600 build the DLL and use GNAT to build your executable
27601 (@pxref{Using DLLs with GNAT}).
27604 Or you can encapsulate your Ada code in a DLL to be linked with the
27605 other part of your application. In this case, use GNAT to build the DLL
27606 (@pxref{Building DLLs with GNAT Project files}) and use the Microsoft
27607 or whatever environment to build your executable.
27610 In addition to the description about C main in
27611 @pxref{Mixed Language Programming} section, if the C main uses a
27612 stand-alone library it is required on x86-windows to
27613 setup the SEH context. For this the C main must looks like this:
27617 extern void adainit (void);
27618 extern void adafinal (void);
27619 extern void __gnat_initialize(void*);
27620 extern void call_to_ada (void);
27622 int main (int argc, char *argv[])
27626 /* Initialize the SEH context */
27627 __gnat_initialize (&SEH);
27631 /* Then call Ada services in the stand-alone library */
27639 Note that this is not needed on x86_64-windows where the Windows
27640 native SEH support is used.
27642 @node Windows Calling Conventions
27643 @section Windows Calling Conventions
27647 This section pertain only to Win32. On Win64 there is a single native
27648 calling convention. All convention specifiers are ignored on this
27652 * C Calling Convention::
27653 * Stdcall Calling Convention::
27654 * Win32 Calling Convention::
27655 * DLL Calling Convention::
27659 When a subprogram @code{F} (caller) calls a subprogram @code{G}
27660 (callee), there are several ways to push @code{G}'s parameters on the
27661 stack and there are several possible scenarios to clean up the stack
27662 upon @code{G}'s return. A calling convention is an agreed upon software
27663 protocol whereby the responsibilities between the caller (@code{F}) and
27664 the callee (@code{G}) are clearly defined. Several calling conventions
27665 are available for Windows:
27669 @code{C} (Microsoft defined)
27672 @code{Stdcall} (Microsoft defined)
27675 @code{Win32} (GNAT specific)
27678 @code{DLL} (GNAT specific)
27681 @node C Calling Convention
27682 @subsection @code{C} Calling Convention
27685 This is the default calling convention used when interfacing to C/C++
27686 routines compiled with either @command{gcc} or Microsoft Visual C++.
27688 In the @code{C} calling convention subprogram parameters are pushed on the
27689 stack by the caller from right to left. The caller itself is in charge of
27690 cleaning up the stack after the call. In addition, the name of a routine
27691 with @code{C} calling convention is mangled by adding a leading underscore.
27693 The name to use on the Ada side when importing (or exporting) a routine
27694 with @code{C} calling convention is the name of the routine. For
27695 instance the C function:
27698 int get_val (long);
27702 should be imported from Ada as follows:
27704 @smallexample @c ada
27706 @b{function} Get_Val (V : Interfaces.C.long) @b{return} Interfaces.C.int;
27707 @b{pragma} Import (C, Get_Val, External_Name => "get_val");
27712 Note that in this particular case the @code{External_Name} parameter could
27713 have been omitted since, when missing, this parameter is taken to be the
27714 name of the Ada entity in lower case. When the @code{Link_Name} parameter
27715 is missing, as in the above example, this parameter is set to be the
27716 @code{External_Name} with a leading underscore.
27718 When importing a variable defined in C, you should always use the @code{C}
27719 calling convention unless the object containing the variable is part of a
27720 DLL (in which case you should use the @code{Stdcall} calling
27721 convention, @pxref{Stdcall Calling Convention}).
27723 @node Stdcall Calling Convention
27724 @subsection @code{Stdcall} Calling Convention
27727 This convention, which was the calling convention used for Pascal
27728 programs, is used by Microsoft for all the routines in the Win32 API for
27729 efficiency reasons. It must be used to import any routine for which this
27730 convention was specified.
27732 In the @code{Stdcall} calling convention subprogram parameters are pushed
27733 on the stack by the caller from right to left. The callee (and not the
27734 caller) is in charge of cleaning the stack on routine exit. In addition,
27735 the name of a routine with @code{Stdcall} calling convention is mangled by
27736 adding a leading underscore (as for the @code{C} calling convention) and a
27737 trailing @code{@@}@code{@var{nn}}, where @var{nn} is the overall size (in
27738 bytes) of the parameters passed to the routine.
27740 The name to use on the Ada side when importing a C routine with a
27741 @code{Stdcall} calling convention is the name of the C routine. The leading
27742 underscore and trailing @code{@@}@code{@var{nn}} are added automatically by
27743 the compiler. For instance the Win32 function:
27746 @b{APIENTRY} int get_val (long);
27750 should be imported from Ada as follows:
27752 @smallexample @c ada
27754 @b{function} Get_Val (V : Interfaces.C.long) @b{return} Interfaces.C.int;
27755 @b{pragma} Import (Stdcall, Get_Val);
27756 --@i{ On the x86 a long is 4 bytes, so the Link_Name is "_get_val@@4"}
27761 As for the @code{C} calling convention, when the @code{External_Name}
27762 parameter is missing, it is taken to be the name of the Ada entity in lower
27763 case. If instead of writing the above import pragma you write:
27765 @smallexample @c ada
27767 @b{function} Get_Val (V : Interfaces.C.long) @b{return} Interfaces.C.int;
27768 @b{pragma} Import (Stdcall, Get_Val, External_Name => "retrieve_val");
27773 then the imported routine is @code{_retrieve_val@@4}. However, if instead
27774 of specifying the @code{External_Name} parameter you specify the
27775 @code{Link_Name} as in the following example:
27777 @smallexample @c ada
27779 @b{function} Get_Val (V : Interfaces.C.long) @b{return} Interfaces.C.int;
27780 @b{pragma} Import (Stdcall, Get_Val, Link_Name => "retrieve_val");
27785 then the imported routine is @code{retrieve_val}, that is, there is no
27786 decoration at all. No leading underscore and no Stdcall suffix
27787 @code{@@}@code{@var{nn}}.
27790 This is especially important as in some special cases a DLL's entry
27791 point name lacks a trailing @code{@@}@code{@var{nn}} while the exported
27792 name generated for a call has it.
27795 It is also possible to import variables defined in a DLL by using an
27796 import pragma for a variable. As an example, if a DLL contains a
27797 variable defined as:
27804 then, to access this variable from Ada you should write:
27806 @smallexample @c ada
27808 My_Var : Interfaces.C.int;
27809 @b{pragma} Import (Stdcall, My_Var);
27814 Note that to ease building cross-platform bindings this convention
27815 will be handled as a @code{C} calling convention on non-Windows platforms.
27817 @node Win32 Calling Convention
27818 @subsection @code{Win32} Calling Convention
27821 This convention, which is GNAT-specific is fully equivalent to the
27822 @code{Stdcall} calling convention described above.
27824 @node DLL Calling Convention
27825 @subsection @code{DLL} Calling Convention
27828 This convention, which is GNAT-specific is fully equivalent to the
27829 @code{Stdcall} calling convention described above.
27831 @node Introduction to Dynamic Link Libraries (DLLs)
27832 @section Introduction to Dynamic Link Libraries (DLLs)
27836 A Dynamically Linked Library (DLL) is a library that can be shared by
27837 several applications running under Windows. A DLL can contain any number of
27838 routines and variables.
27840 One advantage of DLLs is that you can change and enhance them without
27841 forcing all the applications that depend on them to be relinked or
27842 recompiled. However, you should be aware than all calls to DLL routines are
27843 slower since, as you will understand below, such calls are indirect.
27845 To illustrate the remainder of this section, suppose that an application
27846 wants to use the services of a DLL @file{API.dll}. To use the services
27847 provided by @file{API.dll} you must statically link against the DLL or
27848 an import library which contains a jump table with an entry for each
27849 routine and variable exported by the DLL. In the Microsoft world this
27850 import library is called @file{API.lib}. When using GNAT this import
27851 library is called either @file{libAPI.dll.a}, @file{libapi.dll.a},
27852 @file{libAPI.a} or @file{libapi.a} (names are case insensitive).
27854 After you have linked your application with the DLL or the import library
27855 and you run your application, here is what happens:
27859 Your application is loaded into memory.
27862 The DLL @file{API.dll} is mapped into the address space of your
27863 application. This means that:
27867 The DLL will use the stack of the calling thread.
27870 The DLL will use the virtual address space of the calling process.
27873 The DLL will allocate memory from the virtual address space of the calling
27877 Handles (pointers) can be safely exchanged between routines in the DLL
27878 routines and routines in the application using the DLL.
27882 The entries in the jump table (from the import library @file{libAPI.dll.a}
27883 or @file{API.lib} or automatically created when linking against a DLL)
27884 which is part of your application are initialized with the addresses
27885 of the routines and variables in @file{API.dll}.
27888 If present in @file{API.dll}, routines @code{DllMain} or
27889 @code{DllMainCRTStartup} are invoked. These routines typically contain
27890 the initialization code needed for the well-being of the routines and
27891 variables exported by the DLL.
27895 There is an additional point which is worth mentioning. In the Windows
27896 world there are two kind of DLLs: relocatable and non-relocatable
27897 DLLs. Non-relocatable DLLs can only be loaded at a very specific address
27898 in the target application address space. If the addresses of two
27899 non-relocatable DLLs overlap and these happen to be used by the same
27900 application, a conflict will occur and the application will run
27901 incorrectly. Hence, when possible, it is always preferable to use and
27902 build relocatable DLLs. Both relocatable and non-relocatable DLLs are
27903 supported by GNAT. Note that the @option{-s} linker option (see GNU Linker
27904 User's Guide) removes the debugging symbols from the DLL but the DLL can
27905 still be relocated.
27907 As a side note, an interesting difference between Microsoft DLLs and
27908 Unix shared libraries, is the fact that on most Unix systems all public
27909 routines are exported by default in a Unix shared library, while under
27910 Windows it is possible (but not required) to list exported routines in
27911 a definition file (@pxref{The Definition File}).
27913 @node Using DLLs with GNAT
27914 @section Using DLLs with GNAT
27917 * Creating an Ada Spec for the DLL Services::
27918 * Creating an Import Library::
27922 To use the services of a DLL, say @file{API.dll}, in your Ada application
27927 The Ada spec for the routines and/or variables you want to access in
27928 @file{API.dll}. If not available this Ada spec must be built from the C/C++
27929 header files provided with the DLL.
27932 The import library (@file{libAPI.dll.a} or @file{API.lib}). As previously
27933 mentioned an import library is a statically linked library containing the
27934 import table which will be filled at load time to point to the actual
27935 @file{API.dll} routines. Sometimes you don't have an import library for the
27936 DLL you want to use. The following sections will explain how to build
27937 one. Note that this is optional.
27940 The actual DLL, @file{API.dll}.
27944 Once you have all the above, to compile an Ada application that uses the
27945 services of @file{API.dll} and whose main subprogram is @code{My_Ada_App},
27946 you simply issue the command
27949 $ gnatmake my_ada_app -largs -lAPI
27953 The argument @option{-largs -lAPI} at the end of the @command{gnatmake} command
27954 tells the GNAT linker to look for an import library. The linker will
27955 look for a library name in this specific order:
27958 @item @file{libAPI.dll.a}
27959 @item @file{API.dll.a}
27960 @item @file{libAPI.a}
27961 @item @file{API.lib}
27962 @item @file{libAPI.dll}
27963 @item @file{API.dll}
27966 The first three are the GNU style import libraries. The third is the
27967 Microsoft style import libraries. The last two are the actual DLL names.
27969 Note that if the Ada package spec for @file{API.dll} contains the
27972 @smallexample @c ada
27973 @b{pragma} Linker_Options ("-lAPI");
27977 you do not have to add @option{-largs -lAPI} at the end of the
27978 @command{gnatmake} command.
27980 If any one of the items above is missing you will have to create it
27981 yourself. The following sections explain how to do so using as an
27982 example a fictitious DLL called @file{API.dll}.
27984 @node Creating an Ada Spec for the DLL Services
27985 @subsection Creating an Ada Spec for the DLL Services
27988 A DLL typically comes with a C/C++ header file which provides the
27989 definitions of the routines and variables exported by the DLL. The Ada
27990 equivalent of this header file is a package spec that contains definitions
27991 for the imported entities. If the DLL you intend to use does not come with
27992 an Ada spec you have to generate one such spec yourself. For example if
27993 the header file of @file{API.dll} is a file @file{api.h} containing the
27994 following two definitions:
28006 then the equivalent Ada spec could be:
28008 @smallexample @c ada
28011 @b{with} Interfaces.C.Strings;
28012 @b{package} API @b{is}
28013 @b{use} Interfaces;
28016 @b{function} Get (Str : C.Strings.Chars_Ptr) @b{return} C.int;
28019 @b{pragma} Import (C, Get);
28020 @b{pragma} Import (DLL, Some_Var);
28026 @node Creating an Import Library
28027 @subsection Creating an Import Library
28028 @cindex Import library
28031 * The Definition File::
28032 * GNAT-Style Import Library::
28033 * Microsoft-Style Import Library::
28037 If a Microsoft-style import library @file{API.lib} or a GNAT-style
28038 import library @file{libAPI.dll.a} or @file{libAPI.a} is available
28039 with @file{API.dll} you can skip this section. You can also skip this
28040 section if @file{API.dll} or @file{libAPI.dll} is built with GNU tools
28041 as in this case it is possible to link directly against the
28042 DLL. Otherwise read on.
28044 @node The Definition File
28045 @subsubsection The Definition File
28046 @cindex Definition file
28050 As previously mentioned, and unlike Unix systems, the list of symbols
28051 that are exported from a DLL must be provided explicitly in Windows.
28052 The main goal of a definition file is precisely that: list the symbols
28053 exported by a DLL. A definition file (usually a file with a @code{.def}
28054 suffix) has the following structure:
28059 @r{[}LIBRARY @var{name}@r{]}
28060 @r{[}DESCRIPTION @var{string}@r{]}
28070 @item LIBRARY @var{name}
28071 This section, which is optional, gives the name of the DLL.
28073 @item DESCRIPTION @var{string}
28074 This section, which is optional, gives a description string that will be
28075 embedded in the import library.
28078 This section gives the list of exported symbols (procedures, functions or
28079 variables). For instance in the case of @file{API.dll} the @code{EXPORTS}
28080 section of @file{API.def} looks like:
28094 Note that you must specify the correct suffix (@code{@@}@code{@var{nn}})
28095 (@pxref{Windows Calling Conventions}) for a Stdcall
28096 calling convention function in the exported symbols list.
28099 There can actually be other sections in a definition file, but these
28100 sections are not relevant to the discussion at hand.
28102 @node GNAT-Style Import Library
28103 @subsubsection GNAT-Style Import Library
28106 To create a static import library from @file{API.dll} with the GNAT tools
28107 you should proceed as follows:
28111 Create the definition file @file{API.def} (@pxref{The Definition File}).
28112 For that use the @code{dll2def} tool as follows:
28115 $ dll2def API.dll > API.def
28119 @code{dll2def} is a very simple tool: it takes as input a DLL and prints
28120 to standard output the list of entry points in the DLL. Note that if
28121 some routines in the DLL have the @code{Stdcall} convention
28122 (@pxref{Windows Calling Conventions}) with stripped @code{@@}@var{nn}
28123 suffix then you'll have to edit @file{api.def} to add it, and specify
28124 @option{-k} to @command{gnatdll} when creating the import library.
28127 Here are some hints to find the right @code{@@}@var{nn} suffix.
28131 If you have the Microsoft import library (.lib), it is possible to get
28132 the right symbols by using Microsoft @code{dumpbin} tool (see the
28133 corresponding Microsoft documentation for further details).
28136 $ dumpbin /exports api.lib
28140 If you have a message about a missing symbol at link time the compiler
28141 tells you what symbol is expected. You just have to go back to the
28142 definition file and add the right suffix.
28146 Build the import library @code{libAPI.dll.a}, using @code{gnatdll}
28147 (@pxref{Using gnatdll}) as follows:
28150 $ gnatdll -e API.def -d API.dll
28154 @code{gnatdll} takes as input a definition file @file{API.def} and the
28155 name of the DLL containing the services listed in the definition file
28156 @file{API.dll}. The name of the static import library generated is
28157 computed from the name of the definition file as follows: if the
28158 definition file name is @var{xyz}@code{.def}, the import library name will
28159 be @code{lib}@var{xyz}@code{.a}. Note that in the previous example option
28160 @option{-e} could have been removed because the name of the definition
28161 file (before the ``@code{.def}'' suffix) is the same as the name of the
28162 DLL (@pxref{Using gnatdll} for more information about @code{gnatdll}).
28165 @node Microsoft-Style Import Library
28166 @subsubsection Microsoft-Style Import Library
28169 With GNAT you can either use a GNAT-style or Microsoft-style import
28170 library. A Microsoft import library is needed only if you plan to make an
28171 Ada DLL available to applications developed with Microsoft
28172 tools (@pxref{Mixed-Language Programming on Windows}).
28174 To create a Microsoft-style import library for @file{API.dll} you
28175 should proceed as follows:
28179 Create the definition file @file{API.def} from the DLL. For this use either
28180 the @code{dll2def} tool as described above or the Microsoft @code{dumpbin}
28181 tool (see the corresponding Microsoft documentation for further details).
28184 Build the actual import library using Microsoft's @code{lib} utility:
28187 $ lib -machine:IX86 -def:API.def -out:API.lib
28191 If you use the above command the definition file @file{API.def} must
28192 contain a line giving the name of the DLL:
28199 See the Microsoft documentation for further details about the usage of
28203 @node Building DLLs with GNAT Project files
28204 @section Building DLLs with GNAT Project files
28205 @cindex DLLs, building
28208 There is nothing specific to Windows in the build process.
28209 @pxref{Library Projects}.
28212 Due to a system limitation, it is not possible under Windows to create threads
28213 when inside the @code{DllMain} routine which is used for auto-initialization
28214 of shared libraries, so it is not possible to have library level tasks in SALs.
28216 @node Building DLLs with GNAT
28217 @section Building DLLs with GNAT
28218 @cindex DLLs, building
28221 This section explain how to build DLLs using the GNAT built-in DLL
28222 support. With the following procedure it is straight forward to build
28223 and use DLLs with GNAT.
28227 @item building object files
28229 The first step is to build all objects files that are to be included
28230 into the DLL. This is done by using the standard @command{gnatmake} tool.
28232 @item building the DLL
28234 To build the DLL you must use @command{gcc}'s @option{-shared} and
28235 @option{-shared-libgcc} options. It is quite simple to use this method:
28238 $ gcc -shared -shared-libgcc -o api.dll obj1.o obj2.o @dots{}
28241 It is important to note that in this case all symbols found in the
28242 object files are automatically exported. It is possible to restrict
28243 the set of symbols to export by passing to @command{gcc} a definition
28244 file, @pxref{The Definition File}. For example:
28247 $ gcc -shared -shared-libgcc -o api.dll api.def obj1.o obj2.o @dots{}
28250 If you use a definition file you must export the elaboration procedures
28251 for every package that required one. Elaboration procedures are named
28252 using the package name followed by "_E".
28254 @item preparing DLL to be used
28256 For the DLL to be used by client programs the bodies must be hidden
28257 from it and the .ali set with read-only attribute. This is very important
28258 otherwise GNAT will recompile all packages and will not actually use
28259 the code in the DLL. For example:
28263 $ copy *.ads *.ali api.dll apilib
28264 $ attrib +R apilib\*.ali
28269 At this point it is possible to use the DLL by directly linking
28270 against it. Note that you must use the GNAT shared runtime when using
28271 GNAT shared libraries. This is achieved by using @option{-shared} binder's
28275 $ gnatmake main -Iapilib -bargs -shared -largs -Lapilib -lAPI
28278 @node Building DLLs with gnatdll
28279 @section Building DLLs with gnatdll
28280 @cindex DLLs, building
28283 * Limitations When Using Ada DLLs from Ada::
28284 * Exporting Ada Entities::
28285 * Ada DLLs and Elaboration::
28286 * Ada DLLs and Finalization::
28287 * Creating a Spec for Ada DLLs::
28288 * Creating the Definition File::
28293 Note that it is preferred to use GNAT Project files
28294 (@pxref{Building DLLs with GNAT Project files}) or the built-in GNAT
28295 DLL support (@pxref{Building DLLs with GNAT}) or to build DLLs.
28297 This section explains how to build DLLs containing Ada code using
28298 @code{gnatdll}. These DLLs will be referred to as Ada DLLs in the
28299 remainder of this section.
28301 The steps required to build an Ada DLL that is to be used by Ada as well as
28302 non-Ada applications are as follows:
28306 You need to mark each Ada @i{entity} exported by the DLL with a @code{C} or
28307 @code{Stdcall} calling convention to avoid any Ada name mangling for the
28308 entities exported by the DLL (@pxref{Exporting Ada Entities}). You can
28309 skip this step if you plan to use the Ada DLL only from Ada applications.
28312 Your Ada code must export an initialization routine which calls the routine
28313 @code{adainit} generated by @command{gnatbind} to perform the elaboration of
28314 the Ada code in the DLL (@pxref{Ada DLLs and Elaboration}). The initialization
28315 routine exported by the Ada DLL must be invoked by the clients of the DLL
28316 to initialize the DLL.
28319 When useful, the DLL should also export a finalization routine which calls
28320 routine @code{adafinal} generated by @command{gnatbind} to perform the
28321 finalization of the Ada code in the DLL (@pxref{Ada DLLs and Finalization}).
28322 The finalization routine exported by the Ada DLL must be invoked by the
28323 clients of the DLL when the DLL services are no further needed.
28326 You must provide a spec for the services exported by the Ada DLL in each
28327 of the programming languages to which you plan to make the DLL available.
28330 You must provide a definition file listing the exported entities
28331 (@pxref{The Definition File}).
28334 Finally you must use @code{gnatdll} to produce the DLL and the import
28335 library (@pxref{Using gnatdll}).
28339 Note that a relocatable DLL stripped using the @code{strip}
28340 binutils tool will not be relocatable anymore. To build a DLL without
28341 debug information pass @code{-largs -s} to @code{gnatdll}. This
28342 restriction does not apply to a DLL built using a Library Project.
28343 @pxref{Library Projects}.
28345 @node Limitations When Using Ada DLLs from Ada
28346 @subsection Limitations When Using Ada DLLs from Ada
28349 When using Ada DLLs from Ada applications there is a limitation users
28350 should be aware of. Because on Windows the GNAT run time is not in a DLL of
28351 its own, each Ada DLL includes a part of the GNAT run time. Specifically,
28352 each Ada DLL includes the services of the GNAT run time that are necessary
28353 to the Ada code inside the DLL. As a result, when an Ada program uses an
28354 Ada DLL there are two independent GNAT run times: one in the Ada DLL and
28355 one in the main program.
28357 It is therefore not possible to exchange GNAT run-time objects between the
28358 Ada DLL and the main Ada program. Example of GNAT run-time objects are file
28359 handles (e.g.@: @code{Text_IO.File_Type}), tasks types, protected objects
28362 It is completely safe to exchange plain elementary, array or record types,
28363 Windows object handles, etc.
28365 @node Exporting Ada Entities
28366 @subsection Exporting Ada Entities
28367 @cindex Export table
28370 Building a DLL is a way to encapsulate a set of services usable from any
28371 application. As a result, the Ada entities exported by a DLL should be
28372 exported with the @code{C} or @code{Stdcall} calling conventions to avoid
28373 any Ada name mangling. As an example here is an Ada package
28374 @code{API}, spec and body, exporting two procedures, a function, and a
28377 @smallexample @c ada
28380 @b{with} Interfaces.C; @b{use} Interfaces;
28381 @b{package} API @b{is}
28382 Count : C.int := 0;
28383 @b{function} Factorial (Val : C.int) @b{return} C.int;
28385 @b{procedure} Initialize_API;
28386 @b{procedure} Finalize_API;
28387 --@i{ Initialization & Finalization routines. More in the next section.}
28389 @b{pragma} Export (C, Initialize_API);
28390 @b{pragma} Export (C, Finalize_API);
28391 @b{pragma} Export (C, Count);
28392 @b{pragma} Export (C, Factorial);
28398 @smallexample @c ada
28401 @b{package} @b{body} API @b{is}
28402 @b{function} Factorial (Val : C.int) @b{return} C.int @b{is}
28405 Count := Count + 1;
28406 @b{for} K @b{in} 1 .. Val @b{loop}
28412 @b{procedure} Initialize_API @b{is}
28413 @b{procedure} Adainit;
28414 @b{pragma} Import (C, Adainit);
28417 @b{end} Initialize_API;
28419 @b{procedure} Finalize_API @b{is}
28420 @b{procedure} Adafinal;
28421 @b{pragma} Import (C, Adafinal);
28424 @b{end} Finalize_API;
28431 If the Ada DLL you are building will only be used by Ada applications
28432 you do not have to export Ada entities with a @code{C} or @code{Stdcall}
28433 convention. As an example, the previous package could be written as
28436 @smallexample @c ada
28439 @b{package} API @b{is}
28440 Count : Integer := 0;
28441 @b{function} Factorial (Val : Integer) @b{return} Integer;
28443 @b{procedure} Initialize_API;
28444 @b{procedure} Finalize_API;
28445 --@i{ Initialization and Finalization routines.}
28451 @smallexample @c ada
28454 @b{package} @b{body} API @b{is}
28455 @b{function} Factorial (Val : Integer) @b{return} Integer @b{is}
28456 Fact : Integer := 1;
28458 Count := Count + 1;
28459 @b{for} K @b{in} 1 .. Val @b{loop}
28466 --@i{ The remainder of this package body is unchanged.}
28473 Note that if you do not export the Ada entities with a @code{C} or
28474 @code{Stdcall} convention you will have to provide the mangled Ada names
28475 in the definition file of the Ada DLL
28476 (@pxref{Creating the Definition File}).
28478 @node Ada DLLs and Elaboration
28479 @subsection Ada DLLs and Elaboration
28480 @cindex DLLs and elaboration
28483 The DLL that you are building contains your Ada code as well as all the
28484 routines in the Ada library that are needed by it. The first thing a
28485 user of your DLL must do is elaborate the Ada code
28486 (@pxref{Elaboration Order Handling in GNAT}).
28488 To achieve this you must export an initialization routine
28489 (@code{Initialize_API} in the previous example), which must be invoked
28490 before using any of the DLL services. This elaboration routine must call
28491 the Ada elaboration routine @code{adainit} generated by the GNAT binder
28492 (@pxref{Binding with Non-Ada Main Programs}). See the body of
28493 @code{Initialize_Api} for an example. Note that the GNAT binder is
28494 automatically invoked during the DLL build process by the @code{gnatdll}
28495 tool (@pxref{Using gnatdll}).
28497 When a DLL is loaded, Windows systematically invokes a routine called
28498 @code{DllMain}. It would therefore be possible to call @code{adainit}
28499 directly from @code{DllMain} without having to provide an explicit
28500 initialization routine. Unfortunately, it is not possible to call
28501 @code{adainit} from the @code{DllMain} if your program has library level
28502 tasks because access to the @code{DllMain} entry point is serialized by
28503 the system (that is, only a single thread can execute ``through'' it at a
28504 time), which means that the GNAT run time will deadlock waiting for the
28505 newly created task to complete its initialization.
28507 @node Ada DLLs and Finalization
28508 @subsection Ada DLLs and Finalization
28509 @cindex DLLs and finalization
28512 When the services of an Ada DLL are no longer needed, the client code should
28513 invoke the DLL finalization routine, if available. The DLL finalization
28514 routine is in charge of releasing all resources acquired by the DLL. In the
28515 case of the Ada code contained in the DLL, this is achieved by calling
28516 routine @code{adafinal} generated by the GNAT binder
28517 (@pxref{Binding with Non-Ada Main Programs}).
28518 See the body of @code{Finalize_Api} for an
28519 example. As already pointed out the GNAT binder is automatically invoked
28520 during the DLL build process by the @code{gnatdll} tool
28521 (@pxref{Using gnatdll}).
28523 @node Creating a Spec for Ada DLLs
28524 @subsection Creating a Spec for Ada DLLs
28527 To use the services exported by the Ada DLL from another programming
28528 language (e.g.@: C), you have to translate the specs of the exported Ada
28529 entities in that language. For instance in the case of @code{API.dll},
28530 the corresponding C header file could look like:
28535 extern int *_imp__count;
28536 #define count (*_imp__count)
28537 int factorial (int);
28543 It is important to understand that when building an Ada DLL to be used by
28544 other Ada applications, you need two different specs for the packages
28545 contained in the DLL: one for building the DLL and the other for using
28546 the DLL. This is because the @code{DLL} calling convention is needed to
28547 use a variable defined in a DLL, but when building the DLL, the variable
28548 must have either the @code{Ada} or @code{C} calling convention. As an
28549 example consider a DLL comprising the following package @code{API}:
28551 @smallexample @c ada
28554 @b{package} API @b{is}
28555 Count : Integer := 0;
28557 --@i{ Remainder of the package omitted.}
28564 After producing a DLL containing package @code{API}, the spec that
28565 must be used to import @code{API.Count} from Ada code outside of the
28568 @smallexample @c ada
28571 @b{package} API @b{is}
28573 @b{pragma} Import (DLL, Count);
28579 @node Creating the Definition File
28580 @subsection Creating the Definition File
28583 The definition file is the last file needed to build the DLL. It lists
28584 the exported symbols. As an example, the definition file for a DLL
28585 containing only package @code{API} (where all the entities are exported
28586 with a @code{C} calling convention) is:
28601 If the @code{C} calling convention is missing from package @code{API},
28602 then the definition file contains the mangled Ada names of the above
28603 entities, which in this case are:
28612 api__initialize_api
28617 @node Using gnatdll
28618 @subsection Using @code{gnatdll}
28622 * gnatdll Example::
28623 * gnatdll behind the Scenes::
28628 @code{gnatdll} is a tool to automate the DLL build process once all the Ada
28629 and non-Ada sources that make up your DLL have been compiled.
28630 @code{gnatdll} is actually in charge of two distinct tasks: build the
28631 static import library for the DLL and the actual DLL. The form of the
28632 @code{gnatdll} command is
28636 @c $ gnatdll @ovar{switches} @var{list-of-files} @r{[}-largs @var{opts}@r{]}
28637 @c Expanding @ovar macro inline (explanation in macro def comments)
28638 $ gnatdll @r{[}@var{switches}@r{]} @var{list-of-files} @r{[}-largs @var{opts}@r{]}
28643 where @var{list-of-files} is a list of ALI and object files. The object
28644 file list must be the exact list of objects corresponding to the non-Ada
28645 sources whose services are to be included in the DLL. The ALI file list
28646 must be the exact list of ALI files for the corresponding Ada sources
28647 whose services are to be included in the DLL. If @var{list-of-files} is
28648 missing, only the static import library is generated.
28651 You may specify any of the following switches to @code{gnatdll}:
28654 @c @item -a@ovar{address}
28655 @c Expanding @ovar macro inline (explanation in macro def comments)
28656 @item -a@r{[}@var{address}@r{]}
28657 @cindex @option{-a} (@code{gnatdll})
28658 Build a non-relocatable DLL at @var{address}. If @var{address} is not
28659 specified the default address @var{0x11000000} will be used. By default,
28660 when this switch is missing, @code{gnatdll} builds relocatable DLL. We
28661 advise the reader to build relocatable DLL.
28663 @item -b @var{address}
28664 @cindex @option{-b} (@code{gnatdll})
28665 Set the relocatable DLL base address. By default the address is
28668 @item -bargs @var{opts}
28669 @cindex @option{-bargs} (@code{gnatdll})
28670 Binder options. Pass @var{opts} to the binder.
28672 @item -d @var{dllfile}
28673 @cindex @option{-d} (@code{gnatdll})
28674 @var{dllfile} is the name of the DLL. This switch must be present for
28675 @code{gnatdll} to do anything. The name of the generated import library is
28676 obtained algorithmically from @var{dllfile} as shown in the following
28677 example: if @var{dllfile} is @code{xyz.dll}, the import library name is
28678 @code{libxyz.dll.a}. The name of the definition file to use (if not specified
28679 by option @option{-e}) is obtained algorithmically from @var{dllfile}
28680 as shown in the following example:
28681 if @var{dllfile} is @code{xyz.dll}, the definition
28682 file used is @code{xyz.def}.
28684 @item -e @var{deffile}
28685 @cindex @option{-e} (@code{gnatdll})
28686 @var{deffile} is the name of the definition file.
28689 @cindex @option{-g} (@code{gnatdll})
28690 Generate debugging information. This information is stored in the object
28691 file and copied from there to the final DLL file by the linker,
28692 where it can be read by the debugger. You must use the
28693 @option{-g} switch if you plan on using the debugger or the symbolic
28697 @cindex @option{-h} (@code{gnatdll})
28698 Help mode. Displays @code{gnatdll} switch usage information.
28701 @cindex @option{-I} (@code{gnatdll})
28702 Direct @code{gnatdll} to search the @var{dir} directory for source and
28703 object files needed to build the DLL.
28704 (@pxref{Search Paths and the Run-Time Library (RTL)}).
28707 @cindex @option{-k} (@code{gnatdll})
28708 Removes the @code{@@}@var{nn} suffix from the import library's exported
28709 names, but keeps them for the link names. You must specify this
28710 option if you want to use a @code{Stdcall} function in a DLL for which
28711 the @code{@@}@var{nn} suffix has been removed. This is the case for most
28712 of the Windows NT DLL for example. This option has no effect when
28713 @option{-n} option is specified.
28715 @item -l @var{file}
28716 @cindex @option{-l} (@code{gnatdll})
28717 The list of ALI and object files used to build the DLL are listed in
28718 @var{file}, instead of being given in the command line. Each line in
28719 @var{file} contains the name of an ALI or object file.
28722 @cindex @option{-n} (@code{gnatdll})
28723 No Import. Do not create the import library.
28726 @cindex @option{-q} (@code{gnatdll})
28727 Quiet mode. Do not display unnecessary messages.
28730 @cindex @option{-v} (@code{gnatdll})
28731 Verbose mode. Display extra information.
28733 @item -largs @var{opts}
28734 @cindex @option{-largs} (@code{gnatdll})
28735 Linker options. Pass @var{opts} to the linker.
28738 @node gnatdll Example
28739 @subsubsection @code{gnatdll} Example
28742 As an example the command to build a relocatable DLL from @file{api.adb}
28743 once @file{api.adb} has been compiled and @file{api.def} created is
28746 $ gnatdll -d api.dll api.ali
28750 The above command creates two files: @file{libapi.dll.a} (the import
28751 library) and @file{api.dll} (the actual DLL). If you want to create
28752 only the DLL, just type:
28755 $ gnatdll -d api.dll -n api.ali
28759 Alternatively if you want to create just the import library, type:
28762 $ gnatdll -d api.dll
28765 @node gnatdll behind the Scenes
28766 @subsubsection @code{gnatdll} behind the Scenes
28769 This section details the steps involved in creating a DLL. @code{gnatdll}
28770 does these steps for you. Unless you are interested in understanding what
28771 goes on behind the scenes, you should skip this section.
28773 We use the previous example of a DLL containing the Ada package @code{API},
28774 to illustrate the steps necessary to build a DLL. The starting point is a
28775 set of objects that will make up the DLL and the corresponding ALI
28776 files. In the case of this example this means that @file{api.o} and
28777 @file{api.ali} are available. To build a relocatable DLL, @code{gnatdll} does
28782 @code{gnatdll} builds the base file (@file{api.base}). A base file gives
28783 the information necessary to generate relocation information for the
28789 $ gnatlink api -o api.jnk -mdll -Wl,--base-file,api.base
28794 In addition to the base file, the @command{gnatlink} command generates an
28795 output file @file{api.jnk} which can be discarded. The @option{-mdll} switch
28796 asks @command{gnatlink} to generate the routines @code{DllMain} and
28797 @code{DllMainCRTStartup} that are called by the Windows loader when the DLL
28798 is loaded into memory.
28801 @code{gnatdll} uses @code{dlltool} (@pxref{Using dlltool}) to build the
28802 export table (@file{api.exp}). The export table contains the relocation
28803 information in a form which can be used during the final link to ensure
28804 that the Windows loader is able to place the DLL anywhere in memory.
28808 $ dlltool --dllname api.dll --def api.def --base-file api.base \
28809 --output-exp api.exp
28814 @code{gnatdll} builds the base file using the new export table. Note that
28815 @command{gnatbind} must be called once again since the binder generated file
28816 has been deleted during the previous call to @command{gnatlink}.
28821 $ gnatlink api -o api.jnk api.exp -mdll
28822 -Wl,--base-file,api.base
28827 @code{gnatdll} builds the new export table using the new base file and
28828 generates the DLL import library @file{libAPI.dll.a}.
28832 $ dlltool --dllname api.dll --def api.def --base-file api.base \
28833 --output-exp api.exp --output-lib libAPI.a
28838 Finally @code{gnatdll} builds the relocatable DLL using the final export
28844 $ gnatlink api api.exp -o api.dll -mdll
28849 @node Using dlltool
28850 @subsubsection Using @code{dlltool}
28853 @code{dlltool} is the low-level tool used by @code{gnatdll} to build
28854 DLLs and static import libraries. This section summarizes the most
28855 common @code{dlltool} switches. The form of the @code{dlltool} command
28859 @c $ dlltool @ovar{switches}
28860 @c Expanding @ovar macro inline (explanation in macro def comments)
28861 $ dlltool @r{[}@var{switches}@r{]}
28865 @code{dlltool} switches include:
28868 @item --base-file @var{basefile}
28869 @cindex @option{--base-file} (@command{dlltool})
28870 Read the base file @var{basefile} generated by the linker. This switch
28871 is used to create a relocatable DLL.
28873 @item --def @var{deffile}
28874 @cindex @option{--def} (@command{dlltool})
28875 Read the definition file.
28877 @item --dllname @var{name}
28878 @cindex @option{--dllname} (@command{dlltool})
28879 Gives the name of the DLL. This switch is used to embed the name of the
28880 DLL in the static import library generated by @code{dlltool} with switch
28881 @option{--output-lib}.
28884 @cindex @option{-k} (@command{dlltool})
28885 Kill @code{@@}@var{nn} from exported names
28886 (@pxref{Windows Calling Conventions}
28887 for a discussion about @code{Stdcall}-style symbols.
28890 @cindex @option{--help} (@command{dlltool})
28891 Prints the @code{dlltool} switches with a concise description.
28893 @item --output-exp @var{exportfile}
28894 @cindex @option{--output-exp} (@command{dlltool})
28895 Generate an export file @var{exportfile}. The export file contains the
28896 export table (list of symbols in the DLL) and is used to create the DLL.
28898 @item --output-lib @var{libfile}
28899 @cindex @option{--output-lib} (@command{dlltool})
28900 Generate a static import library @var{libfile}.
28903 @cindex @option{-v} (@command{dlltool})
28906 @item --as @var{assembler-name}
28907 @cindex @option{--as} (@command{dlltool})
28908 Use @var{assembler-name} as the assembler. The default is @code{as}.
28911 @node GNAT and Windows Resources
28912 @section GNAT and Windows Resources
28913 @cindex Resources, windows
28916 * Building Resources::
28917 * Compiling Resources::
28918 * Using Resources::
28922 Resources are an easy way to add Windows specific objects to your
28923 application. The objects that can be added as resources include:
28932 @item string tables
28942 @item version information
28945 For example, a version information resource can be defined as follow and
28946 embedded into an executable or DLL:
28948 A version information resource can be used to embed information into an
28949 executable or a DLL. These information can be viewed using the file properties
28950 from the Windows Explorer. Here is an example of a version information
28956 FILEVERSION 1,0,0,0
28957 PRODUCTVERSION 1,0,0,0
28959 BLOCK "StringFileInfo"
28963 VALUE "CompanyName", "My Company Name"
28964 VALUE "FileDescription", "My application"
28965 VALUE "FileVersion", "1.0"
28966 VALUE "InternalName", "my_app"
28967 VALUE "LegalCopyright", "My Name"
28968 VALUE "OriginalFilename", "my_app.exe"
28969 VALUE "ProductName", "My App"
28970 VALUE "ProductVersion", "1.0"
28974 BLOCK "VarFileInfo"
28976 VALUE "Translation", 0x809, 1252
28982 The value @code{0809} (langID) is for the U.K English language and
28983 @code{04E4} (charsetID), which is equal to @code{1252} decimal, for
28987 This section explains how to build, compile and use resources. Note that this
28988 section does not cover all resource objects, for a complete description see
28989 the corresponding Microsoft documentation.
28991 @node Building Resources
28992 @subsection Building Resources
28993 @cindex Resources, building
28996 A resource file is an ASCII file. By convention resource files have an
28997 @file{.rc} extension.
28998 The easiest way to build a resource file is to use Microsoft tools
28999 such as @code{imagedit.exe} to build bitmaps, icons and cursors and
29000 @code{dlgedit.exe} to build dialogs.
29001 It is always possible to build an @file{.rc} file yourself by writing a
29004 It is not our objective to explain how to write a resource file. A
29005 complete description of the resource script language can be found in the
29006 Microsoft documentation.
29008 @node Compiling Resources
29009 @subsection Compiling Resources
29012 @cindex Resources, compiling
29015 This section describes how to build a GNAT-compatible (COFF) object file
29016 containing the resources. This is done using the Resource Compiler
29017 @code{windres} as follows:
29020 $ windres -i myres.rc -o myres.o
29024 By default @code{windres} will run @command{gcc} to preprocess the @file{.rc}
29025 file. You can specify an alternate preprocessor (usually named
29026 @file{cpp.exe}) using the @code{windres} @option{--preprocessor}
29027 parameter. A list of all possible options may be obtained by entering
29028 the command @code{windres} @option{--help}.
29030 It is also possible to use the Microsoft resource compiler @code{rc.exe}
29031 to produce a @file{.res} file (binary resource file). See the
29032 corresponding Microsoft documentation for further details. In this case
29033 you need to use @code{windres} to translate the @file{.res} file to a
29034 GNAT-compatible object file as follows:
29037 $ windres -i myres.res -o myres.o
29040 @node Using Resources
29041 @subsection Using Resources
29042 @cindex Resources, using
29045 To include the resource file in your program just add the
29046 GNAT-compatible object file for the resource(s) to the linker
29047 arguments. With @command{gnatmake} this is done by using the @option{-largs}
29051 $ gnatmake myprog -largs myres.o
29054 @node Debugging a DLL
29055 @section Debugging a DLL
29056 @cindex DLL debugging
29059 * Program and DLL Both Built with GCC/GNAT::
29060 * Program Built with Foreign Tools and DLL Built with GCC/GNAT::
29064 Debugging a DLL is similar to debugging a standard program. But
29065 we have to deal with two different executable parts: the DLL and the
29066 program that uses it. We have the following four possibilities:
29070 The program and the DLL are built with @code{GCC/GNAT}.
29072 The program is built with foreign tools and the DLL is built with
29075 The program is built with @code{GCC/GNAT} and the DLL is built with
29080 In this section we address only cases one and two above.
29081 There is no point in trying to debug
29082 a DLL with @code{GNU/GDB}, if there is no GDB-compatible debugging
29083 information in it. To do so you must use a debugger compatible with the
29084 tools suite used to build the DLL.
29086 @node Program and DLL Both Built with GCC/GNAT
29087 @subsection Program and DLL Both Built with GCC/GNAT
29090 This is the simplest case. Both the DLL and the program have @code{GDB}
29091 compatible debugging information. It is then possible to break anywhere in
29092 the process. Let's suppose here that the main procedure is named
29093 @code{ada_main} and that in the DLL there is an entry point named
29097 The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) and
29098 program must have been built with the debugging information (see GNAT -g
29099 switch). Here are the step-by-step instructions for debugging it:
29102 @item Launch @code{GDB} on the main program.
29108 @item Start the program and stop at the beginning of the main procedure
29115 This step is required to be able to set a breakpoint inside the DLL. As long
29116 as the program is not run, the DLL is not loaded. This has the
29117 consequence that the DLL debugging information is also not loaded, so it is not
29118 possible to set a breakpoint in the DLL.
29120 @item Set a breakpoint inside the DLL
29123 (gdb) break ada_dll
29130 At this stage a breakpoint is set inside the DLL. From there on
29131 you can use the standard approach to debug the whole program
29132 (@pxref{Running and Debugging Ada Programs}).
29135 @c This used to work, probably because the DLLs were non-relocatable
29136 @c keep this section around until the problem is sorted out.
29138 To break on the @code{DllMain} routine it is not possible to follow
29139 the procedure above. At the time the program stop on @code{ada_main}
29140 the @code{DllMain} routine as already been called. Either you can use
29141 the procedure below @pxref{Debugging the DLL Directly} or this procedure:
29144 @item Launch @code{GDB} on the main program.
29150 @item Load DLL symbols
29153 (gdb) add-sym api.dll
29156 @item Set a breakpoint inside the DLL
29159 (gdb) break ada_dll.adb:45
29162 Note that at this point it is not possible to break using the routine symbol
29163 directly as the program is not yet running. The solution is to break
29164 on the proper line (break in @file{ada_dll.adb} line 45).
29166 @item Start the program
29175 @node Program Built with Foreign Tools and DLL Built with GCC/GNAT
29176 @subsection Program Built with Foreign Tools and DLL Built with GCC/GNAT
29179 * Debugging the DLL Directly::
29180 * Attaching to a Running Process::
29184 In this case things are slightly more complex because it is not possible to
29185 start the main program and then break at the beginning to load the DLL and the
29186 associated DLL debugging information. It is not possible to break at the
29187 beginning of the program because there is no @code{GDB} debugging information,
29188 and therefore there is no direct way of getting initial control. This
29189 section addresses this issue by describing some methods that can be used
29190 to break somewhere in the DLL to debug it.
29193 First suppose that the main procedure is named @code{main} (this is for
29194 example some C code built with Microsoft Visual C) and that there is a
29195 DLL named @code{test.dll} containing an Ada entry point named
29199 The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) must have
29200 been built with debugging information (see GNAT -g option).
29202 @node Debugging the DLL Directly
29203 @subsubsection Debugging the DLL Directly
29207 Find out the executable starting address
29210 $ objdump --file-header main.exe
29213 The starting address is reported on the last line. For example:
29216 main.exe: file format pei-i386
29217 architecture: i386, flags 0x0000010a:
29218 EXEC_P, HAS_DEBUG, D_PAGED
29219 start address 0x00401010
29223 Launch the debugger on the executable.
29230 Set a breakpoint at the starting address, and launch the program.
29233 $ (gdb) break *0x00401010
29237 The program will stop at the given address.
29240 Set a breakpoint on a DLL subroutine.
29243 (gdb) break ada_dll.adb:45
29246 Or if you want to break using a symbol on the DLL, you need first to
29247 select the Ada language (language used by the DLL).
29250 (gdb) set language ada
29251 (gdb) break ada_dll
29255 Continue the program.
29262 This will run the program until it reaches the breakpoint that has been
29263 set. From that point you can use the standard way to debug a program
29264 as described in (@pxref{Running and Debugging Ada Programs}).
29269 It is also possible to debug the DLL by attaching to a running process.
29271 @node Attaching to a Running Process
29272 @subsubsection Attaching to a Running Process
29273 @cindex DLL debugging, attach to process
29276 With @code{GDB} it is always possible to debug a running process by
29277 attaching to it. It is possible to debug a DLL this way. The limitation
29278 of this approach is that the DLL must run long enough to perform the
29279 attach operation. It may be useful for instance to insert a time wasting
29280 loop in the code of the DLL to meet this criterion.
29284 @item Launch the main program @file{main.exe}.
29290 @item Use the Windows @i{Task Manager} to find the process ID. Let's say
29291 that the process PID for @file{main.exe} is 208.
29299 @item Attach to the running process to be debugged.
29305 @item Load the process debugging information.
29308 (gdb) symbol-file main.exe
29311 @item Break somewhere in the DLL.
29314 (gdb) break ada_dll
29317 @item Continue process execution.
29326 This last step will resume the process execution, and stop at
29327 the breakpoint we have set. From there you can use the standard
29328 approach to debug a program as described in
29329 (@pxref{Running and Debugging Ada Programs}).
29331 @node Setting Stack Size from gnatlink
29332 @section Setting Stack Size from @command{gnatlink}
29335 It is possible to specify the program stack size at link time. On modern
29336 versions of Windows, starting with XP, this is mostly useful to set the size of
29337 the main stack (environment task). The other task stacks are set with pragma
29338 Storage_Size or with the @command{gnatbind -d} command.
29340 Since older versions of Windows (2000, NT4, etc.) do not allow setting the
29341 reserve size of individual tasks, the link-time stack size applies to all
29342 tasks, and pragma Storage_Size has no effect.
29343 In particular, Stack Overflow checks are made against this
29344 link-time specified size.
29346 This setting can be done with
29347 @command{gnatlink} using either:
29351 @item using @option{-Xlinker} linker option
29354 $ gnatlink hello -Xlinker --stack=0x10000,0x1000
29357 This sets the stack reserve size to 0x10000 bytes and the stack commit
29358 size to 0x1000 bytes.
29360 @item using @option{-Wl} linker option
29363 $ gnatlink hello -Wl,--stack=0x1000000
29366 This sets the stack reserve size to 0x1000000 bytes. Note that with
29367 @option{-Wl} option it is not possible to set the stack commit size
29368 because the coma is a separator for this option.
29372 @node Setting Heap Size from gnatlink
29373 @section Setting Heap Size from @command{gnatlink}
29376 Under Windows systems, it is possible to specify the program heap size from
29377 @command{gnatlink} using either:
29381 @item using @option{-Xlinker} linker option
29384 $ gnatlink hello -Xlinker --heap=0x10000,0x1000
29387 This sets the heap reserve size to 0x10000 bytes and the heap commit
29388 size to 0x1000 bytes.
29390 @item using @option{-Wl} linker option
29393 $ gnatlink hello -Wl,--heap=0x1000000
29396 This sets the heap reserve size to 0x1000000 bytes. Note that with
29397 @option{-Wl} option it is not possible to set the heap commit size
29398 because the coma is a separator for this option.
29402 @node Mac OS Topics
29403 @appendix Mac OS Topics
29407 This chapter describes topics that are specific to Apple's OS X
29411 * Codesigning the Debugger::
29414 @node Codesigning the Debugger
29415 @section Codesigning the Debugger
29418 The Darwin Kernel requires the debugger to have special permissions
29419 before it is allowed to control other processes. These permissions
29420 are granted by codesigning the GDB executable. Without these
29421 permissions, the debugger will report error messages such as:
29424 Starting program: /x/y/foo
29425 Unable to find Mach task port for process-id 28885: (os/kern) failure (0x5).
29426 (please check gdb is codesigned - see taskgated(8))
29429 Codesigning requires a certificate. The following procedure explains
29433 @item Start the Keychain Access application (in
29434 /Applications/Utilities/Keychain Access.app)
29436 @item Select the Keychain Access -> Certificate Assistant ->
29437 Create a Certificate... menu
29442 @item Choose a name for the new certificate (this procedure will use
29443 "gdb-cert" as an example)
29445 @item Set "Identity Type" to "Self Signed Root"
29447 @item Set "Certificate Type" to "Code Signing"
29449 @item Activate the "Let me override defaults" option
29453 @item Click several times on "Continue" until the "Specify a Location
29454 For The Certificate" screen appears, then set "Keychain" to "System"
29456 @item Click on "Continue" until the certificate is created
29458 @item Finally, in the view, double-click on the new certificate,
29459 and set "When using this certificate" to "Always Trust"
29461 @item Exit the Keychain Access application and restart the computer
29462 (this is unfortunately required)
29466 Once a certificate has been created, the debugger can be codesigned
29467 as follow. In a Terminal, run the following command...
29470 codesign -f -s "gdb-cert" <gnat_install_prefix>/bin/gdb
29473 ... where "gdb-cert" should be replaced by the actual certificate
29474 name chosen above, and <gnat_install_prefix> should be replaced by
29475 the location where you installed GNAT. Also, be sure that users are
29476 in the Unix group @samp{_developer}.
29478 @c **********************************
29479 @c * GNU Free Documentation License *
29480 @c **********************************
29482 @c GNU Free Documentation License
29490 @c Put table of contents at end, otherwise it precedes the "title page" in
29491 @c the .txt version
29492 @c Edit the pdf file to move the contents to the beginning, after the title