1 \input texinfo @c -*-texinfo-*-
4 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
6 @c GNAT DOCUMENTATION o
10 @c Copyright (C) 1992-2013, Free Software Foundation, Inc. o
12 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
14 @setfilename gnat_ugn.info
17 Copyright @copyright{} 1995-2009 Free Software Foundation,
20 Permission is granted to copy, distribute and/or modify this document
21 under the terms of the GNU Free Documentation License, Version 1.3 or
22 any later version published by the Free Software Foundation; with no
23 Invariant Sections, with no Front-Cover Texts and with no Back-Cover
24 Texts. A copy of the license is included in the section entitled
25 ``GNU Free Documentation License''.
28 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
30 @c GNAT_UGN Style Guide
32 @c 1. Always put a @noindent on the line before the first paragraph
33 @c after any of these commands:
45 @c 2. DO NOT use @example. Use @smallexample instead.
46 @c a) DO NOT use highlighting commands (@b{}, @i{}) inside an @smallexample
47 @c context. These can interfere with the readability of the texi
48 @c source file. Instead, use one of the following annotated
49 @c @smallexample commands, and preprocess the texi file with the
50 @c ada2texi tool (which generates appropriate highlighting):
51 @c @smallexample @c ada
52 @c @smallexample @c adanocomment
53 @c @smallexample @c projectfile
54 @c b) The "@c ada" markup will result in boldface for reserved words
55 @c and italics for comments
56 @c c) The "@c adanocomment" markup will result only in boldface for
57 @c reserved words (comments are left alone)
58 @c d) The "@c projectfile" markup is like "@c ada" except that the set
59 @c of reserved words include the new reserved words for project files
61 @c 3. Each @chapter, @section, @subsection, @subsubsection, etc.
62 @c command must be preceded by two empty lines
64 @c 4. The @item command should be on a line of its own if it is in an
65 @c @itemize or @enumerate command.
67 @c 5. When talking about ALI files use "ALI" (all uppercase), not "Ali"
70 @c 6. DO NOT put trailing spaces at the end of a line. Such spaces will
71 @c cause the document build to fail.
73 @c 7. DO NOT use @cartouche for examples that are longer than around 10 lines.
74 @c This command inhibits page breaks, so long examples in a @cartouche can
75 @c lead to large, ugly patches of empty space on a page.
77 @c NOTE: This file should be submitted to xgnatugn with either the vms flag
78 @c or the unw flag set. The unw flag covers topics for both Unix and
81 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
84 @c This flag is used where the text refers to conditions that exist when the
85 @c text was entered into the document but which may change over time.
86 @c Update the setting for the flag, and (if necessary) the text surrounding,
87 @c the references to the flag, on future doc revisions:
88 @c search for @value{NOW}.
100 @set TITLESUFFIX for OpenVMS
105 @c The ARG is an optional argument. To be used for macro arguments in
106 @c their documentation (@defmac).
108 @r{[}@var{\varname\}@r{]}@c
110 @c Status as of November 2009:
111 @c Unfortunately texi2pdf and texi2html treat the trailing "@c"
112 @c differently, and faulty output is produced by one or the other
113 @c depending on whether the "@c" is present or absent.
114 @c As a result, the @ovar macro is not used, and all invocations
115 @c of the @ovar macro have been expanded inline.
118 @settitle @value{EDITION} User's Guide @value{TITLESUFFIX}
119 @dircategory GNU Ada tools
121 * @value{EDITION} User's Guide: (gnat_ugn). @value{PLATFORM}
124 @include gcc-common.texi
126 @setchapternewpage odd
131 @title @value{EDITION} User's Guide
135 @titlefont{@i{@value{PLATFORM}}}
141 @subtitle GNAT, The GNU Ada Compiler
146 @vskip 0pt plus 1filll
153 @node Top, About This Guide, (dir), (dir)
154 @top @value{EDITION} User's Guide
157 @value{EDITION} User's Guide @value{PLATFORM}
160 GNAT, The GNU Ada Compiler@*
161 GCC version @value{version-GCC}@*
168 * Getting Started with GNAT::
169 * The GNAT Compilation Model::
170 * Compiling with gcc::
171 * Binding with gnatbind::
172 * Linking with gnatlink::
173 * The GNAT Make Program gnatmake::
174 * Improving Performance::
175 * Renaming Files with gnatchop::
176 * Configuration Pragmas::
177 * Handling Arbitrary File Naming Conventions with gnatname::
178 * GNAT Project Manager::
179 * Tools Supporting Project Files::
180 * The Cross-Referencing Tools gnatxref and gnatfind::
181 * The GNAT Pretty-Printer gnatpp::
183 * The Ada-to-XML converter gnat2xml::
185 * The GNAT Metrics Tool gnatmetric::
186 * File Name Krunching with gnatkr::
187 * Preprocessing with gnatprep::
188 * The GNAT Library Browser gnatls::
189 * Cleaning Up with gnatclean::
191 * GNAT and Libraries::
192 * Using the GNU make Utility::
194 * Memory Management Issues::
195 * Stack Related Facilities::
196 * Verifying Properties with gnatcheck::
197 * Creating Sample Bodies with gnatstub::
198 * Creating Unit Tests with gnattest::
199 * Performing Dimensionality Analysis in GNAT::
200 * Generating Ada Bindings for C and C++ headers::
201 * Other Utility Programs::
203 * Code Coverage and Profiling::
205 * Running and Debugging Ada Programs::
207 * Compatibility with HP Ada::
209 * Platform-Specific Information for the Run-Time Libraries::
210 * Example of Binder Output File::
211 * Elaboration Order Handling in GNAT::
212 * Overflow Check Handling in GNAT::
213 * Conditional Compilation::
215 * Compatibility and Porting Guide::
216 * Microsoft Windows Topics::
218 * GNU Free Documentation License::
223 @node About This Guide
224 @unnumbered About This Guide
228 This guide describes the use of @value{EDITION},
229 a compiler and software development toolset for the full Ada
230 programming language, implemented on OpenVMS for HP's Alpha and
231 Integrity server (I64) platforms.
234 This guide describes the use of @value{EDITION},
235 a compiler and software development
236 toolset for the full Ada programming language.
238 It documents the features of the compiler and tools, and explains
239 how to use them to build Ada applications.
241 @value{EDITION} implements Ada 95, Ada 2005 and Ada 2012, and it may also be
242 invoked in Ada 83 compatibility mode.
243 By default, @value{EDITION} assumes Ada 2012, but you can override with a
244 compiler switch (@pxref{Compiling Different Versions of Ada})
245 to explicitly specify the language version.
246 Throughout this manual, references to ``Ada'' without a year suffix
247 apply to all Ada 95/2005/2012 versions of the language.
250 For ease of exposition, ``@value{EDITION}'' will be referred to simply as
251 ``GNAT'' in the remainder of this document.
256 * What This Guide Contains::
257 * What You Should Know before Reading This Guide::
258 * Related Information::
262 @node What This Guide Contains
263 @unnumberedsec What This Guide Contains
266 This guide contains the following chapters:
270 @ref{Getting Started with GNAT}, describes how to get started compiling
271 and running Ada programs with the GNAT Ada programming environment.
273 @ref{The GNAT Compilation Model}, describes the compilation model used
277 @ref{Compiling with gcc}, describes how to compile
278 Ada programs with @command{gcc}, the Ada compiler.
281 @ref{Binding with gnatbind}, describes how to
282 perform binding of Ada programs with @code{gnatbind}, the GNAT binding
286 @ref{Linking with gnatlink},
287 describes @command{gnatlink}, a
288 program that provides for linking using the GNAT run-time library to
289 construct a program. @command{gnatlink} can also incorporate foreign language
290 object units into the executable.
293 @ref{The GNAT Make Program gnatmake}, describes @command{gnatmake}, a
294 utility that automatically determines the set of sources
295 needed by an Ada compilation unit, and executes the necessary compilations
299 @ref{Improving Performance}, shows various techniques for making your
300 Ada program run faster or take less space.
301 It discusses the effect of the compiler's optimization switch and
302 also describes the @command{gnatelim} tool and unused subprogram/data
306 @ref{Renaming Files with gnatchop}, describes
307 @code{gnatchop}, a utility that allows you to preprocess a file that
308 contains Ada source code, and split it into one or more new files, one
309 for each compilation unit.
312 @ref{Configuration Pragmas}, describes the configuration pragmas
316 @ref{Handling Arbitrary File Naming Conventions with gnatname},
317 shows how to override the default GNAT file naming conventions,
318 either for an individual unit or globally.
321 @ref{GNAT Project Manager}, describes how to use project files
322 to organize large projects.
325 @ref{The Cross-Referencing Tools gnatxref and gnatfind}, discusses
326 @code{gnatxref} and @code{gnatfind}, two tools that provide an easy
327 way to navigate through sources.
330 @ref{The GNAT Pretty-Printer gnatpp}, shows how to produce a reformatted
331 version of an Ada source file with control over casing, indentation,
332 comment placement, and other elements of program presentation style.
336 @ref{The Ada-to-XML converter gnat2xml}, shows how to convert Ada
337 source code into XML.
341 @ref{The GNAT Metrics Tool gnatmetric}, shows how to compute various
342 metrics for an Ada source file, such as the number of types and subprograms,
343 and assorted complexity measures.
346 @ref{File Name Krunching with gnatkr}, describes the @code{gnatkr}
347 file name krunching utility, used to handle shortened
348 file names on operating systems with a limit on the length of names.
351 @ref{Preprocessing with gnatprep}, describes @code{gnatprep}, a
352 preprocessor utility that allows a single source file to be used to
353 generate multiple or parameterized source files by means of macro
357 @ref{The GNAT Library Browser gnatls}, describes @code{gnatls}, a
358 utility that displays information about compiled units, including dependences
359 on the corresponding sources files, and consistency of compilations.
362 @ref{Cleaning Up with gnatclean}, describes @code{gnatclean}, a utility
363 to delete files that are produced by the compiler, binder and linker.
367 @ref{GNAT and Libraries}, describes the process of creating and using
368 Libraries with GNAT. It also describes how to recompile the GNAT run-time
372 @ref{Using the GNU make Utility}, describes some techniques for using
373 the GNAT toolset in Makefiles.
377 @ref{Memory Management Issues}, describes some useful predefined storage pools
378 and in particular the GNAT Debug Pool facility, which helps detect incorrect
381 It also describes @command{gnatmem}, a utility that monitors dynamic
382 allocation and deallocation and helps detect ``memory leaks''.
386 @ref{Stack Related Facilities}, describes some useful tools associated with
387 stack checking and analysis.
390 @ref{Verifying Properties with gnatcheck}, discusses @code{gnatcheck},
391 a utility that checks Ada code against a set of rules.
394 @ref{Creating Sample Bodies with gnatstub}, discusses @code{gnatstub},
395 a utility that generates empty but compilable bodies for library units.
398 @ref{Creating Unit Tests with gnattest}, discusses @code{gnattest},
399 a utility that generates unit testing templates for library units.
402 @ref{Performing Dimensionality Analysis in GNAT}, describes the Ada 2012
403 facilities used in GNAT to declare dimensioned objects, and to verify that
404 uses of these objects are consistent with their given physical dimensions
405 (so that meters cannot be assigned to kilograms, and so on).
408 @ref{Generating Ada Bindings for C and C++ headers}, describes how to
409 generate automatically Ada bindings from C and C++ headers.
412 @ref{Other Utility Programs}, discusses several other GNAT utilities,
413 including @code{gnathtml}.
417 @ref{Code Coverage and Profiling}, describes how to perform a structural
418 coverage and profile the execution of Ada programs.
422 @ref{Running and Debugging Ada Programs}, describes how to run and debug
427 @ref{Compatibility with HP Ada}, details the compatibility of GNAT with
428 HP Ada 83 @footnote{``HP Ada'' refers to the legacy product originally
429 developed by Digital Equipment Corporation and currently supported by HP.}
430 for OpenVMS Alpha. This product was formerly known as DEC Ada,
433 historical compatibility reasons, the relevant libraries still use the
438 @ref{Platform-Specific Information for the Run-Time Libraries},
439 describes the various run-time
440 libraries supported by GNAT on various platforms and explains how to
441 choose a particular library.
444 @ref{Example of Binder Output File}, shows the source code for the binder
445 output file for a sample program.
448 @ref{Elaboration Order Handling in GNAT}, describes how GNAT helps
449 you deal with elaboration order issues.
452 @ref{Overflow Check Handling in GNAT}, describes how GNAT helps
453 you deal with arithmetic overflow issues.
456 @ref{Conditional Compilation}, describes how to model conditional compilation,
457 both with Ada in general and with GNAT facilities in particular.
460 @ref{Inline Assembler}, shows how to use the inline assembly facility
464 @ref{Compatibility and Porting Guide}, contains sections on compatibility
465 of GNAT with other Ada development environments (including Ada 83 systems),
466 to assist in porting code from those environments.
470 @ref{Microsoft Windows Topics}, presents information relevant to the
471 Microsoft Windows platform.
474 @ref{Mac OS Topics}, presents information relevant to Apple's OS X
479 @c *************************************************
480 @node What You Should Know before Reading This Guide
481 @c *************************************************
482 @unnumberedsec What You Should Know before Reading This Guide
484 @cindex Ada 95 Language Reference Manual
485 @cindex Ada 2005 Language Reference Manual
487 This guide assumes a basic familiarity with the Ada 95 language, as
488 described in the International Standard ANSI/ISO/IEC-8652:1995, January
490 It does not require knowledge of the new features introduced by Ada 2005,
491 (officially known as ISO/IEC 8652:1995 with Technical Corrigendum 1
493 Both reference manuals are included in the GNAT documentation
496 @node Related Information
497 @unnumberedsec Related Information
500 For further information about related tools, refer to the following
505 @xref{Top, GNAT Reference Manual, About This Guide, gnat_rm, GNAT
506 Reference Manual}, which contains all reference material for the GNAT
507 implementation of Ada.
511 @cite{Using the GNAT Programming Studio}, which describes the GPS
512 Integrated Development Environment.
515 @cite{GNAT Programming Studio Tutorial}, which introduces the
516 main GPS features through examples.
520 @cite{Ada 95 Reference Manual}, which contains reference
521 material for the Ada 95 programming language.
524 @cite{Ada 2005 Reference Manual}, which contains reference
525 material for the Ada 2005 programming language.
528 @xref{Top,, Debugging with GDB, gdb, Debugging with GDB},
530 in the GNU:[DOCS] directory,
532 for all details on the use of the GNU source-level debugger.
535 @xref{Top,, The extensible self-documenting text editor, emacs,
538 located in the GNU:[DOCS] directory if the EMACS kit is installed,
540 for full information on the extensible editor and programming
547 @unnumberedsec Conventions
549 @cindex Typographical conventions
552 Following are examples of the typographical and graphic conventions used
557 @code{Functions}, @command{utility program names}, @code{standard names},
561 @option{Option flags}
564 @file{File names}, @samp{button names}, and @samp{field names}.
567 @code{Variables}, @env{environment variables}, and @var{metasyntactic
574 @r{[}optional information or parameters@r{]}
577 Examples are described by text
579 and then shown this way.
584 Commands that are entered by the user are preceded in this manual by the
585 characters @w{``@code{$ }''} (dollar sign followed by space). If your system
586 uses this sequence as a prompt, then the commands will appear exactly as
587 you see them in the manual. If your system uses some other prompt, then
588 the command will appear with the @code{$} replaced by whatever prompt
589 character you are using.
592 Full file names are shown with the ``@code{/}'' character
593 as the directory separator; e.g., @file{parent-dir/subdir/myfile.adb}.
594 If you are using GNAT on a Windows platform, please note that
595 the ``@code{\}'' character should be used instead.
598 @c ****************************
599 @node Getting Started with GNAT
600 @chapter Getting Started with GNAT
603 This chapter describes some simple ways of using GNAT to build
604 executable Ada programs.
606 @ref{Running GNAT}, through @ref{Using the gnatmake Utility},
607 show how to use the command line environment.
608 @ref{Introduction to GPS}, provides a brief
609 introduction to the GNAT Programming Studio, a visually-oriented
610 Integrated Development Environment for GNAT.
611 GPS offers a graphical ``look and feel'', support for development in
612 other programming languages, comprehensive browsing features, and
613 many other capabilities.
614 For information on GPS please refer to
615 @cite{Using the GNAT Programming Studio}.
620 * Running a Simple Ada Program::
621 * Running a Program with Multiple Units::
622 * Using the gnatmake Utility::
624 * Editing with Emacs::
627 * Introduction to GPS::
632 @section Running GNAT
635 Three steps are needed to create an executable file from an Ada source
640 The source file(s) must be compiled.
642 The file(s) must be bound using the GNAT binder.
644 All appropriate object files must be linked to produce an executable.
648 All three steps are most commonly handled by using the @command{gnatmake}
649 utility program that, given the name of the main program, automatically
650 performs the necessary compilation, binding and linking steps.
652 @node Running a Simple Ada Program
653 @section Running a Simple Ada Program
656 Any text editor may be used to prepare an Ada program.
658 used, the optional Ada mode may be helpful in laying out the program.)
660 program text is a normal text file. We will assume in our initial
661 example that you have used your editor to prepare the following
662 standard format text file:
666 with Ada.Text_IO; use Ada.Text_IO;
669 Put_Line ("Hello WORLD!");
675 This file should be named @file{hello.adb}.
676 With the normal default file naming conventions, GNAT requires
678 contain a single compilation unit whose file name is the
680 with periods replaced by hyphens; the
681 extension is @file{ads} for a
682 spec and @file{adb} for a body.
683 You can override this default file naming convention by use of the
684 special pragma @code{Source_File_Name} (@pxref{Using Other File Names}).
685 Alternatively, if you want to rename your files according to this default
686 convention, which is probably more convenient if you will be using GNAT
687 for all your compilations, then the @code{gnatchop} utility
688 can be used to generate correctly-named source files
689 (@pxref{Renaming Files with gnatchop}).
691 You can compile the program using the following command (@code{$} is used
692 as the command prompt in the examples in this document):
699 @command{gcc} is the command used to run the compiler. This compiler is
700 capable of compiling programs in several languages, including Ada and
701 C. It assumes that you have given it an Ada program if the file extension is
702 either @file{.ads} or @file{.adb}, and it will then call
703 the GNAT compiler to compile the specified file.
706 The @option{-c} switch is required. It tells @command{gcc} to only do a
707 compilation. (For C programs, @command{gcc} can also do linking, but this
708 capability is not used directly for Ada programs, so the @option{-c}
709 switch must always be present.)
712 This compile command generates a file
713 @file{hello.o}, which is the object
714 file corresponding to your Ada program. It also generates
715 an ``Ada Library Information'' file @file{hello.ali},
716 which contains additional information used to check
717 that an Ada program is consistent.
718 To build an executable file,
719 use @code{gnatbind} to bind the program
720 and @command{gnatlink} to link it. The
721 argument to both @code{gnatbind} and @command{gnatlink} is the name of the
722 @file{ALI} file, but the default extension of @file{.ali} can
723 be omitted. This means that in the most common case, the argument
724 is simply the name of the main program:
732 A simpler method of carrying out these steps is to use
734 a master program that invokes all the required
735 compilation, binding and linking tools in the correct order. In particular,
736 @command{gnatmake} automatically recompiles any sources that have been
737 modified since they were last compiled, or sources that depend
738 on such modified sources, so that ``version skew'' is avoided.
739 @cindex Version skew (avoided by @command{gnatmake})
746 The result is an executable program called @file{hello}, which can be
754 assuming that the current directory is on the search path
755 for executable programs.
758 and, if all has gone well, you will see
765 appear in response to this command.
767 @c ****************************************
768 @node Running a Program with Multiple Units
769 @section Running a Program with Multiple Units
772 Consider a slightly more complicated example that has three files: a
773 main program, and the spec and body of a package:
783 with Ada.Text_IO; use Ada.Text_IO;
784 package body Greetings is
787 Put_Line ("Hello WORLD!");
792 Put_Line ("Goodbye WORLD!");
809 Following the one-unit-per-file rule, place this program in the
810 following three separate files:
814 spec of package @code{Greetings}
817 body of package @code{Greetings}
824 To build an executable version of
825 this program, we could use four separate steps to compile, bind, and link
826 the program, as follows:
830 $ gcc -c greetings.adb
836 Note that there is no required order of compilation when using GNAT.
837 In particular it is perfectly fine to compile the main program first.
838 Also, it is not necessary to compile package specs in the case where
839 there is an accompanying body; you only need to compile the body. If you want
840 to submit these files to the compiler for semantic checking and not code
841 generation, then use the
842 @option{-gnatc} switch:
845 $ gcc -c greetings.ads -gnatc
849 Although the compilation can be done in separate steps as in the
850 above example, in practice it is almost always more convenient
851 to use the @command{gnatmake} tool. All you need to know in this case
852 is the name of the main program's source file. The effect of the above four
853 commands can be achieved with a single one:
860 In the next section we discuss the advantages of using @command{gnatmake} in
863 @c *****************************
864 @node Using the gnatmake Utility
865 @section Using the @command{gnatmake} Utility
868 If you work on a program by compiling single components at a time using
869 @command{gcc}, you typically keep track of the units you modify. In order to
870 build a consistent system, you compile not only these units, but also any
871 units that depend on the units you have modified.
872 For example, in the preceding case,
873 if you edit @file{gmain.adb}, you only need to recompile that file. But if
874 you edit @file{greetings.ads}, you must recompile both
875 @file{greetings.adb} and @file{gmain.adb}, because both files contain
876 units that depend on @file{greetings.ads}.
878 @code{gnatbind} will warn you if you forget one of these compilation
879 steps, so that it is impossible to generate an inconsistent program as a
880 result of forgetting to do a compilation. Nevertheless it is tedious and
881 error-prone to keep track of dependencies among units.
882 One approach to handle the dependency-bookkeeping is to use a
883 makefile. However, makefiles present maintenance problems of their own:
884 if the dependencies change as you change the program, you must make
885 sure that the makefile is kept up-to-date manually, which is also an
888 The @command{gnatmake} utility takes care of these details automatically.
889 Invoke it using either one of the following forms:
893 $ gnatmake ^gmain^GMAIN^
897 The argument is the name of the file containing the main program;
898 you may omit the extension. @command{gnatmake}
899 examines the environment, automatically recompiles any files that need
900 recompiling, and binds and links the resulting set of object files,
901 generating the executable file, @file{^gmain^GMAIN.EXE^}.
902 In a large program, it
903 can be extremely helpful to use @command{gnatmake}, because working out by hand
904 what needs to be recompiled can be difficult.
906 Note that @command{gnatmake}
907 takes into account all the Ada rules that
908 establish dependencies among units. These include dependencies that result
909 from inlining subprogram bodies, and from
910 generic instantiation. Unlike some other
911 Ada make tools, @command{gnatmake} does not rely on the dependencies that were
912 found by the compiler on a previous compilation, which may possibly
913 be wrong when sources change. @command{gnatmake} determines the exact set of
914 dependencies from scratch each time it is run.
917 @node Editing with Emacs
918 @section Editing with Emacs
922 Emacs is an extensible self-documenting text editor that is available in a
923 separate VMSINSTAL kit.
925 Invoke Emacs by typing @kbd{Emacs} at the command prompt. To get started,
926 click on the Emacs Help menu and run the Emacs Tutorial.
927 In a character cell terminal, Emacs help is invoked with @kbd{Ctrl-h} (also
928 written as @kbd{C-h}), and the tutorial by @kbd{C-h t}.
930 Documentation on Emacs and other tools is available in Emacs under the
931 pull-down menu button: @code{Help - Info}. After selecting @code{Info},
932 use the middle mouse button to select a topic (e.g.@: Emacs).
934 In a character cell terminal, do @kbd{C-h i} to invoke info, and then @kbd{m}
935 (stands for menu) followed by the menu item desired, as in @kbd{m Emacs}, to
936 get to the Emacs manual.
937 Help on Emacs is also available by typing @kbd{HELP EMACS} at the DCL command
940 The tutorial is highly recommended in order to learn the intricacies of Emacs,
941 which is sufficiently extensible to provide for a complete programming
942 environment and shell for the sophisticated user.
946 @node Introduction to GPS
947 @section Introduction to GPS
948 @cindex GPS (GNAT Programming Studio)
949 @cindex GNAT Programming Studio (GPS)
951 Although the command line interface (@command{gnatmake}, etc.) alone
952 is sufficient, a graphical Interactive Development
953 Environment can make it easier for you to compose, navigate, and debug
954 programs. This section describes the main features of GPS
955 (``GNAT Programming Studio''), the GNAT graphical IDE.
956 You will see how to use GPS to build and debug an executable, and
957 you will also learn some of the basics of the GNAT ``project'' facility.
959 GPS enables you to do much more than is presented here;
960 e.g., you can produce a call graph, interface to a third-party
961 Version Control System, and inspect the generated assembly language
963 Indeed, GPS also supports languages other than Ada.
964 Such additional information, and an explanation of all of the GPS menu
965 items. may be found in the on-line help, which includes
966 a user's guide and a tutorial (these are also accessible from the GNAT
970 * Building a New Program with GPS::
971 * Simple Debugging with GPS::
974 @node Building a New Program with GPS
975 @subsection Building a New Program with GPS
977 GPS invokes the GNAT compilation tools using information
978 contained in a @emph{project} (also known as a @emph{project file}):
979 a collection of properties such
980 as source directories, identities of main subprograms, tool switches, etc.,
981 and their associated values.
982 See @ref{GNAT Project Manager} for details.
983 In order to run GPS, you will need to either create a new project
984 or else open an existing one.
986 This section will explain how you can use GPS to create a project,
987 to associate Ada source files with a project, and to build and run
991 @item @emph{Creating a project}
993 Invoke GPS, either from the command line or the platform's IDE.
994 After it starts, GPS will display a ``Welcome'' screen with three
999 @code{Start with default project in directory}
1002 @code{Create new project with wizard}
1005 @code{Open existing project}
1009 Select @code{Create new project with wizard} and press @code{OK}.
1010 A new window will appear. In the text box labeled with
1011 @code{Enter the name of the project to create}, type @file{sample}
1012 as the project name.
1013 In the next box, browse to choose the directory in which you
1014 would like to create the project file.
1015 After selecting an appropriate directory, press @code{Forward}.
1017 A window will appear with the title
1018 @code{Version Control System Configuration}.
1019 Simply press @code{Forward}.
1021 A window will appear with the title
1022 @code{Please select the source directories for this project}.
1023 The directory that you specified for the project file will be selected
1024 by default as the one to use for sources; simply press @code{Forward}.
1026 A window will appear with the title
1027 @code{Please select the build directory for this project}.
1028 The directory that you specified for the project file will be selected
1029 by default for object files and executables;
1030 simply press @code{Forward}.
1032 A window will appear with the title
1033 @code{Please select the main units for this project}.
1034 You will supply this information later, after creating the source file.
1035 Simply press @code{Forward} for now.
1037 A window will appear with the title
1038 @code{Please select the switches to build the project}.
1039 Press @code{Apply}. This will create a project file named
1040 @file{sample.prj} in the directory that you had specified.
1042 @item @emph{Creating and saving the source file}
1044 After you create the new project, a GPS window will appear, which is
1045 partitioned into two main sections:
1049 A @emph{Workspace area}, initially greyed out, which you will use for
1050 creating and editing source files
1053 Directly below, a @emph{Messages area}, which initially displays a
1054 ``Welcome'' message.
1055 (If the Messages area is not visible, drag its border upward to expand it.)
1059 Select @code{File} on the menu bar, and then the @code{New} command.
1060 The Workspace area will become white, and you can now
1061 enter the source program explicitly.
1062 Type the following text
1064 @smallexample @c ada
1066 with Ada.Text_IO; use Ada.Text_IO;
1069 Put_Line("Hello from GPS!");
1075 Select @code{File}, then @code{Save As}, and enter the source file name
1077 The file will be saved in the same directory you specified as the
1078 location of the default project file.
1080 @item @emph{Updating the project file}
1082 You need to add the new source file to the project.
1084 the @code{Project} menu and then @code{Edit project properties}.
1085 Click the @code{Main files} tab on the left, and then the
1087 Choose @file{hello.adb} from the list, and press @code{Open}.
1088 The project settings window will reflect this action.
1091 @item @emph{Building and running the program}
1093 In the main GPS window, now choose the @code{Build} menu, then @code{Make},
1094 and select @file{hello.adb}.
1095 The Messages window will display the resulting invocations of @command{gcc},
1096 @command{gnatbind}, and @command{gnatlink}
1097 (reflecting the default switch settings from the
1098 project file that you created) and then a ``successful compilation/build''
1101 To run the program, choose the @code{Build} menu, then @code{Run}, and
1102 select @command{hello}.
1103 An @emph{Arguments Selection} window will appear.
1104 There are no command line arguments, so just click @code{OK}.
1106 The Messages window will now display the program's output (the string
1107 @code{Hello from GPS}), and at the bottom of the GPS window a status
1108 update is displayed (@code{Run: hello}).
1109 Close the GPS window (or select @code{File}, then @code{Exit}) to
1110 terminate this GPS session.
1113 @node Simple Debugging with GPS
1114 @subsection Simple Debugging with GPS
1116 This section illustrates basic debugging techniques (setting breakpoints,
1117 examining/modifying variables, single stepping).
1120 @item @emph{Opening a project}
1122 Start GPS and select @code{Open existing project}; browse to
1123 specify the project file @file{sample.prj} that you had created in the
1126 @item @emph{Creating a source file}
1128 Select @code{File}, then @code{New}, and type in the following program:
1130 @smallexample @c ada
1132 with Ada.Text_IO; use Ada.Text_IO;
1133 procedure Example is
1134 Line : String (1..80);
1137 Put_Line("Type a line of text at each prompt; an empty line to exit");
1141 Put_Line (Line (1..N) );
1149 Select @code{File}, then @code{Save as}, and enter the file name
1152 @item @emph{Updating the project file}
1154 Add @code{Example} as a new main unit for the project:
1157 Select @code{Project}, then @code{Edit Project Properties}.
1160 Select the @code{Main files} tab, click @code{Add}, then
1161 select the file @file{example.adb} from the list, and
1163 You will see the file name appear in the list of main units
1169 @item @emph{Building/running the executable}
1171 To build the executable
1172 select @code{Build}, then @code{Make}, and then choose @file{example.adb}.
1174 Run the program to see its effect (in the Messages area).
1175 Each line that you enter is displayed; an empty line will
1176 cause the loop to exit and the program to terminate.
1178 @item @emph{Debugging the program}
1180 Note that the @option{-g} switches to @command{gcc} and @command{gnatlink},
1181 which are required for debugging, are on by default when you create
1183 Thus unless you intentionally remove these settings, you will be able
1184 to debug any program that you develop using GPS.
1187 @item @emph{Initializing}
1189 Select @code{Debug}, then @code{Initialize}, then @file{example}
1191 @item @emph{Setting a breakpoint}
1193 After performing the initialization step, you will observe a small
1194 icon to the right of each line number.
1195 This serves as a toggle for breakpoints; clicking the icon will
1196 set a breakpoint at the corresponding line (the icon will change to
1197 a red circle with an ``x''), and clicking it again
1198 will remove the breakpoint / reset the icon.
1200 For purposes of this example, set a breakpoint at line 10 (the
1201 statement @code{Put_Line@ (Line@ (1..N));}
1203 @item @emph{Starting program execution}
1205 Select @code{Debug}, then @code{Run}. When the
1206 @code{Program Arguments} window appears, click @code{OK}.
1207 A console window will appear; enter some line of text,
1208 e.g.@: @code{abcde}, at the prompt.
1209 The program will pause execution when it gets to the
1210 breakpoint, and the corresponding line is highlighted.
1212 @item @emph{Examining a variable}
1214 Move the mouse over one of the occurrences of the variable @code{N}.
1215 You will see the value (5) displayed, in ``tool tip'' fashion.
1216 Right click on @code{N}, select @code{Debug}, then select @code{Display N}.
1217 You will see information about @code{N} appear in the @code{Debugger Data}
1218 pane, showing the value as 5.
1220 @item @emph{Assigning a new value to a variable}
1222 Right click on the @code{N} in the @code{Debugger Data} pane, and
1223 select @code{Set value of N}.
1224 When the input window appears, enter the value @code{4} and click
1226 This value does not automatically appear in the @code{Debugger Data}
1227 pane; to see it, right click again on the @code{N} in the
1228 @code{Debugger Data} pane and select @code{Update value}.
1229 The new value, 4, will appear in red.
1231 @item @emph{Single stepping}
1233 Select @code{Debug}, then @code{Next}.
1234 This will cause the next statement to be executed, in this case the
1235 call of @code{Put_Line} with the string slice.
1236 Notice in the console window that the displayed string is simply
1237 @code{abcd} and not @code{abcde} which you had entered.
1238 This is because the upper bound of the slice is now 4 rather than 5.
1240 @item @emph{Removing a breakpoint}
1242 Toggle the breakpoint icon at line 10.
1244 @item @emph{Resuming execution from a breakpoint}
1246 Select @code{Debug}, then @code{Continue}.
1247 The program will reach the next iteration of the loop, and
1248 wait for input after displaying the prompt.
1249 This time, just hit the @kbd{Enter} key.
1250 The value of @code{N} will be 0, and the program will terminate.
1251 The console window will disappear.
1256 @node The GNAT Compilation Model
1257 @chapter The GNAT Compilation Model
1258 @cindex GNAT compilation model
1259 @cindex Compilation model
1262 * Source Representation::
1263 * Foreign Language Representation::
1264 * File Naming Rules::
1265 * Using Other File Names::
1266 * Alternative File Naming Schemes::
1267 * Generating Object Files::
1268 * Source Dependencies::
1269 * The Ada Library Information Files::
1270 * Binding an Ada Program::
1271 * Mixed Language Programming::
1273 * Building Mixed Ada & C++ Programs::
1274 * Comparison between GNAT and C/C++ Compilation Models::
1276 * Comparison between GNAT and Conventional Ada Library Models::
1278 * Placement of temporary files::
1283 This chapter describes the compilation model used by GNAT. Although
1284 similar to that used by other languages, such as C and C++, this model
1285 is substantially different from the traditional Ada compilation models,
1286 which are based on a library. The model is initially described without
1287 reference to the library-based model. If you have not previously used an
1288 Ada compiler, you need only read the first part of this chapter. The
1289 last section describes and discusses the differences between the GNAT
1290 model and the traditional Ada compiler models. If you have used other
1291 Ada compilers, this section will help you to understand those
1292 differences, and the advantages of the GNAT model.
1294 @node Source Representation
1295 @section Source Representation
1299 Ada source programs are represented in standard text files, using
1300 Latin-1 coding. Latin-1 is an 8-bit code that includes the familiar
1301 7-bit ASCII set, plus additional characters used for
1302 representing foreign languages (@pxref{Foreign Language Representation}
1303 for support of non-USA character sets). The format effector characters
1304 are represented using their standard ASCII encodings, as follows:
1309 Vertical tab, @code{16#0B#}
1313 Horizontal tab, @code{16#09#}
1317 Carriage return, @code{16#0D#}
1321 Line feed, @code{16#0A#}
1325 Form feed, @code{16#0C#}
1329 Source files are in standard text file format. In addition, GNAT will
1330 recognize a wide variety of stream formats, in which the end of
1331 physical lines is marked by any of the following sequences:
1332 @code{LF}, @code{CR}, @code{CR-LF}, or @code{LF-CR}. This is useful
1333 in accommodating files that are imported from other operating systems.
1335 @cindex End of source file
1336 @cindex Source file, end
1338 The end of a source file is normally represented by the physical end of
1339 file. However, the control character @code{16#1A#} (@code{SUB}) is also
1340 recognized as signalling the end of the source file. Again, this is
1341 provided for compatibility with other operating systems where this
1342 code is used to represent the end of file.
1344 Each file contains a single Ada compilation unit, including any pragmas
1345 associated with the unit. For example, this means you must place a
1346 package declaration (a package @dfn{spec}) and the corresponding body in
1347 separate files. An Ada @dfn{compilation} (which is a sequence of
1348 compilation units) is represented using a sequence of files. Similarly,
1349 you will place each subunit or child unit in a separate file.
1351 @node Foreign Language Representation
1352 @section Foreign Language Representation
1355 GNAT supports the standard character sets defined in Ada as well as
1356 several other non-standard character sets for use in localized versions
1357 of the compiler (@pxref{Character Set Control}).
1360 * Other 8-Bit Codes::
1361 * Wide Character Encodings::
1369 The basic character set is Latin-1. This character set is defined by ISO
1370 standard 8859, part 1. The lower half (character codes @code{16#00#}
1371 @dots{} @code{16#7F#)} is identical to standard ASCII coding, but the upper
1372 half is used to represent additional characters. These include extended letters
1373 used by European languages, such as French accents, the vowels with umlauts
1374 used in German, and the extra letter A-ring used in Swedish.
1376 @findex Ada.Characters.Latin_1
1377 For a complete list of Latin-1 codes and their encodings, see the source
1378 file of library unit @code{Ada.Characters.Latin_1} in file
1379 @file{a-chlat1.ads}.
1380 You may use any of these extended characters freely in character or
1381 string literals. In addition, the extended characters that represent
1382 letters can be used in identifiers.
1384 @node Other 8-Bit Codes
1385 @subsection Other 8-Bit Codes
1388 GNAT also supports several other 8-bit coding schemes:
1391 @item ISO 8859-2 (Latin-2)
1394 Latin-2 letters allowed in identifiers, with uppercase and lowercase
1397 @item ISO 8859-3 (Latin-3)
1400 Latin-3 letters allowed in identifiers, with uppercase and lowercase
1403 @item ISO 8859-4 (Latin-4)
1406 Latin-4 letters allowed in identifiers, with uppercase and lowercase
1409 @item ISO 8859-5 (Cyrillic)
1412 ISO 8859-5 letters (Cyrillic) allowed in identifiers, with uppercase and
1413 lowercase equivalence.
1415 @item ISO 8859-15 (Latin-9)
1418 ISO 8859-15 (Latin-9) letters allowed in identifiers, with uppercase and
1419 lowercase equivalence
1421 @item IBM PC (code page 437)
1422 @cindex code page 437
1423 This code page is the normal default for PCs in the U.S. It corresponds
1424 to the original IBM PC character set. This set has some, but not all, of
1425 the extended Latin-1 letters, but these letters do not have the same
1426 encoding as Latin-1. In this mode, these letters are allowed in
1427 identifiers with uppercase and lowercase equivalence.
1429 @item IBM PC (code page 850)
1430 @cindex code page 850
1431 This code page is a modification of 437 extended to include all the
1432 Latin-1 letters, but still not with the usual Latin-1 encoding. In this
1433 mode, all these letters are allowed in identifiers with uppercase and
1434 lowercase equivalence.
1436 @item Full Upper 8-bit
1437 Any character in the range 80-FF allowed in identifiers, and all are
1438 considered distinct. In other words, there are no uppercase and lowercase
1439 equivalences in this range. This is useful in conjunction with
1440 certain encoding schemes used for some foreign character sets (e.g.,
1441 the typical method of representing Chinese characters on the PC).
1444 No upper-half characters in the range 80-FF are allowed in identifiers.
1445 This gives Ada 83 compatibility for identifier names.
1449 For precise data on the encodings permitted, and the uppercase and lowercase
1450 equivalences that are recognized, see the file @file{csets.adb} in
1451 the GNAT compiler sources. You will need to obtain a full source release
1452 of GNAT to obtain this file.
1454 @node Wide Character Encodings
1455 @subsection Wide Character Encodings
1458 GNAT allows wide character codes to appear in character and string
1459 literals, and also optionally in identifiers, by means of the following
1460 possible encoding schemes:
1465 In this encoding, a wide character is represented by the following five
1473 Where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal
1474 characters (using uppercase letters) of the wide character code. For
1475 example, ESC A345 is used to represent the wide character with code
1477 This scheme is compatible with use of the full Wide_Character set.
1479 @item Upper-Half Coding
1480 @cindex Upper-Half Coding
1481 The wide character with encoding @code{16#abcd#} where the upper bit is on
1482 (in other words, ``a'' is in the range 8-F) is represented as two bytes,
1483 @code{16#ab#} and @code{16#cd#}. The second byte cannot be a format control
1484 character, but is not required to be in the upper half. This method can
1485 be also used for shift-JIS or EUC, where the internal coding matches the
1488 @item Shift JIS Coding
1489 @cindex Shift JIS Coding
1490 A wide character is represented by a two-character sequence,
1492 @code{16#cd#}, with the restrictions described for upper-half encoding as
1493 described above. The internal character code is the corresponding JIS
1494 character according to the standard algorithm for Shift-JIS
1495 conversion. Only characters defined in the JIS code set table can be
1496 used with this encoding method.
1500 A wide character is represented by a two-character sequence
1502 @code{16#cd#}, with both characters being in the upper half. The internal
1503 character code is the corresponding JIS character according to the EUC
1504 encoding algorithm. Only characters defined in the JIS code set table
1505 can be used with this encoding method.
1508 A wide character is represented using
1509 UCS Transformation Format 8 (UTF-8) as defined in Annex R of ISO
1510 10646-1/Am.2. Depending on the character value, the representation
1511 is a one, two, or three byte sequence:
1516 16#0000#-16#007f#: 2#0@var{xxxxxxx}#
1517 16#0080#-16#07ff#: 2#110@var{xxxxx}# 2#10@var{xxxxxx}#
1518 16#0800#-16#ffff#: 2#1110@var{xxxx}# 2#10@var{xxxxxx}# 2#10@var{xxxxxx}#
1523 where the @var{xxx} bits correspond to the left-padded bits of the
1524 16-bit character value. Note that all lower half ASCII characters
1525 are represented as ASCII bytes and all upper half characters and
1526 other wide characters are represented as sequences of upper-half
1527 (The full UTF-8 scheme allows for encoding 31-bit characters as
1528 6-byte sequences, but in this implementation, all UTF-8 sequences
1529 of four or more bytes length will be treated as illegal).
1530 @item Brackets Coding
1531 In this encoding, a wide character is represented by the following eight
1539 Where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal
1540 characters (using uppercase letters) of the wide character code. For
1541 example, [``A345''] is used to represent the wide character with code
1542 @code{16#A345#}. It is also possible (though not required) to use the
1543 Brackets coding for upper half characters. For example, the code
1544 @code{16#A3#} can be represented as @code{[``A3'']}.
1546 This scheme is compatible with use of the full Wide_Character set,
1547 and is also the method used for wide character encoding in the standard
1548 ACVC (Ada Compiler Validation Capability) test suite distributions.
1553 Note: Some of these coding schemes do not permit the full use of the
1554 Ada character set. For example, neither Shift JIS, nor EUC allow the
1555 use of the upper half of the Latin-1 set.
1557 @node File Naming Rules
1558 @section File Naming Rules
1561 The default file name is determined by the name of the unit that the
1562 file contains. The name is formed by taking the full expanded name of
1563 the unit and replacing the separating dots with hyphens and using
1564 ^lowercase^uppercase^ for all letters.
1566 An exception arises if the file name generated by the above rules starts
1567 with one of the characters
1569 @samp{A}, @samp{G}, @samp{I}, or @samp{S},
1572 @samp{a}, @samp{g}, @samp{i}, or @samp{s},
1574 and the second character is a
1575 minus. In this case, the character ^tilde^dollar sign^ is used in place
1576 of the minus. The reason for this special rule is to avoid clashes with
1577 the standard names for child units of the packages System, Ada,
1578 Interfaces, and GNAT, which use the prefixes
1580 @samp{S-}, @samp{A-}, @samp{I-}, and @samp{G-},
1583 @samp{s-}, @samp{a-}, @samp{i-}, and @samp{g-},
1587 The file extension is @file{.ads} for a spec and
1588 @file{.adb} for a body. The following list shows some
1589 examples of these rules.
1596 @item arith_functions.ads
1597 Arith_Functions (package spec)
1598 @item arith_functions.adb
1599 Arith_Functions (package body)
1601 Func.Spec (child package spec)
1603 Func.Spec (child package body)
1605 Sub (subunit of Main)
1606 @item ^a~bad.adb^A$BAD.ADB^
1607 A.Bad (child package body)
1611 Following these rules can result in excessively long
1612 file names if corresponding
1613 unit names are long (for example, if child units or subunits are
1614 heavily nested). An option is available to shorten such long file names
1615 (called file name ``krunching''). This may be particularly useful when
1616 programs being developed with GNAT are to be used on operating systems
1617 with limited file name lengths. @xref{Using gnatkr}.
1619 Of course, no file shortening algorithm can guarantee uniqueness over
1620 all possible unit names; if file name krunching is used, it is your
1621 responsibility to ensure no name clashes occur. Alternatively you
1622 can specify the exact file names that you want used, as described
1623 in the next section. Finally, if your Ada programs are migrating from a
1624 compiler with a different naming convention, you can use the gnatchop
1625 utility to produce source files that follow the GNAT naming conventions.
1626 (For details @pxref{Renaming Files with gnatchop}.)
1628 Note: in the case of @code{Windows NT/XP} or @code{OpenVMS} operating
1629 systems, case is not significant. So for example on @code{Windows XP}
1630 if the canonical name is @code{main-sub.adb}, you can use the file name
1631 @code{Main-Sub.adb} instead. However, case is significant for other
1632 operating systems, so for example, if you want to use other than
1633 canonically cased file names on a Unix system, you need to follow
1634 the procedures described in the next section.
1636 @node Using Other File Names
1637 @section Using Other File Names
1641 In the previous section, we have described the default rules used by
1642 GNAT to determine the file name in which a given unit resides. It is
1643 often convenient to follow these default rules, and if you follow them,
1644 the compiler knows without being explicitly told where to find all
1647 However, in some cases, particularly when a program is imported from
1648 another Ada compiler environment, it may be more convenient for the
1649 programmer to specify which file names contain which units. GNAT allows
1650 arbitrary file names to be used by means of the Source_File_Name pragma.
1651 The form of this pragma is as shown in the following examples:
1652 @cindex Source_File_Name pragma
1654 @smallexample @c ada
1656 pragma Source_File_Name (My_Utilities.Stacks,
1657 Spec_File_Name => "myutilst_a.ada");
1658 pragma Source_File_name (My_Utilities.Stacks,
1659 Body_File_Name => "myutilst.ada");
1664 As shown in this example, the first argument for the pragma is the unit
1665 name (in this example a child unit). The second argument has the form
1666 of a named association. The identifier
1667 indicates whether the file name is for a spec or a body;
1668 the file name itself is given by a string literal.
1670 The source file name pragma is a configuration pragma, which means that
1671 normally it will be placed in the @file{gnat.adc}
1672 file used to hold configuration
1673 pragmas that apply to a complete compilation environment.
1674 For more details on how the @file{gnat.adc} file is created and used
1675 see @ref{Handling of Configuration Pragmas}.
1676 @cindex @file{gnat.adc}
1679 GNAT allows completely arbitrary file names to be specified using the
1680 source file name pragma. However, if the file name specified has an
1681 extension other than @file{.ads} or @file{.adb} it is necessary to use
1682 a special syntax when compiling the file. The name in this case must be
1683 preceded by the special sequence @option{-x} followed by a space and the name
1684 of the language, here @code{ada}, as in:
1687 $ gcc -c -x ada peculiar_file_name.sim
1692 @command{gnatmake} handles non-standard file names in the usual manner (the
1693 non-standard file name for the main program is simply used as the
1694 argument to gnatmake). Note that if the extension is also non-standard,
1695 then it must be included in the @command{gnatmake} command, it may not
1698 @node Alternative File Naming Schemes
1699 @section Alternative File Naming Schemes
1700 @cindex File naming schemes, alternative
1703 In the previous section, we described the use of the @code{Source_File_Name}
1704 pragma to allow arbitrary names to be assigned to individual source files.
1705 However, this approach requires one pragma for each file, and especially in
1706 large systems can result in very long @file{gnat.adc} files, and also create
1707 a maintenance problem.
1709 GNAT also provides a facility for specifying systematic file naming schemes
1710 other than the standard default naming scheme previously described. An
1711 alternative scheme for naming is specified by the use of
1712 @code{Source_File_Name} pragmas having the following format:
1713 @cindex Source_File_Name pragma
1715 @smallexample @c ada
1716 pragma Source_File_Name (
1717 Spec_File_Name => FILE_NAME_PATTERN
1718 @r{[},Casing => CASING_SPEC@r{]}
1719 @r{[},Dot_Replacement => STRING_LITERAL@r{]});
1721 pragma Source_File_Name (
1722 Body_File_Name => FILE_NAME_PATTERN
1723 @r{[},Casing => CASING_SPEC@r{]}
1724 @r{[},Dot_Replacement => STRING_LITERAL@r{]});
1726 pragma Source_File_Name (
1727 Subunit_File_Name => FILE_NAME_PATTERN
1728 @r{[},Casing => CASING_SPEC@r{]}
1729 @r{[},Dot_Replacement => STRING_LITERAL@r{]});
1731 FILE_NAME_PATTERN ::= STRING_LITERAL
1732 CASING_SPEC ::= Lowercase | Uppercase | Mixedcase
1736 The @code{FILE_NAME_PATTERN} string shows how the file name is constructed.
1737 It contains a single asterisk character, and the unit name is substituted
1738 systematically for this asterisk. The optional parameter
1739 @code{Casing} indicates
1740 whether the unit name is to be all upper-case letters, all lower-case letters,
1741 or mixed-case. If no
1742 @code{Casing} parameter is used, then the default is all
1743 ^lower-case^upper-case^.
1745 The optional @code{Dot_Replacement} string is used to replace any periods
1746 that occur in subunit or child unit names. If no @code{Dot_Replacement}
1747 argument is used then separating dots appear unchanged in the resulting
1749 Although the above syntax indicates that the
1750 @code{Casing} argument must appear
1751 before the @code{Dot_Replacement} argument, but it
1752 is also permissible to write these arguments in the opposite order.
1754 As indicated, it is possible to specify different naming schemes for
1755 bodies, specs, and subunits. Quite often the rule for subunits is the
1756 same as the rule for bodies, in which case, there is no need to give
1757 a separate @code{Subunit_File_Name} rule, and in this case the
1758 @code{Body_File_name} rule is used for subunits as well.
1760 The separate rule for subunits can also be used to implement the rather
1761 unusual case of a compilation environment (e.g.@: a single directory) which
1762 contains a subunit and a child unit with the same unit name. Although
1763 both units cannot appear in the same partition, the Ada Reference Manual
1764 allows (but does not require) the possibility of the two units coexisting
1765 in the same environment.
1767 The file name translation works in the following steps:
1772 If there is a specific @code{Source_File_Name} pragma for the given unit,
1773 then this is always used, and any general pattern rules are ignored.
1776 If there is a pattern type @code{Source_File_Name} pragma that applies to
1777 the unit, then the resulting file name will be used if the file exists. If
1778 more than one pattern matches, the latest one will be tried first, and the
1779 first attempt resulting in a reference to a file that exists will be used.
1782 If no pattern type @code{Source_File_Name} pragma that applies to the unit
1783 for which the corresponding file exists, then the standard GNAT default
1784 naming rules are used.
1789 As an example of the use of this mechanism, consider a commonly used scheme
1790 in which file names are all lower case, with separating periods copied
1791 unchanged to the resulting file name, and specs end with @file{.1.ada}, and
1792 bodies end with @file{.2.ada}. GNAT will follow this scheme if the following
1795 @smallexample @c ada
1796 pragma Source_File_Name
1797 (Spec_File_Name => "*.1.ada");
1798 pragma Source_File_Name
1799 (Body_File_Name => "*.2.ada");
1803 The default GNAT scheme is actually implemented by providing the following
1804 default pragmas internally:
1806 @smallexample @c ada
1807 pragma Source_File_Name
1808 (Spec_File_Name => "*.ads", Dot_Replacement => "-");
1809 pragma Source_File_Name
1810 (Body_File_Name => "*.adb", Dot_Replacement => "-");
1814 Our final example implements a scheme typically used with one of the
1815 Ada 83 compilers, where the separator character for subunits was ``__''
1816 (two underscores), specs were identified by adding @file{_.ADA}, bodies
1817 by adding @file{.ADA}, and subunits by
1818 adding @file{.SEP}. All file names were
1819 upper case. Child units were not present of course since this was an
1820 Ada 83 compiler, but it seems reasonable to extend this scheme to use
1821 the same double underscore separator for child units.
1823 @smallexample @c ada
1824 pragma Source_File_Name
1825 (Spec_File_Name => "*_.ADA",
1826 Dot_Replacement => "__",
1827 Casing = Uppercase);
1828 pragma Source_File_Name
1829 (Body_File_Name => "*.ADA",
1830 Dot_Replacement => "__",
1831 Casing = Uppercase);
1832 pragma Source_File_Name
1833 (Subunit_File_Name => "*.SEP",
1834 Dot_Replacement => "__",
1835 Casing = Uppercase);
1838 @node Generating Object Files
1839 @section Generating Object Files
1842 An Ada program consists of a set of source files, and the first step in
1843 compiling the program is to generate the corresponding object files.
1844 These are generated by compiling a subset of these source files.
1845 The files you need to compile are the following:
1849 If a package spec has no body, compile the package spec to produce the
1850 object file for the package.
1853 If a package has both a spec and a body, compile the body to produce the
1854 object file for the package. The source file for the package spec need
1855 not be compiled in this case because there is only one object file, which
1856 contains the code for both the spec and body of the package.
1859 For a subprogram, compile the subprogram body to produce the object file
1860 for the subprogram. The spec, if one is present, is as usual in a
1861 separate file, and need not be compiled.
1865 In the case of subunits, only compile the parent unit. A single object
1866 file is generated for the entire subunit tree, which includes all the
1870 Compile child units independently of their parent units
1871 (though, of course, the spec of all the ancestor unit must be present in order
1872 to compile a child unit).
1876 Compile generic units in the same manner as any other units. The object
1877 files in this case are small dummy files that contain at most the
1878 flag used for elaboration checking. This is because GNAT always handles generic
1879 instantiation by means of macro expansion. However, it is still necessary to
1880 compile generic units, for dependency checking and elaboration purposes.
1884 The preceding rules describe the set of files that must be compiled to
1885 generate the object files for a program. Each object file has the same
1886 name as the corresponding source file, except that the extension is
1889 You may wish to compile other files for the purpose of checking their
1890 syntactic and semantic correctness. For example, in the case where a
1891 package has a separate spec and body, you would not normally compile the
1892 spec. However, it is convenient in practice to compile the spec to make
1893 sure it is error-free before compiling clients of this spec, because such
1894 compilations will fail if there is an error in the spec.
1896 GNAT provides an option for compiling such files purely for the
1897 purposes of checking correctness; such compilations are not required as
1898 part of the process of building a program. To compile a file in this
1899 checking mode, use the @option{-gnatc} switch.
1901 @node Source Dependencies
1902 @section Source Dependencies
1905 A given object file clearly depends on the source file which is compiled
1906 to produce it. Here we are using @dfn{depends} in the sense of a typical
1907 @code{make} utility; in other words, an object file depends on a source
1908 file if changes to the source file require the object file to be
1910 In addition to this basic dependency, a given object may depend on
1911 additional source files as follows:
1915 If a file being compiled @code{with}'s a unit @var{X}, the object file
1916 depends on the file containing the spec of unit @var{X}. This includes
1917 files that are @code{with}'ed implicitly either because they are parents
1918 of @code{with}'ed child units or they are run-time units required by the
1919 language constructs used in a particular unit.
1922 If a file being compiled instantiates a library level generic unit, the
1923 object file depends on both the spec and body files for this generic
1927 If a file being compiled instantiates a generic unit defined within a
1928 package, the object file depends on the body file for the package as
1929 well as the spec file.
1933 @cindex @option{-gnatn} switch
1934 If a file being compiled contains a call to a subprogram for which
1935 pragma @code{Inline} applies and inlining is activated with the
1936 @option{-gnatn} switch, the object file depends on the file containing the
1937 body of this subprogram as well as on the file containing the spec. Note
1938 that for inlining to actually occur as a result of the use of this switch,
1939 it is necessary to compile in optimizing mode.
1941 @cindex @option{-gnatN} switch
1942 The use of @option{-gnatN} activates inlining optimization
1943 that is performed by the front end of the compiler. This inlining does
1944 not require that the code generation be optimized. Like @option{-gnatn},
1945 the use of this switch generates additional dependencies.
1947 When using a gcc-based back end (in practice this means using any version
1948 of GNAT other than the JGNAT, .NET or GNAAMP versions), then the use of
1949 @option{-gnatN} is deprecated, and the use of @option{-gnatn} is preferred.
1950 Historically front end inlining was more extensive than the gcc back end
1951 inlining, but that is no longer the case.
1954 If an object file @file{O} depends on the proper body of a subunit through
1955 inlining or instantiation, it depends on the parent unit of the subunit.
1956 This means that any modification of the parent unit or one of its subunits
1957 affects the compilation of @file{O}.
1960 The object file for a parent unit depends on all its subunit body files.
1963 The previous two rules meant that for purposes of computing dependencies and
1964 recompilation, a body and all its subunits are treated as an indivisible whole.
1967 These rules are applied transitively: if unit @code{A} @code{with}'s
1968 unit @code{B}, whose elaboration calls an inlined procedure in package
1969 @code{C}, the object file for unit @code{A} will depend on the body of
1970 @code{C}, in file @file{c.adb}.
1972 The set of dependent files described by these rules includes all the
1973 files on which the unit is semantically dependent, as dictated by the
1974 Ada language standard. However, it is a superset of what the
1975 standard describes, because it includes generic, inline, and subunit
1978 An object file must be recreated by recompiling the corresponding source
1979 file if any of the source files on which it depends are modified. For
1980 example, if the @code{make} utility is used to control compilation,
1981 the rule for an Ada object file must mention all the source files on
1982 which the object file depends, according to the above definition.
1983 The determination of the necessary
1984 recompilations is done automatically when one uses @command{gnatmake}.
1987 @node The Ada Library Information Files
1988 @section The Ada Library Information Files
1989 @cindex Ada Library Information files
1990 @cindex @file{ALI} files
1993 Each compilation actually generates two output files. The first of these
1994 is the normal object file that has a @file{.o} extension. The second is a
1995 text file containing full dependency information. It has the same
1996 name as the source file, but an @file{.ali} extension.
1997 This file is known as the Ada Library Information (@file{ALI}) file.
1998 The following information is contained in the @file{ALI} file.
2002 Version information (indicates which version of GNAT was used to compile
2003 the unit(s) in question)
2006 Main program information (including priority and time slice settings,
2007 as well as the wide character encoding used during compilation).
2010 List of arguments used in the @command{gcc} command for the compilation
2013 Attributes of the unit, including configuration pragmas used, an indication
2014 of whether the compilation was successful, exception model used etc.
2017 A list of relevant restrictions applying to the unit (used for consistency)
2021 Categorization information (e.g.@: use of pragma @code{Pure}).
2024 Information on all @code{with}'ed units, including presence of
2025 @code{Elaborate} or @code{Elaborate_All} pragmas.
2028 Information from any @code{Linker_Options} pragmas used in the unit
2031 Information on the use of @code{Body_Version} or @code{Version}
2032 attributes in the unit.
2035 Dependency information. This is a list of files, together with
2036 time stamp and checksum information. These are files on which
2037 the unit depends in the sense that recompilation is required
2038 if any of these units are modified.
2041 Cross-reference data. Contains information on all entities referenced
2042 in the unit. Used by tools like @code{gnatxref} and @code{gnatfind} to
2043 provide cross-reference information.
2048 For a full detailed description of the format of the @file{ALI} file,
2049 see the source of the body of unit @code{Lib.Writ}, contained in file
2050 @file{lib-writ.adb} in the GNAT compiler sources.
2052 @node Binding an Ada Program
2053 @section Binding an Ada Program
2056 When using languages such as C and C++, once the source files have been
2057 compiled the only remaining step in building an executable program
2058 is linking the object modules together. This means that it is possible to
2059 link an inconsistent version of a program, in which two units have
2060 included different versions of the same header.
2062 The rules of Ada do not permit such an inconsistent program to be built.
2063 For example, if two clients have different versions of the same package,
2064 it is illegal to build a program containing these two clients.
2065 These rules are enforced by the GNAT binder, which also determines an
2066 elaboration order consistent with the Ada rules.
2068 The GNAT binder is run after all the object files for a program have
2069 been created. It is given the name of the main program unit, and from
2070 this it determines the set of units required by the program, by reading the
2071 corresponding ALI files. It generates error messages if the program is
2072 inconsistent or if no valid order of elaboration exists.
2074 If no errors are detected, the binder produces a main program, in Ada by
2075 default, that contains calls to the elaboration procedures of those
2076 compilation unit that require them, followed by
2077 a call to the main program. This Ada program is compiled to generate the
2078 object file for the main program. The name of
2079 the Ada file is @file{b~@var{xxx}.adb} (with the corresponding spec
2080 @file{b~@var{xxx}.ads}) where @var{xxx} is the name of the
2083 Finally, the linker is used to build the resulting executable program,
2084 using the object from the main program from the bind step as well as the
2085 object files for the Ada units of the program.
2087 @node Mixed Language Programming
2088 @section Mixed Language Programming
2089 @cindex Mixed Language Programming
2092 This section describes how to develop a mixed-language program,
2093 specifically one that comprises units in both Ada and C.
2096 * Interfacing to C::
2097 * Calling Conventions::
2100 @node Interfacing to C
2101 @subsection Interfacing to C
2103 Interfacing Ada with a foreign language such as C involves using
2104 compiler directives to import and/or export entity definitions in each
2105 language---using @code{extern} statements in C, for instance, and the
2106 @code{Import}, @code{Export}, and @code{Convention} pragmas in Ada.
2107 A full treatment of these topics is provided in Appendix B, section 1
2108 of the Ada Reference Manual.
2110 There are two ways to build a program using GNAT that contains some Ada
2111 sources and some foreign language sources, depending on whether or not
2112 the main subprogram is written in Ada. Here is a source example with
2113 the main subprogram in Ada:
2119 void print_num (int num)
2121 printf ("num is %d.\n", num);
2127 /* num_from_Ada is declared in my_main.adb */
2128 extern int num_from_Ada;
2132 return num_from_Ada;
2136 @smallexample @c ada
2138 procedure My_Main is
2140 -- Declare then export an Integer entity called num_from_Ada
2141 My_Num : Integer := 10;
2142 pragma Export (C, My_Num, "num_from_Ada");
2144 -- Declare an Ada function spec for Get_Num, then use
2145 -- C function get_num for the implementation.
2146 function Get_Num return Integer;
2147 pragma Import (C, Get_Num, "get_num");
2149 -- Declare an Ada procedure spec for Print_Num, then use
2150 -- C function print_num for the implementation.
2151 procedure Print_Num (Num : Integer);
2152 pragma Import (C, Print_Num, "print_num");
2155 Print_Num (Get_Num);
2161 To build this example, first compile the foreign language files to
2162 generate object files:
2164 ^gcc -c file1.c^gcc -c FILE1.C^
2165 ^gcc -c file2.c^gcc -c FILE2.C^
2169 Then, compile the Ada units to produce a set of object files and ALI
2172 gnatmake ^-c^/ACTIONS=COMPILE^ my_main.adb
2176 Run the Ada binder on the Ada main program:
2178 gnatbind my_main.ali
2182 Link the Ada main program, the Ada objects and the other language
2185 gnatlink my_main.ali file1.o file2.o
2189 The last three steps can be grouped in a single command:
2191 gnatmake my_main.adb -largs file1.o file2.o
2194 @cindex Binder output file
2196 If the main program is in a language other than Ada, then you may have
2197 more than one entry point into the Ada subsystem. You must use a special
2198 binder option to generate callable routines that initialize and
2199 finalize the Ada units (@pxref{Binding with Non-Ada Main Programs}).
2200 Calls to the initialization and finalization routines must be inserted
2201 in the main program, or some other appropriate point in the code. The
2202 call to initialize the Ada units must occur before the first Ada
2203 subprogram is called, and the call to finalize the Ada units must occur
2204 after the last Ada subprogram returns. The binder will place the
2205 initialization and finalization subprograms into the
2206 @file{b~@var{xxx}.adb} file where they can be accessed by your C
2207 sources. To illustrate, we have the following example:
2211 extern void adainit (void);
2212 extern void adafinal (void);
2213 extern int add (int, int);
2214 extern int sub (int, int);
2216 int main (int argc, char *argv[])
2222 /* Should print "21 + 7 = 28" */
2223 printf ("%d + %d = %d\n", a, b, add (a, b));
2224 /* Should print "21 - 7 = 14" */
2225 printf ("%d - %d = %d\n", a, b, sub (a, b));
2231 @smallexample @c ada
2234 function Add (A, B : Integer) return Integer;
2235 pragma Export (C, Add, "add");
2239 package body Unit1 is
2240 function Add (A, B : Integer) return Integer is
2248 function Sub (A, B : Integer) return Integer;
2249 pragma Export (C, Sub, "sub");
2253 package body Unit2 is
2254 function Sub (A, B : Integer) return Integer is
2263 The build procedure for this application is similar to the last
2264 example's. First, compile the foreign language files to generate object
2267 ^gcc -c main.c^gcc -c main.c^
2271 Next, compile the Ada units to produce a set of object files and ALI
2274 gnatmake ^-c^/ACTIONS=COMPILE^ unit1.adb
2275 gnatmake ^-c^/ACTIONS=COMPILE^ unit2.adb
2279 Run the Ada binder on every generated ALI file. Make sure to use the
2280 @option{-n} option to specify a foreign main program:
2282 gnatbind ^-n^/NOMAIN^ unit1.ali unit2.ali
2286 Link the Ada main program, the Ada objects and the foreign language
2287 objects. You need only list the last ALI file here:
2289 gnatlink unit2.ali main.o -o exec_file
2292 This procedure yields a binary executable called @file{exec_file}.
2296 Depending on the circumstances (for example when your non-Ada main object
2297 does not provide symbol @code{main}), you may also need to instruct the
2298 GNAT linker not to include the standard startup objects by passing the
2299 @option{^-nostartfiles^/NOSTART_FILES^} switch to @command{gnatlink}.
2301 @node Calling Conventions
2302 @subsection Calling Conventions
2303 @cindex Foreign Languages
2304 @cindex Calling Conventions
2305 GNAT follows standard calling sequence conventions and will thus interface
2306 to any other language that also follows these conventions. The following
2307 Convention identifiers are recognized by GNAT:
2310 @cindex Interfacing to Ada
2311 @cindex Other Ada compilers
2312 @cindex Convention Ada
2314 This indicates that the standard Ada calling sequence will be
2315 used and all Ada data items may be passed without any limitations in the
2316 case where GNAT is used to generate both the caller and callee. It is also
2317 possible to mix GNAT generated code and code generated by another Ada
2318 compiler. In this case, the data types should be restricted to simple
2319 cases, including primitive types. Whether complex data types can be passed
2320 depends on the situation. Probably it is safe to pass simple arrays, such
2321 as arrays of integers or floats. Records may or may not work, depending
2322 on whether both compilers lay them out identically. Complex structures
2323 involving variant records, access parameters, tasks, or protected types,
2324 are unlikely to be able to be passed.
2326 Note that in the case of GNAT running
2327 on a platform that supports HP Ada 83, a higher degree of compatibility
2328 can be guaranteed, and in particular records are laid out in an identical
2329 manner in the two compilers. Note also that if output from two different
2330 compilers is mixed, the program is responsible for dealing with elaboration
2331 issues. Probably the safest approach is to write the main program in the
2332 version of Ada other than GNAT, so that it takes care of its own elaboration
2333 requirements, and then call the GNAT-generated adainit procedure to ensure
2334 elaboration of the GNAT components. Consult the documentation of the other
2335 Ada compiler for further details on elaboration.
2337 However, it is not possible to mix the tasking run time of GNAT and
2338 HP Ada 83, All the tasking operations must either be entirely within
2339 GNAT compiled sections of the program, or entirely within HP Ada 83
2340 compiled sections of the program.
2342 @cindex Interfacing to Assembly
2343 @cindex Convention Assembler
2345 Specifies assembler as the convention. In practice this has the
2346 same effect as convention Ada (but is not equivalent in the sense of being
2347 considered the same convention).
2349 @cindex Convention Asm
2352 Equivalent to Assembler.
2354 @cindex Interfacing to COBOL
2355 @cindex Convention COBOL
2358 Data will be passed according to the conventions described
2359 in section B.4 of the Ada Reference Manual.
2362 @cindex Interfacing to C
2363 @cindex Convention C
2365 Data will be passed according to the conventions described
2366 in section B.3 of the Ada Reference Manual.
2368 A note on interfacing to a C ``varargs'' function:
2369 @findex C varargs function
2370 @cindex Interfacing to C varargs function
2371 @cindex varargs function interfaces
2375 In C, @code{varargs} allows a function to take a variable number of
2376 arguments. There is no direct equivalent in this to Ada. One
2377 approach that can be used is to create a C wrapper for each
2378 different profile and then interface to this C wrapper. For
2379 example, to print an @code{int} value using @code{printf},
2380 create a C function @code{printfi} that takes two arguments, a
2381 pointer to a string and an int, and calls @code{printf}.
2382 Then in the Ada program, use pragma @code{Import} to
2383 interface to @code{printfi}.
2386 It may work on some platforms to directly interface to
2387 a @code{varargs} function by providing a specific Ada profile
2388 for a particular call. However, this does not work on
2389 all platforms, since there is no guarantee that the
2390 calling sequence for a two argument normal C function
2391 is the same as for calling a @code{varargs} C function with
2392 the same two arguments.
2395 @cindex Convention Default
2400 @cindex Convention External
2407 @cindex Interfacing to C++
2408 @cindex Convention C++
2409 @item C_Plus_Plus (or CPP)
2410 This stands for C++. For most purposes this is identical to C.
2411 See the separate description of the specialized GNAT pragmas relating to
2412 C++ interfacing for further details.
2416 @cindex Interfacing to Fortran
2417 @cindex Convention Fortran
2419 Data will be passed according to the conventions described
2420 in section B.5 of the Ada Reference Manual.
2423 This applies to an intrinsic operation, as defined in the Ada
2424 Reference Manual. If a pragma Import (Intrinsic) applies to a subprogram,
2425 this means that the body of the subprogram is provided by the compiler itself,
2426 usually by means of an efficient code sequence, and that the user does not
2427 supply an explicit body for it. In an application program, the pragma may
2428 be applied to the following sets of names:
2432 Rotate_Left, Rotate_Right, Shift_Left, Shift_Right,
2433 Shift_Right_Arithmetic. The corresponding subprogram declaration must have
2434 two formal parameters. The
2435 first one must be a signed integer type or a modular type with a binary
2436 modulus, and the second parameter must be of type Natural.
2437 The return type must be the same as the type of the first argument. The size
2438 of this type can only be 8, 16, 32, or 64.
2441 Binary arithmetic operators: ``+'', ``-'', ``*'', ``/''
2442 The corresponding operator declaration must have parameters and result type
2443 that have the same root numeric type (for example, all three are long_float
2444 types). This simplifies the definition of operations that use type checking
2445 to perform dimensional checks:
2447 @smallexample @c ada
2448 type Distance is new Long_Float;
2449 type Time is new Long_Float;
2450 type Velocity is new Long_Float;
2451 function "/" (D : Distance; T : Time)
2453 pragma Import (Intrinsic, "/");
2457 This common idiom is often programmed with a generic definition and an
2458 explicit body. The pragma makes it simpler to introduce such declarations.
2459 It incurs no overhead in compilation time or code size, because it is
2460 implemented as a single machine instruction.
2463 General subprogram entities, to bind an Ada subprogram declaration to
2464 a compiler builtin by name with back-ends where such interfaces are
2465 available. A typical example is the set of ``__builtin'' functions
2466 exposed by the GCC back-end, as in the following example:
2468 @smallexample @c ada
2469 function builtin_sqrt (F : Float) return Float;
2470 pragma Import (Intrinsic, builtin_sqrt, "__builtin_sqrtf");
2473 Most of the GCC builtins are accessible this way, and as for other
2474 import conventions (e.g. C), it is the user's responsibility to ensure
2475 that the Ada subprogram profile matches the underlying builtin
2483 @cindex Convention Stdcall
2485 This is relevant only to Windows XP/2000/NT implementations of GNAT,
2486 and specifies that the @code{Stdcall} calling sequence will be used,
2487 as defined by the NT API. Nevertheless, to ease building
2488 cross-platform bindings this convention will be handled as a @code{C} calling
2489 convention on non-Windows platforms.
2492 @cindex Convention DLL
2494 This is equivalent to @code{Stdcall}.
2497 @cindex Convention Win32
2499 This is equivalent to @code{Stdcall}.
2503 @cindex Convention Stubbed
2505 This is a special convention that indicates that the compiler
2506 should provide a stub body that raises @code{Program_Error}.
2510 GNAT additionally provides a useful pragma @code{Convention_Identifier}
2511 that can be used to parameterize conventions and allow additional synonyms
2512 to be specified. For example if you have legacy code in which the convention
2513 identifier Fortran77 was used for Fortran, you can use the configuration
2516 @smallexample @c ada
2517 pragma Convention_Identifier (Fortran77, Fortran);
2521 And from now on the identifier Fortran77 may be used as a convention
2522 identifier (for example in an @code{Import} pragma) with the same
2526 @node Building Mixed Ada & C++ Programs
2527 @section Building Mixed Ada and C++ Programs
2530 A programmer inexperienced with mixed-language development may find that
2531 building an application containing both Ada and C++ code can be a
2532 challenge. This section gives a few
2533 hints that should make this task easier. The first section addresses
2534 the differences between interfacing with C and interfacing with C++.
2536 looks into the delicate problem of linking the complete application from
2537 its Ada and C++ parts. The last section gives some hints on how the GNAT
2538 run-time library can be adapted in order to allow inter-language dispatching
2539 with a new C++ compiler.
2542 * Interfacing to C++::
2543 * Linking a Mixed C++ & Ada Program::
2544 * A Simple Example::
2545 * Interfacing with C++ constructors::
2546 * Interfacing with C++ at the Class Level::
2549 @node Interfacing to C++
2550 @subsection Interfacing to C++
2553 GNAT supports interfacing with the G++ compiler (or any C++ compiler
2554 generating code that is compatible with the G++ Application Binary
2555 Interface ---see http://www.codesourcery.com/archives/cxx-abi).
2558 Interfacing can be done at 3 levels: simple data, subprograms, and
2559 classes. In the first two cases, GNAT offers a specific @code{Convention
2560 C_Plus_Plus} (or @code{CPP}) that behaves exactly like @code{Convention C}.
2561 Usually, C++ mangles the names of subprograms. To generate proper mangled
2562 names automatically, see @ref{Generating Ada Bindings for C and C++ headers}).
2563 This problem can also be addressed manually in two ways:
2567 by modifying the C++ code in order to force a C convention using
2568 the @code{extern "C"} syntax.
2571 by figuring out the mangled name (using e.g. @command{nm}) and using it as the
2572 Link_Name argument of the pragma import.
2576 Interfacing at the class level can be achieved by using the GNAT specific
2577 pragmas such as @code{CPP_Constructor}. @xref{Interfacing to C++,,,
2578 gnat_rm, GNAT Reference Manual}, for additional information.
2580 @node Linking a Mixed C++ & Ada Program
2581 @subsection Linking a Mixed C++ & Ada Program
2584 Usually the linker of the C++ development system must be used to link
2585 mixed applications because most C++ systems will resolve elaboration
2586 issues (such as calling constructors on global class instances)
2587 transparently during the link phase. GNAT has been adapted to ease the
2588 use of a foreign linker for the last phase. Three cases can be
2593 Using GNAT and G++ (GNU C++ compiler) from the same GCC installation:
2594 The C++ linker can simply be called by using the C++ specific driver
2597 Note that if the C++ code uses inline functions, you will need to
2598 compile your C++ code with the @code{-fkeep-inline-functions} switch in
2599 order to provide an existing function implementation that the Ada code can
2603 $ g++ -c -fkeep-inline-functions file1.C
2604 $ g++ -c -fkeep-inline-functions file2.C
2605 $ gnatmake ada_unit -largs file1.o file2.o --LINK=g++
2609 Using GNAT and G++ from two different GCC installations: If both
2610 compilers are on the @env{PATH}, the previous method may be used. It is
2611 important to note that environment variables such as
2612 @env{C_INCLUDE_PATH}, @env{GCC_EXEC_PREFIX}, @env{BINUTILS_ROOT}, and
2613 @env{GCC_ROOT} will affect both compilers
2614 at the same time and may make one of the two compilers operate
2615 improperly if set during invocation of the wrong compiler. It is also
2616 very important that the linker uses the proper @file{libgcc.a} GCC
2617 library -- that is, the one from the C++ compiler installation. The
2618 implicit link command as suggested in the @command{gnatmake} command
2619 from the former example can be replaced by an explicit link command with
2620 the full-verbosity option in order to verify which library is used:
2623 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=c++
2625 If there is a problem due to interfering environment variables, it can
2626 be worked around by using an intermediate script. The following example
2627 shows the proper script to use when GNAT has not been installed at its
2628 default location and g++ has been installed at its default location:
2636 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=./my_script
2640 Using a non-GNU C++ compiler: The commands previously described can be
2641 used to insure that the C++ linker is used. Nonetheless, you need to add
2642 a few more parameters to the link command line, depending on the exception
2645 If the @code{setjmp/longjmp} exception mechanism is used, only the paths
2646 to the libgcc libraries are required:
2651 CC $* `gcc -print-file-name=libgcc.a` `gcc -print-file-name=libgcc_eh.a`
2652 $ gnatlink ada_unit file1.o file2.o --LINK=./my_script
2655 Where CC is the name of the non-GNU C++ compiler.
2657 If the @code{zero cost} exception mechanism is used, and the platform
2658 supports automatic registration of exception tables (e.g.@: Solaris),
2659 paths to more objects are required:
2664 CC `gcc -print-file-name=crtbegin.o` $* \
2665 `gcc -print-file-name=libgcc.a` `gcc -print-file-name=libgcc_eh.a` \
2666 `gcc -print-file-name=crtend.o`
2667 $ gnatlink ada_unit file1.o file2.o --LINK=./my_script
2670 If the @code{zero cost} exception mechanism is used, and the platform
2671 doesn't support automatic registration of exception tables (e.g.@: HP-UX
2672 or AIX), the simple approach described above will not work and
2673 a pre-linking phase using GNAT will be necessary.
2677 Another alternative is to use the @command{gprbuild} multi-language builder
2678 which has a large knowledge base and knows how to link Ada and C++ code
2679 together automatically in most cases.
2681 @node A Simple Example
2682 @subsection A Simple Example
2684 The following example, provided as part of the GNAT examples, shows how
2685 to achieve procedural interfacing between Ada and C++ in both
2686 directions. The C++ class A has two methods. The first method is exported
2687 to Ada by the means of an extern C wrapper function. The second method
2688 calls an Ada subprogram. On the Ada side, The C++ calls are modelled by
2689 a limited record with a layout comparable to the C++ class. The Ada
2690 subprogram, in turn, calls the C++ method. So, starting from the C++
2691 main program, the process passes back and forth between the two
2695 Here are the compilation commands:
2697 $ gnatmake -c simple_cpp_interface
2700 $ gnatbind -n simple_cpp_interface
2701 $ gnatlink simple_cpp_interface -o cpp_main --LINK=g++
2702 -lstdc++ ex7.o cpp_main.o
2706 Here are the corresponding sources:
2714 void adainit (void);
2715 void adafinal (void);
2716 void method1 (A *t);
2738 class A : public Origin @{
2740 void method1 (void);
2741 void method2 (int v);
2751 extern "C" @{ void ada_method2 (A *t, int v);@}
2753 void A::method1 (void)
2756 printf ("in A::method1, a_value = %d \n",a_value);
2760 void A::method2 (int v)
2762 ada_method2 (this, v);
2763 printf ("in A::method2, a_value = %d \n",a_value);
2770 printf ("in A::A, a_value = %d \n",a_value);
2774 @smallexample @c ada
2776 package body Simple_Cpp_Interface is
2778 procedure Ada_Method2 (This : in out A; V : Integer) is
2784 end Simple_Cpp_Interface;
2787 package Simple_Cpp_Interface is
2790 Vptr : System.Address;
2794 pragma Convention (C, A);
2796 procedure Method1 (This : in out A);
2797 pragma Import (C, Method1);
2799 procedure Ada_Method2 (This : in out A; V : Integer);
2800 pragma Export (C, Ada_Method2);
2802 end Simple_Cpp_Interface;
2805 @node Interfacing with C++ constructors
2806 @subsection Interfacing with C++ constructors
2809 In order to interface with C++ constructors GNAT provides the
2810 @code{pragma CPP_Constructor} (@xref{Interfacing to C++,,,
2811 gnat_rm, GNAT Reference Manual}, for additional information).
2812 In this section we present some common uses of C++ constructors
2813 in mixed-languages programs in GNAT.
2815 Let us assume that we need to interface with the following
2823 @b{virtual} int Get_Value ();
2824 Root(); // Default constructor
2825 Root(int v); // 1st non-default constructor
2826 Root(int v, int w); // 2nd non-default constructor
2830 For this purpose we can write the following package spec (further
2831 information on how to build this spec is available in
2832 @ref{Interfacing with C++ at the Class Level} and
2833 @ref{Generating Ada Bindings for C and C++ headers}).
2835 @smallexample @c ada
2836 with Interfaces.C; use Interfaces.C;
2838 type Root is tagged limited record
2842 pragma Import (CPP, Root);
2844 function Get_Value (Obj : Root) return int;
2845 pragma Import (CPP, Get_Value);
2847 function Constructor return Root;
2848 pragma Cpp_Constructor (Constructor, "_ZN4RootC1Ev");
2850 function Constructor (v : Integer) return Root;
2851 pragma Cpp_Constructor (Constructor, "_ZN4RootC1Ei");
2853 function Constructor (v, w : Integer) return Root;
2854 pragma Cpp_Constructor (Constructor, "_ZN4RootC1Eii");
2858 On the Ada side the constructor is represented by a function (whose
2859 name is arbitrary) that returns the classwide type corresponding to
2860 the imported C++ class. Although the constructor is described as a
2861 function, it is typically a procedure with an extra implicit argument
2862 (the object being initialized) at the implementation level. GNAT
2863 issues the appropriate call, whatever it is, to get the object
2864 properly initialized.
2866 Constructors can only appear in the following contexts:
2870 On the right side of an initialization of an object of type @var{T}.
2872 On the right side of an initialization of a record component of type @var{T}.
2874 In an Ada 2005 limited aggregate.
2876 In an Ada 2005 nested limited aggregate.
2878 In an Ada 2005 limited aggregate that initializes an object built in
2879 place by an extended return statement.
2883 In a declaration of an object whose type is a class imported from C++,
2884 either the default C++ constructor is implicitly called by GNAT, or
2885 else the required C++ constructor must be explicitly called in the
2886 expression that initializes the object. For example:
2888 @smallexample @c ada
2890 Obj2 : Root := Constructor;
2891 Obj3 : Root := Constructor (v => 10);
2892 Obj4 : Root := Constructor (30, 40);
2895 The first two declarations are equivalent: in both cases the default C++
2896 constructor is invoked (in the former case the call to the constructor is
2897 implicit, and in the latter case the call is explicit in the object
2898 declaration). @code{Obj3} is initialized by the C++ non-default constructor
2899 that takes an integer argument, and @code{Obj4} is initialized by the
2900 non-default C++ constructor that takes two integers.
2902 Let us derive the imported C++ class in the Ada side. For example:
2904 @smallexample @c ada
2905 type DT is new Root with record
2906 C_Value : Natural := 2009;
2910 In this case the components DT inherited from the C++ side must be
2911 initialized by a C++ constructor, and the additional Ada components
2912 of type DT are initialized by GNAT. The initialization of such an
2913 object is done either by default, or by means of a function returning
2914 an aggregate of type DT, or by means of an extension aggregate.
2916 @smallexample @c ada
2918 Obj6 : DT := Function_Returning_DT (50);
2919 Obj7 : DT := (Constructor (30,40) with C_Value => 50);
2922 The declaration of @code{Obj5} invokes the default constructors: the
2923 C++ default constructor of the parent type takes care of the initialization
2924 of the components inherited from Root, and GNAT takes care of the default
2925 initialization of the additional Ada components of type DT (that is,
2926 @code{C_Value} is initialized to value 2009). The order of invocation of
2927 the constructors is consistent with the order of elaboration required by
2928 Ada and C++. That is, the constructor of the parent type is always called
2929 before the constructor of the derived type.
2931 Let us now consider a record that has components whose type is imported
2932 from C++. For example:
2934 @smallexample @c ada
2935 type Rec1 is limited record
2936 Data1 : Root := Constructor (10);
2937 Value : Natural := 1000;
2940 type Rec2 (D : Integer := 20) is limited record
2942 Data2 : Root := Constructor (D, 30);
2946 The initialization of an object of type @code{Rec2} will call the
2947 non-default C++ constructors specified for the imported components.
2950 @smallexample @c ada
2954 Using Ada 2005 we can use limited aggregates to initialize an object
2955 invoking C++ constructors that differ from those specified in the type
2956 declarations. For example:
2958 @smallexample @c ada
2959 Obj9 : Rec2 := (Rec => (Data1 => Constructor (15, 16),
2964 The above declaration uses an Ada 2005 limited aggregate to
2965 initialize @code{Obj9}, and the C++ constructor that has two integer
2966 arguments is invoked to initialize the @code{Data1} component instead
2967 of the constructor specified in the declaration of type @code{Rec1}. In
2968 Ada 2005 the box in the aggregate indicates that unspecified components
2969 are initialized using the expression (if any) available in the component
2970 declaration. That is, in this case discriminant @code{D} is initialized
2971 to value @code{20}, @code{Value} is initialized to value 1000, and the
2972 non-default C++ constructor that handles two integers takes care of
2973 initializing component @code{Data2} with values @code{20,30}.
2975 In Ada 2005 we can use the extended return statement to build the Ada
2976 equivalent to C++ non-default constructors. For example:
2978 @smallexample @c ada
2979 function Constructor (V : Integer) return Rec2 is
2981 return Obj : Rec2 := (Rec => (Data1 => Constructor (V, 20),
2984 -- Further actions required for construction of
2985 -- objects of type Rec2
2991 In this example the extended return statement construct is used to
2992 build in place the returned object whose components are initialized
2993 by means of a limited aggregate. Any further action associated with
2994 the constructor can be placed inside the construct.
2996 @node Interfacing with C++ at the Class Level
2997 @subsection Interfacing with C++ at the Class Level
2999 In this section we demonstrate the GNAT features for interfacing with
3000 C++ by means of an example making use of Ada 2005 abstract interface
3001 types. This example consists of a classification of animals; classes
3002 have been used to model our main classification of animals, and
3003 interfaces provide support for the management of secondary
3004 classifications. We first demonstrate a case in which the types and
3005 constructors are defined on the C++ side and imported from the Ada
3006 side, and latter the reverse case.
3008 The root of our derivation will be the @code{Animal} class, with a
3009 single private attribute (the @code{Age} of the animal) and two public
3010 primitives to set and get the value of this attribute.
3015 @b{virtual} void Set_Age (int New_Age);
3016 @b{virtual} int Age ();
3022 Abstract interface types are defined in C++ by means of classes with pure
3023 virtual functions and no data members. In our example we will use two
3024 interfaces that provide support for the common management of @code{Carnivore}
3025 and @code{Domestic} animals:
3028 @b{class} Carnivore @{
3030 @b{virtual} int Number_Of_Teeth () = 0;
3033 @b{class} Domestic @{
3035 @b{virtual void} Set_Owner (char* Name) = 0;
3039 Using these declarations, we can now say that a @code{Dog} is an animal that is
3040 both Carnivore and Domestic, that is:
3043 @b{class} Dog : Animal, Carnivore, Domestic @{
3045 @b{virtual} int Number_Of_Teeth ();
3046 @b{virtual} void Set_Owner (char* Name);
3048 Dog(); // Constructor
3055 In the following examples we will assume that the previous declarations are
3056 located in a file named @code{animals.h}. The following package demonstrates
3057 how to import these C++ declarations from the Ada side:
3059 @smallexample @c ada
3060 with Interfaces.C.Strings; use Interfaces.C.Strings;
3062 type Carnivore is interface;
3063 pragma Convention (C_Plus_Plus, Carnivore);
3064 function Number_Of_Teeth (X : Carnivore)
3065 return Natural is abstract;
3067 type Domestic is interface;
3068 pragma Convention (C_Plus_Plus, Set_Owner);
3070 (X : in out Domestic;
3071 Name : Chars_Ptr) is abstract;
3073 type Animal is tagged record
3076 pragma Import (C_Plus_Plus, Animal);
3078 procedure Set_Age (X : in out Animal; Age : Integer);
3079 pragma Import (C_Plus_Plus, Set_Age);
3081 function Age (X : Animal) return Integer;
3082 pragma Import (C_Plus_Plus, Age);
3084 type Dog is new Animal and Carnivore and Domestic with record
3085 Tooth_Count : Natural;
3086 Owner : String (1 .. 30);
3088 pragma Import (C_Plus_Plus, Dog);
3090 function Number_Of_Teeth (A : Dog) return Integer;
3091 pragma Import (C_Plus_Plus, Number_Of_Teeth);
3093 procedure Set_Owner (A : in out Dog; Name : Chars_Ptr);
3094 pragma Import (C_Plus_Plus, Set_Owner);
3096 function New_Dog return Dog;
3097 pragma CPP_Constructor (New_Dog);
3098 pragma Import (CPP, New_Dog, "_ZN3DogC2Ev");
3102 Thanks to the compatibility between GNAT run-time structures and the C++ ABI,
3103 interfacing with these C++ classes is easy. The only requirement is that all
3104 the primitives and components must be declared exactly in the same order in
3107 Regarding the abstract interfaces, we must indicate to the GNAT compiler by
3108 means of a @code{pragma Convention (C_Plus_Plus)}, the convention used to pass
3109 the arguments to the called primitives will be the same as for C++. For the
3110 imported classes we use @code{pragma Import} with convention @code{C_Plus_Plus}
3111 to indicate that they have been defined on the C++ side; this is required
3112 because the dispatch table associated with these tagged types will be built
3113 in the C++ side and therefore will not contain the predefined Ada primitives
3114 which Ada would otherwise expect.
3116 As the reader can see there is no need to indicate the C++ mangled names
3117 associated with each subprogram because it is assumed that all the calls to
3118 these primitives will be dispatching calls. The only exception is the
3119 constructor, which must be registered with the compiler by means of
3120 @code{pragma CPP_Constructor} and needs to provide its associated C++
3121 mangled name because the Ada compiler generates direct calls to it.
3123 With the above packages we can now declare objects of type Dog on the Ada side
3124 and dispatch calls to the corresponding subprograms on the C++ side. We can
3125 also extend the tagged type Dog with further fields and primitives, and
3126 override some of its C++ primitives on the Ada side. For example, here we have
3127 a type derivation defined on the Ada side that inherits all the dispatching
3128 primitives of the ancestor from the C++ side.
3131 @b{with} Animals; @b{use} Animals;
3132 @b{package} Vaccinated_Animals @b{is}
3133 @b{type} Vaccinated_Dog @b{is new} Dog @b{with null record};
3134 @b{function} Vaccination_Expired (A : Vaccinated_Dog) @b{return} Boolean;
3135 @b{end} Vaccinated_Animals;
3138 It is important to note that, because of the ABI compatibility, the programmer
3139 does not need to add any further information to indicate either the object
3140 layout or the dispatch table entry associated with each dispatching operation.
3142 Now let us define all the types and constructors on the Ada side and export
3143 them to C++, using the same hierarchy of our previous example:
3145 @smallexample @c ada
3146 with Interfaces.C.Strings;
3147 use Interfaces.C.Strings;
3149 type Carnivore is interface;
3150 pragma Convention (C_Plus_Plus, Carnivore);
3151 function Number_Of_Teeth (X : Carnivore)
3152 return Natural is abstract;
3154 type Domestic is interface;
3155 pragma Convention (C_Plus_Plus, Set_Owner);
3157 (X : in out Domestic;
3158 Name : Chars_Ptr) is abstract;
3160 type Animal is tagged record
3163 pragma Convention (C_Plus_Plus, Animal);
3165 procedure Set_Age (X : in out Animal; Age : Integer);
3166 pragma Export (C_Plus_Plus, Set_Age);
3168 function Age (X : Animal) return Integer;
3169 pragma Export (C_Plus_Plus, Age);
3171 type Dog is new Animal and Carnivore and Domestic with record
3172 Tooth_Count : Natural;
3173 Owner : String (1 .. 30);
3175 pragma Convention (C_Plus_Plus, Dog);
3177 function Number_Of_Teeth (A : Dog) return Integer;
3178 pragma Export (C_Plus_Plus, Number_Of_Teeth);
3180 procedure Set_Owner (A : in out Dog; Name : Chars_Ptr);
3181 pragma Export (C_Plus_Plus, Set_Owner);
3183 function New_Dog return Dog'Class;
3184 pragma Export (C_Plus_Plus, New_Dog);
3188 Compared with our previous example the only difference is the use of
3189 @code{pragma Export} to indicate to the GNAT compiler that the primitives will
3190 be available to C++. Thanks to the ABI compatibility, on the C++ side there is
3191 nothing else to be done; as explained above, the only requirement is that all
3192 the primitives and components are declared in exactly the same order.
3194 For completeness, let us see a brief C++ main program that uses the
3195 declarations available in @code{animals.h} (presented in our first example) to
3196 import and use the declarations from the Ada side, properly initializing and
3197 finalizing the Ada run-time system along the way:
3200 @b{#include} "animals.h"
3201 @b{#include} <iostream>
3202 @b{using namespace} std;
3204 void Check_Carnivore (Carnivore *obj) @{@dots{}@}
3205 void Check_Domestic (Domestic *obj) @{@dots{}@}
3206 void Check_Animal (Animal *obj) @{@dots{}@}
3207 void Check_Dog (Dog *obj) @{@dots{}@}
3210 void adainit (void);
3211 void adafinal (void);
3217 Dog *obj = new_dog(); // Ada constructor
3218 Check_Carnivore (obj); // Check secondary DT
3219 Check_Domestic (obj); // Check secondary DT
3220 Check_Animal (obj); // Check primary DT
3221 Check_Dog (obj); // Check primary DT
3226 adainit (); test(); adafinal ();
3231 @node Comparison between GNAT and C/C++ Compilation Models
3232 @section Comparison between GNAT and C/C++ Compilation Models
3235 The GNAT model of compilation is close to the C and C++ models. You can
3236 think of Ada specs as corresponding to header files in C. As in C, you
3237 don't need to compile specs; they are compiled when they are used. The
3238 Ada @code{with} is similar in effect to the @code{#include} of a C
3241 One notable difference is that, in Ada, you may compile specs separately
3242 to check them for semantic and syntactic accuracy. This is not always
3243 possible with C headers because they are fragments of programs that have
3244 less specific syntactic or semantic rules.
3246 The other major difference is the requirement for running the binder,
3247 which performs two important functions. First, it checks for
3248 consistency. In C or C++, the only defense against assembling
3249 inconsistent programs lies outside the compiler, in a makefile, for
3250 example. The binder satisfies the Ada requirement that it be impossible
3251 to construct an inconsistent program when the compiler is used in normal
3254 @cindex Elaboration order control
3255 The other important function of the binder is to deal with elaboration
3256 issues. There are also elaboration issues in C++ that are handled
3257 automatically. This automatic handling has the advantage of being
3258 simpler to use, but the C++ programmer has no control over elaboration.
3259 Where @code{gnatbind} might complain there was no valid order of
3260 elaboration, a C++ compiler would simply construct a program that
3261 malfunctioned at run time.
3264 @node Comparison between GNAT and Conventional Ada Library Models
3265 @section Comparison between GNAT and Conventional Ada Library Models
3268 This section is intended for Ada programmers who have
3269 used an Ada compiler implementing the traditional Ada library
3270 model, as described in the Ada Reference Manual.
3272 @cindex GNAT library
3273 In GNAT, there is no ``library'' in the normal sense. Instead, the set of
3274 source files themselves acts as the library. Compiling Ada programs does
3275 not generate any centralized information, but rather an object file and
3276 a ALI file, which are of interest only to the binder and linker.
3277 In a traditional system, the compiler reads information not only from
3278 the source file being compiled, but also from the centralized library.
3279 This means that the effect of a compilation depends on what has been
3280 previously compiled. In particular:
3284 When a unit is @code{with}'ed, the unit seen by the compiler corresponds
3285 to the version of the unit most recently compiled into the library.
3288 Inlining is effective only if the necessary body has already been
3289 compiled into the library.
3292 Compiling a unit may obsolete other units in the library.
3296 In GNAT, compiling one unit never affects the compilation of any other
3297 units because the compiler reads only source files. Only changes to source
3298 files can affect the results of a compilation. In particular:
3302 When a unit is @code{with}'ed, the unit seen by the compiler corresponds
3303 to the source version of the unit that is currently accessible to the
3308 Inlining requires the appropriate source files for the package or
3309 subprogram bodies to be available to the compiler. Inlining is always
3310 effective, independent of the order in which units are complied.
3313 Compiling a unit never affects any other compilations. The editing of
3314 sources may cause previous compilations to be out of date if they
3315 depended on the source file being modified.
3319 The most important result of these differences is that order of compilation
3320 is never significant in GNAT. There is no situation in which one is
3321 required to do one compilation before another. What shows up as order of
3322 compilation requirements in the traditional Ada library becomes, in
3323 GNAT, simple source dependencies; in other words, there is only a set
3324 of rules saying what source files must be present when a file is
3328 @node Placement of temporary files
3329 @section Placement of temporary files
3330 @cindex Temporary files (user control over placement)
3333 GNAT creates temporary files in the directory designated by the environment
3334 variable @env{TMPDIR}.
3335 (See the HP @emph{C RTL Reference Manual} on the function @code{getenv()}
3336 for detailed information on how environment variables are resolved.
3337 For most users the easiest way to make use of this feature is to simply
3338 define @env{TMPDIR} as a job level logical name).
3339 For example, if you wish to use a Ramdisk (assuming DECRAM is installed)
3340 for compiler temporary files, then you can include something like the
3341 following command in your @file{LOGIN.COM} file:
3344 $ define/job TMPDIR "/disk$scratchram/000000/temp/"
3348 If @env{TMPDIR} is not defined, then GNAT uses the directory designated by
3349 @env{TMP}; if @env{TMP} is not defined, then GNAT uses the directory
3350 designated by @env{TEMP}.
3351 If none of these environment variables are defined then GNAT uses the
3352 directory designated by the logical name @code{SYS$SCRATCH:}
3353 (by default the user's home directory). If all else fails
3354 GNAT uses the current directory for temporary files.
3357 @c *************************
3358 @node Compiling with gcc
3359 @chapter Compiling with @command{gcc}
3362 This chapter discusses how to compile Ada programs using the @command{gcc}
3363 command. It also describes the set of switches
3364 that can be used to control the behavior of the compiler.
3366 * Compiling Programs::
3367 * Switches for gcc::
3368 * Search Paths and the Run-Time Library (RTL)::
3369 * Order of Compilation Issues::
3373 @node Compiling Programs
3374 @section Compiling Programs
3377 The first step in creating an executable program is to compile the units
3378 of the program using the @command{gcc} command. You must compile the
3383 the body file (@file{.adb}) for a library level subprogram or generic
3387 the spec file (@file{.ads}) for a library level package or generic
3388 package that has no body
3391 the body file (@file{.adb}) for a library level package
3392 or generic package that has a body
3397 You need @emph{not} compile the following files
3402 the spec of a library unit which has a body
3409 because they are compiled as part of compiling related units. GNAT
3411 when the corresponding body is compiled, and subunits when the parent is
3414 @cindex cannot generate code
3415 If you attempt to compile any of these files, you will get one of the
3416 following error messages (where @var{fff} is the name of the file you
3420 cannot generate code for file @var{fff} (package spec)
3421 to check package spec, use -gnatc
3423 cannot generate code for file @var{fff} (missing subunits)
3424 to check parent unit, use -gnatc
3426 cannot generate code for file @var{fff} (subprogram spec)
3427 to check subprogram spec, use -gnatc
3429 cannot generate code for file @var{fff} (subunit)
3430 to check subunit, use -gnatc
3434 As indicated by the above error messages, if you want to submit
3435 one of these files to the compiler to check for correct semantics
3436 without generating code, then use the @option{-gnatc} switch.
3438 The basic command for compiling a file containing an Ada unit is
3441 @c $ gcc -c @ovar{switches} @file{file name}
3442 @c Expanding @ovar macro inline (explanation in macro def comments)
3443 $ gcc -c @r{[}@var{switches}@r{]} @file{file name}
3447 where @var{file name} is the name of the Ada file (usually
3449 @file{.ads} for a spec or @file{.adb} for a body).
3452 @option{-c} switch to tell @command{gcc} to compile, but not link, the file.
3454 The result of a successful compilation is an object file, which has the
3455 same name as the source file but an extension of @file{.o} and an Ada
3456 Library Information (ALI) file, which also has the same name as the
3457 source file, but with @file{.ali} as the extension. GNAT creates these
3458 two output files in the current directory, but you may specify a source
3459 file in any directory using an absolute or relative path specification
3460 containing the directory information.
3463 @command{gcc} is actually a driver program that looks at the extensions of
3464 the file arguments and loads the appropriate compiler. For example, the
3465 GNU C compiler is @file{cc1}, and the Ada compiler is @file{gnat1}.
3466 These programs are in directories known to the driver program (in some
3467 configurations via environment variables you set), but need not be in
3468 your path. The @command{gcc} driver also calls the assembler and any other
3469 utilities needed to complete the generation of the required object
3472 It is possible to supply several file names on the same @command{gcc}
3473 command. This causes @command{gcc} to call the appropriate compiler for
3474 each file. For example, the following command lists two separate
3475 files to be compiled:
3478 $ gcc -c x.adb y.adb
3482 calls @code{gnat1} (the Ada compiler) twice to compile @file{x.adb} and
3484 The compiler generates two object files @file{x.o} and @file{y.o}
3485 and the two ALI files @file{x.ali} and @file{y.ali}.
3486 Any switches apply to all the files ^listed,^listed.^
3488 @node Switches for gcc
3489 @section Switches for @command{gcc}
3492 The @command{gcc} command accepts switches that control the
3493 compilation process. These switches are fully described in this section.
3494 First we briefly list all the switches, in alphabetical order, then we
3495 describe the switches in more detail in functionally grouped sections.
3497 More switches exist for GCC than those documented here, especially
3498 for specific targets. However, their use is not recommended as
3499 they may change code generation in ways that are incompatible with
3500 the Ada run-time library, or can cause inconsistencies between
3504 * Output and Error Message Control::
3505 * Warning Message Control::
3506 * Debugging and Assertion Control::
3507 * Validity Checking::
3510 * Using gcc for Syntax Checking::
3511 * Using gcc for Semantic Checking::
3512 * Compiling Different Versions of Ada::
3513 * Character Set Control::
3514 * File Naming Control::
3515 * Subprogram Inlining Control::
3516 * Auxiliary Output Control::
3517 * Debugging Control::
3518 * Exception Handling Control::
3519 * Units to Sources Mapping Files::
3520 * Integrated Preprocessing::
3521 * Code Generation Control::
3530 @cindex @option{-b} (@command{gcc})
3531 @item -b @var{target}
3532 Compile your program to run on @var{target}, which is the name of a
3533 system configuration. You must have a GNAT cross-compiler built if
3534 @var{target} is not the same as your host system.
3537 @cindex @option{-B} (@command{gcc})
3538 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
3539 from @var{dir} instead of the default location. Only use this switch
3540 when multiple versions of the GNAT compiler are available.
3541 @xref{Directory Options,, Options for Directory Search, gcc, Using the
3542 GNU Compiler Collection (GCC)}, for further details. You would normally
3543 use the @option{-b} or @option{-V} switch instead.
3546 @cindex @option{-c} (@command{gcc})
3547 Compile. Always use this switch when compiling Ada programs.
3549 Note: for some other languages when using @command{gcc}, notably in
3550 the case of C and C++, it is possible to use
3551 use @command{gcc} without a @option{-c} switch to
3552 compile and link in one step. In the case of GNAT, you
3553 cannot use this approach, because the binder must be run
3554 and @command{gcc} cannot be used to run the GNAT binder.
3557 @item -fcallgraph-info@r{[}=su,da@r{]}
3558 @cindex @option{-fcallgraph-info} (@command{gcc})
3559 Makes the compiler output callgraph information for the program, on a
3560 per-file basis. The information is generated in the VCG format. It can
3561 be decorated with additional, per-node and/or per-edge information, if a
3562 list of comma-separated markers is additionally specified. When the
3563 @var{su} marker is specified, the callgraph is decorated with stack usage information; it is equivalent to @option{-fstack-usage}. When the @var{da}
3564 marker is specified, the callgraph is decorated with information about
3565 dynamically allocated objects.
3568 @cindex @option{-fdump-scos} (@command{gcc})
3569 Generates SCO (Source Coverage Obligation) information in the ALI file.
3570 This information is used by advanced coverage tools. See unit @file{SCOs}
3571 in the compiler sources for details in files @file{scos.ads} and
3574 @item -flto@r{[}=n@r{]}
3575 @cindex @option{-flto} (@command{gcc})
3576 Enables Link Time Optimization. This switch must be used in conjunction
3577 with the traditional @option{-Ox} switches and instructs the compiler to
3578 defer most optimizations until the link stage. The advantage of this
3579 approach is that the compiler can do a whole-program analysis and choose
3580 the best interprocedural optimization strategy based on a complete view
3581 of the program, instead of a fragmentary view with the usual approach.
3582 This can also speed up the compilation of huge programs and reduce the
3583 size of the final executable, compared with a per-unit compilation with
3584 full inlining across modules enabled with the @option{-gnatn2} switch.
3585 The drawback of this approach is that it may require much more memory.
3586 The switch, as well as the accompanying @option{-Ox} switches, must be
3587 specified both for the compilation and the link phases.
3588 If the @var{n} parameter is specified, the optimization and final code
3589 generation at link time are executed using @var{n} parallel jobs by
3590 means of an installed @command{make} program.
3593 @cindex @option{-fno-inline} (@command{gcc})
3594 Suppresses all inlining, even if other optimization or inlining
3595 switches are set. This includes suppression of inlining that
3596 results from the use of the pragma @code{Inline_Always}.
3597 Any occurrences of pragma @code{Inline} or @code{Inline_Always}
3598 are ignored, and @option{-gnatn} and @option{-gnatN} have no
3599 effects if this switch is present. Note that inlining can also
3600 be suppressed on a finer-grained basis with pragma @code{No_Inline}.
3602 @item -fno-inline-functions
3603 @cindex @option{-fno-inline-functions} (@command{gcc})
3604 Suppresses automatic inlining of subprograms, which is enabled
3605 if @option{-O3} is used.
3607 @item -fno-inline-small-functions
3608 @cindex @option{-fno-inline-small-functions} (@command{gcc})
3609 Suppresses automatic inlining of small subprograms, which is enabled
3610 if @option{-O2} is used.
3612 @item -fno-inline-functions-called-once
3613 @cindex @option{-fno-inline-functions-called-once} (@command{gcc})
3614 Suppresses inlining of subprograms local to the unit and called once
3615 from within it, which is enabled if @option{-O1} is used.
3618 @cindex @option{-fno-ivopts} (@command{gcc})
3619 Suppresses high-level loop induction variable optimizations, which are
3620 enabled if @option{-O1} is used. These optimizations are generally
3621 profitable but, for some specific cases of loops with numerous uses
3622 of the iteration variable that follow a common pattern, they may end
3623 up destroying the regularity that could be exploited at a lower level
3624 and thus producing inferior code.
3626 @item -fno-strict-aliasing
3627 @cindex @option{-fno-strict-aliasing} (@command{gcc})
3628 Causes the compiler to avoid assumptions regarding non-aliasing
3629 of objects of different types. See
3630 @ref{Optimization and Strict Aliasing} for details.
3633 @cindex @option{-fstack-check} (@command{gcc})
3634 Activates stack checking.
3635 See @ref{Stack Overflow Checking} for details.
3638 @cindex @option{-fstack-usage} (@command{gcc})
3639 Makes the compiler output stack usage information for the program, on a
3640 per-subprogram basis. See @ref{Static Stack Usage Analysis} for details.
3643 @cindex @option{^-g^/DEBUG^} (@command{gcc})
3644 Generate debugging information. This information is stored in the object
3645 file and copied from there to the final executable file by the linker,
3646 where it can be read by the debugger. You must use the
3647 @option{^-g^/DEBUG^} switch if you plan on using the debugger.
3650 @cindex @option{-gnat83} (@command{gcc})
3651 Enforce Ada 83 restrictions.
3654 @cindex @option{-gnat95} (@command{gcc})
3655 Enforce Ada 95 restrictions.
3658 @cindex @option{-gnat05} (@command{gcc})
3659 Allow full Ada 2005 features.
3662 @cindex @option{-gnat2005} (@command{gcc})
3663 Allow full Ada 2005 features (same as @option{-gnat05})
3666 @cindex @option{-gnat12} (@command{gcc})
3669 @cindex @option{-gnat2012} (@command{gcc})
3670 Allow full Ada 2012 features (same as @option{-gnat12})
3673 @cindex @option{-gnata} (@command{gcc})
3674 Assertions enabled. @code{Pragma Assert} and @code{pragma Debug} to be
3675 activated. Note that these pragmas can also be controlled using the
3676 configuration pragmas @code{Assertion_Policy} and @code{Debug_Policy}.
3677 It also activates pragmas @code{Check}, @code{Precondition}, and
3678 @code{Postcondition}. Note that these pragmas can also be controlled
3679 using the configuration pragma @code{Check_Policy}. In Ada 2012, it
3680 also activates all assertions defined in the RM as aspects: preconditions,
3681 postconditions, type invariants and (sub)type predicates. In all Ada modes,
3682 corresponding pragmas for type invariants and (sub)type predicates are
3686 @cindex @option{-gnatA} (@command{gcc})
3687 Avoid processing @file{gnat.adc}. If a @file{gnat.adc} file is present,
3691 @cindex @option{-gnatb} (@command{gcc})
3692 Generate brief messages to @file{stderr} even if verbose mode set.
3695 @cindex @option{-gnatB} (@command{gcc})
3696 Assume no invalid (bad) values except for 'Valid attribute use
3697 (@pxref{Validity Checking}).
3700 @cindex @option{-gnatc} (@command{gcc})
3701 Check syntax and semantics only (no code generation attempted). When the
3702 compiler is invoked by @command{gnatmake}, if the switch @option{-gnatc} is
3703 only given to the compiler (after @option{-cargs} or in package Compiler of
3704 the project file, @command{gnatmake} will fail because it will not find the
3705 object file after compilation. If @command{gnatmake} is called with
3706 @option{-gnatc} as a builder switch (before @option{-cargs} or in package
3707 Builder of the project file) then @command{gnatmake} will not fail because
3708 it will not look for the object files after compilation, and it will not try
3709 to build and link. This switch may not be given if a previous @code{-gnatR}
3710 switch has been given, since @code{-gnatR} requires that the code generator
3711 be called to complete determination of representation information.
3714 @cindex @option{-gnatC} (@command{gcc})
3715 Generate CodePeer information (no code generation attempted).
3716 This switch will generate an intermediate representation suitable for
3717 use by CodePeer (@file{.scil} files). This switch is not compatible with
3718 code generation (it will, among other things, disable some switches such
3719 as -gnatn, and enable others such as -gnata).
3722 @cindex @option{-gnatd} (@command{gcc})
3723 Specify debug options for the compiler. The string of characters after
3724 the @option{-gnatd} specify the specific debug options. The possible
3725 characters are 0-9, a-z, A-Z, optionally preceded by a dot. See
3726 compiler source file @file{debug.adb} for details of the implemented
3727 debug options. Certain debug options are relevant to applications
3728 programmers, and these are documented at appropriate points in this
3733 @cindex @option{-gnatD[nn]} (@command{gcc})
3736 @item /XDEBUG /LXDEBUG=nnn
3738 Create expanded source files for source level debugging. This switch
3739 also suppress generation of cross-reference information
3740 (see @option{-gnatx}). Note that this switch is not allowed if a previous
3741 -gnatR switch has been given, since these two switches are not compatible.
3743 @item ^-gnateA^/ALIASING_CHECK^
3744 @cindex @option{-gnateA} (@command{gcc})
3745 Check that there is no aliasing between two parameters of the same subprogram.
3747 @item -gnatec=@var{path}
3748 @cindex @option{-gnatec} (@command{gcc})
3749 Specify a configuration pragma file
3751 (the equal sign is optional)
3753 (@pxref{The Configuration Pragmas Files}).
3755 @item ^-gnated^/DISABLE_ATOMIC_SYNCHRONIZATION^
3756 @cindex @option{-gnated} (@command{gcc})
3757 Disable atomic synchronization
3759 @item ^-gnateD^/DATA_PREPROCESSING=^symbol@r{[}=@var{value}@r{]}
3760 @cindex @option{-gnateD} (@command{gcc})
3761 Defines a symbol, associated with @var{value}, for preprocessing.
3762 (@pxref{Integrated Preprocessing}).
3765 @cindex @option{-gnateE} (@command{gcc})
3766 Generate extra information in exception messages. In particular, display
3767 extra column information and the value and range associated with index and
3768 range check failures, and extra column information for access checks.
3769 In cases where the compiler is able to determine at compile time that
3770 a check will fail, it gives a warning, and the extra information is not
3771 produced at run time.
3774 @cindex @option{-gnatef} (@command{gcc})
3775 Display full source path name in brief error messages.
3778 @cindex @option{-gnateF} (@command{gcc})
3779 Check for overflow on all floating-point operations, including those
3780 for unconstrained predefined types. See description of pragma
3781 @code{Check_Float_Overflow} in GNAT RM.
3784 @cindex @option{-gnateG} (@command{gcc})
3785 Save result of preprocessing in a text file.
3787 @item -gnatei@var{nnn}
3788 @cindex @option{-gnatei} (@command{gcc})
3789 Set maximum number of instantiations during compilation of a single unit to
3790 @var{nnn}. This may be useful in increasing the default maximum of 8000 for
3791 the rare case when a single unit legitimately exceeds this limit.
3793 @item -gnateI@var{nnn}
3794 @cindex @option{-gnateI} (@command{gcc})
3795 Indicates that the source is a multi-unit source and that the index of the
3796 unit to compile is @var{nnn}. @var{nnn} needs to be a positive number and need
3797 to be a valid index in the multi-unit source.
3799 @item -gnatem=@var{path}
3800 @cindex @option{-gnatem} (@command{gcc})
3801 Specify a mapping file
3803 (the equal sign is optional)
3805 (@pxref{Units to Sources Mapping Files}).
3807 @item -gnatep=@var{file}
3808 @cindex @option{-gnatep} (@command{gcc})
3809 Specify a preprocessing data file
3811 (the equal sign is optional)
3813 (@pxref{Integrated Preprocessing}).
3816 @cindex @option{-gnateP} (@command{gcc})
3817 Turn categorization dependency errors into warnings.
3818 Ada requires that units that WITH one another have compatible categories, for
3819 example a Pure unit cannot WITH a Preelaborate unit. If this switch is used,
3820 these errors become warnings (which can be ignored, or suppressed in the usual
3821 manner). This can be useful in some specialized circumstances such as the
3822 temporary use of special test software.
3825 @cindex @option{-gnateS} (@command{gcc})
3826 Synonym of @option{-fdump-scos}, kept for backards compatibility.
3828 @item ^-gnatet^/TARGET_DEPENDENT_INFO^
3829 @cindex @option{-gnatet} (@command{gcc})
3830 Generate target dependent information.
3832 @item ^-gnateV^/PARAMETER_VALIDITY_CHECK^
3833 @cindex @option{-gnateV} (@command{gcc})
3834 Check validity of subprogram parameters.
3836 @item ^-gnateY^/IGNORE_SUPPRESS_SYLE_CHECK_PRAGMAS^
3837 @cindex @option{-gnateY} (@command{gcc})
3838 Ignore all STYLE_CHECKS pragmas. Full legality checks
3839 are still carried out, but the pragmas have no effect
3840 on what style checks are active. This allows all style
3841 checking options to be controlled from the command line.
3844 @cindex @option{-gnatE} (@command{gcc})
3845 Full dynamic elaboration checks.
3848 @cindex @option{-gnatf} (@command{gcc})
3849 Full errors. Multiple errors per line, all undefined references, do not
3850 attempt to suppress cascaded errors.
3853 @cindex @option{-gnatF} (@command{gcc})
3854 Externals names are folded to all uppercase.
3856 @item ^-gnatg^/GNAT_INTERNAL^
3857 @cindex @option{^-gnatg^/GNAT_INTERNAL^} (@command{gcc})
3858 Internal GNAT implementation mode. This should not be used for
3859 applications programs, it is intended only for use by the compiler
3860 and its run-time library. For documentation, see the GNAT sources.
3861 Note that @option{^-gnatg^/GNAT_INTERNAL^} implies
3862 @option{^-gnatwae^/WARNINGS=ALL,ERRORS^} and
3863 @option{^-gnatyg^/STYLE_CHECKS=GNAT^}
3864 so that all standard warnings and all standard style options are turned on.
3865 All warnings and style messages are treated as errors.
3869 @cindex @option{-gnatG[nn]} (@command{gcc})
3872 @item /EXPAND_SOURCE, /LEXPAND_SOURCE=nnn
3874 List generated expanded code in source form.
3876 @item ^-gnath^/HELP^
3877 @cindex @option{^-gnath^/HELP^} (@command{gcc})
3878 Output usage information. The output is written to @file{stdout}.
3880 @item ^-gnati^/IDENTIFIER_CHARACTER_SET=^@var{c}
3881 @cindex @option{^-gnati^/IDENTIFIER_CHARACTER_SET^} (@command{gcc})
3882 Identifier character set
3884 (@var{c}=1/2/3/4/8/9/p/f/n/w).
3886 For details of the possible selections for @var{c},
3887 see @ref{Character Set Control}.
3889 @item ^-gnatI^/IGNORE_REP_CLAUSES^
3890 @cindex @option{^-gnatI^IGNORE_REP_CLAUSES^} (@command{gcc})
3891 Ignore representation clauses. When this switch is used,
3892 representation clauses are treated as comments. This is useful
3893 when initially porting code where you want to ignore rep clause
3894 problems, and also for compiling foreign code (particularly
3895 for use with ASIS). The representation clauses that are ignored
3896 are: enumeration_representation_clause, record_representation_clause,
3897 and attribute_definition_clause for the following attributes:
3898 Address, Alignment, Bit_Order, Component_Size, Machine_Radix,
3899 Object_Size, Size, Small, Stream_Size, and Value_Size.
3900 Note that this option should be used only for compiling -- the
3901 code is likely to malfunction at run time.
3904 @cindex @option{-gnatjnn} (@command{gcc})
3905 Reformat error messages to fit on nn character lines
3907 @item -gnatk=@var{n}
3908 @cindex @option{-gnatk} (@command{gcc})
3909 Limit file names to @var{n} (1-999) characters ^(@code{k} = krunch)^^.
3912 @cindex @option{-gnatl} (@command{gcc})
3913 Output full source listing with embedded error messages.
3916 @cindex @option{-gnatL} (@command{gcc})
3917 Used in conjunction with -gnatG or -gnatD to intersperse original
3918 source lines (as comment lines with line numbers) in the expanded
3921 @item -gnatm=@var{n}
3922 @cindex @option{-gnatm} (@command{gcc})
3923 Limit number of detected error or warning messages to @var{n}
3924 where @var{n} is in the range 1..999999. The default setting if
3925 no switch is given is 9999. If the number of warnings reaches this
3926 limit, then a message is output and further warnings are suppressed,
3927 but the compilation is continued. If the number of error messages
3928 reaches this limit, then a message is output and the compilation
3929 is abandoned. The equal sign here is optional. A value of zero
3930 means that no limit applies.
3933 @cindex @option{-gnatn} (@command{gcc})
3934 Activate inlining for subprograms for which pragma @code{Inline} is
3935 specified. This inlining is performed by the GCC back-end. An optional
3936 digit sets the inlining level: 1 for moderate inlining across modules
3937 or 2 for full inlining across modules. If no inlining level is specified,
3938 the compiler will pick it based on the optimization level.
3941 @cindex @option{-gnatN} (@command{gcc})
3942 Activate front end inlining for subprograms for which
3943 pragma @code{Inline} is specified. This inlining is performed
3944 by the front end and will be visible in the
3945 @option{-gnatG} output.
3947 When using a gcc-based back end (in practice this means using any version
3948 of GNAT other than the JGNAT, .NET or GNAAMP versions), then the use of
3949 @option{-gnatN} is deprecated, and the use of @option{-gnatn} is preferred.
3950 Historically front end inlining was more extensive than the gcc back end
3951 inlining, but that is no longer the case.
3954 @cindex @option{-gnato??} (@command{gcc})
3955 Set default mode for handling generation of code to avoid intermediate
3956 arithmetic overflow. Here `@code{??}' is two digits, a
3957 single digit, or nothing. Each digit is one of the digits `@code{1}'
3962 all intermediate overflows checked against base type (@code{STRICT})
3964 minimize intermediate overflows (@code{MINIMIZED})
3966 eliminate intermediate overflows (@code{ELIMINATED})
3969 If only one digit appears then it applies to all
3970 cases; if two digits are given, then the first applies outside
3971 assertions, and the second within assertions.
3973 If no digits follow the @option{-gnato}, then it is equivalent to
3974 @option{^-gnato11^/OVERFLOW_CHECKS=11^},
3975 causing all intermediate overflows to be handled in strict mode.
3977 This switch also causes arithmetic overflow checking to be performed
3978 (as though pragma @code{Unsuppress (Overflow_Mode)} has been specified.
3980 The default if no option @option{-gnato} is given is that overflow handling
3981 is in @code{STRICT} mode (computations done using the base type), and that
3982 overflow checking is suppressed.
3984 Note that division by zero is a separate check that is not
3985 controlled by this switch (division by zero checking is on by default).
3987 See also @ref{Specifying the Desired Mode}.
3990 @cindex @option{-gnatp} (@command{gcc})
3991 Suppress all checks. See @ref{Run-Time Checks} for details. This switch
3992 has no effect if cancelled by a subsequent @option{-gnat-p} switch.
3995 @cindex @option{-gnat-p} (@command{gcc})
3996 Cancel effect of previous @option{-gnatp} switch.
3999 @cindex @option{-gnatP} (@command{gcc})
4000 Enable polling. This is required on some systems (notably Windows NT) to
4001 obtain asynchronous abort and asynchronous transfer of control capability.
4002 @xref{Pragma Polling,,, gnat_rm, GNAT Reference Manual}, for full
4006 @cindex @option{-gnatq} (@command{gcc})
4007 Don't quit. Try semantics, even if parse errors.
4010 @cindex @option{-gnatQ} (@command{gcc})
4011 Don't quit. Generate @file{ALI} and tree files even if illegalities.
4014 @cindex @option{-gnatr} (@command{gcc})
4015 Treat pragma Restrictions as Restriction_Warnings.
4017 @item ^-gnatR@r{[}0@r{/}1@r{/}2@r{/}3@r{[}s@r{]]}^/REPRESENTATION_INFO^
4018 @cindex @option{-gnatR} (@command{gcc})
4019 Output representation information for declared types and objects.
4020 Note that this switch is not allowed if a previous @code{-gnatD} switch has
4021 been given, since these two switches are not compatible. It is also not allowed
4022 if a previous @code{-gnatc} switch has been given, since we must be generating
4023 code to be able to determine representation information.
4025 @item ^-gnatRm[s]^/REPRESENTATION_INFO^
4026 Output convention and parameter passing mechanisms for all subprograms.
4027 This form is also incompatible with the use of @code{-gnatc}.
4030 @cindex @option{-gnats} (@command{gcc})
4034 @cindex @option{-gnatS} (@command{gcc})
4035 Print package Standard.
4038 @cindex @option{-gnatt} (@command{gcc})
4039 Generate tree output file.
4041 @item ^-gnatT^/TABLE_MULTIPLIER=^@var{nnn}
4042 @cindex @option{^-gnatT^/TABLE_MULTIPLIER^} (@command{gcc})
4043 All compiler tables start at @var{nnn} times usual starting size.
4046 @cindex @option{-gnatu} (@command{gcc})
4047 List units for this compilation.
4050 @cindex @option{-gnatU} (@command{gcc})
4051 Tag all error messages with the unique string ``error:''
4054 @cindex @option{-gnatv} (@command{gcc})
4055 Verbose mode. Full error output with source lines to @file{stdout}.
4058 @cindex @option{-gnatV} (@command{gcc})
4059 Control level of validity checking (@pxref{Validity Checking}).
4061 @item ^-gnatw@var{xxx}^/WARNINGS=(@var{option}@r{[},@dots{}@r{]})^
4062 @cindex @option{^-gnatw^/WARNINGS^} (@command{gcc})
4064 ^@var{xxx} is a string of option letters that^the list of options^ denotes
4065 the exact warnings that
4066 are enabled or disabled (@pxref{Warning Message Control}).
4068 @item ^-gnatW^/WIDE_CHARACTER_ENCODING=^@var{e}
4069 @cindex @option{^-gnatW^/WIDE_CHARACTER_ENCODING^} (@command{gcc})
4070 Wide character encoding method
4072 (@var{e}=n/h/u/s/e/8).
4075 (@var{e}=@code{BRACKETS, NONE, HEX, UPPER, SHIFT_JIS, EUC, UTF8})
4079 @cindex @option{-gnatx} (@command{gcc})
4080 Suppress generation of cross-reference information.
4083 @cindex @option{-gnatX} (@command{gcc})
4084 Enable GNAT implementation extensions and latest Ada version.
4086 @item ^-gnaty^/STYLE_CHECKS=(option,option@dots{})^
4087 @cindex @option{^-gnaty^/STYLE_CHECKS^} (@command{gcc})
4088 Enable built-in style checks (@pxref{Style Checking}).
4090 @item ^-gnatz^/DISTRIBUTION_STUBS=^@var{m}
4091 @cindex @option{^-gnatz^/DISTRIBUTION_STUBS^} (@command{gcc})
4092 Distribution stub generation and compilation
4094 (@var{m}=r/c for receiver/caller stubs).
4097 (@var{m}=@code{RECEIVER} or @code{CALLER} to specify the type of stubs
4098 to be generated and compiled).
4101 @item ^-I^/SEARCH=^@var{dir}
4102 @cindex @option{^-I^/SEARCH^} (@command{gcc})
4104 Direct GNAT to search the @var{dir} directory for source files needed by
4105 the current compilation
4106 (@pxref{Search Paths and the Run-Time Library (RTL)}).
4108 @item ^-I-^/NOCURRENT_DIRECTORY^
4109 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gcc})
4111 Except for the source file named in the command line, do not look for source
4112 files in the directory containing the source file named in the command line
4113 (@pxref{Search Paths and the Run-Time Library (RTL)}).
4117 @cindex @option{-mbig-switch} (@command{gcc})
4118 @cindex @code{case} statement (effect of @option{-mbig-switch} option)
4119 This standard gcc switch causes the compiler to use larger offsets in its
4120 jump table representation for @code{case} statements.
4121 This may result in less efficient code, but is sometimes necessary
4122 (for example on HP-UX targets)
4123 @cindex HP-UX and @option{-mbig-switch} option
4124 in order to compile large and/or nested @code{case} statements.
4127 @cindex @option{-o} (@command{gcc})
4128 This switch is used in @command{gcc} to redirect the generated object file
4129 and its associated ALI file. Beware of this switch with GNAT, because it may
4130 cause the object file and ALI file to have different names which in turn
4131 may confuse the binder and the linker.
4135 @cindex @option{-nostdinc} (@command{gcc})
4136 Inhibit the search of the default location for the GNAT Run Time
4137 Library (RTL) source files.
4140 @cindex @option{-nostdlib} (@command{gcc})
4141 Inhibit the search of the default location for the GNAT Run Time
4142 Library (RTL) ALI files.
4146 @c Expanding @ovar macro inline (explanation in macro def comments)
4147 @item -O@r{[}@var{n}@r{]}
4148 @cindex @option{-O} (@command{gcc})
4149 @var{n} controls the optimization level.
4153 No optimization, the default setting if no @option{-O} appears
4156 Normal optimization, the default if you specify @option{-O} without
4157 an operand. A good compromise between code quality and compilation
4161 Extensive optimization, may improve execution time, possibly at the cost of
4162 substantially increased compilation time.
4165 Same as @option{-O2}, and also includes inline expansion for small subprograms
4169 Optimize space usage
4173 See also @ref{Optimization Levels}.
4178 @cindex @option{/NOOPTIMIZE} (@code{GNAT COMPILE})
4179 Equivalent to @option{/OPTIMIZE=NONE}.
4180 This is the default behavior in the absence of an @option{/OPTIMIZE}
4183 @item /OPTIMIZE@r{[}=(keyword@r{[},@dots{}@r{]})@r{]}
4184 @cindex @option{/OPTIMIZE} (@code{GNAT COMPILE})
4185 Selects the level of optimization for your program. The supported
4186 keywords are as follows:
4189 Perform most optimizations, including those that
4191 This is the default if the @option{/OPTIMIZE} qualifier is supplied
4192 without keyword options.
4195 Do not do any optimizations. Same as @code{/NOOPTIMIZE}.
4198 Perform some optimizations, but omit ones that are costly.
4201 Same as @code{SOME}.
4204 Full optimization as in @option{/OPTIMIZE=ALL}, and also attempts
4205 automatic inlining of small subprograms within a unit
4208 Try to unroll loops. This keyword may be specified together with
4209 any keyword above other than @code{NONE}. Loop unrolling
4210 usually, but not always, improves the performance of programs.
4213 Optimize space usage
4217 See also @ref{Optimization Levels}.
4221 @item -pass-exit-codes
4222 @cindex @option{-pass-exit-codes} (@command{gcc})
4223 Catch exit codes from the compiler and use the most meaningful as
4227 @item --RTS=@var{rts-path}
4228 @cindex @option{--RTS} (@command{gcc})
4229 Specifies the default location of the runtime library. Same meaning as the
4230 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
4233 @cindex @option{^-S^/ASM^} (@command{gcc})
4234 ^Used in place of @option{-c} to^Used to^
4235 cause the assembler source file to be
4236 generated, using @file{^.s^.S^} as the extension,
4237 instead of the object file.
4238 This may be useful if you need to examine the generated assembly code.
4240 @item ^-fverbose-asm^/VERBOSE_ASM^
4241 @cindex @option{^-fverbose-asm^/VERBOSE_ASM^} (@command{gcc})
4242 ^Used in conjunction with @option{-S}^Used in place of @option{/ASM}^
4243 to cause the generated assembly code file to be annotated with variable
4244 names, making it significantly easier to follow.
4247 @cindex @option{^-v^/VERBOSE^} (@command{gcc})
4248 Show commands generated by the @command{gcc} driver. Normally used only for
4249 debugging purposes or if you need to be sure what version of the
4250 compiler you are executing.
4254 @cindex @option{-V} (@command{gcc})
4255 Execute @var{ver} version of the compiler. This is the @command{gcc}
4256 version, not the GNAT version.
4259 @item ^-w^/NO_BACK_END_WARNINGS^
4260 @cindex @option{-w} (@command{gcc})
4261 Turn off warnings generated by the back end of the compiler. Use of
4262 this switch also causes the default for front end warnings to be set
4263 to suppress (as though @option{-gnatws} had appeared at the start of
4269 @c Combining qualifiers does not work on VMS
4270 You may combine a sequence of GNAT switches into a single switch. For
4271 example, the combined switch
4273 @cindex Combining GNAT switches
4279 is equivalent to specifying the following sequence of switches:
4282 -gnato -gnatf -gnati3
4287 The following restrictions apply to the combination of switches
4292 The switch @option{-gnatc} if combined with other switches must come
4293 first in the string.
4296 The switch @option{-gnats} if combined with other switches must come
4297 first in the string.
4301 ^^@option{/DISTRIBUTION_STUBS=},^
4302 @option{-gnatzc} and @option{-gnatzr} may not be combined with any other
4303 switches, and only one of them may appear in the command line.
4306 The switch @option{-gnat-p} may not be combined with any other switch.
4310 Once a ``y'' appears in the string (that is a use of the @option{-gnaty}
4311 switch), then all further characters in the switch are interpreted
4312 as style modifiers (see description of @option{-gnaty}).
4315 Once a ``d'' appears in the string (that is a use of the @option{-gnatd}
4316 switch), then all further characters in the switch are interpreted
4317 as debug flags (see description of @option{-gnatd}).
4320 Once a ``w'' appears in the string (that is a use of the @option{-gnatw}
4321 switch), then all further characters in the switch are interpreted
4322 as warning mode modifiers (see description of @option{-gnatw}).
4325 Once a ``V'' appears in the string (that is a use of the @option{-gnatV}
4326 switch), then all further characters in the switch are interpreted
4327 as validity checking options (@pxref{Validity Checking}).
4330 Option ``em'', ``ec'', ``ep'', ``l='' and ``R'' must be the last options in
4331 a combined list of options.
4335 @node Output and Error Message Control
4336 @subsection Output and Error Message Control
4340 The standard default format for error messages is called ``brief format''.
4341 Brief format messages are written to @file{stderr} (the standard error
4342 file) and have the following form:
4345 e.adb:3:04: Incorrect spelling of keyword "function"
4346 e.adb:4:20: ";" should be "is"
4350 The first integer after the file name is the line number in the file,
4351 and the second integer is the column number within the line.
4353 @code{GPS} can parse the error messages
4354 and point to the referenced character.
4356 The following switches provide control over the error message
4362 @cindex @option{-gnatv} (@command{gcc})
4365 The v stands for verbose.
4367 The effect of this setting is to write long-format error
4368 messages to @file{stdout} (the standard output file.
4369 The same program compiled with the
4370 @option{-gnatv} switch would generate:
4374 3. funcion X (Q : Integer)
4376 >>> Incorrect spelling of keyword "function"
4379 >>> ";" should be "is"
4384 The vertical bar indicates the location of the error, and the @samp{>>>}
4385 prefix can be used to search for error messages. When this switch is
4386 used the only source lines output are those with errors.
4389 @cindex @option{-gnatl} (@command{gcc})
4391 The @code{l} stands for list.
4393 This switch causes a full listing of
4394 the file to be generated. In the case where a body is
4395 compiled, the corresponding spec is also listed, along
4396 with any subunits. Typical output from compiling a package
4397 body @file{p.adb} might look like:
4399 @smallexample @c ada
4403 1. package body p is
4405 3. procedure a is separate;
4416 2. pragma Elaborate_Body
4440 When you specify the @option{-gnatv} or @option{-gnatl} switches and
4441 standard output is redirected, a brief summary is written to
4442 @file{stderr} (standard error) giving the number of error messages and
4443 warning messages generated.
4445 @item ^-gnatl^/OUTPUT_FILE^=file
4446 @cindex @option{^-gnatl^/OUTPUT_FILE^=fname} (@command{gcc})
4447 This has the same effect as @option{-gnatl} except that the output is
4448 written to a file instead of to standard output. If the given name
4449 @file{fname} does not start with a period, then it is the full name
4450 of the file to be written. If @file{fname} is an extension, it is
4451 appended to the name of the file being compiled. For example, if
4452 file @file{xyz.adb} is compiled with @option{^-gnatl^/OUTPUT_FILE^=.lst},
4453 then the output is written to file ^xyz.adb.lst^xyz.adb_lst^.
4456 @cindex @option{-gnatU} (@command{gcc})
4457 This switch forces all error messages to be preceded by the unique
4458 string ``error:''. This means that error messages take a few more
4459 characters in space, but allows easy searching for and identification
4463 @cindex @option{-gnatb} (@command{gcc})
4465 The @code{b} stands for brief.
4467 This switch causes GNAT to generate the
4468 brief format error messages to @file{stderr} (the standard error
4469 file) as well as the verbose
4470 format message or full listing (which as usual is written to
4471 @file{stdout} (the standard output file).
4473 @item -gnatm=@var{n}
4474 @cindex @option{-gnatm} (@command{gcc})
4476 The @code{m} stands for maximum.
4478 @var{n} is a decimal integer in the
4479 range of 1 to 999999 and limits the number of error or warning
4480 messages to be generated. For example, using
4481 @option{-gnatm2} might yield
4484 e.adb:3:04: Incorrect spelling of keyword "function"
4485 e.adb:5:35: missing ".."
4486 fatal error: maximum number of errors detected
4487 compilation abandoned
4491 The default setting if
4492 no switch is given is 9999. If the number of warnings reaches this
4493 limit, then a message is output and further warnings are suppressed,
4494 but the compilation is continued. If the number of error messages
4495 reaches this limit, then a message is output and the compilation
4496 is abandoned. A value of zero means that no limit applies.
4499 Note that the equal sign is optional, so the switches
4500 @option{-gnatm2} and @option{-gnatm=2} are equivalent.
4503 @cindex @option{-gnatf} (@command{gcc})
4504 @cindex Error messages, suppressing
4506 The @code{f} stands for full.
4508 Normally, the compiler suppresses error messages that are likely to be
4509 redundant. This switch causes all error
4510 messages to be generated. In particular, in the case of
4511 references to undefined variables. If a given variable is referenced
4512 several times, the normal format of messages is
4514 e.adb:7:07: "V" is undefined (more references follow)
4518 where the parenthetical comment warns that there are additional
4519 references to the variable @code{V}. Compiling the same program with the
4520 @option{-gnatf} switch yields
4523 e.adb:7:07: "V" is undefined
4524 e.adb:8:07: "V" is undefined
4525 e.adb:8:12: "V" is undefined
4526 e.adb:8:16: "V" is undefined
4527 e.adb:9:07: "V" is undefined
4528 e.adb:9:12: "V" is undefined
4532 The @option{-gnatf} switch also generates additional information for
4533 some error messages. Some examples are:
4537 Details on possibly non-portable unchecked conversion
4539 List possible interpretations for ambiguous calls
4541 Additional details on incorrect parameters
4545 @cindex @option{-gnatjnn} (@command{gcc})
4546 In normal operation mode (or if @option{-gnatj0} is used), then error messages
4547 with continuation lines are treated as though the continuation lines were
4548 separate messages (and so a warning with two continuation lines counts as
4549 three warnings, and is listed as three separate messages).
4551 If the @option{-gnatjnn} switch is used with a positive value for nn, then
4552 messages are output in a different manner. A message and all its continuation
4553 lines are treated as a unit, and count as only one warning or message in the
4554 statistics totals. Furthermore, the message is reformatted so that no line
4555 is longer than nn characters.
4558 @cindex @option{-gnatq} (@command{gcc})
4560 The @code{q} stands for quit (really ``don't quit'').
4562 In normal operation mode, the compiler first parses the program and
4563 determines if there are any syntax errors. If there are, appropriate
4564 error messages are generated and compilation is immediately terminated.
4566 GNAT to continue with semantic analysis even if syntax errors have been
4567 found. This may enable the detection of more errors in a single run. On
4568 the other hand, the semantic analyzer is more likely to encounter some
4569 internal fatal error when given a syntactically invalid tree.
4572 @cindex @option{-gnatQ} (@command{gcc})
4573 In normal operation mode, the @file{ALI} file is not generated if any
4574 illegalities are detected in the program. The use of @option{-gnatQ} forces
4575 generation of the @file{ALI} file. This file is marked as being in
4576 error, so it cannot be used for binding purposes, but it does contain
4577 reasonably complete cross-reference information, and thus may be useful
4578 for use by tools (e.g., semantic browsing tools or integrated development
4579 environments) that are driven from the @file{ALI} file. This switch
4580 implies @option{-gnatq}, since the semantic phase must be run to get a
4581 meaningful ALI file.
4583 In addition, if @option{-gnatt} is also specified, then the tree file is
4584 generated even if there are illegalities. It may be useful in this case
4585 to also specify @option{-gnatq} to ensure that full semantic processing
4586 occurs. The resulting tree file can be processed by ASIS, for the purpose
4587 of providing partial information about illegal units, but if the error
4588 causes the tree to be badly malformed, then ASIS may crash during the
4591 When @option{-gnatQ} is used and the generated @file{ALI} file is marked as
4592 being in error, @command{gnatmake} will attempt to recompile the source when it
4593 finds such an @file{ALI} file, including with switch @option{-gnatc}.
4595 Note that @option{-gnatQ} has no effect if @option{-gnats} is specified,
4596 since ALI files are never generated if @option{-gnats} is set.
4600 @node Warning Message Control
4601 @subsection Warning Message Control
4602 @cindex Warning messages
4604 In addition to error messages, which correspond to illegalities as defined
4605 in the Ada Reference Manual, the compiler detects two kinds of warning
4608 First, the compiler considers some constructs suspicious and generates a
4609 warning message to alert you to a possible error. Second, if the
4610 compiler detects a situation that is sure to raise an exception at
4611 run time, it generates a warning message. The following shows an example
4612 of warning messages:
4614 e.adb:4:24: warning: creation of object may raise Storage_Error
4615 e.adb:10:17: warning: static value out of range
4616 e.adb:10:17: warning: "Constraint_Error" will be raised at run time
4620 GNAT considers a large number of situations as appropriate
4621 for the generation of warning messages. As always, warnings are not
4622 definite indications of errors. For example, if you do an out-of-range
4623 assignment with the deliberate intention of raising a
4624 @code{Constraint_Error} exception, then the warning that may be
4625 issued does not indicate an error. Some of the situations for which GNAT
4626 issues warnings (at least some of the time) are given in the following
4627 list. This list is not complete, and new warnings are often added to
4628 subsequent versions of GNAT. The list is intended to give a general idea
4629 of the kinds of warnings that are generated.
4633 Possible infinitely recursive calls
4636 Out-of-range values being assigned
4639 Possible order of elaboration problems
4642 Assertions (pragma Assert) that are sure to fail
4648 Address clauses with possibly unaligned values, or where an attempt is
4649 made to overlay a smaller variable with a larger one.
4652 Fixed-point type declarations with a null range
4655 Direct_IO or Sequential_IO instantiated with a type that has access values
4658 Variables that are never assigned a value
4661 Variables that are referenced before being initialized
4664 Task entries with no corresponding @code{accept} statement
4667 Duplicate accepts for the same task entry in a @code{select}
4670 Objects that take too much storage
4673 Unchecked conversion between types of differing sizes
4676 Missing @code{return} statement along some execution path in a function
4679 Incorrect (unrecognized) pragmas
4682 Incorrect external names
4685 Allocation from empty storage pool
4688 Potentially blocking operation in protected type
4691 Suspicious parenthesization of expressions
4694 Mismatching bounds in an aggregate
4697 Attempt to return local value by reference
4700 Premature instantiation of a generic body
4703 Attempt to pack aliased components
4706 Out of bounds array subscripts
4709 Wrong length on string assignment
4712 Violations of style rules if style checking is enabled
4715 Unused @code{with} clauses
4718 @code{Bit_Order} usage that does not have any effect
4721 @code{Standard.Duration} used to resolve universal fixed expression
4724 Dereference of possibly null value
4727 Declaration that is likely to cause storage error
4730 Internal GNAT unit @code{with}'ed by application unit
4733 Values known to be out of range at compile time
4736 Unreferenced labels and variables
4739 Address overlays that could clobber memory
4742 Unexpected initialization when address clause present
4745 Bad alignment for address clause
4748 Useless type conversions
4751 Redundant assignment statements and other redundant constructs
4754 Useless exception handlers
4757 Accidental hiding of name by child unit
4760 Access before elaboration detected at compile time
4763 A range in a @code{for} loop that is known to be null or might be null
4768 The following section lists compiler switches that are available
4769 to control the handling of warning messages. It is also possible
4770 to exercise much finer control over what warnings are issued and
4771 suppressed using the GNAT pragma Warnings, @xref{Pragma Warnings,,,
4772 gnat_rm, GNAT Reference manual}.
4777 @emph{Activate most optional warnings.}
4778 @cindex @option{-gnatwa} (@command{gcc})
4779 This switch activates most optional warning messages. See the remaining list
4780 in this section for details on optional warning messages that can be
4781 individually controlled. The warnings that are not turned on by this
4783 @option{-gnatwd} (implicit dereferencing),
4784 @option{-gnatwh} (hiding),
4785 @option{-gnatw.d} (tag warnings with -gnatw switch)
4786 @option{-gnatw.h} (holes (gaps) in record layouts)
4787 @option{-gnatw.i} (overlapping actuals),
4788 @option{-gnatw.k} (redefinition of names in standard),
4789 @option{-gnatwl} (elaboration warnings),
4790 @option{-gnatw.l} (inherited aspects),
4791 @option{-gnatw.o} (warn on values set by out parameters ignored),
4792 @option{-gnatwt} (tracking of deleted conditional code)
4793 and @option{-gnatw.u} (unordered enumeration),
4794 All other optional warnings are turned on.
4797 @emph{Suppress all optional errors.}
4798 @cindex @option{-gnatwA} (@command{gcc})
4799 This switch suppresses all optional warning messages, see remaining list
4800 in this section for details on optional warning messages that can be
4801 individually controlled. Note that unlike switch @option{-gnatws}, the
4802 use of switch @option{-gnatwA} does not suppress warnings that are
4803 normally given unconditionally and cannot be individually controlled
4804 (for example, the warning about a missing exit path in a function).
4805 Also, again unlike switch @option{-gnatws}, warnings suppressed by
4806 the use of switch @option{-gnatwA} can be individually turned back
4807 on. For example the use of switch @option{-gnatwA} followed by
4808 switch @option{-gnatwd} will suppress all optional warnings except
4809 the warnings for implicit dereferencing.
4812 @emph{Activate warnings on failing assertions.}
4813 @cindex @option{-gnatw.a} (@command{gcc})
4814 @cindex Assert failures
4815 This switch activates warnings for assertions where the compiler can tell at
4816 compile time that the assertion will fail. Note that this warning is given
4817 even if assertions are disabled. The default is that such warnings are
4821 @emph{Suppress warnings on failing assertions.}
4822 @cindex @option{-gnatw.A} (@command{gcc})
4823 @cindex Assert failures
4824 This switch suppresses warnings for assertions where the compiler can tell at
4825 compile time that the assertion will fail.
4828 @emph{Activate warnings on bad fixed values.}
4829 @cindex @option{-gnatwb} (@command{gcc})
4830 @cindex Bad fixed values
4831 @cindex Fixed-point Small value
4833 This switch activates warnings for static fixed-point expressions whose
4834 value is not an exact multiple of Small. Such values are implementation
4835 dependent, since an implementation is free to choose either of the multiples
4836 that surround the value. GNAT always chooses the closer one, but this is not
4837 required behavior, and it is better to specify a value that is an exact
4838 multiple, ensuring predictable execution. The default is that such warnings
4842 @emph{Suppress warnings on bad fixed values.}
4843 @cindex @option{-gnatwB} (@command{gcc})
4844 This switch suppresses warnings for static fixed-point expressions whose
4845 value is not an exact multiple of Small.
4848 @emph{Activate warnings on biased representation.}
4849 @cindex @option{-gnatw.b} (@command{gcc})
4850 @cindex Biased representation
4851 This switch activates warnings when a size clause, value size clause, component
4852 clause, or component size clause forces the use of biased representation for an
4853 integer type (e.g. representing a range of 10..11 in a single bit by using 0/1
4854 to represent 10/11). The default is that such warnings are generated.
4857 @emph{Suppress warnings on biased representation.}
4858 @cindex @option{-gnatwB} (@command{gcc})
4859 This switch suppresses warnings for representation clauses that force the use
4860 of biased representation.
4863 @emph{Activate warnings on conditionals.}
4864 @cindex @option{-gnatwc} (@command{gcc})
4865 @cindex Conditionals, constant
4866 This switch activates warnings for conditional expressions used in
4867 tests that are known to be True or False at compile time. The default
4868 is that such warnings are not generated.
4869 Note that this warning does
4870 not get issued for the use of boolean variables or constants whose
4871 values are known at compile time, since this is a standard technique
4872 for conditional compilation in Ada, and this would generate too many
4873 false positive warnings.
4875 This warning option also activates a special test for comparisons using
4876 the operators ``>='' and`` <=''.
4877 If the compiler can tell that only the equality condition is possible,
4878 then it will warn that the ``>'' or ``<'' part of the test
4879 is useless and that the operator could be replaced by ``=''.
4880 An example would be comparing a @code{Natural} variable <= 0.
4882 This warning option also generates warnings if
4883 one or both tests is optimized away in a membership test for integer
4884 values if the result can be determined at compile time. Range tests on
4885 enumeration types are not included, since it is common for such tests
4886 to include an end point.
4888 This warning can also be turned on using @option{-gnatwa}.
4891 @emph{Suppress warnings on conditionals.}
4892 @cindex @option{-gnatwC} (@command{gcc})
4893 This switch suppresses warnings for conditional expressions used in
4894 tests that are known to be True or False at compile time.
4897 @emph{Activate warnings on missing component clauses.}
4898 @cindex @option{-gnatw.c} (@command{gcc})
4899 @cindex Component clause, missing
4900 This switch activates warnings for record components where a record
4901 representation clause is present and has component clauses for the
4902 majority, but not all, of the components. A warning is given for each
4903 component for which no component clause is present.
4905 This warning can also be turned on using @option{-gnatwa}.
4908 @emph{Suppress warnings on missing component clauses.}
4909 @cindex @option{-gnatwC} (@command{gcc})
4910 This switch suppresses warnings for record components that are
4911 missing a component clause in the situation described above.
4914 @emph{Activate warnings on implicit dereferencing.}
4915 @cindex @option{-gnatwd} (@command{gcc})
4916 If this switch is set, then the use of a prefix of an access type
4917 in an indexed component, slice, or selected component without an
4918 explicit @code{.all} will generate a warning. With this warning
4919 enabled, access checks occur only at points where an explicit
4920 @code{.all} appears in the source code (assuming no warnings are
4921 generated as a result of this switch). The default is that such
4922 warnings are not generated.
4923 Note that @option{-gnatwa} does not affect the setting of
4924 this warning option.
4927 @emph{Suppress warnings on implicit dereferencing.}
4928 @cindex @option{-gnatwD} (@command{gcc})
4929 @cindex Implicit dereferencing
4930 @cindex Dereferencing, implicit
4931 This switch suppresses warnings for implicit dereferences in
4932 indexed components, slices, and selected components.
4935 @emph{Activate tagging of warning messages.}
4936 @cindex @option{-gnatw.d} (@command{gcc})
4937 If this switch is set, then warning messages are tagged, either with
4938 the string ``@option{-gnatw?}'' showing which switch controls the warning,
4939 or with ``[enabled by default]'' if the warning is not under control of a
4940 specific @option{-gnatw?} switch. This mode is off by default, and is not
4941 affected by the use of @code{-gnatwa}.
4944 @emph{Deactivate tagging of warning messages.}
4945 @cindex @option{-gnatw.d} (@command{gcc})
4946 If this switch is set, then warning messages return to the default
4947 mode in which warnings are not tagged as described above for
4951 @emph{Treat warnings and style checks as errors.}
4952 @cindex @option{-gnatwe} (@command{gcc})
4953 @cindex Warnings, treat as error
4954 This switch causes warning messages and style check messages to be
4956 The warning string still appears, but the warning messages are counted
4957 as errors, and prevent the generation of an object file. Note that this
4958 is the only -gnatw switch that affects the handling of style check messages.
4961 @emph{Activate every optional warning}
4962 @cindex @option{-gnatw.e} (@command{gcc})
4963 @cindex Warnings, activate every optional warning
4964 This switch activates all optional warnings, including those which
4965 are not activated by @code{-gnatwa}. The use of this switch is not
4966 recommended for normal use. If you turn this switch on, it is almost
4967 certain that you will get large numbers of useless warnings. The
4968 warnings that are excluded from @code{-gnatwa} are typically highly
4969 specialized warnings that are suitable for use only in code that has
4970 been specifically designed according to specialized coding rules.
4973 @emph{Activate warnings on unreferenced formals.}
4974 @cindex @option{-gnatwf} (@command{gcc})
4975 @cindex Formals, unreferenced
4976 This switch causes a warning to be generated if a formal parameter
4977 is not referenced in the body of the subprogram. This warning can
4978 also be turned on using @option{-gnatwa} or @option{-gnatwu}. The
4979 default is that these warnings are not generated.
4982 @emph{Suppress warnings on unreferenced formals.}
4983 @cindex @option{-gnatwF} (@command{gcc})
4984 This switch suppresses warnings for unreferenced formal
4985 parameters. Note that the
4986 combination @option{-gnatwu} followed by @option{-gnatwF} has the
4987 effect of warning on unreferenced entities other than subprogram
4991 @emph{Activate warnings on unrecognized pragmas.}
4992 @cindex @option{-gnatwg} (@command{gcc})
4993 @cindex Pragmas, unrecognized
4994 This switch causes a warning to be generated if an unrecognized
4995 pragma is encountered. Apart from issuing this warning, the
4996 pragma is ignored and has no effect. This warning can
4997 also be turned on using @option{-gnatwa}. The default
4998 is that such warnings are issued (satisfying the Ada Reference
4999 Manual requirement that such warnings appear).
5002 @emph{Suppress warnings on unrecognized pragmas.}
5003 @cindex @option{-gnatwG} (@command{gcc})
5004 This switch suppresses warnings for unrecognized pragmas.
5007 @emph{Activate warnings on hiding.}
5008 @cindex @option{-gnatwh} (@command{gcc})
5009 @cindex Hiding of Declarations
5010 This switch activates warnings on hiding declarations.
5011 A declaration is considered hiding
5012 if it is for a non-overloadable entity, and it declares an entity with the
5013 same name as some other entity that is directly or use-visible. The default
5014 is that such warnings are not generated.
5015 Note that @option{-gnatwa} does not affect the setting of this warning option.
5018 @emph{Suppress warnings on hiding.}
5019 @cindex @option{-gnatwH} (@command{gcc})
5020 This switch suppresses warnings on hiding declarations.
5023 @emph{Activate warnings on holes/gaps in records.}
5024 @cindex @option{-gnatw.h} (@command{gcc})
5025 @cindex Record Representation (gaps)
5026 This switch activates warnings on component clauses in record
5027 representation clauses that leave holes (gaps) in the record layout.
5028 If this warning option is active, then record representation clauses
5029 should specify a contiguous layout, adding unused fill fields if needed.
5030 Note that @option{-gnatwa} does not affect the setting of this warning option.
5033 @emph{Suppress warnings on holes/gaps in records.}
5034 @cindex @option{-gnatw.H} (@command{gcc})
5035 This switch suppresses warnings on component clauses in record
5036 representation clauses that leave holes (haps) in the record layout.
5039 @emph{Activate warnings on implementation units.}
5040 @cindex @option{-gnatwi} (@command{gcc})
5041 This switch activates warnings for a @code{with} of an internal GNAT
5042 implementation unit, defined as any unit from the @code{Ada},
5043 @code{Interfaces}, @code{GNAT},
5044 ^^@code{DEC},^ or @code{System}
5045 hierarchies that is not
5046 documented in either the Ada Reference Manual or the GNAT
5047 Programmer's Reference Manual. Such units are intended only
5048 for internal implementation purposes and should not be @code{with}'ed
5049 by user programs. The default is that such warnings are generated
5050 This warning can also be turned on using @option{-gnatwa}.
5053 @emph{Disable warnings on implementation units.}
5054 @cindex @option{-gnatwI} (@command{gcc})
5055 This switch disables warnings for a @code{with} of an internal GNAT
5056 implementation unit.
5059 @emph{Activate warnings on overlapping actuals.}
5060 @cindex @option{-gnatw.i} (@command{gcc})
5061 This switch enables a warning on statically detectable overlapping actuals in
5062 a subprogram call, when one of the actuals is an in-out parameter, and the
5063 types of the actuals are not by-copy types. The warning is off by default,
5064 and is not included under -gnatwa.
5067 @emph{Disable warnings on overlapping actuals.}
5068 @cindex @option{-gnatw.I} (@command{gcc})
5069 This switch disables warnings on overlapping actuals in a call..
5072 @emph{Activate warnings on obsolescent features (Annex J).}
5073 @cindex @option{-gnatwj} (@command{gcc})
5074 @cindex Features, obsolescent
5075 @cindex Obsolescent features
5076 If this warning option is activated, then warnings are generated for
5077 calls to subprograms marked with @code{pragma Obsolescent} and
5078 for use of features in Annex J of the Ada Reference Manual. In the
5079 case of Annex J, not all features are flagged. In particular use
5080 of the renamed packages (like @code{Text_IO}) and use of package
5081 @code{ASCII} are not flagged, since these are very common and
5082 would generate many annoying positive warnings. The default is that
5083 such warnings are not generated. This warning is also turned on by
5084 the use of @option{-gnatwa}.
5086 In addition to the above cases, warnings are also generated for
5087 GNAT features that have been provided in past versions but which
5088 have been superseded (typically by features in the new Ada standard).
5089 For example, @code{pragma Ravenscar} will be flagged since its
5090 function is replaced by @code{pragma Profile(Ravenscar)}, and
5091 @code{pragma Interface_Name} will be flagged since its function
5092 is replaced by @code{pragma Import}.
5094 Note that this warning option functions differently from the
5095 restriction @code{No_Obsolescent_Features} in two respects.
5096 First, the restriction applies only to annex J features.
5097 Second, the restriction does flag uses of package @code{ASCII}.
5100 @emph{Suppress warnings on obsolescent features (Annex J).}
5101 @cindex @option{-gnatwJ} (@command{gcc})
5102 This switch disables warnings on use of obsolescent features.
5105 @emph{Activate warnings on variables that could be constants.}
5106 @cindex @option{-gnatwk} (@command{gcc})
5107 This switch activates warnings for variables that are initialized but
5108 never modified, and then could be declared constants. The default is that
5109 such warnings are not given.
5110 This warning can also be turned on using @option{-gnatwa}.
5113 @emph{Suppress warnings on variables that could be constants.}
5114 @cindex @option{-gnatwK} (@command{gcc})
5115 This switch disables warnings on variables that could be declared constants.
5118 @emph{Activate warnings on redefinition of names in standard.}
5119 @cindex @option{-gnatw.k} (@command{gcc})
5120 This switch activates warnings for declarations that declare a name that
5121 is defined in package Standard. Such declarations can be confusing,
5122 especially since the names in package Standard continue to be directly
5123 visible, meaning that use visibiliy on such redeclared names does not
5124 work as expected. Names of discriminants and components in records are
5125 not included in this check.
5126 This warning is not part of the warnings activated by @option{-gnatwa}.
5127 It must be explicitly activated.
5130 @emph{Suppress warnings on variables that could be constants.}
5131 @cindex @option{-gnatwK} (@command{gcc})
5132 This switch activates warnings for declarations that declare a name that
5133 is defined in package Standard.
5136 @emph{Activate warnings for elaboration pragmas.}
5137 @cindex @option{-gnatwl} (@command{gcc})
5138 @cindex Elaboration, warnings
5139 This switch activates warnings on missing
5140 @code{Elaborate_All} and @code{Elaborate} pragmas.
5141 See the section in this guide on elaboration checking for details on
5142 when such pragmas should be used. In dynamic elaboration mode, this switch
5143 generations warnings about the need to add elaboration pragmas. Note however,
5144 that if you blindly follow these warnings, and add @code{Elaborate_All}
5145 warnings wherever they are recommended, you basically end up with the
5146 equivalent of the static elaboration model, which may not be what you want for
5147 legacy code for which the static model does not work.
5149 For the static model, the messages generated are labeled "info:" (for
5150 information messages). They are not warnings to add elaboration pragmas,
5151 merely informational messages showing what implicit elaboration pragmas
5152 have been added, for use in analyzing elaboration circularity problems.
5154 Warnings are also generated if you
5155 are using the static mode of elaboration, and a @code{pragma Elaborate}
5156 is encountered. The default is that such warnings
5158 This warning is not automatically turned on by the use of @option{-gnatwa}.
5161 @emph{Suppress warnings for elaboration pragmas.}
5162 @cindex @option{-gnatwL} (@command{gcc})
5163 This switch suppresses warnings on missing Elaborate and Elaborate_All pragmas.
5164 See the section in this guide on elaboration checking for details on
5165 when such pragmas should be used.
5168 @emph{List inherited aspects.}
5169 @cindex @option{-gnatw.l} (@command{gcc})
5170 This switch causes the compiler to list inherited invariants,
5171 preconditions, and postconditions from Type_Invariant'Class, Invariant'Class,
5172 Pre'Class, and Post'Class aspects. Also list inherited subtype predicates.
5173 These messages are not automatically turned on by the use of @option{-gnatwa}.
5176 @emph{Suppress listing of inherited aspects.}
5177 @cindex @option{-gnatw.L} (@command{gcc})
5178 This switch suppresses listing of inherited aspects.
5181 @emph{Activate warnings on modified but unreferenced variables.}
5182 @cindex @option{-gnatwm} (@command{gcc})
5183 This switch activates warnings for variables that are assigned (using
5184 an initialization value or with one or more assignment statements) but
5185 whose value is never read. The warning is suppressed for volatile
5186 variables and also for variables that are renamings of other variables
5187 or for which an address clause is given.
5188 This warning can also be turned on using @option{-gnatwa}.
5189 The default is that these warnings are not given.
5192 @emph{Disable warnings on modified but unreferenced variables.}
5193 @cindex @option{-gnatwM} (@command{gcc})
5194 This switch disables warnings for variables that are assigned or
5195 initialized, but never read.
5198 @emph{Activate warnings on suspicious modulus values.}
5199 @cindex @option{-gnatw.m} (@command{gcc})
5200 This switch activates warnings for modulus values that seem suspicious.
5201 The cases caught are where the size is the same as the modulus (e.g.
5202 a modulus of 7 with a size of 7 bits), and modulus values of 32 or 64
5203 with no size clause. The guess in both cases is that 2**x was intended
5204 rather than x. In addition expressions of the form 2*x for small x
5205 generate a warning (the almost certainly accurate guess being that
5206 2**x was intended). The default is that these warnings are given.
5209 @emph{Disable warnings on suspicious modulus values.}
5210 @cindex @option{-gnatw.M} (@command{gcc})
5211 This switch disables warnings for suspicious modulus values.
5214 @emph{Set normal warnings mode.}
5215 @cindex @option{-gnatwn} (@command{gcc})
5216 This switch sets normal warning mode, in which enabled warnings are
5217 issued and treated as warnings rather than errors. This is the default
5218 mode. the switch @option{-gnatwn} can be used to cancel the effect of
5219 an explicit @option{-gnatws} or
5220 @option{-gnatwe}. It also cancels the effect of the
5221 implicit @option{-gnatwe} that is activated by the
5222 use of @option{-gnatg}.
5225 @emph{Activate warnings on address clause overlays.}
5226 @cindex @option{-gnatwo} (@command{gcc})
5227 @cindex Address Clauses, warnings
5228 This switch activates warnings for possibly unintended initialization
5229 effects of defining address clauses that cause one variable to overlap
5230 another. The default is that such warnings are generated.
5231 This warning can also be turned on using @option{-gnatwa}.
5234 @emph{Suppress warnings on address clause overlays.}
5235 @cindex @option{-gnatwO} (@command{gcc})
5236 This switch suppresses warnings on possibly unintended initialization
5237 effects of defining address clauses that cause one variable to overlap
5241 @emph{Activate warnings on modified but unreferenced out parameters.}
5242 @cindex @option{-gnatw.o} (@command{gcc})
5243 This switch activates warnings for variables that are modified by using
5244 them as actuals for a call to a procedure with an out mode formal, where
5245 the resulting assigned value is never read. It is applicable in the case
5246 where there is more than one out mode formal. If there is only one out
5247 mode formal, the warning is issued by default (controlled by -gnatwu).
5248 The warning is suppressed for volatile
5249 variables and also for variables that are renamings of other variables
5250 or for which an address clause is given.
5251 The default is that these warnings are not given. Note that this warning
5252 is not included in -gnatwa, it must be activated explicitly.
5255 @emph{Disable warnings on modified but unreferenced out parameters.}
5256 @cindex @option{-gnatw.O} (@command{gcc})
5257 This switch suppresses warnings for variables that are modified by using
5258 them as actuals for a call to a procedure with an out mode formal, where
5259 the resulting assigned value is never read.
5262 @emph{Activate warnings on ineffective pragma Inlines.}
5263 @cindex @option{-gnatwp} (@command{gcc})
5264 @cindex Inlining, warnings
5265 This switch activates warnings for failure of front end inlining
5266 (activated by @option{-gnatN}) to inline a particular call. There are
5267 many reasons for not being able to inline a call, including most
5268 commonly that the call is too complex to inline. The default is
5269 that such warnings are not given.
5270 This warning can also be turned on using @option{-gnatwa}.
5271 Warnings on ineffective inlining by the gcc back-end can be activated
5272 separately, using the gcc switch -Winline.
5275 @emph{Suppress warnings on ineffective pragma Inlines.}
5276 @cindex @option{-gnatwP} (@command{gcc})
5277 This switch suppresses warnings on ineffective pragma Inlines. If the
5278 inlining mechanism cannot inline a call, it will simply ignore the
5282 @emph{Activate warnings on parameter ordering.}
5283 @cindex @option{-gnatw.p} (@command{gcc})
5284 @cindex Parameter order, warnings
5285 This switch activates warnings for cases of suspicious parameter
5286 ordering when the list of arguments are all simple identifiers that
5287 match the names of the formals, but are in a different order. The
5288 warning is suppressed if any use of named parameter notation is used,
5289 so this is the appropriate way to suppress a false positive (and
5290 serves to emphasize that the "misordering" is deliberate). The
5292 that such warnings are not given.
5293 This warning can also be turned on using @option{-gnatwa}.
5296 @emph{Suppress warnings on parameter ordering.}
5297 @cindex @option{-gnatw.P} (@command{gcc})
5298 This switch suppresses warnings on cases of suspicious parameter
5302 @emph{Activate warnings on questionable missing parentheses.}
5303 @cindex @option{-gnatwq} (@command{gcc})
5304 @cindex Parentheses, warnings
5305 This switch activates warnings for cases where parentheses are not used and
5306 the result is potential ambiguity from a readers point of view. For example
5307 (not a > b) when a and b are modular means ((not a) > b) and very likely the
5308 programmer intended (not (a > b)). Similarly (-x mod 5) means (-(x mod 5)) and
5309 quite likely ((-x) mod 5) was intended. In such situations it seems best to
5310 follow the rule of always parenthesizing to make the association clear, and
5311 this warning switch warns if such parentheses are not present. The default
5312 is that these warnings are given.
5313 This warning can also be turned on using @option{-gnatwa}.
5316 @emph{Suppress warnings on questionable missing parentheses.}
5317 @cindex @option{-gnatwQ} (@command{gcc})
5318 This switch suppresses warnings for cases where the association is not
5319 clear and the use of parentheses is preferred.
5322 @emph{Activate warnings on redundant constructs.}
5323 @cindex @option{-gnatwr} (@command{gcc})
5324 This switch activates warnings for redundant constructs. The following
5325 is the current list of constructs regarded as redundant:
5329 Assignment of an item to itself.
5331 Type conversion that converts an expression to its own type.
5333 Use of the attribute @code{Base} where @code{typ'Base} is the same
5336 Use of pragma @code{Pack} when all components are placed by a record
5337 representation clause.
5339 Exception handler containing only a reraise statement (raise with no
5340 operand) which has no effect.
5342 Use of the operator abs on an operand that is known at compile time
5345 Comparison of boolean expressions to an explicit True value.
5348 This warning can also be turned on using @option{-gnatwa}.
5349 The default is that warnings for redundant constructs are not given.
5352 @emph{Suppress warnings on redundant constructs.}
5353 @cindex @option{-gnatwR} (@command{gcc})
5354 This switch suppresses warnings for redundant constructs.
5357 @emph{Activate warnings for object renaming function.}
5358 @cindex @option{-gnatw.r} (@command{gcc})
5359 This switch activates warnings for an object renaming that renames a
5360 function call, which is equivalent to a constant declaration (as
5361 opposed to renaming the function itself). The default is that these
5362 warnings are given. This warning can also be turned on using
5366 @emph{Suppress warnings for object renaming function.}
5367 @cindex @option{-gnatwT} (@command{gcc})
5368 This switch suppresses warnings for object renaming function.
5371 @emph{Suppress all warnings.}
5372 @cindex @option{-gnatws} (@command{gcc})
5373 This switch completely suppresses the
5374 output of all warning messages from the GNAT front end, including
5375 both warnings that can be controlled by switches described in this
5376 section, and those that are normally given unconditionally. The
5377 effect of this suppress action can only be cancelled by a subsequent
5378 use of the switch @option{-gnatwn}.
5380 Note that switch @option{-gnatws} does not suppress
5381 warnings from the @command{gcc} back end.
5382 To suppress these back end warnings as well, use the switch @option{-w}
5383 in addition to @option{-gnatws}. Also this switch has no effect on the
5384 handling of style check messages.
5387 @emph{Activate warnings on overridden size clauses.}
5388 @cindex @option{-gnatw.s} (@command{gcc})
5389 @cindex Record Representation (component sizes)
5390 This switch activates warnings on component clauses in record
5391 representation clauses where the length given overrides that
5392 specified by an explicit size clause for the component type. A
5393 warning is similarly given in the array case if a specified
5394 component size overrides an explicit size clause for the array
5396 Note that @option{-gnatwa} does not affect the setting of this warning option.
5399 @emph{Suppress warnings on overridden size clauses.}
5400 @cindex @option{-gnatw.S} (@command{gcc})
5401 This switch suppresses warnings on component clauses in record
5402 representation clauses that override size clauses, and similar
5403 warnings when an array component size overrides a size clause.
5406 @emph{Activate warnings for tracking of deleted conditional code.}
5407 @cindex @option{-gnatwt} (@command{gcc})
5408 @cindex Deactivated code, warnings
5409 @cindex Deleted code, warnings
5410 This switch activates warnings for tracking of code in conditionals (IF and
5411 CASE statements) that is detected to be dead code which cannot be executed, and
5412 which is removed by the front end. This warning is off by default, and is not
5413 turned on by @option{-gnatwa}, it has to be turned on explicitly. This may be
5414 useful for detecting deactivated code in certified applications.
5417 @emph{Suppress warnings for tracking of deleted conditional code.}
5418 @cindex @option{-gnatwT} (@command{gcc})
5419 This switch suppresses warnings for tracking of deleted conditional code.
5422 @emph{Activate warnings on suspicious contracts.}
5423 @cindex @option{-gnatw.t} (@command{gcc})
5424 This switch activates warnings on suspicious postconditions (whether a
5425 pragma @code{Postcondition} or a @code{Post} aspect in Ada 2012)
5426 and suspicious contract cases (pragma @code{Contract_Cases}). A
5427 function postcondition or contract case is suspicious when no postcondition
5428 or contract case for this function mentions the result of the function.
5429 A procedure postcondition or contract case is suspicious when it only
5430 refers to the pre-state of the procedure, because in that case it should
5431 rather be expressed as a precondition. The default is that such warnings
5432 are not generated. This warning can also be turned on using @option{-gnatwa}.
5435 @emph{Suppress warnings on suspicious contracts.}
5436 @cindex @option{-gnatw.T} (@command{gcc})
5437 This switch suppresses warnings on suspicious postconditions.
5440 @emph{Activate warnings on unused entities.}
5441 @cindex @option{-gnatwu} (@command{gcc})
5442 This switch activates warnings to be generated for entities that
5443 are declared but not referenced, and for units that are @code{with}'ed
5445 referenced. In the case of packages, a warning is also generated if
5446 no entities in the package are referenced. This means that if a with'ed
5447 package is referenced but the only references are in @code{use}
5448 clauses or @code{renames}
5449 declarations, a warning is still generated. A warning is also generated
5450 for a generic package that is @code{with}'ed but never instantiated.
5451 In the case where a package or subprogram body is compiled, and there
5452 is a @code{with} on the corresponding spec
5453 that is only referenced in the body,
5454 a warning is also generated, noting that the
5455 @code{with} can be moved to the body. The default is that
5456 such warnings are not generated.
5457 This switch also activates warnings on unreferenced formals
5458 (it includes the effect of @option{-gnatwf}).
5459 This warning can also be turned on using @option{-gnatwa}.
5462 @emph{Suppress warnings on unused entities.}
5463 @cindex @option{-gnatwU} (@command{gcc})
5464 This switch suppresses warnings for unused entities and packages.
5465 It also turns off warnings on unreferenced formals (and thus includes
5466 the effect of @option{-gnatwF}).
5469 @emph{Activate warnings on unordered enumeration types.}
5470 @cindex @option{-gnatw.u} (@command{gcc})
5471 This switch causes enumeration types to be considered as conceptually
5472 unordered, unless an explicit pragma @code{Ordered} is given for the type.
5473 The effect is to generate warnings in clients that use explicit comparisons
5474 or subranges, since these constructs both treat objects of the type as
5475 ordered. (A @emph{client} is defined as a unit that is other than the unit in
5476 which the type is declared, or its body or subunits.) Please refer to
5477 the description of pragma @code{Ordered} in the
5478 @cite{@value{EDITION} Reference Manual} for further details.
5479 The default is that such warnings are not generated.
5480 This warning is not automatically turned on by the use of @option{-gnatwa}.
5483 @emph{Deactivate warnings on unordered enumeration types.}
5484 @cindex @option{-gnatw.U} (@command{gcc})
5485 This switch causes all enumeration types to be considered as ordered, so
5486 that no warnings are given for comparisons or subranges for any type.
5489 @emph{Activate warnings on unassigned variables.}
5490 @cindex @option{-gnatwv} (@command{gcc})
5491 @cindex Unassigned variable warnings
5492 This switch activates warnings for access to variables which
5493 may not be properly initialized. The default is that
5494 such warnings are generated.
5495 This warning can also be turned on using @option{-gnatwa}.
5498 @emph{Suppress warnings on unassigned variables.}
5499 @cindex @option{-gnatwV} (@command{gcc})
5500 This switch suppresses warnings for access to variables which
5501 may not be properly initialized.
5502 For variables of a composite type, the warning can also be suppressed in
5503 Ada 2005 by using a default initialization with a box. For example, if
5504 Table is an array of records whose components are only partially uninitialized,
5505 then the following code:
5507 @smallexample @c ada
5508 Tab : Table := (others => <>);
5511 will suppress warnings on subsequent statements that access components
5515 @emph{Activate info messages for non-default bit order.}
5516 @cindex @option{-gnatw.v} (@command{gcc})
5517 @cindex bit order warnings
5518 This switch activates messages (labeled "info", they are not warnings,
5519 just informational messages) about the effects of non-default bit-order
5520 on records to which a component clause is applied. The effect of specifying
5521 non-default bit ordering is a bit subtle (and changed with Ada 2005), so
5522 these messages, which are given by default, are useful in understanding the
5523 exact consequences of using this feature. These messages
5524 can also be turned on using @option{-gnatwa}
5527 @emph{Suppress info messages for non-default bit order.}
5528 @cindex @option{-gnatw.V} (@command{gcc})
5529 This switch suppresses information messages for the effects of specifying
5530 non-default bit order on record components with component clauses.
5533 @emph{Activate warnings on wrong low bound assumption.}
5534 @cindex @option{-gnatww} (@command{gcc})
5535 @cindex String indexing warnings
5536 This switch activates warnings for indexing an unconstrained string parameter
5537 with a literal or S'Length. This is a case where the code is assuming that the
5538 low bound is one, which is in general not true (for example when a slice is
5539 passed). The default is that such warnings are generated.
5540 This warning can also be turned on using @option{-gnatwa}.
5543 @emph{Suppress warnings on wrong low bound assumption.}
5544 @cindex @option{-gnatwW} (@command{gcc})
5545 This switch suppresses warnings for indexing an unconstrained string parameter
5546 with a literal or S'Length. Note that this warning can also be suppressed
5547 in a particular case by adding an
5548 assertion that the lower bound is 1,
5549 as shown in the following example.
5551 @smallexample @c ada
5552 procedure K (S : String) is
5553 pragma Assert (S'First = 1);
5558 @emph{Activate warnings on unnecessary Warnings Off pragmas}
5559 @cindex @option{-gnatw.w} (@command{gcc})
5560 @cindex Warnings Off control
5561 This switch activates warnings for use of @code{pragma Warnings (Off, entity)}
5562 where either the pragma is entirely useless (because it suppresses no
5563 warnings), or it could be replaced by @code{pragma Unreferenced} or
5564 @code{pragma Unmodified}. The default is that these warnings are not given.
5565 Note that this warning is not included in -gnatwa, it must be
5566 activated explicitly.
5569 @emph{Suppress warnings on unnecessary Warnings Off pragmas}
5570 @cindex @option{-gnatw.W} (@command{gcc})
5571 This switch suppresses warnings for use of @code{pragma Warnings (Off, entity)}.
5574 @emph{Activate warnings on Export/Import pragmas.}
5575 @cindex @option{-gnatwx} (@command{gcc})
5576 @cindex Export/Import pragma warnings
5577 This switch activates warnings on Export/Import pragmas when
5578 the compiler detects a possible conflict between the Ada and
5579 foreign language calling sequences. For example, the use of
5580 default parameters in a convention C procedure is dubious
5581 because the C compiler cannot supply the proper default, so
5582 a warning is issued. The default is that such warnings are
5584 This warning can also be turned on using @option{-gnatwa}.
5587 @emph{Suppress warnings on Export/Import pragmas.}
5588 @cindex @option{-gnatwX} (@command{gcc})
5589 This switch suppresses warnings on Export/Import pragmas.
5590 The sense of this is that you are telling the compiler that
5591 you know what you are doing in writing the pragma, and it
5592 should not complain at you.
5595 @emph{Activate warnings for No_Exception_Propagation mode.}
5596 @cindex @option{-gnatwm} (@command{gcc})
5597 This switch activates warnings for exception usage when pragma Restrictions
5598 (No_Exception_Propagation) is in effect. Warnings are given for implicit or
5599 explicit exception raises which are not covered by a local handler, and for
5600 exception handlers which do not cover a local raise. The default is that these
5601 warnings are not given.
5604 @emph{Disable warnings for No_Exception_Propagation mode.}
5605 This switch disables warnings for exception usage when pragma Restrictions
5606 (No_Exception_Propagation) is in effect.
5609 @emph{Activate warnings for Ada compatibility issues.}
5610 @cindex @option{-gnatwy} (@command{gcc})
5611 @cindex Ada compatibility issues warnings
5612 For the most part, newer versions of Ada are upwards compatible
5613 with older versions. For example, Ada 2005 programs will almost
5614 always work when compiled as Ada 2012.
5615 However there are some exceptions (for example the fact that
5616 @code{some} is now a reserved word in Ada 2012). This
5617 switch activates several warnings to help in identifying
5618 and correcting such incompatibilities. The default is that
5619 these warnings are generated. Note that at one point Ada 2005
5620 was called Ada 0Y, hence the choice of character.
5621 This warning can also be turned on using @option{-gnatwa}.
5624 @emph{Disable warnings for Ada compatibility issues.}
5625 @cindex @option{-gnatwY} (@command{gcc})
5626 @cindex Ada compatibility issues warnings
5627 This switch suppresses the warnings intended to help in identifying
5628 incompatibilities between Ada language versions.
5631 @emph{Activate warnings on unchecked conversions.}
5632 @cindex @option{-gnatwz} (@command{gcc})
5633 @cindex Unchecked_Conversion warnings
5634 This switch activates warnings for unchecked conversions
5635 where the types are known at compile time to have different
5637 is that such warnings are generated. Warnings are also
5638 generated for subprogram pointers with different conventions,
5639 and, on VMS only, for data pointers with different conventions.
5640 This warning can also be turned on using @option{-gnatwa}.
5643 @emph{Suppress warnings on unchecked conversions.}
5644 @cindex @option{-gnatwZ} (@command{gcc})
5645 This switch suppresses warnings for unchecked conversions
5646 where the types are known at compile time to have different
5647 sizes or conventions.
5649 @item ^-Wunused^WARNINGS=UNUSED^
5650 @cindex @option{-Wunused}
5651 The warnings controlled by the @option{-gnatw} switch are generated by
5652 the front end of the compiler. The @option{GCC} back end can provide
5653 additional warnings and they are controlled by the @option{-W} switch.
5654 For example, @option{^-Wunused^WARNINGS=UNUSED^} activates back end
5655 warnings for entities that are declared but not referenced.
5657 @item ^-Wuninitialized^WARNINGS=UNINITIALIZED^
5658 @cindex @option{-Wuninitialized}
5659 Similarly, @option{^-Wuninitialized^WARNINGS=UNINITIALIZED^} activates
5660 the back end warning for uninitialized variables. This switch must be
5661 used in conjunction with an optimization level greater than zero.
5663 @item -Wstack-usage=@var{len}
5664 @cindex @option{-Wstack-usage}
5665 Warn if the stack usage of a subprogram might be larger than @var{len} bytes.
5666 See @ref{Static Stack Usage Analysis} for details.
5668 @item ^-Wall^/ALL_BACK_END_WARNINGS^
5669 @cindex @option{-Wall}
5670 This switch enables most warnings from the @option{GCC} back end.
5671 The code generator detects a number of warning situations that are missed
5672 by the @option{GNAT} front end, and this switch can be used to activate them.
5673 The use of this switch also sets the default front end warning mode to
5674 @option{-gnatwa}, that is, most front end warnings activated as well.
5676 @item ^-w^/NO_BACK_END_WARNINGS^
5678 Conversely, this switch suppresses warnings from the @option{GCC} back end.
5679 The use of this switch also sets the default front end warning mode to
5680 @option{-gnatws}, that is, front end warnings suppressed as well.
5686 A string of warning parameters can be used in the same parameter. For example:
5693 will turn on all optional warnings except for unrecognized pragma warnings,
5694 and also specify that warnings should be treated as errors.
5697 When no switch @option{^-gnatw^/WARNINGS^} is used, this is equivalent to:
5740 @node Debugging and Assertion Control
5741 @subsection Debugging and Assertion Control
5745 @cindex @option{-gnata} (@command{gcc})
5751 The pragmas @code{Assert} and @code{Debug} normally have no effect and
5752 are ignored. This switch, where @samp{a} stands for assert, causes
5753 @code{Assert} and @code{Debug} pragmas to be activated.
5755 The pragmas have the form:
5759 @b{pragma} Assert (@var{Boolean-expression} @r{[},
5760 @var{static-string-expression}@r{]})
5761 @b{pragma} Debug (@var{procedure call})
5766 The @code{Assert} pragma causes @var{Boolean-expression} to be tested.
5767 If the result is @code{True}, the pragma has no effect (other than
5768 possible side effects from evaluating the expression). If the result is
5769 @code{False}, the exception @code{Assert_Failure} declared in the package
5770 @code{System.Assertions} is
5771 raised (passing @var{static-string-expression}, if present, as the
5772 message associated with the exception). If no string expression is
5773 given the default is a string giving the file name and line number
5776 The @code{Debug} pragma causes @var{procedure} to be called. Note that
5777 @code{pragma Debug} may appear within a declaration sequence, allowing
5778 debugging procedures to be called between declarations.
5781 @item /DEBUG@r{[}=debug-level@r{]}
5783 Specifies how much debugging information is to be included in
5784 the resulting object file where 'debug-level' is one of the following:
5787 Include both debugger symbol records and traceback
5789 This is the default setting.
5791 Include both debugger symbol records and traceback in
5794 Excludes both debugger symbol records and traceback
5795 the object file. Same as /NODEBUG.
5797 Includes only debugger symbol records in the object
5798 file. Note that this doesn't include traceback information.
5803 @node Validity Checking
5804 @subsection Validity Checking
5805 @findex Validity Checking
5808 The Ada Reference Manual defines the concept of invalid values (see
5809 RM 13.9.1). The primary source of invalid values is uninitialized
5810 variables. A scalar variable that is left uninitialized may contain
5811 an invalid value; the concept of invalid does not apply to access or
5814 It is an error to read an invalid value, but the RM does not require
5815 run-time checks to detect such errors, except for some minimal
5816 checking to prevent erroneous execution (i.e. unpredictable
5817 behavior). This corresponds to the @option{-gnatVd} switch below,
5818 which is the default. For example, by default, if the expression of a
5819 case statement is invalid, it will raise Constraint_Error rather than
5820 causing a wild jump, and if an array index on the left-hand side of an
5821 assignment is invalid, it will raise Constraint_Error rather than
5822 overwriting an arbitrary memory location.
5824 The @option{-gnatVa} may be used to enable additional validity checks,
5825 which are not required by the RM. These checks are often very
5826 expensive (which is why the RM does not require them). These checks
5827 are useful in tracking down uninitialized variables, but they are
5828 not usually recommended for production builds.
5830 The other @option{-gnatV^@var{x}^^} switches below allow finer-grained
5831 control; you can enable whichever validity checks you desire. However,
5832 for most debugging purposes, @option{-gnatVa} is sufficient, and the
5833 default @option{-gnatVd} (i.e. standard Ada behavior) is usually
5834 sufficient for non-debugging use.
5836 The @option{-gnatB} switch tells the compiler to assume that all
5837 values are valid (that is, within their declared subtype range)
5838 except in the context of a use of the Valid attribute. This means
5839 the compiler can generate more efficient code, since the range
5840 of values is better known at compile time. However, an uninitialized
5841 variable can cause wild jumps and memory corruption in this mode.
5843 The @option{-gnatV^@var{x}^^} switch allows control over the validity
5844 checking mode as described below.
5846 The @code{x} argument is a string of letters that
5847 indicate validity checks that are performed or not performed in addition
5848 to the default checks required by Ada as described above.
5851 The options allowed for this qualifier
5852 indicate validity checks that are performed or not performed in addition
5853 to the default checks required by Ada as described above.
5859 @emph{All validity checks.}
5860 @cindex @option{-gnatVa} (@command{gcc})
5861 All validity checks are turned on.
5863 That is, @option{-gnatVa} is
5864 equivalent to @option{gnatVcdfimorst}.
5868 @emph{Validity checks for copies.}
5869 @cindex @option{-gnatVc} (@command{gcc})
5870 The right hand side of assignments, and the initializing values of
5871 object declarations are validity checked.
5874 @emph{Default (RM) validity checks.}
5875 @cindex @option{-gnatVd} (@command{gcc})
5876 Some validity checks are done by default following normal Ada semantics
5878 A check is done in case statements that the expression is within the range
5879 of the subtype. If it is not, Constraint_Error is raised.
5880 For assignments to array components, a check is done that the expression used
5881 as index is within the range. If it is not, Constraint_Error is raised.
5882 Both these validity checks may be turned off using switch @option{-gnatVD}.
5883 They are turned on by default. If @option{-gnatVD} is specified, a subsequent
5884 switch @option{-gnatVd} will leave the checks turned on.
5885 Switch @option{-gnatVD} should be used only if you are sure that all such
5886 expressions have valid values. If you use this switch and invalid values
5887 are present, then the program is erroneous, and wild jumps or memory
5888 overwriting may occur.
5891 @emph{Validity checks for elementary components.}
5892 @cindex @option{-gnatVe} (@command{gcc})
5893 In the absence of this switch, assignments to record or array components are
5894 not validity checked, even if validity checks for assignments generally
5895 (@option{-gnatVc}) are turned on. In Ada, assignment of composite values do not
5896 require valid data, but assignment of individual components does. So for
5897 example, there is a difference between copying the elements of an array with a
5898 slice assignment, compared to assigning element by element in a loop. This
5899 switch allows you to turn off validity checking for components, even when they
5900 are assigned component by component.
5903 @emph{Validity checks for floating-point values.}
5904 @cindex @option{-gnatVf} (@command{gcc})
5905 In the absence of this switch, validity checking occurs only for discrete
5906 values. If @option{-gnatVf} is specified, then validity checking also applies
5907 for floating-point values, and NaNs and infinities are considered invalid,
5908 as well as out of range values for constrained types. Note that this means
5909 that standard IEEE infinity mode is not allowed. The exact contexts
5910 in which floating-point values are checked depends on the setting of other
5911 options. For example,
5912 @option{^-gnatVif^VALIDITY_CHECKING=(IN_PARAMS,FLOATS)^} or
5913 @option{^-gnatVfi^VALIDITY_CHECKING=(FLOATS,IN_PARAMS)^}
5914 (the order does not matter) specifies that floating-point parameters of mode
5915 @code{in} should be validity checked.
5918 @emph{Validity checks for @code{in} mode parameters}
5919 @cindex @option{-gnatVi} (@command{gcc})
5920 Arguments for parameters of mode @code{in} are validity checked in function
5921 and procedure calls at the point of call.
5924 @emph{Validity checks for @code{in out} mode parameters.}
5925 @cindex @option{-gnatVm} (@command{gcc})
5926 Arguments for parameters of mode @code{in out} are validity checked in
5927 procedure calls at the point of call. The @code{'m'} here stands for
5928 modify, since this concerns parameters that can be modified by the call.
5929 Note that there is no specific option to test @code{out} parameters,
5930 but any reference within the subprogram will be tested in the usual
5931 manner, and if an invalid value is copied back, any reference to it
5932 will be subject to validity checking.
5935 @emph{No validity checks.}
5936 @cindex @option{-gnatVn} (@command{gcc})
5937 This switch turns off all validity checking, including the default checking
5938 for case statements and left hand side subscripts. Note that the use of
5939 the switch @option{-gnatp} suppresses all run-time checks, including
5940 validity checks, and thus implies @option{-gnatVn}. When this switch
5941 is used, it cancels any other @option{-gnatV} previously issued.
5944 @emph{Validity checks for operator and attribute operands.}
5945 @cindex @option{-gnatVo} (@command{gcc})
5946 Arguments for predefined operators and attributes are validity checked.
5947 This includes all operators in package @code{Standard},
5948 the shift operators defined as intrinsic in package @code{Interfaces}
5949 and operands for attributes such as @code{Pos}. Checks are also made
5950 on individual component values for composite comparisons, and on the
5951 expressions in type conversions and qualified expressions. Checks are
5952 also made on explicit ranges using @samp{..} (e.g.@: slices, loops etc).
5955 @emph{Validity checks for parameters.}
5956 @cindex @option{-gnatVp} (@command{gcc})
5957 This controls the treatment of parameters within a subprogram (as opposed
5958 to @option{-gnatVi} and @option{-gnatVm} which control validity testing
5959 of parameters on a call. If either of these call options is used, then
5960 normally an assumption is made within a subprogram that the input arguments
5961 have been validity checking at the point of call, and do not need checking
5962 again within a subprogram). If @option{-gnatVp} is set, then this assumption
5963 is not made, and parameters are not assumed to be valid, so their validity
5964 will be checked (or rechecked) within the subprogram.
5967 @emph{Validity checks for function returns.}
5968 @cindex @option{-gnatVr} (@command{gcc})
5969 The expression in @code{return} statements in functions is validity
5973 @emph{Validity checks for subscripts.}
5974 @cindex @option{-gnatVs} (@command{gcc})
5975 All subscripts expressions are checked for validity, whether they appear
5976 on the right side or left side (in default mode only left side subscripts
5977 are validity checked).
5980 @emph{Validity checks for tests.}
5981 @cindex @option{-gnatVt} (@command{gcc})
5982 Expressions used as conditions in @code{if}, @code{while} or @code{exit}
5983 statements are checked, as well as guard expressions in entry calls.
5988 The @option{-gnatV} switch may be followed by
5989 ^a string of letters^a list of options^
5990 to turn on a series of validity checking options.
5992 @option{^-gnatVcr^/VALIDITY_CHECKING=(COPIES, RETURNS)^}
5993 specifies that in addition to the default validity checking, copies and
5994 function return expressions are to be validity checked.
5995 In order to make it easier
5996 to specify the desired combination of effects,
5998 the upper case letters @code{CDFIMORST} may
5999 be used to turn off the corresponding lower case option.
6002 the prefix @code{NO} on an option turns off the corresponding validity
6005 @item @code{NOCOPIES}
6006 @item @code{NODEFAULT}
6007 @item @code{NOFLOATS}
6008 @item @code{NOIN_PARAMS}
6009 @item @code{NOMOD_PARAMS}
6010 @item @code{NOOPERANDS}
6011 @item @code{NORETURNS}
6012 @item @code{NOSUBSCRIPTS}
6013 @item @code{NOTESTS}
6017 @option{^-gnatVaM^/VALIDITY_CHECKING=(ALL, NOMOD_PARAMS)^}
6018 turns on all validity checking options except for
6019 checking of @code{@b{in out}} procedure arguments.
6021 The specification of additional validity checking generates extra code (and
6022 in the case of @option{-gnatVa} the code expansion can be substantial).
6023 However, these additional checks can be very useful in detecting
6024 uninitialized variables, incorrect use of unchecked conversion, and other
6025 errors leading to invalid values. The use of pragma @code{Initialize_Scalars}
6026 is useful in conjunction with the extra validity checking, since this
6027 ensures that wherever possible uninitialized variables have invalid values.
6029 See also the pragma @code{Validity_Checks} which allows modification of
6030 the validity checking mode at the program source level, and also allows for
6031 temporary disabling of validity checks.
6033 @node Style Checking
6034 @subsection Style Checking
6035 @findex Style checking
6038 The @option{-gnaty^x^(option,option,@dots{})^} switch
6039 @cindex @option{-gnaty} (@command{gcc})
6040 causes the compiler to
6041 enforce specified style rules. A limited set of style rules has been used
6042 in writing the GNAT sources themselves. This switch allows user programs
6043 to activate all or some of these checks. If the source program fails a
6044 specified style check, an appropriate message is given, preceded by
6045 the character sequence ``(style)''. This message does not prevent
6046 successful compilation (unless the @option{-gnatwe} switch is used).
6048 Note that this is by no means intended to be a general facility for
6049 checking arbitrary coding standards. It is simply an embedding of the
6050 style rules we have chosen for the GNAT sources. If you are starting
6051 a project which does not have established style standards, you may
6052 find it useful to adopt the entire set of GNAT coding standards, or
6053 some subset of them. If you already have an established set of coding
6054 standards, then it may be that selected style checking options do
6055 indeed correspond to choices you have made, but for general checking
6056 of an existing set of coding rules, you should look to the gnatcheck
6057 tool, which is designed for that purpose.
6060 @code{(option,option,@dots{})} is a sequence of keywords
6063 The string @var{x} is a sequence of letters or digits
6065 indicating the particular style
6066 checks to be performed. The following checks are defined:
6071 @emph{Specify indentation level.}
6072 If a digit from 1-9 appears
6073 ^in the string after @option{-gnaty}^as an option for /STYLE_CHECKS^
6074 then proper indentation is checked, with the digit indicating the
6075 indentation level required. A value of zero turns off this style check.
6076 The general style of required indentation is as specified by
6077 the examples in the Ada Reference Manual. Full line comments must be
6078 aligned with the @code{--} starting on a column that is a multiple of
6079 the alignment level, or they may be aligned the same way as the following
6080 non-blank line (this is useful when full line comments appear in the middle
6081 of a statement, or they may be aligned with the source line on the previous
6085 @emph{Check attribute casing.}
6086 Attribute names, including the case of keywords such as @code{digits}
6087 used as attributes names, must be written in mixed case, that is, the
6088 initial letter and any letter following an underscore must be uppercase.
6089 All other letters must be lowercase.
6091 @item ^A^ARRAY_INDEXES^
6092 @emph{Use of array index numbers in array attributes.}
6093 When using the array attributes First, Last, Range,
6094 or Length, the index number must be omitted for one-dimensional arrays
6095 and is required for multi-dimensional arrays.
6098 @emph{Blanks not allowed at statement end.}
6099 Trailing blanks are not allowed at the end of statements. The purpose of this
6100 rule, together with h (no horizontal tabs), is to enforce a canonical format
6101 for the use of blanks to separate source tokens.
6103 @item ^B^BOOLEAN_OPERATORS^
6104 @emph{Check Boolean operators.}
6105 The use of AND/OR operators is not permitted except in the cases of modular
6106 operands, array operands, and simple stand-alone boolean variables or
6107 boolean constants. In all other cases @code{and then}/@code{or else} are
6111 @emph{Check comments, double space.}
6112 Comments must meet the following set of rules:
6117 The ``@code{--}'' that starts the column must either start in column one,
6118 or else at least one blank must precede this sequence.
6121 Comments that follow other tokens on a line must have at least one blank
6122 following the ``@code{--}'' at the start of the comment.
6125 Full line comments must have at least two blanks following the
6126 ``@code{--}'' that starts the comment, with the following exceptions.
6129 A line consisting only of the ``@code{--}'' characters, possibly preceded
6130 by blanks is permitted.
6133 A comment starting with ``@code{--x}'' where @code{x} is a special character
6135 This allows proper processing of the output generated by specialized tools
6136 including @command{gnatprep} (where ``@code{--!}'' is used) and the SPARK
6138 language (where ``@code{--#}'' is used). For the purposes of this rule, a
6139 special character is defined as being in one of the ASCII ranges
6140 @code{16#21#@dots{}16#2F#} or @code{16#3A#@dots{}16#3F#}.
6141 Note that this usage is not permitted
6142 in GNAT implementation units (i.e., when @option{-gnatg} is used).
6145 A line consisting entirely of minus signs, possibly preceded by blanks, is
6146 permitted. This allows the construction of box comments where lines of minus
6147 signs are used to form the top and bottom of the box.
6150 A comment that starts and ends with ``@code{--}'' is permitted as long as at
6151 least one blank follows the initial ``@code{--}''. Together with the preceding
6152 rule, this allows the construction of box comments, as shown in the following
6155 ---------------------------
6156 -- This is a box comment --
6157 -- with two text lines. --
6158 ---------------------------
6163 @emph{Check comments, single space.}
6164 This is identical to @code{^c^COMMENTS^} except that only one space
6165 is required following the @code{--} of a comment instead of two.
6167 @item ^d^DOS_LINE_ENDINGS^
6168 @emph{Check no DOS line terminators present.}
6169 All lines must be terminated by a single ASCII.LF
6170 character (in particular the DOS line terminator sequence CR/LF is not
6174 @emph{Check end/exit labels.}
6175 Optional labels on @code{end} statements ending subprograms and on
6176 @code{exit} statements exiting named loops, are required to be present.
6179 @emph{No form feeds or vertical tabs.}
6180 Neither form feeds nor vertical tab characters are permitted
6184 @emph{GNAT style mode.}
6185 The set of style check switches is set to match that used by the GNAT sources.
6186 This may be useful when developing code that is eventually intended to be
6187 incorporated into GNAT. For further details, see GNAT sources.
6190 @emph{No horizontal tabs.}
6191 Horizontal tab characters are not permitted in the source text.
6192 Together with the b (no blanks at end of line) check, this
6193 enforces a canonical form for the use of blanks to separate
6197 @emph{Check if-then layout.}
6198 The keyword @code{then} must appear either on the same
6199 line as corresponding @code{if}, or on a line on its own, lined
6200 up under the @code{if} with at least one non-blank line in between
6201 containing all or part of the condition to be tested.
6204 @emph{check mode IN keywords.}
6205 Mode @code{in} (the default mode) is not
6206 allowed to be given explicitly. @code{in out} is fine,
6207 but not @code{in} on its own.
6210 @emph{Check keyword casing.}
6211 All keywords must be in lower case (with the exception of keywords
6212 such as @code{digits} used as attribute names to which this check
6216 @emph{Check layout.}
6217 Layout of statement and declaration constructs must follow the
6218 recommendations in the Ada Reference Manual, as indicated by the
6219 form of the syntax rules. For example an @code{else} keyword must
6220 be lined up with the corresponding @code{if} keyword.
6222 There are two respects in which the style rule enforced by this check
6223 option are more liberal than those in the Ada Reference Manual. First
6224 in the case of record declarations, it is permissible to put the
6225 @code{record} keyword on the same line as the @code{type} keyword, and
6226 then the @code{end} in @code{end record} must line up under @code{type}.
6227 This is also permitted when the type declaration is split on two lines.
6228 For example, any of the following three layouts is acceptable:
6230 @smallexample @c ada
6253 Second, in the case of a block statement, a permitted alternative
6254 is to put the block label on the same line as the @code{declare} or
6255 @code{begin} keyword, and then line the @code{end} keyword up under
6256 the block label. For example both the following are permitted:
6258 @smallexample @c ada
6276 The same alternative format is allowed for loops. For example, both of
6277 the following are permitted:
6279 @smallexample @c ada
6281 Clear : while J < 10 loop
6292 @item ^Lnnn^MAX_NESTING=nnn^
6293 @emph{Set maximum nesting level.}
6294 The maximum level of nesting of constructs (including subprograms, loops,
6295 blocks, packages, and conditionals) may not exceed the given value
6296 @option{nnn}. A value of zero disconnects this style check.
6298 @item ^m^LINE_LENGTH^
6299 @emph{Check maximum line length.}
6300 The length of source lines must not exceed 79 characters, including
6301 any trailing blanks. The value of 79 allows convenient display on an
6302 80 character wide device or window, allowing for possible special
6303 treatment of 80 character lines. Note that this count is of
6304 characters in the source text. This means that a tab character counts
6305 as one character in this count and a wide character sequence counts as
6306 a single character (however many bytes are needed in the encoding).
6308 @item ^Mnnn^MAX_LENGTH=nnn^
6309 @emph{Set maximum line length.}
6310 The length of lines must not exceed the
6311 given value @option{nnn}. The maximum value that can be specified is 32767.
6312 If neither style option for setting the line length is used, then the
6313 default is 255. This also controls the maximum length of lexical elements,
6314 where the only restriction is that they must fit on a single line.
6316 @item ^n^STANDARD_CASING^
6317 @emph{Check casing of entities in Standard.}
6318 Any identifier from Standard must be cased
6319 to match the presentation in the Ada Reference Manual (for example,
6320 @code{Integer} and @code{ASCII.NUL}).
6323 @emph{Turn off all style checks.}
6324 All style check options are turned off.
6326 @item ^o^ORDERED_SUBPROGRAMS^
6327 @emph{Check order of subprogram bodies.}
6328 All subprogram bodies in a given scope
6329 (e.g.@: a package body) must be in alphabetical order. The ordering
6330 rule uses normal Ada rules for comparing strings, ignoring casing
6331 of letters, except that if there is a trailing numeric suffix, then
6332 the value of this suffix is used in the ordering (e.g.@: Junk2 comes
6335 @item ^O^OVERRIDING_INDICATORS^
6336 @emph{Check that overriding subprograms are explicitly marked as such.}
6337 The declaration of a primitive operation of a type extension that overrides
6338 an inherited operation must carry an overriding indicator.
6341 @emph{Check pragma casing.}
6342 Pragma names must be written in mixed case, that is, the
6343 initial letter and any letter following an underscore must be uppercase.
6344 All other letters must be lowercase.
6346 @item ^r^REFERENCES^
6347 @emph{Check references.}
6348 All identifier references must be cased in the same way as the
6349 corresponding declaration. No specific casing style is imposed on
6350 identifiers. The only requirement is for consistency of references
6354 @emph{Check separate specs.}
6355 Separate declarations (``specs'') are required for subprograms (a
6356 body is not allowed to serve as its own declaration). The only
6357 exception is that parameterless library level procedures are
6358 not required to have a separate declaration. This exception covers
6359 the most frequent form of main program procedures.
6361 @item ^S^STATEMENTS_AFTER_THEN_ELSE^
6362 @emph{Check no statements after @code{then}/@code{else}.}
6363 No statements are allowed
6364 on the same line as a @code{then} or @code{else} keyword following the
6365 keyword in an @code{if} statement. @code{or else} and @code{and then} are not
6366 affected, and a special exception allows a pragma to appear after @code{else}.
6369 @emph{Check token spacing.}
6370 The following token spacing rules are enforced:
6375 The keywords @code{abs} and @code{not} must be followed by a space.
6378 The token @code{=>} must be surrounded by spaces.
6381 The token @code{<>} must be preceded by a space or a left parenthesis.
6384 Binary operators other than @code{**} must be surrounded by spaces.
6385 There is no restriction on the layout of the @code{**} binary operator.
6388 Colon must be surrounded by spaces.
6391 Colon-equal (assignment, initialization) must be surrounded by spaces.
6394 Comma must be the first non-blank character on the line, or be
6395 immediately preceded by a non-blank character, and must be followed
6399 If the token preceding a left parenthesis ends with a letter or digit, then
6400 a space must separate the two tokens.
6403 if the token following a right parenthesis starts with a letter or digit, then
6404 a space must separate the two tokens.
6407 A right parenthesis must either be the first non-blank character on
6408 a line, or it must be preceded by a non-blank character.
6411 A semicolon must not be preceded by a space, and must not be followed by
6412 a non-blank character.
6415 A unary plus or minus may not be followed by a space.
6418 A vertical bar must be surrounded by spaces.
6422 Exactly one blank (and no other white space) must appear between
6423 a @code{not} token and a following @code{in} token.
6425 @item ^u^UNNECESSARY_BLANK_LINES^
6426 @emph{Check unnecessary blank lines.}
6427 Unnecessary blank lines are not allowed. A blank line is considered
6428 unnecessary if it appears at the end of the file, or if more than
6429 one blank line occurs in sequence.
6431 @item ^x^XTRA_PARENS^
6432 @emph{Check extra parentheses.}
6433 Unnecessary extra level of parentheses (C-style) are not allowed
6434 around conditions in @code{if} statements, @code{while} statements and
6435 @code{exit} statements.
6437 @item ^y^ALL_BUILTIN^
6438 @emph{Set all standard style check options}
6439 This is equivalent to @code{gnaty3aAbcefhiklmnprst}, that is all checking
6440 options enabled with the exception of @option{-gnatyB}, @option{-gnatyd},
6441 @option{-gnatyI}, @option{-gnatyLnnn}, @option{-gnatyo}, @option{-gnatyO},
6442 @option{-gnatyS}, @option{-gnatyu}, and @option{-gnatyx}.
6446 @emph{Remove style check options}
6447 This causes any subsequent options in the string to act as canceling the
6448 corresponding style check option. To cancel maximum nesting level control,
6449 use @option{L} parameter witout any integer value after that, because any
6450 digit following @option{-} in the parameter string of the @option{-gnaty}
6451 option will be threated as canceling indentation check. The same is true
6452 for @option{M} parameter. @option{y} and @option{N} parameters are not
6453 allowed after @option{-}.
6456 This causes any subsequent options in the string to enable the corresponding
6457 style check option. That is, it cancels the effect of a previous ^-^REMOVE^,
6463 @emph{Removing style check options}
6464 If the name of a style check is preceded by @option{NO} then the corresponding
6465 style check is turned off. For example @option{NOCOMMENTS} turns off style
6466 checking for comments.
6471 In the above rules, appearing in column one is always permitted, that is,
6472 counts as meeting either a requirement for a required preceding space,
6473 or as meeting a requirement for no preceding space.
6475 Appearing at the end of a line is also always permitted, that is, counts
6476 as meeting either a requirement for a following space, or as meeting
6477 a requirement for no following space.
6480 If any of these style rules is violated, a message is generated giving
6481 details on the violation. The initial characters of such messages are
6482 always ``@code{(style)}''. Note that these messages are treated as warning
6483 messages, so they normally do not prevent the generation of an object
6484 file. The @option{-gnatwe} switch can be used to treat warning messages,
6485 including style messages, as fatal errors.
6489 @option{-gnaty} on its own (that is not
6490 followed by any letters or digits) is equivalent
6491 to the use of @option{-gnatyy} as described above, that is all
6492 built-in standard style check options are enabled.
6496 /STYLE_CHECKS=ALL_BUILTIN enables all checking options with
6497 the exception of ORDERED_SUBPROGRAMS, UNNECESSARY_BLANK_LINES,
6498 XTRA_PARENS, and DOS_LINE_ENDINGS. In addition
6508 clears any previously set style checks.
6510 @node Run-Time Checks
6511 @subsection Run-Time Checks
6512 @cindex Division by zero
6513 @cindex Access before elaboration
6514 @cindex Checks, division by zero
6515 @cindex Checks, access before elaboration
6516 @cindex Checks, stack overflow checking
6519 By default, the following checks are suppressed: integer overflow
6520 checks, stack overflow checks, and checks for access before
6521 elaboration on subprogram calls. All other checks, including range
6522 checks and array bounds checks, are turned on by default. The
6523 following @command{gcc} switches refine this default behavior.
6528 @cindex @option{-gnatp} (@command{gcc})
6529 @cindex Suppressing checks
6530 @cindex Checks, suppressing
6532 This switch causes the unit to be compiled
6533 as though @code{pragma Suppress (All_checks)}
6534 had been present in the source. Validity checks are also eliminated (in
6535 other words @option{-gnatp} also implies @option{-gnatVn}.
6536 Use this switch to improve the performance
6537 of the code at the expense of safety in the presence of invalid data or
6540 Note that when checks are suppressed, the compiler is allowed, but not
6541 required, to omit the checking code. If the run-time cost of the
6542 checking code is zero or near-zero, the compiler will generate it even
6543 if checks are suppressed. In particular, if the compiler can prove
6544 that a certain check will necessarily fail, it will generate code to
6545 do an unconditional ``raise'', even if checks are suppressed. The
6546 compiler warns in this case. Another case in which checks may not be
6547 eliminated is when they are embedded in certain run time routines such
6548 as math library routines.
6550 Of course, run-time checks are omitted whenever the compiler can prove
6551 that they will not fail, whether or not checks are suppressed.
6553 Note that if you suppress a check that would have failed, program
6554 execution is erroneous, which means the behavior is totally
6555 unpredictable. The program might crash, or print wrong answers, or
6556 do anything else. It might even do exactly what you wanted it to do
6557 (and then it might start failing mysteriously next week or next
6558 year). The compiler will generate code based on the assumption that
6559 the condition being checked is true, which can result in disaster if
6560 that assumption is wrong.
6562 The checks subject to suppression include all the checks defined by
6563 the Ada standard, the additional implementation defined checks
6564 @code{Alignment_Check}, @code{Atomic_Synchronization}, and
6565 @code{Validity_Check}, as well as any checks introduced using
6566 @code{pragma Check_Name}.
6568 The @option{-gnatp} switch has no effect if a subsequent
6569 @option{-gnat-p} switch appears.
6572 @cindex @option{-gnat-p} (@command{gcc})
6573 @cindex Suppressing checks
6574 @cindex Checks, suppressing
6576 This switch cancels the effect of a previous @option{gnatp} switch.
6579 @cindex @option{-gnato??} (@command{gcc})
6580 @cindex Overflow checks
6581 @cindex Overflow mode
6582 @cindex Check, overflow
6583 This switch controls the mode used for computing intermediate
6584 arithmetic integer operations, and also enables overflow checking.
6585 For a full description of overflow mode and checking control, see
6586 the ``Overflow Check Handling in GNAT'' appendix in this
6589 Overflow checks are always enabled by this switch. The argument
6590 controls the mode, using the codes
6594 In STRICT mode, intermediate operations are always done using the
6595 base type, and overflow checking ensures that the result is within
6596 the base type range.
6599 In MINIMIZED mode, overflows in intermediate operations are avoided
6600 where possible by using a larger integer type for the computation
6601 (typically @code{Long_Long_Integer}). Overflow checking ensures that
6602 the result fits in this larger integer type.
6604 @item 3 = ELIMINATED
6605 In ELIMINATED mode, overflows in intermediate operations are avoided
6606 by using multi-precision arithmetic. In this case, overflow checking
6607 has no effect on intermediate operations (since overflow is impossible).
6610 If two digits are present after @option{-gnato} then the first digit
6611 sets the mode for expressions outside assertions, and the second digit
6612 sets the mode for expressions within assertions. Here assertions is used
6613 in the technical sense (which includes for example precondition and
6614 postcondition expressions).
6616 If one digit is present, the corresponding mode is applicable to both
6617 expressions within and outside assertion expressions.
6619 If no digits are present, the default is to enable overflow checks
6620 and set STRICT mode for both kinds of expressions. This is compatible
6621 with the use of @option{-gnato} in previous versions of GNAT.
6623 @findex Machine_Overflows
6624 Note that the @option{-gnato??} switch does not affect the code generated
6625 for any floating-point operations; it applies only to integer semantics.
6626 For floating-point, @value{EDITION} has the @code{Machine_Overflows}
6627 attribute set to @code{False} and the normal mode of operation is to
6628 generate IEEE NaN and infinite values on overflow or invalid operations
6629 (such as dividing 0.0 by 0.0).
6631 The reason that we distinguish overflow checking from other kinds of
6632 range constraint checking is that a failure of an overflow check, unlike
6633 for example the failure of a range check, can result in an incorrect
6634 value, but cannot cause random memory destruction (like an out of range
6635 subscript), or a wild jump (from an out of range case value). Overflow
6636 checking is also quite expensive in time and space, since in general it
6637 requires the use of double length arithmetic.
6639 Note again that the default is @option{^-gnato00^/OVERFLOW_CHECKS=00^},
6640 so overflow checking is not performed in default mode. This means that out of
6641 the box, with the default settings, @value{EDITION} does not do all the checks
6642 expected from the language description in the Ada Reference Manual.
6643 If you want all constraint checks to be performed, as described in this Manual,
6644 then you must explicitly use the @option{-gnato??}
6645 switch either on the @command{gnatmake} or @command{gcc} command.
6648 @cindex @option{-gnatE} (@command{gcc})
6649 @cindex Elaboration checks
6650 @cindex Check, elaboration
6651 Enables dynamic checks for access-before-elaboration
6652 on subprogram calls and generic instantiations.
6653 Note that @option{-gnatE} is not necessary for safety, because in the
6654 default mode, GNAT ensures statically that the checks would not fail.
6655 For full details of the effect and use of this switch,
6656 @xref{Compiling with gcc}.
6659 @cindex @option{-fstack-check} (@command{gcc})
6660 @cindex Stack Overflow Checking
6661 @cindex Checks, stack overflow checking
6662 Activates stack overflow checking. For full details of the effect and use of
6663 this switch see @ref{Stack Overflow Checking}.
6668 The setting of these switches only controls the default setting of the
6669 checks. You may modify them using either @code{Suppress} (to remove
6670 checks) or @code{Unsuppress} (to add back suppressed checks) pragmas in
6673 @node Using gcc for Syntax Checking
6674 @subsection Using @command{gcc} for Syntax Checking
6677 @cindex @option{-gnats} (@command{gcc})
6681 The @code{s} stands for ``syntax''.
6684 Run GNAT in syntax checking only mode. For
6685 example, the command
6688 $ gcc -c -gnats x.adb
6692 compiles file @file{x.adb} in syntax-check-only mode. You can check a
6693 series of files in a single command
6695 , and can use wild cards to specify such a group of files.
6696 Note that you must specify the @option{-c} (compile
6697 only) flag in addition to the @option{-gnats} flag.
6700 You may use other switches in conjunction with @option{-gnats}. In
6701 particular, @option{-gnatl} and @option{-gnatv} are useful to control the
6702 format of any generated error messages.
6704 When the source file is empty or contains only empty lines and/or comments,
6705 the output is a warning:
6708 $ gcc -c -gnats -x ada toto.txt
6709 toto.txt:1:01: warning: empty file, contains no compilation units
6713 Otherwise, the output is simply the error messages, if any. No object file or
6714 ALI file is generated by a syntax-only compilation. Also, no units other
6715 than the one specified are accessed. For example, if a unit @code{X}
6716 @code{with}'s a unit @code{Y}, compiling unit @code{X} in syntax
6717 check only mode does not access the source file containing unit
6720 @cindex Multiple units, syntax checking
6721 Normally, GNAT allows only a single unit in a source file. However, this
6722 restriction does not apply in syntax-check-only mode, and it is possible
6723 to check a file containing multiple compilation units concatenated
6724 together. This is primarily used by the @code{gnatchop} utility
6725 (@pxref{Renaming Files with gnatchop}).
6728 @node Using gcc for Semantic Checking
6729 @subsection Using @command{gcc} for Semantic Checking
6732 @cindex @option{-gnatc} (@command{gcc})
6736 The @code{c} stands for ``check''.
6738 Causes the compiler to operate in semantic check mode,
6739 with full checking for all illegalities specified in the
6740 Ada Reference Manual, but without generation of any object code
6741 (no object file is generated).
6743 Because dependent files must be accessed, you must follow the GNAT
6744 semantic restrictions on file structuring to operate in this mode:
6748 The needed source files must be accessible
6749 (@pxref{Search Paths and the Run-Time Library (RTL)}).
6752 Each file must contain only one compilation unit.
6755 The file name and unit name must match (@pxref{File Naming Rules}).
6758 The output consists of error messages as appropriate. No object file is
6759 generated. An @file{ALI} file is generated for use in the context of
6760 cross-reference tools, but this file is marked as not being suitable
6761 for binding (since no object file is generated).
6762 The checking corresponds exactly to the notion of
6763 legality in the Ada Reference Manual.
6765 Any unit can be compiled in semantics-checking-only mode, including
6766 units that would not normally be compiled (subunits,
6767 and specifications where a separate body is present).
6770 @node Compiling Different Versions of Ada
6771 @subsection Compiling Different Versions of Ada
6774 The switches described in this section allow you to explicitly specify
6775 the version of the Ada language that your programs are written in.
6776 The default mode is Ada 2012,
6777 but you can also specify Ada 95, Ada 2005 mode, or
6778 indicate Ada 83 compatibility mode.
6781 @cindex Compatibility with Ada 83
6783 @item -gnat83 (Ada 83 Compatibility Mode)
6784 @cindex @option{-gnat83} (@command{gcc})
6785 @cindex ACVC, Ada 83 tests
6789 Although GNAT is primarily an Ada 95 / Ada 2005 compiler, this switch
6790 specifies that the program is to be compiled in Ada 83 mode. With
6791 @option{-gnat83}, GNAT rejects most post-Ada 83 extensions and applies Ada 83
6792 semantics where this can be done easily.
6793 It is not possible to guarantee this switch does a perfect
6794 job; some subtle tests, such as are
6795 found in earlier ACVC tests (and that have been removed from the ACATS suite
6796 for Ada 95), might not compile correctly.
6797 Nevertheless, this switch may be useful in some circumstances, for example
6798 where, due to contractual reasons, existing code needs to be maintained
6799 using only Ada 83 features.
6801 With few exceptions (most notably the need to use @code{<>} on
6802 @cindex Generic formal parameters
6803 unconstrained generic formal parameters, the use of the new Ada 95 / Ada 2005
6804 reserved words, and the use of packages
6805 with optional bodies), it is not necessary to specify the
6806 @option{-gnat83} switch when compiling Ada 83 programs, because, with rare
6807 exceptions, Ada 95 and Ada 2005 are upwardly compatible with Ada 83. Thus
6808 a correct Ada 83 program is usually also a correct program
6809 in these later versions of the language standard.
6810 For further information, please refer to @ref{Compatibility and Porting Guide}.
6812 @item -gnat95 (Ada 95 mode)
6813 @cindex @option{-gnat95} (@command{gcc})
6817 This switch directs the compiler to implement the Ada 95 version of the
6819 Since Ada 95 is almost completely upwards
6820 compatible with Ada 83, Ada 83 programs may generally be compiled using
6821 this switch (see the description of the @option{-gnat83} switch for further
6822 information about Ada 83 mode).
6823 If an Ada 2005 program is compiled in Ada 95 mode,
6824 uses of the new Ada 2005 features will cause error
6825 messages or warnings.
6827 This switch also can be used to cancel the effect of a previous
6828 @option{-gnat83}, @option{-gnat05/2005}, or @option{-gnat12/2012}
6829 switch earlier in the command line.
6831 @item -gnat05 or -gnat2005 (Ada 2005 mode)
6832 @cindex @option{-gnat05} (@command{gcc})
6833 @cindex @option{-gnat2005} (@command{gcc})
6834 @cindex Ada 2005 mode
6837 This switch directs the compiler to implement the Ada 2005 version of the
6838 language, as documented in the official Ada standards document.
6839 Since Ada 2005 is almost completely upwards
6840 compatible with Ada 95 (and thus also with Ada 83), Ada 83 and Ada 95 programs
6841 may generally be compiled using this switch (see the description of the
6842 @option{-gnat83} and @option{-gnat95} switches for further
6845 @item -gnat12 or -gnat2012 (Ada 2012 mode)
6846 @cindex @option{-gnat12} (@command{gcc})
6847 @cindex @option{-gnat2012} (@command{gcc})
6848 @cindex Ada 2012 mode
6851 This switch directs the compiler to implement the Ada 2012 version of the
6852 language (also the default).
6853 Since Ada 2012 is almost completely upwards
6854 compatible with Ada 2005 (and thus also with Ada 83, and Ada 95),
6855 Ada 83 and Ada 95 programs
6856 may generally be compiled using this switch (see the description of the
6857 @option{-gnat83}, @option{-gnat95}, and @option{-gnat05/2005} switches
6858 for further information).
6860 @item -gnatX (Enable GNAT Extensions)
6861 @cindex @option{-gnatX} (@command{gcc})
6862 @cindex Ada language extensions
6863 @cindex GNAT extensions
6866 This switch directs the compiler to implement the latest version of the
6867 language (currently Ada 2012) and also to enable certain GNAT implementation
6868 extensions that are not part of any Ada standard. For a full list of these
6869 extensions, see the GNAT reference manual.
6873 @node Character Set Control
6874 @subsection Character Set Control
6876 @item ^-gnati^/IDENTIFIER_CHARACTER_SET=^@var{c}
6877 @cindex @option{^-gnati^/IDENTIFIER_CHARACTER_SET^} (@command{gcc})
6880 Normally GNAT recognizes the Latin-1 character set in source program
6881 identifiers, as described in the Ada Reference Manual.
6883 GNAT to recognize alternate character sets in identifiers. @var{c} is a
6884 single character ^^or word^ indicating the character set, as follows:
6888 ISO 8859-1 (Latin-1) identifiers
6891 ISO 8859-2 (Latin-2) letters allowed in identifiers
6894 ISO 8859-3 (Latin-3) letters allowed in identifiers
6897 ISO 8859-4 (Latin-4) letters allowed in identifiers
6900 ISO 8859-5 (Cyrillic) letters allowed in identifiers
6903 ISO 8859-15 (Latin-9) letters allowed in identifiers
6906 IBM PC letters (code page 437) allowed in identifiers
6909 IBM PC letters (code page 850) allowed in identifiers
6911 @item ^f^FULL_UPPER^
6912 Full upper-half codes allowed in identifiers
6915 No upper-half codes allowed in identifiers
6918 Wide-character codes (that is, codes greater than 255)
6919 allowed in identifiers
6922 @xref{Foreign Language Representation}, for full details on the
6923 implementation of these character sets.
6925 @item ^-gnatW^/WIDE_CHARACTER_ENCODING=^@var{e}
6926 @cindex @option{^-gnatW^/WIDE_CHARACTER_ENCODING^} (@command{gcc})
6927 Specify the method of encoding for wide characters.
6928 @var{e} is one of the following:
6933 Hex encoding (brackets coding also recognized)
6936 Upper half encoding (brackets encoding also recognized)
6939 Shift/JIS encoding (brackets encoding also recognized)
6942 EUC encoding (brackets encoding also recognized)
6945 UTF-8 encoding (brackets encoding also recognized)
6948 Brackets encoding only (default value)
6950 For full details on these encoding
6951 methods see @ref{Wide Character Encodings}.
6952 Note that brackets coding is always accepted, even if one of the other
6953 options is specified, so for example @option{-gnatW8} specifies that both
6954 brackets and UTF-8 encodings will be recognized. The units that are
6955 with'ed directly or indirectly will be scanned using the specified
6956 representation scheme, and so if one of the non-brackets scheme is
6957 used, it must be used consistently throughout the program. However,
6958 since brackets encoding is always recognized, it may be conveniently
6959 used in standard libraries, allowing these libraries to be used with
6960 any of the available coding schemes.
6962 Note that brackets encoding only applies to program text. Within comments,
6963 brackets are considered to be normal graphic characters, and bracket sequences
6964 are never recognized as wide characters.
6966 If no @option{-gnatW?} parameter is present, then the default
6967 representation is normally Brackets encoding only. However, if the
6968 first three characters of the file are 16#EF# 16#BB# 16#BF# (the standard
6969 byte order mark or BOM for UTF-8), then these three characters are
6970 skipped and the default representation for the file is set to UTF-8.
6972 Note that the wide character representation that is specified (explicitly
6973 or by default) for the main program also acts as the default encoding used
6974 for Wide_Text_IO files if not specifically overridden by a WCEM form
6979 When no @option{-gnatW?} is specified, then characters (other than wide
6980 characters represented using brackets notation) are treated as 8-bit
6981 Latin-1 codes. The codes recognized are the Latin-1 graphic characters,
6982 and ASCII format effectors (CR, LF, HT, VT). Other lower half control
6983 characters in the range 16#00#..16#1F# are not accepted in program text
6984 or in comments. Upper half control characters (16#80#..16#9F#) are rejected
6985 in program text, but allowed and ignored in comments. Note in particular
6986 that the Next Line (NEL) character whose encoding is 16#85# is not recognized
6987 as an end of line in this default mode. If your source program contains
6988 instances of the NEL character used as a line terminator,
6989 you must use UTF-8 encoding for the whole
6990 source program. In default mode, all lines must be ended by a standard
6991 end of line sequence (CR, CR/LF, or LF).
6993 Note that the convention of simply accepting all upper half characters in
6994 comments means that programs that use standard ASCII for program text, but
6995 UTF-8 encoding for comments are accepted in default mode, providing that the
6996 comments are ended by an appropriate (CR, or CR/LF, or LF) line terminator.
6997 This is a common mode for many programs with foreign language comments.
6999 @node File Naming Control
7000 @subsection File Naming Control
7003 @item ^-gnatk^/FILE_NAME_MAX_LENGTH=^@var{n}
7004 @cindex @option{-gnatk} (@command{gcc})
7005 Activates file name ``krunching''. @var{n}, a decimal integer in the range
7006 1-999, indicates the maximum allowable length of a file name (not
7007 including the @file{.ads} or @file{.adb} extension). The default is not
7008 to enable file name krunching.
7010 For the source file naming rules, @xref{File Naming Rules}.
7013 @node Subprogram Inlining Control
7014 @subsection Subprogram Inlining Control
7019 @cindex @option{-gnatn} (@command{gcc})
7021 The @code{n} here is intended to suggest the first syllable of the
7024 GNAT recognizes and processes @code{Inline} pragmas. However, for the
7025 inlining to actually occur, optimization must be enabled and, in order
7026 to enable inlining of subprograms specified by pragma @code{Inline},
7027 you must also specify this switch.
7028 In the absence of this switch, GNAT does not attempt
7029 inlining and does not need to access the bodies of
7030 subprograms for which @code{pragma Inline} is specified if they are not
7031 in the current unit.
7033 You can optionally specify the inlining level: 1 for moderate inlining across
7034 modules, which is a good compromise between compilation times and performances
7035 at run time, or 2 for full inlining across modules, which may bring about
7036 longer compilation times. If no inlining level is specified, the compiler will
7037 pick it based on the optimization level: 1 for @option{-O1}, @option{-O2} or
7038 @option{-Os} and 2 for @option{-O3}.
7040 If you specify this switch the compiler will access these bodies,
7041 creating an extra source dependency for the resulting object file, and
7042 where possible, the call will be inlined.
7043 For further details on when inlining is possible
7044 see @ref{Inlining of Subprograms}.
7047 @cindex @option{-gnatN} (@command{gcc})
7048 This switch activates front-end inlining which also
7049 generates additional dependencies.
7051 When using a gcc-based back end (in practice this means using any version
7052 of GNAT other than the JGNAT, .NET or GNAAMP versions), then the use of
7053 @option{-gnatN} is deprecated, and the use of @option{-gnatn} is preferred.
7054 Historically front end inlining was more extensive than the gcc back end
7055 inlining, but that is no longer the case.
7058 @node Auxiliary Output Control
7059 @subsection Auxiliary Output Control
7063 @cindex @option{-gnatt} (@command{gcc})
7064 @cindex Writing internal trees
7065 @cindex Internal trees, writing to file
7066 Causes GNAT to write the internal tree for a unit to a file (with the
7067 extension @file{.adt}.
7068 This not normally required, but is used by separate analysis tools.
7070 these tools do the necessary compilations automatically, so you should
7071 not have to specify this switch in normal operation.
7072 Note that the combination of switches @option{-gnatct}
7073 generates a tree in the form required by ASIS applications.
7076 @cindex @option{-gnatu} (@command{gcc})
7077 Print a list of units required by this compilation on @file{stdout}.
7078 The listing includes all units on which the unit being compiled depends
7079 either directly or indirectly.
7082 @item -pass-exit-codes
7083 @cindex @option{-pass-exit-codes} (@command{gcc})
7084 If this switch is not used, the exit code returned by @command{gcc} when
7085 compiling multiple files indicates whether all source files have
7086 been successfully used to generate object files or not.
7088 When @option{-pass-exit-codes} is used, @command{gcc} exits with an extended
7089 exit status and allows an integrated development environment to better
7090 react to a compilation failure. Those exit status are:
7094 There was an error in at least one source file.
7096 At least one source file did not generate an object file.
7098 The compiler died unexpectedly (internal error for example).
7100 An object file has been generated for every source file.
7105 @node Debugging Control
7106 @subsection Debugging Control
7110 @cindex Debugging options
7113 @cindex @option{-gnatd} (@command{gcc})
7114 Activate internal debugging switches. @var{x} is a letter or digit, or
7115 string of letters or digits, which specifies the type of debugging
7116 outputs desired. Normally these are used only for internal development
7117 or system debugging purposes. You can find full documentation for these
7118 switches in the body of the @code{Debug} unit in the compiler source
7119 file @file{debug.adb}.
7123 @cindex @option{-gnatG} (@command{gcc})
7124 This switch causes the compiler to generate auxiliary output containing
7125 a pseudo-source listing of the generated expanded code. Like most Ada
7126 compilers, GNAT works by first transforming the high level Ada code into
7127 lower level constructs. For example, tasking operations are transformed
7128 into calls to the tasking run-time routines. A unique capability of GNAT
7129 is to list this expanded code in a form very close to normal Ada source.
7130 This is very useful in understanding the implications of various Ada
7131 usage on the efficiency of the generated code. There are many cases in
7132 Ada (e.g.@: the use of controlled types), where simple Ada statements can
7133 generate a lot of run-time code. By using @option{-gnatG} you can identify
7134 these cases, and consider whether it may be desirable to modify the coding
7135 approach to improve efficiency.
7137 The optional parameter @code{nn} if present after -gnatG specifies an
7138 alternative maximum line length that overrides the normal default of 72.
7139 This value is in the range 40-999999, values less than 40 being silently
7140 reset to 40. The equal sign is optional.
7142 The format of the output is very similar to standard Ada source, and is
7143 easily understood by an Ada programmer. The following special syntactic
7144 additions correspond to low level features used in the generated code that
7145 do not have any exact analogies in pure Ada source form. The following
7146 is a partial list of these special constructions. See the spec
7147 of package @code{Sprint} in file @file{sprint.ads} for a full list.
7149 If the switch @option{-gnatL} is used in conjunction with
7150 @cindex @option{-gnatL} (@command{gcc})
7151 @option{-gnatG}, then the original source lines are interspersed
7152 in the expanded source (as comment lines with the original line number).
7155 @item new @var{xxx} @r{[}storage_pool = @var{yyy}@r{]}
7156 Shows the storage pool being used for an allocator.
7158 @item at end @var{procedure-name};
7159 Shows the finalization (cleanup) procedure for a scope.
7161 @item (if @var{expr} then @var{expr} else @var{expr})
7162 Conditional expression equivalent to the @code{x?y:z} construction in C.
7164 @item @var{target}^^^(@var{source})
7165 A conversion with floating-point truncation instead of rounding.
7167 @item @var{target}?(@var{source})
7168 A conversion that bypasses normal Ada semantic checking. In particular
7169 enumeration types and fixed-point types are treated simply as integers.
7171 @item @var{target}?^^^(@var{source})
7172 Combines the above two cases.
7174 @item @var{x} #/ @var{y}
7175 @itemx @var{x} #mod @var{y}
7176 @itemx @var{x} #* @var{y}
7177 @itemx @var{x} #rem @var{y}
7178 A division or multiplication of fixed-point values which are treated as
7179 integers without any kind of scaling.
7181 @item free @var{expr} @r{[}storage_pool = @var{xxx}@r{]}
7182 Shows the storage pool associated with a @code{free} statement.
7184 @item [subtype or type declaration]
7185 Used to list an equivalent declaration for an internally generated
7186 type that is referenced elsewhere in the listing.
7188 @c @item freeze @var{type-name} @ovar{actions}
7189 @c Expanding @ovar macro inline (explanation in macro def comments)
7190 @item freeze @var{type-name} @r{[}@var{actions}@r{]}
7191 Shows the point at which @var{type-name} is frozen, with possible
7192 associated actions to be performed at the freeze point.
7194 @item reference @var{itype}
7195 Reference (and hence definition) to internal type @var{itype}.
7197 @item @var{function-name}! (@var{arg}, @var{arg}, @var{arg})
7198 Intrinsic function call.
7200 @item @var{label-name} : label
7201 Declaration of label @var{labelname}.
7203 @item #$ @var{subprogram-name}
7204 An implicit call to a run-time support routine
7205 (to meet the requirement of H.3.1(9) in a
7208 @item @var{expr} && @var{expr} && @var{expr} @dots{} && @var{expr}
7209 A multiple concatenation (same effect as @var{expr} & @var{expr} &
7210 @var{expr}, but handled more efficiently).
7212 @item [constraint_error]
7213 Raise the @code{Constraint_Error} exception.
7215 @item @var{expression}'reference
7216 A pointer to the result of evaluating @var{expression}.
7218 @item @var{target-type}!(@var{source-expression})
7219 An unchecked conversion of @var{source-expression} to @var{target-type}.
7221 @item [@var{numerator}/@var{denominator}]
7222 Used to represent internal real literals (that) have no exact
7223 representation in base 2-16 (for example, the result of compile time
7224 evaluation of the expression 1.0/27.0).
7228 @cindex @option{-gnatD} (@command{gcc})
7229 When used in conjunction with @option{-gnatG}, this switch causes
7230 the expanded source, as described above for
7231 @option{-gnatG} to be written to files with names
7232 @file{^xxx.dg^XXX_DG^}, where @file{xxx} is the normal file name,
7233 instead of to the standard output file. For
7234 example, if the source file name is @file{hello.adb}, then a file
7235 @file{^hello.adb.dg^HELLO.ADB_DG^} will be written. The debugging
7236 information generated by the @command{gcc} @option{^-g^/DEBUG^} switch
7237 will refer to the generated @file{^xxx.dg^XXX_DG^} file. This allows
7238 you to do source level debugging using the generated code which is
7239 sometimes useful for complex code, for example to find out exactly
7240 which part of a complex construction raised an exception. This switch
7241 also suppress generation of cross-reference information (see
7242 @option{-gnatx}) since otherwise the cross-reference information
7243 would refer to the @file{^.dg^.DG^} file, which would cause
7244 confusion since this is not the original source file.
7246 Note that @option{-gnatD} actually implies @option{-gnatG}
7247 automatically, so it is not necessary to give both options.
7248 In other words @option{-gnatD} is equivalent to @option{-gnatDG}).
7250 If the switch @option{-gnatL} is used in conjunction with
7251 @cindex @option{-gnatL} (@command{gcc})
7252 @option{-gnatDG}, then the original source lines are interspersed
7253 in the expanded source (as comment lines with the original line number).
7255 The optional parameter @code{nn} if present after -gnatD specifies an
7256 alternative maximum line length that overrides the normal default of 72.
7257 This value is in the range 40-999999, values less than 40 being silently
7258 reset to 40. The equal sign is optional.
7261 @cindex @option{-gnatr} (@command{gcc})
7262 @cindex pragma Restrictions
7263 This switch causes pragma Restrictions to be treated as Restriction_Warnings
7264 so that violation of restrictions causes warnings rather than illegalities.
7265 This is useful during the development process when new restrictions are added
7266 or investigated. The switch also causes pragma Profile to be treated as
7267 Profile_Warnings, and pragma Restricted_Run_Time and pragma Ravenscar set
7268 restriction warnings rather than restrictions.
7271 @item -gnatR@r{[}0@r{|}1@r{|}2@r{|}3@r{[}s@r{]]}
7272 @cindex @option{-gnatR} (@command{gcc})
7273 This switch controls output from the compiler of a listing showing
7274 representation information for declared types and objects. For
7275 @option{-gnatR0}, no information is output (equivalent to omitting
7276 the @option{-gnatR} switch). For @option{-gnatR1} (which is the default,
7277 so @option{-gnatR} with no parameter has the same effect), size and alignment
7278 information is listed for declared array and record types. For
7279 @option{-gnatR2}, size and alignment information is listed for all
7280 declared types and objects. Finally @option{-gnatR3} includes symbolic
7281 expressions for values that are computed at run time for
7282 variant records. These symbolic expressions have a mostly obvious
7283 format with #n being used to represent the value of the n'th
7284 discriminant. See source files @file{repinfo.ads/adb} in the
7285 @code{GNAT} sources for full details on the format of @option{-gnatR3}
7286 output. If the switch is followed by an s (e.g.@: @option{-gnatR2s}), then
7287 the output is to a file with the name @file{^file.rep^file_REP^} where
7288 file is the name of the corresponding source file.
7291 This form of the switch controls output of subprogram conventions
7292 and parameter passing mechanisms for all subprograms. A following
7293 @code{s} means output to a file as described above.
7296 @item /REPRESENTATION_INFO
7297 @cindex @option{/REPRESENTATION_INFO} (@command{gcc})
7298 This qualifier controls output from the compiler of a listing showing
7299 representation information for declared types and objects. For
7300 @option{/REPRESENTATION_INFO=NONE}, no information is output
7301 (equivalent to omitting the @option{/REPRESENTATION_INFO} qualifier).
7302 @option{/REPRESENTATION_INFO} without option is equivalent to
7303 @option{/REPRESENTATION_INFO=ARRAYS}.
7304 For @option{/REPRESENTATION_INFO=ARRAYS}, size and alignment
7305 information is listed for declared array and record types. For
7306 @option{/REPRESENTATION_INFO=OBJECTS}, size and alignment information
7307 is listed for all expression information for values that are computed
7308 at run time for variant records. These symbolic expressions have a mostly
7309 obvious format with #n being used to represent the value of the n'th
7310 discriminant. See source files @file{REPINFO.ADS/ADB} in the
7311 @code{GNAT} sources for full details on the format of
7312 @option{/REPRESENTATION_INFO=SYMBOLIC} output.
7313 If _FILE is added at the end of an option
7314 (e.g.@: @option{/REPRESENTATION_INFO=ARRAYS_FILE}),
7315 then the output is to a file with the name @file{file_REP} where
7316 file is the name of the corresponding source file.
7318 @item /REPRESENTATION_INFO=MECHANISMS
7319 This qualifier form controls output of subprogram conventions
7320 and parameter passing mechanisms for all subprograms. It is
7321 possible to append _FILE as described above to cause information
7322 to be written to a file.
7325 Note that it is possible for record components to have zero size. In
7326 this case, the component clause uses an obvious extension of permitted
7327 Ada syntax, for example @code{at 0 range 0 .. -1}.
7329 Representation information requires that code be generated (since it is the
7330 code generator that lays out complex data structures). If an attempt is made
7331 to output representation information when no code is generated, for example
7332 when a subunit is compiled on its own, then no information can be generated
7333 and the compiler outputs a message to this effect.
7336 @cindex @option{-gnatS} (@command{gcc})
7337 The use of the switch @option{-gnatS} for an
7338 Ada compilation will cause the compiler to output a
7339 representation of package Standard in a form very
7340 close to standard Ada. It is not quite possible to
7341 do this entirely in standard Ada (since new
7342 numeric base types cannot be created in standard
7343 Ada), but the output is easily
7344 readable to any Ada programmer, and is useful to
7345 determine the characteristics of target dependent
7346 types in package Standard.
7349 @cindex @option{-gnatx} (@command{gcc})
7350 Normally the compiler generates full cross-referencing information in
7351 the @file{ALI} file. This information is used by a number of tools,
7352 including @code{gnatfind} and @code{gnatxref}. The @option{-gnatx} switch
7353 suppresses this information. This saves some space and may slightly
7354 speed up compilation, but means that these tools cannot be used.
7357 @node Exception Handling Control
7358 @subsection Exception Handling Control
7361 GNAT uses two methods for handling exceptions at run-time. The
7362 @code{setjmp/longjmp} method saves the context when entering
7363 a frame with an exception handler. Then when an exception is
7364 raised, the context can be restored immediately, without the
7365 need for tracing stack frames. This method provides very fast
7366 exception propagation, but introduces significant overhead for
7367 the use of exception handlers, even if no exception is raised.
7369 The other approach is called ``zero cost'' exception handling.
7370 With this method, the compiler builds static tables to describe
7371 the exception ranges. No dynamic code is required when entering
7372 a frame containing an exception handler. When an exception is
7373 raised, the tables are used to control a back trace of the
7374 subprogram invocation stack to locate the required exception
7375 handler. This method has considerably poorer performance for
7376 the propagation of exceptions, but there is no overhead for
7377 exception handlers if no exception is raised. Note that in this
7378 mode and in the context of mixed Ada and C/C++ programming,
7379 to propagate an exception through a C/C++ code, the C/C++ code
7380 must be compiled with the @option{-funwind-tables} GCC's
7383 The following switches may be used to control which of the
7384 two exception handling methods is used.
7390 @cindex @option{--RTS=sjlj} (@command{gnatmake})
7391 This switch causes the setjmp/longjmp run-time (when available) to be used
7392 for exception handling. If the default
7393 mechanism for the target is zero cost exceptions, then
7394 this switch can be used to modify this default, and must be
7395 used for all units in the partition.
7396 This option is rarely used. One case in which it may be
7397 advantageous is if you have an application where exception
7398 raising is common and the overall performance of the
7399 application is improved by favoring exception propagation.
7402 @cindex @option{--RTS=zcx} (@command{gnatmake})
7403 @cindex Zero Cost Exceptions
7404 This switch causes the zero cost approach to be used
7405 for exception handling. If this is the default mechanism for the
7406 target (see below), then this switch is unneeded. If the default
7407 mechanism for the target is setjmp/longjmp exceptions, then
7408 this switch can be used to modify this default, and must be
7409 used for all units in the partition.
7410 This option can only be used if the zero cost approach
7411 is available for the target in use, otherwise it will generate an error.
7415 The same option @option{--RTS} must be used both for @command{gcc}
7416 and @command{gnatbind}. Passing this option to @command{gnatmake}
7417 (@pxref{Switches for gnatmake}) will ensure the required consistency
7418 through the compilation and binding steps.
7420 @node Units to Sources Mapping Files
7421 @subsection Units to Sources Mapping Files
7425 @item -gnatem=@var{path}
7426 @cindex @option{-gnatem} (@command{gcc})
7427 A mapping file is a way to communicate to the compiler two mappings:
7428 from unit names to file names (without any directory information) and from
7429 file names to path names (with full directory information). These mappings
7430 are used by the compiler to short-circuit the path search.
7432 The use of mapping files is not required for correct operation of the
7433 compiler, but mapping files can improve efficiency, particularly when
7434 sources are read over a slow network connection. In normal operation,
7435 you need not be concerned with the format or use of mapping files,
7436 and the @option{-gnatem} switch is not a switch that you would use
7437 explicitly. It is intended primarily for use by automatic tools such as
7438 @command{gnatmake} running under the project file facility. The
7439 description here of the format of mapping files is provided
7440 for completeness and for possible use by other tools.
7442 A mapping file is a sequence of sets of three lines. In each set, the
7443 first line is the unit name, in lower case, with @code{%s} appended
7444 for specs and @code{%b} appended for bodies; the second line is the
7445 file name; and the third line is the path name.
7451 /gnat/project1/sources/main.2.ada
7454 When the switch @option{-gnatem} is specified, the compiler will
7455 create in memory the two mappings from the specified file. If there is
7456 any problem (nonexistent file, truncated file or duplicate entries),
7457 no mapping will be created.
7459 Several @option{-gnatem} switches may be specified; however, only the
7460 last one on the command line will be taken into account.
7462 When using a project file, @command{gnatmake} creates a temporary
7463 mapping file and communicates it to the compiler using this switch.
7467 @node Integrated Preprocessing
7468 @subsection Integrated Preprocessing
7471 GNAT sources may be preprocessed immediately before compilation.
7472 In this case, the actual
7473 text of the source is not the text of the source file, but is derived from it
7474 through a process called preprocessing. Integrated preprocessing is specified
7475 through switches @option{-gnatep} and/or @option{-gnateD}. @option{-gnatep}
7476 indicates, through a text file, the preprocessing data to be used.
7477 @option{-gnateD} specifies or modifies the values of preprocessing symbol.
7480 Note that when integrated preprocessing is used, the output from the
7481 preprocessor is not written to any external file. Instead it is passed
7482 internally to the compiler. If you need to preserve the result of
7483 preprocessing in a file, then you should use @command{gnatprep}
7484 to perform the desired preprocessing in stand-alone mode.
7487 It is recommended that @command{gnatmake} switch ^-s^/SWITCH_CHECK^ should be
7488 used when Integrated Preprocessing is used. The reason is that preprocessing
7489 with another Preprocessing Data file without changing the sources will
7490 not trigger recompilation without this switch.
7493 Note that @command{gnatmake} switch ^-m^/MINIMAL_RECOMPILATION^ will almost
7494 always trigger recompilation for sources that are preprocessed,
7495 because @command{gnatmake} cannot compute the checksum of the source after
7499 The actual preprocessing function is described in details in section
7500 @ref{Preprocessing with gnatprep}. This section only describes how integrated
7501 preprocessing is triggered and parameterized.
7505 @item -gnatep=@var{file}
7506 @cindex @option{-gnatep} (@command{gcc})
7507 This switch indicates to the compiler the file name (without directory
7508 information) of the preprocessor data file to use. The preprocessor data file
7509 should be found in the source directories. Note that when the compiler is
7510 called by a builder such as (@command{gnatmake} with a project
7511 file, if the object directory is not also a source directory, the builder needs
7512 to be called with @option{-x}.
7515 A preprocessing data file is a text file with significant lines indicating
7516 how should be preprocessed either a specific source or all sources not
7517 mentioned in other lines. A significant line is a nonempty, non-comment line.
7518 Comments are similar to Ada comments.
7521 Each significant line starts with either a literal string or the character '*'.
7522 A literal string is the file name (without directory information) of the source
7523 to preprocess. A character '*' indicates the preprocessing for all the sources
7524 that are not specified explicitly on other lines (order of the lines is not
7525 significant). It is an error to have two lines with the same file name or two
7526 lines starting with the character '*'.
7529 After the file name or the character '*', another optional literal string
7530 indicating the file name of the definition file to be used for preprocessing
7531 (@pxref{Form of Definitions File}). The definition files are found by the
7532 compiler in one of the source directories. In some cases, when compiling
7533 a source in a directory other than the current directory, if the definition
7534 file is in the current directory, it may be necessary to add the current
7535 directory as a source directory through switch ^-I.^/SEARCH=[]^, otherwise
7536 the compiler would not find the definition file.
7539 Then, optionally, ^switches^switches^ similar to those of @code{gnatprep} may
7540 be found. Those ^switches^switches^ are:
7545 Causes both preprocessor lines and the lines deleted by
7546 preprocessing to be replaced by blank lines, preserving the line number.
7547 This ^switch^switch^ is always implied; however, if specified after @option{-c}
7548 it cancels the effect of @option{-c}.
7551 Causes both preprocessor lines and the lines deleted
7552 by preprocessing to be retained as comments marked
7553 with the special string ``@code{--! }''.
7555 @item -Dsymbol=value
7556 Define or redefine a symbol, associated with value. A symbol is an Ada
7557 identifier, or an Ada reserved word, with the exception of @code{if},
7558 @code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}.
7559 @code{value} is either a literal string, an Ada identifier or any Ada reserved
7560 word. A symbol declared with this ^switch^switch^ replaces a symbol with the
7561 same name defined in a definition file.
7564 Causes a sorted list of symbol names and values to be
7565 listed on the standard output file.
7568 Causes undefined symbols to be treated as having the value @code{FALSE}
7570 of a preprocessor test. In the absence of this option, an undefined symbol in
7571 a @code{#if} or @code{#elsif} test will be treated as an error.
7576 Examples of valid lines in a preprocessor data file:
7579 "toto.adb" "prep.def" -u
7580 -- preprocess "toto.adb", using definition file "prep.def",
7581 -- undefined symbol are False.
7584 -- preprocess all other sources without a definition file;
7585 -- suppressed lined are commented; symbol VERSION has the value V101.
7587 "titi.adb" "prep2.def" -s
7588 -- preprocess "titi.adb", using definition file "prep2.def";
7589 -- list all symbols with their values.
7592 @item ^-gnateD^/DATA_PREPROCESSING=^symbol@r{[}=value@r{]}
7593 @cindex @option{-gnateD} (@command{gcc})
7594 Define or redefine a preprocessing symbol, associated with value. If no value
7595 is given on the command line, then the value of the symbol is @code{True}.
7596 A symbol is an identifier, following normal Ada (case-insensitive)
7597 rules for its syntax, and value is any sequence (including an empty sequence)
7598 of characters from the set (letters, digits, period, underline).
7599 Ada reserved words may be used as symbols, with the exceptions of @code{if},
7600 @code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}.
7603 A symbol declared with this ^switch^switch^ on the command line replaces a
7604 symbol with the same name either in a definition file or specified with a
7605 ^switch^switch^ -D in the preprocessor data file.
7608 This switch is similar to switch @option{^-D^/ASSOCIATE^} of @code{gnatprep}.
7611 When integrated preprocessing is performed and the preprocessor modifies
7612 the source text, write the result of this preprocessing into a file
7613 <source>^.prep^_prep^.
7617 @node Code Generation Control
7618 @subsection Code Generation Control
7622 The GCC technology provides a wide range of target dependent
7623 @option{-m} switches for controlling
7624 details of code generation with respect to different versions of
7625 architectures. This includes variations in instruction sets (e.g.@:
7626 different members of the power pc family), and different requirements
7627 for optimal arrangement of instructions (e.g.@: different members of
7628 the x86 family). The list of available @option{-m} switches may be
7629 found in the GCC documentation.
7631 Use of these @option{-m} switches may in some cases result in improved
7634 The @value{EDITION} technology is tested and qualified without any
7635 @option{-m} switches,
7636 so generally the most reliable approach is to avoid the use of these
7637 switches. However, we generally expect most of these switches to work
7638 successfully with @value{EDITION}, and many customers have reported successful
7639 use of these options.
7641 Our general advice is to avoid the use of @option{-m} switches unless
7642 special needs lead to requirements in this area. In particular,
7643 there is no point in using @option{-m} switches to improve performance
7644 unless you actually see a performance improvement.
7648 @subsection Return Codes
7649 @cindex Return Codes
7650 @cindex @option{/RETURN_CODES=VMS}
7653 On VMS, GNAT compiled programs return POSIX-style codes by default,
7654 e.g.@: @option{/RETURN_CODES=POSIX}.
7656 To enable VMS style return codes, use GNAT BIND and LINK with the option
7657 @option{/RETURN_CODES=VMS}. For example:
7660 GNAT BIND MYMAIN.ALI /RETURN_CODES=VMS
7661 GNAT LINK MYMAIN.ALI /RETURN_CODES=VMS
7665 Programs built with /RETURN_CODES=VMS are suitable to be called in
7666 VMS DCL scripts. Programs compiled with the default /RETURN_CODES=POSIX
7667 are suitable for spawning with appropriate GNAT RTL routines.
7671 @node Search Paths and the Run-Time Library (RTL)
7672 @section Search Paths and the Run-Time Library (RTL)
7675 With the GNAT source-based library system, the compiler must be able to
7676 find source files for units that are needed by the unit being compiled.
7677 Search paths are used to guide this process.
7679 The compiler compiles one source file whose name must be given
7680 explicitly on the command line. In other words, no searching is done
7681 for this file. To find all other source files that are needed (the most
7682 common being the specs of units), the compiler examines the following
7683 directories, in the following order:
7687 The directory containing the source file of the main unit being compiled
7688 (the file name on the command line).
7691 Each directory named by an @option{^-I^/SOURCE_SEARCH^} switch given on the
7692 @command{gcc} command line, in the order given.
7695 @findex ADA_PRJ_INCLUDE_FILE
7696 Each of the directories listed in the text file whose name is given
7697 by the @env{ADA_PRJ_INCLUDE_FILE} ^environment variable^logical name^.
7700 @env{ADA_PRJ_INCLUDE_FILE} is normally set by gnatmake or by the ^gnat^GNAT^
7701 driver when project files are used. It should not normally be set
7705 @findex ADA_INCLUDE_PATH
7706 Each of the directories listed in the value of the
7707 @env{ADA_INCLUDE_PATH} ^environment variable^logical name^.
7709 Construct this value
7710 exactly as the @env{PATH} environment variable: a list of directory
7711 names separated by colons (semicolons when working with the NT version).
7714 Normally, define this value as a logical name containing a comma separated
7715 list of directory names.
7717 This variable can also be defined by means of an environment string
7718 (an argument to the HP C exec* set of functions).
7722 DEFINE ANOTHER_PATH FOO:[BAG]
7723 DEFINE ADA_INCLUDE_PATH ANOTHER_PATH,FOO:[BAM],FOO:[BAR]
7726 By default, the path includes GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB]
7727 first, followed by the standard Ada
7728 libraries in GNU:[LIB.OPENVMS7_x.2_8_x.ADAINCLUDE].
7729 If this is not redefined, the user will obtain the HP Ada 83 IO packages
7730 (Text_IO, Sequential_IO, etc)
7731 instead of the standard Ada packages. Thus, in order to get the standard Ada
7732 packages by default, ADA_INCLUDE_PATH must be redefined.
7736 The content of the @file{ada_source_path} file which is part of the GNAT
7737 installation tree and is used to store standard libraries such as the
7738 GNAT Run Time Library (RTL) source files.
7740 @ref{Installing a library}
7745 Specifying the switch @option{^-I-^/NOCURRENT_DIRECTORY^}
7746 inhibits the use of the directory
7747 containing the source file named in the command line. You can still
7748 have this directory on your search path, but in this case it must be
7749 explicitly requested with a @option{^-I^/SOURCE_SEARCH^} switch.
7751 Specifying the switch @option{-nostdinc}
7752 inhibits the search of the default location for the GNAT Run Time
7753 Library (RTL) source files.
7755 The compiler outputs its object files and ALI files in the current
7758 Caution: The object file can be redirected with the @option{-o} switch;
7759 however, @command{gcc} and @code{gnat1} have not been coordinated on this
7760 so the @file{ALI} file will not go to the right place. Therefore, you should
7761 avoid using the @option{-o} switch.
7765 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
7766 children make up the GNAT RTL, together with the simple @code{System.IO}
7767 package used in the @code{"Hello World"} example. The sources for these units
7768 are needed by the compiler and are kept together in one directory. Not
7769 all of the bodies are needed, but all of the sources are kept together
7770 anyway. In a normal installation, you need not specify these directory
7771 names when compiling or binding. Either the environment variables or
7772 the built-in defaults cause these files to be found.
7774 In addition to the language-defined hierarchies (@code{System}, @code{Ada} and
7775 @code{Interfaces}), the GNAT distribution provides a fourth hierarchy,
7776 consisting of child units of @code{GNAT}. This is a collection of generally
7777 useful types, subprograms, etc. @xref{Top, GNAT Reference Manual, About
7778 This Guid, gnat_rm, GNAT Reference Manual}, for further details.
7780 Besides simplifying access to the RTL, a major use of search paths is
7781 in compiling sources from multiple directories. This can make
7782 development environments much more flexible.
7784 @node Order of Compilation Issues
7785 @section Order of Compilation Issues
7788 If, in our earlier example, there was a spec for the @code{hello}
7789 procedure, it would be contained in the file @file{hello.ads}; yet this
7790 file would not have to be explicitly compiled. This is the result of the
7791 model we chose to implement library management. Some of the consequences
7792 of this model are as follows:
7796 There is no point in compiling specs (except for package
7797 specs with no bodies) because these are compiled as needed by clients. If
7798 you attempt a useless compilation, you will receive an error message.
7799 It is also useless to compile subunits because they are compiled as needed
7803 There are no order of compilation requirements: performing a
7804 compilation never obsoletes anything. The only way you can obsolete
7805 something and require recompilations is to modify one of the
7806 source files on which it depends.
7809 There is no library as such, apart from the ALI files
7810 (@pxref{The Ada Library Information Files}, for information on the format
7811 of these files). For now we find it convenient to create separate ALI files,
7812 but eventually the information therein may be incorporated into the object
7816 When you compile a unit, the source files for the specs of all units
7817 that it @code{with}'s, all its subunits, and the bodies of any generics it
7818 instantiates must be available (reachable by the search-paths mechanism
7819 described above), or you will receive a fatal error message.
7826 The following are some typical Ada compilation command line examples:
7829 @item $ gcc -c xyz.adb
7830 Compile body in file @file{xyz.adb} with all default options.
7833 @item $ gcc -c -O2 -gnata xyz-def.adb
7836 @item $ GNAT COMPILE /OPTIMIZE=ALL -gnata xyz-def.adb
7839 Compile the child unit package in file @file{xyz-def.adb} with extensive
7840 optimizations, and pragma @code{Assert}/@code{Debug} statements
7843 @item $ gcc -c -gnatc abc-def.adb
7844 Compile the subunit in file @file{abc-def.adb} in semantic-checking-only
7848 @node Binding with gnatbind
7849 @chapter Binding with @code{gnatbind}
7853 * Running gnatbind::
7854 * Switches for gnatbind::
7855 * Command-Line Access::
7856 * Search Paths for gnatbind::
7857 * Examples of gnatbind Usage::
7861 This chapter describes the GNAT binder, @code{gnatbind}, which is used
7862 to bind compiled GNAT objects.
7864 Note: to invoke @code{gnatbind} with a project file, use the @code{gnat}
7865 driver (see @ref{The GNAT Driver and Project Files}).
7867 The @code{gnatbind} program performs four separate functions:
7871 Checks that a program is consistent, in accordance with the rules in
7872 Chapter 10 of the Ada Reference Manual. In particular, error
7873 messages are generated if a program uses inconsistent versions of a
7877 Checks that an acceptable order of elaboration exists for the program
7878 and issues an error message if it cannot find an order of elaboration
7879 that satisfies the rules in Chapter 10 of the Ada Language Manual.
7882 Generates a main program incorporating the given elaboration order.
7883 This program is a small Ada package (body and spec) that
7884 must be subsequently compiled
7885 using the GNAT compiler. The necessary compilation step is usually
7886 performed automatically by @command{gnatlink}. The two most important
7887 functions of this program
7888 are to call the elaboration routines of units in an appropriate order
7889 and to call the main program.
7892 Determines the set of object files required by the given main program.
7893 This information is output in the forms of comments in the generated program,
7894 to be read by the @command{gnatlink} utility used to link the Ada application.
7897 @node Running gnatbind
7898 @section Running @code{gnatbind}
7901 The form of the @code{gnatbind} command is
7904 @c $ gnatbind @ovar{switches} @var{mainprog}@r{[}.ali@r{]} @ovar{switches}
7905 @c Expanding @ovar macro inline (explanation in macro def comments)
7906 $ gnatbind @r{[}@var{switches}@r{]} @var{mainprog}@r{[}.ali@r{]} @r{[}@var{switches}@r{]}
7910 where @file{@var{mainprog}.adb} is the Ada file containing the main program
7911 unit body. @code{gnatbind} constructs an Ada
7912 package in two files whose names are
7913 @file{b~@var{mainprog}.ads}, and @file{b~@var{mainprog}.adb}.
7914 For example, if given the
7915 parameter @file{hello.ali}, for a main program contained in file
7916 @file{hello.adb}, the binder output files would be @file{b~hello.ads}
7917 and @file{b~hello.adb}.
7919 When doing consistency checking, the binder takes into consideration
7920 any source files it can locate. For example, if the binder determines
7921 that the given main program requires the package @code{Pack}, whose
7923 file is @file{pack.ali} and whose corresponding source spec file is
7924 @file{pack.ads}, it attempts to locate the source file @file{pack.ads}
7925 (using the same search path conventions as previously described for the
7926 @command{gcc} command). If it can locate this source file, it checks that
7928 or source checksums of the source and its references to in @file{ALI} files
7929 match. In other words, any @file{ALI} files that mentions this spec must have
7930 resulted from compiling this version of the source file (or in the case
7931 where the source checksums match, a version close enough that the
7932 difference does not matter).
7934 @cindex Source files, use by binder
7935 The effect of this consistency checking, which includes source files, is
7936 that the binder ensures that the program is consistent with the latest
7937 version of the source files that can be located at bind time. Editing a
7938 source file without compiling files that depend on the source file cause
7939 error messages to be generated by the binder.
7941 For example, suppose you have a main program @file{hello.adb} and a
7942 package @code{P}, from file @file{p.ads} and you perform the following
7947 Enter @code{gcc -c hello.adb} to compile the main program.
7950 Enter @code{gcc -c p.ads} to compile package @code{P}.
7953 Edit file @file{p.ads}.
7956 Enter @code{gnatbind hello}.
7960 At this point, the file @file{p.ali} contains an out-of-date time stamp
7961 because the file @file{p.ads} has been edited. The attempt at binding
7962 fails, and the binder generates the following error messages:
7965 error: "hello.adb" must be recompiled ("p.ads" has been modified)
7966 error: "p.ads" has been modified and must be recompiled
7970 Now both files must be recompiled as indicated, and then the bind can
7971 succeed, generating a main program. You need not normally be concerned
7972 with the contents of this file, but for reference purposes a sample
7973 binder output file is given in @ref{Example of Binder Output File}.
7975 In most normal usage, the default mode of @command{gnatbind} which is to
7976 generate the main package in Ada, as described in the previous section.
7977 In particular, this means that any Ada programmer can read and understand
7978 the generated main program. It can also be debugged just like any other
7979 Ada code provided the @option{^-g^/DEBUG^} switch is used for
7980 @command{gnatbind} and @command{gnatlink}.
7982 @node Switches for gnatbind
7983 @section Switches for @command{gnatbind}
7986 The following switches are available with @code{gnatbind}; details will
7987 be presented in subsequent sections.
7990 * Consistency-Checking Modes::
7991 * Binder Error Message Control::
7992 * Elaboration Control::
7994 * Dynamic Allocation Control::
7995 * Binding with Non-Ada Main Programs::
7996 * Binding Programs with No Main Subprogram::
8003 @cindex @option{--version} @command{gnatbind}
8004 Display Copyright and version, then exit disregarding all other options.
8007 @cindex @option{--help} @command{gnatbind}
8008 If @option{--version} was not used, display usage, then exit disregarding
8012 @cindex @option{-a} @command{gnatbind}
8013 Indicates that, if supported by the platform, the adainit procedure should
8014 be treated as an initialisation routine by the linker (a constructor). This
8015 is intended to be used by the Project Manager to automatically initialize
8016 shared Stand-Alone Libraries.
8018 @item ^-aO^/OBJECT_SEARCH^
8019 @cindex @option{^-aO^/OBJECT_SEARCH^} (@command{gnatbind})
8020 Specify directory to be searched for ALI files.
8022 @item ^-aI^/SOURCE_SEARCH^
8023 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatbind})
8024 Specify directory to be searched for source file.
8026 @item ^-A^/ALI_LIST^@r{[=}@var{filename}@r{]}
8027 @cindex @option{^-A^/ALI_LIST^} (@command{gnatbind})
8028 Output ALI list (to standard output or to the named file).
8030 @item ^-b^/REPORT_ERRORS=BRIEF^
8031 @cindex @option{^-b^/REPORT_ERRORS=BRIEF^} (@command{gnatbind})
8032 Generate brief messages to @file{stderr} even if verbose mode set.
8034 @item ^-c^/NOOUTPUT^
8035 @cindex @option{^-c^/NOOUTPUT^} (@command{gnatbind})
8036 Check only, no generation of binder output file.
8038 @item ^-d^/DEFAULT_STACK_SIZE=^@var{nn}@r{[}k@r{|}m@r{]}
8039 @cindex @option{^-d^/DEFAULT_STACK_SIZE=^@var{nn}@r{[}k@r{|}m@r{]}} (@command{gnatbind})
8040 This switch can be used to change the default task stack size value
8041 to a specified size @var{nn}, which is expressed in bytes by default, or
8042 in kilobytes when suffixed with @var{k} or in megabytes when suffixed
8044 In the absence of a @samp{@r{[}k@r{|}m@r{]}} suffix, this switch is equivalent,
8045 in effect, to completing all task specs with
8046 @smallexample @c ada
8047 pragma Storage_Size (nn);
8049 When they do not already have such a pragma.
8051 @item ^-D^/DEFAULT_SECONDARY_STACK_SIZE=^@var{nn}@r{[}k@r{|}m@r{]}
8052 @cindex @option{^-D^/DEFAULT_SECONDARY_STACK_SIZE=nnnnn^} (@command{gnatbind})
8053 This switch can be used to change the default secondary stack size value
8054 to a specified size @var{nn}, which is expressed in bytes by default, or
8055 in kilobytes when suffixed with @var{k} or in megabytes when suffixed
8058 The secondary stack is used to deal with functions that return a variable
8059 sized result, for example a function returning an unconstrained
8060 String. There are two ways in which this secondary stack is allocated.
8062 For most targets, the secondary stack is growing on demand and is allocated
8063 as a chain of blocks in the heap. The -D option is not very
8064 relevant. It only give some control over the size of the allocated
8065 blocks (whose size is the minimum of the default secondary stack size value,
8066 and the actual size needed for the current allocation request).
8068 For certain targets, notably VxWorks 653,
8069 the secondary stack is allocated by carving off a fixed ratio chunk of the
8070 primary task stack. The -D option is used to define the
8071 size of the environment task's secondary stack.
8073 @item ^-e^/ELABORATION_DEPENDENCIES^
8074 @cindex @option{^-e^/ELABORATION_DEPENDENCIES^} (@command{gnatbind})
8075 Output complete list of elaboration-order dependencies.
8077 @item ^-E^/STORE_TRACEBACKS^
8078 @cindex @option{^-E^/STORE_TRACEBACKS^} (@command{gnatbind})
8079 Store tracebacks in exception occurrences when the target supports it.
8081 @c The following may get moved to an appendix
8082 This option is currently supported on the following targets:
8083 all x86 ports, Solaris, Windows, HP-UX, AIX, PowerPC VxWorks and Alpha VxWorks.
8085 See also the packages @code{GNAT.Traceback} and
8086 @code{GNAT.Traceback.Symbolic} for more information.
8088 Note that on x86 ports, you must not use @option{-fomit-frame-pointer}
8089 @command{gcc} option.
8092 @item ^-F^/FORCE_ELABS_FLAGS^
8093 @cindex @option{^-F^/FORCE_ELABS_FLAGS^} (@command{gnatbind})
8094 Force the checks of elaboration flags. @command{gnatbind} does not normally
8095 generate checks of elaboration flags for the main executable, except when
8096 a Stand-Alone Library is used. However, there are cases when this cannot be
8097 detected by gnatbind. An example is importing an interface of a Stand-Alone
8098 Library through a pragma Import and only specifying through a linker switch
8099 this Stand-Alone Library. This switch is used to guarantee that elaboration
8100 flag checks are generated.
8103 @cindex @option{^-h^/HELP^} (@command{gnatbind})
8104 Output usage (help) information
8106 @item ^-H32^/32_MALLOC^
8107 @cindex @option{^-H32^/32_MALLOC^} (@command{gnatbind})
8108 Use 32-bit allocations for @code{__gnat_malloc} (and thus for access types).
8109 For further details see @ref{Dynamic Allocation Control}.
8111 @item ^-H64^/64_MALLOC^
8112 @cindex @option{^-H64^/64_MALLOC^} (@command{gnatbind})
8113 Use 64-bit allocations for @code{__gnat_malloc} (and thus for access types).
8114 @cindex @code{__gnat_malloc}
8115 For further details see @ref{Dynamic Allocation Control}.
8118 @cindex @option{^-I^/SEARCH^} (@command{gnatbind})
8119 Specify directory to be searched for source and ALI files.
8121 @item ^-I-^/NOCURRENT_DIRECTORY^
8122 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gnatbind})
8123 Do not look for sources in the current directory where @code{gnatbind} was
8124 invoked, and do not look for ALI files in the directory containing the
8125 ALI file named in the @code{gnatbind} command line.
8127 @item ^-l^/ORDER_OF_ELABORATION^
8128 @cindex @option{^-l^/ORDER_OF_ELABORATION^} (@command{gnatbind})
8129 Output chosen elaboration order.
8131 @item ^-L@var{xxx}^/BUILD_LIBRARY=@var{xxx}^
8132 @cindex @option{^-L^/BUILD_LIBRARY^} (@command{gnatbind})
8133 Bind the units for library building. In this case the adainit and
8134 adafinal procedures (@pxref{Binding with Non-Ada Main Programs})
8135 are renamed to ^@var{xxx}init^@var{XXX}INIT^ and
8136 ^@var{xxx}final^@var{XXX}FINAL^.
8137 Implies ^-n^/NOCOMPILE^.
8139 (@xref{GNAT and Libraries}, for more details.)
8142 On OpenVMS, these init and final procedures are exported in uppercase
8143 letters. For example if /BUILD_LIBRARY=toto is used, the exported name of
8144 the init procedure will be "TOTOINIT" and the exported name of the final
8145 procedure will be "TOTOFINAL".
8148 @item ^-Mxyz^/RENAME_MAIN=xyz^
8149 @cindex @option{^-M^/RENAME_MAIN^} (@command{gnatbind})
8150 Rename generated main program from main to xyz. This option is
8151 supported on cross environments only.
8153 @item ^-m^/ERROR_LIMIT=^@var{n}
8154 @cindex @option{^-m^/ERROR_LIMIT^} (@command{gnatbind})
8155 Limit number of detected errors or warnings to @var{n}, where @var{n} is
8156 in the range 1..999999. The default value if no switch is
8157 given is 9999. If the number of warnings reaches this limit, then a
8158 message is output and further warnings are suppressed, the bind
8159 continues in this case. If the number of errors reaches this
8160 limit, then a message is output and the bind is abandoned.
8161 A value of zero means that no limit is enforced. The equal
8165 Furthermore, under Windows, the sources pointed to by the libraries path
8166 set in the registry are not searched for.
8170 @cindex @option{^-n^/NOMAIN^} (@command{gnatbind})
8174 @cindex @option{-nostdinc} (@command{gnatbind})
8175 Do not look for sources in the system default directory.
8178 @cindex @option{-nostdlib} (@command{gnatbind})
8179 Do not look for library files in the system default directory.
8181 @item --RTS=@var{rts-path}
8182 @cindex @option{--RTS} (@code{gnatbind})
8183 Specifies the default location of the runtime library. Same meaning as the
8184 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
8186 @item ^-o ^/OUTPUT=^@var{file}
8187 @cindex @option{^-o ^/OUTPUT^} (@command{gnatbind})
8188 Name the output file @var{file} (default is @file{b~@var{xxx}.adb}).
8189 Note that if this option is used, then linking must be done manually,
8190 gnatlink cannot be used.
8192 @item ^-O^/OBJECT_LIST^@r{[=}@var{filename}@r{]}
8193 @cindex @option{^-O^/OBJECT_LIST^} (@command{gnatbind})
8194 Output object list (to standard output or to the named file).
8196 @item ^-p^/PESSIMISTIC_ELABORATION^
8197 @cindex @option{^-p^/PESSIMISTIC_ELABORATION^} (@command{gnatbind})
8198 Pessimistic (worst-case) elaboration order
8201 @cindex @option{^-P^/CODEPEER^} (@command{gnatbind})
8202 Generate binder file suitable for CodePeer.
8205 @cindex @option{^-R^-R^} (@command{gnatbind})
8206 Output closure source list.
8208 @item ^-s^/READ_SOURCES=ALL^
8209 @cindex @option{^-s^/READ_SOURCES=ALL^} (@command{gnatbind})
8210 Require all source files to be present.
8212 @item ^-S@var{xxx}^/INITIALIZE_SCALARS=@var{xxx}^
8213 @cindex @option{^-S^/INITIALIZE_SCALARS^} (@command{gnatbind})
8214 Specifies the value to be used when detecting uninitialized scalar
8215 objects with pragma Initialize_Scalars.
8216 The @var{xxx} ^string specified with the switch^option^ may be either
8218 @item ``@option{^in^INVALID^}'' requesting an invalid value where possible
8219 @item ``@option{^lo^LOW^}'' for the lowest possible value
8220 @item ``@option{^hi^HIGH^}'' for the highest possible value
8221 @item ``@option{@var{xx}}'' for a value consisting of repeated bytes with the
8222 value @code{16#@var{xx}#} (i.e., @var{xx} is a string of two hexadecimal digits).
8225 In addition, you can specify @option{-Sev} to indicate that the value is
8226 to be set at run time. In this case, the program will look for an environment
8227 @cindex GNAT_INIT_SCALARS
8228 variable of the form @env{GNAT_INIT_SCALARS=@var{xx}}, where @var{xx} is one
8229 of @option{in/lo/hi/@var{xx}} with the same meanings as above.
8230 If no environment variable is found, or if it does not have a valid value,
8231 then the default is @option{in} (invalid values).
8235 @cindex @option{-static} (@code{gnatbind})
8236 Link against a static GNAT run time.
8239 @cindex @option{-shared} (@code{gnatbind})
8240 Link against a shared GNAT run time when available.
8243 @item ^-t^/NOTIME_STAMP_CHECK^
8244 @cindex @option{^-t^/NOTIME_STAMP_CHECK^} (@code{gnatbind})
8245 Tolerate time stamp and other consistency errors
8247 @item ^-T@var{n}^/TIME_SLICE=@var{n}^
8248 @cindex @option{^-T^/TIME_SLICE^} (@code{gnatbind})
8249 Set the time slice value to @var{n} milliseconds. If the system supports
8250 the specification of a specific time slice value, then the indicated value
8251 is used. If the system does not support specific time slice values, but
8252 does support some general notion of round-robin scheduling, then any
8253 nonzero value will activate round-robin scheduling.
8255 A value of zero is treated specially. It turns off time
8256 slicing, and in addition, indicates to the tasking run time that the
8257 semantics should match as closely as possible the Annex D
8258 requirements of the Ada RM, and in particular sets the default
8259 scheduling policy to @code{FIFO_Within_Priorities}.
8261 @item ^-u@var{n}^/DYNAMIC_STACK_USAGE=@var{n}^
8262 @cindex @option{^-u^/DYNAMIC_STACK_USAGE^} (@code{gnatbind})
8263 Enable dynamic stack usage, with @var{n} results stored and displayed
8264 at program termination. A result is generated when a task
8265 terminates. Results that can't be stored are displayed on the fly, at
8266 task termination. This option is currently not supported on Itanium
8267 platforms. (See @ref{Dynamic Stack Usage Analysis} for details.)
8269 @item ^-v^/REPORT_ERRORS=VERBOSE^
8270 @cindex @option{^-v^/REPORT_ERRORS=VERBOSE^} (@code{gnatbind})
8271 Verbose mode. Write error messages, header, summary output to
8276 @cindex @option{-w} (@code{gnatbind})
8277 Warning mode (@var{x}=s/e for suppress/treat as error)
8281 @item /WARNINGS=NORMAL
8282 @cindex @option{/WARNINGS} (@code{gnatbind})
8283 Normal warnings mode. Warnings are issued but ignored
8285 @item /WARNINGS=SUPPRESS
8286 @cindex @option{/WARNINGS} (@code{gnatbind})
8287 All warning messages are suppressed
8289 @item /WARNINGS=ERROR
8290 @cindex @option{/WARNINGS} (@code{gnatbind})
8291 Warning messages are treated as fatal errors
8294 @item ^-Wx^/WIDE_CHARACTER_ENCODING=^@var{e}
8295 @cindex @option{^-Wx^/WIDE_CHARACTER_ENCODING^} (@code{gnatbind})
8296 Override default wide character encoding for standard Text_IO files.
8298 @item ^-x^/READ_SOURCES=NONE^
8299 @cindex @option{^-x^/READ_SOURCES^} (@code{gnatbind})
8300 Exclude source files (check object consistency only).
8303 @item /READ_SOURCES=AVAILABLE
8304 @cindex @option{/READ_SOURCES} (@code{gnatbind})
8305 Default mode, in which sources are checked for consistency only if
8309 @item ^-y^/ENABLE_LEAP_SECONDS^
8310 @cindex @option{^-y^/ENABLE_LEAP_SECONDS^} (@code{gnatbind})
8311 Enable leap seconds support in @code{Ada.Calendar} and its children.
8313 @item ^-z^/ZERO_MAIN^
8314 @cindex @option{^-z^/ZERO_MAIN^} (@code{gnatbind})
8320 You may obtain this listing of switches by running @code{gnatbind} with
8324 @node Consistency-Checking Modes
8325 @subsection Consistency-Checking Modes
8328 As described earlier, by default @code{gnatbind} checks
8329 that object files are consistent with one another and are consistent
8330 with any source files it can locate. The following switches control binder
8335 @item ^-s^/READ_SOURCES=ALL^
8336 @cindex @option{^-s^/READ_SOURCES=ALL^} (@code{gnatbind})
8337 Require source files to be present. In this mode, the binder must be
8338 able to locate all source files that are referenced, in order to check
8339 their consistency. In normal mode, if a source file cannot be located it
8340 is simply ignored. If you specify this switch, a missing source
8343 @item ^-Wx^/WIDE_CHARACTER_ENCODING=^@var{e}
8344 @cindex @option{^-Wx^/WIDE_CHARACTER_ENCODING^} (@code{gnatbind})
8345 Override default wide character encoding for standard Text_IO files.
8346 Normally the default wide character encoding method used for standard
8347 [Wide_[Wide_]]Text_IO files is taken from the encoding specified for
8348 the main source input (see description of switch
8349 @option{^-gnatWx^/WIDE_CHARACTER_ENCODING^} for the compiler). The
8350 use of this switch for the binder (which has the same set of
8351 possible arguments) overrides this default as specified.
8353 @item ^-x^/READ_SOURCES=NONE^
8354 @cindex @option{^-x^/READ_SOURCES=NONE^} (@code{gnatbind})
8355 Exclude source files. In this mode, the binder only checks that ALI
8356 files are consistent with one another. Source files are not accessed.
8357 The binder runs faster in this mode, and there is still a guarantee that
8358 the resulting program is self-consistent.
8359 If a source file has been edited since it was last compiled, and you
8360 specify this switch, the binder will not detect that the object
8361 file is out of date with respect to the source file. Note that this is the
8362 mode that is automatically used by @command{gnatmake} because in this
8363 case the checking against sources has already been performed by
8364 @command{gnatmake} in the course of compilation (i.e.@: before binding).
8367 @item /READ_SOURCES=AVAILABLE
8368 @cindex @code{/READ_SOURCES=AVAILABLE} (@code{gnatbind})
8369 This is the default mode in which source files are checked if they are
8370 available, and ignored if they are not available.
8374 @node Binder Error Message Control
8375 @subsection Binder Error Message Control
8378 The following switches provide control over the generation of error
8379 messages from the binder:
8383 @item ^-v^/REPORT_ERRORS=VERBOSE^
8384 @cindex @option{^-v^/REPORT_ERRORS=VERBOSE^} (@code{gnatbind})
8385 Verbose mode. In the normal mode, brief error messages are generated to
8386 @file{stderr}. If this switch is present, a header is written
8387 to @file{stdout} and any error messages are directed to @file{stdout}.
8388 All that is written to @file{stderr} is a brief summary message.
8390 @item ^-b^/REPORT_ERRORS=BRIEF^
8391 @cindex @option{^-b^/REPORT_ERRORS=BRIEF^} (@code{gnatbind})
8392 Generate brief error messages to @file{stderr} even if verbose mode is
8393 specified. This is relevant only when used with the
8394 @option{^-v^/REPORT_ERRORS=VERBOSE^} switch.
8398 @cindex @option{-m} (@code{gnatbind})
8399 Limits the number of error messages to @var{n}, a decimal integer in the
8400 range 1-999. The binder terminates immediately if this limit is reached.
8403 @cindex @option{-M} (@code{gnatbind})
8404 Renames the generated main program from @code{main} to @code{xxx}.
8405 This is useful in the case of some cross-building environments, where
8406 the actual main program is separate from the one generated
8410 @item ^-ws^/WARNINGS=SUPPRESS^
8411 @cindex @option{^-ws^/WARNINGS=SUPPRESS^} (@code{gnatbind})
8413 Suppress all warning messages.
8415 @item ^-we^/WARNINGS=ERROR^
8416 @cindex @option{^-we^/WARNINGS=ERROR^} (@code{gnatbind})
8417 Treat any warning messages as fatal errors.
8420 @item /WARNINGS=NORMAL
8421 Standard mode with warnings generated, but warnings do not get treated
8425 @item ^-t^/NOTIME_STAMP_CHECK^
8426 @cindex @option{^-t^/NOTIME_STAMP_CHECK^} (@code{gnatbind})
8427 @cindex Time stamp checks, in binder
8428 @cindex Binder consistency checks
8429 @cindex Consistency checks, in binder
8430 The binder performs a number of consistency checks including:
8434 Check that time stamps of a given source unit are consistent
8436 Check that checksums of a given source unit are consistent
8438 Check that consistent versions of @code{GNAT} were used for compilation
8440 Check consistency of configuration pragmas as required
8444 Normally failure of such checks, in accordance with the consistency
8445 requirements of the Ada Reference Manual, causes error messages to be
8446 generated which abort the binder and prevent the output of a binder
8447 file and subsequent link to obtain an executable.
8449 The @option{^-t^/NOTIME_STAMP_CHECK^} switch converts these error messages
8450 into warnings, so that
8451 binding and linking can continue to completion even in the presence of such
8452 errors. The result may be a failed link (due to missing symbols), or a
8453 non-functional executable which has undefined semantics.
8454 @emph{This means that
8455 @option{^-t^/NOTIME_STAMP_CHECK^} should be used only in unusual situations,
8459 @node Elaboration Control
8460 @subsection Elaboration Control
8463 The following switches provide additional control over the elaboration
8464 order. For full details see @ref{Elaboration Order Handling in GNAT}.
8467 @item ^-p^/PESSIMISTIC_ELABORATION^
8468 @cindex @option{^-p^/PESSIMISTIC_ELABORATION^} (@code{gnatbind})
8469 Normally the binder attempts to choose an elaboration order that is
8470 likely to minimize the likelihood of an elaboration order error resulting
8471 in raising a @code{Program_Error} exception. This switch reverses the
8472 action of the binder, and requests that it deliberately choose an order
8473 that is likely to maximize the likelihood of an elaboration error.
8474 This is useful in ensuring portability and avoiding dependence on
8475 accidental fortuitous elaboration ordering.
8477 Normally it only makes sense to use the @option{^-p^/PESSIMISTIC_ELABORATION^}
8479 elaboration checking is used (@option{-gnatE} switch used for compilation).
8480 This is because in the default static elaboration mode, all necessary
8481 @code{Elaborate} and @code{Elaborate_All} pragmas are implicitly inserted.
8482 These implicit pragmas are still respected by the binder in
8483 @option{^-p^/PESSIMISTIC_ELABORATION^} mode, so a
8484 safe elaboration order is assured.
8486 Note that @option{^-p^/PESSIMISTIC_ELABORATION^} is not intended for
8487 production use; it is more for debugging/experimental use.
8490 @node Output Control
8491 @subsection Output Control
8494 The following switches allow additional control over the output
8495 generated by the binder.
8500 @item ^-c^/NOOUTPUT^
8501 @cindex @option{^-c^/NOOUTPUT^} (@code{gnatbind})
8502 Check only. Do not generate the binder output file. In this mode the
8503 binder performs all error checks but does not generate an output file.
8505 @item ^-e^/ELABORATION_DEPENDENCIES^
8506 @cindex @option{^-e^/ELABORATION_DEPENDENCIES^} (@code{gnatbind})
8507 Output complete list of elaboration-order dependencies, showing the
8508 reason for each dependency. This output can be rather extensive but may
8509 be useful in diagnosing problems with elaboration order. The output is
8510 written to @file{stdout}.
8513 @cindex @option{^-h^/HELP^} (@code{gnatbind})
8514 Output usage information. The output is written to @file{stdout}.
8516 @item ^-K^/LINKER_OPTION_LIST^
8517 @cindex @option{^-K^/LINKER_OPTION_LIST^} (@code{gnatbind})
8518 Output linker options to @file{stdout}. Includes library search paths,
8519 contents of pragmas Ident and Linker_Options, and libraries added
8522 @item ^-l^/ORDER_OF_ELABORATION^
8523 @cindex @option{^-l^/ORDER_OF_ELABORATION^} (@code{gnatbind})
8524 Output chosen elaboration order. The output is written to @file{stdout}.
8526 @item ^-O^/OBJECT_LIST^
8527 @cindex @option{^-O^/OBJECT_LIST^} (@code{gnatbind})
8528 Output full names of all the object files that must be linked to provide
8529 the Ada component of the program. The output is written to @file{stdout}.
8530 This list includes the files explicitly supplied and referenced by the user
8531 as well as implicitly referenced run-time unit files. The latter are
8532 omitted if the corresponding units reside in shared libraries. The
8533 directory names for the run-time units depend on the system configuration.
8535 @item ^-o ^/OUTPUT=^@var{file}
8536 @cindex @option{^-o^/OUTPUT^} (@code{gnatbind})
8537 Set name of output file to @var{file} instead of the normal
8538 @file{b~@var{mainprog}.adb} default. Note that @var{file} denote the Ada
8539 binder generated body filename.
8540 Note that if this option is used, then linking must be done manually.
8541 It is not possible to use gnatlink in this case, since it cannot locate
8544 @item ^-r^/RESTRICTION_LIST^
8545 @cindex @option{^-r^/RESTRICTION_LIST^} (@code{gnatbind})
8546 Generate list of @code{pragma Restrictions} that could be applied to
8547 the current unit. This is useful for code audit purposes, and also may
8548 be used to improve code generation in some cases.
8552 @node Dynamic Allocation Control
8553 @subsection Dynamic Allocation Control
8556 The heap control switches -- @option{-H32} and @option{-H64} --
8557 determine whether dynamic allocation uses 32-bit or 64-bit memory.
8558 They only affect compiler-generated allocations via @code{__gnat_malloc};
8559 explicit calls to @code{malloc} and related functions from the C
8560 run-time library are unaffected.
8564 Allocate memory on 32-bit heap
8567 Allocate memory on 64-bit heap. This is the default
8568 unless explicitly overridden by a @code{'Size} clause on the access type.
8573 See also @ref{Access types and 32/64-bit allocation}.
8577 These switches are only effective on VMS platforms.
8581 @node Binding with Non-Ada Main Programs
8582 @subsection Binding with Non-Ada Main Programs
8585 In our description so far we have assumed that the main
8586 program is in Ada, and that the task of the binder is to generate a
8587 corresponding function @code{main} that invokes this Ada main
8588 program. GNAT also supports the building of executable programs where
8589 the main program is not in Ada, but some of the called routines are
8590 written in Ada and compiled using GNAT (@pxref{Mixed Language Programming}).
8591 The following switch is used in this situation:
8595 @cindex @option{^-n^/NOMAIN^} (@code{gnatbind})
8596 No main program. The main program is not in Ada.
8600 In this case, most of the functions of the binder are still required,
8601 but instead of generating a main program, the binder generates a file
8602 containing the following callable routines:
8607 You must call this routine to initialize the Ada part of the program by
8608 calling the necessary elaboration routines. A call to @code{adainit} is
8609 required before the first call to an Ada subprogram.
8611 Note that it is assumed that the basic execution environment must be setup
8612 to be appropriate for Ada execution at the point where the first Ada
8613 subprogram is called. In particular, if the Ada code will do any
8614 floating-point operations, then the FPU must be setup in an appropriate
8615 manner. For the case of the x86, for example, full precision mode is
8616 required. The procedure GNAT.Float_Control.Reset may be used to ensure
8617 that the FPU is in the right state.
8621 You must call this routine to perform any library-level finalization
8622 required by the Ada subprograms. A call to @code{adafinal} is required
8623 after the last call to an Ada subprogram, and before the program
8628 If the @option{^-n^/NOMAIN^} switch
8629 @cindex @option{^-n^/NOMAIN^} (@command{gnatbind})
8630 @cindex Binder, multiple input files
8631 is given, more than one ALI file may appear on
8632 the command line for @code{gnatbind}. The normal @dfn{closure}
8633 calculation is performed for each of the specified units. Calculating
8634 the closure means finding out the set of units involved by tracing
8635 @code{with} references. The reason it is necessary to be able to
8636 specify more than one ALI file is that a given program may invoke two or
8637 more quite separate groups of Ada units.
8639 The binder takes the name of its output file from the last specified ALI
8640 file, unless overridden by the use of the @option{^-o file^/OUTPUT=file^}.
8641 @cindex @option{^-o^/OUTPUT^} (@command{gnatbind})
8642 The output is an Ada unit in source form that can be compiled with GNAT.
8643 This compilation occurs automatically as part of the @command{gnatlink}
8646 Currently the GNAT run time requires a FPU using 80 bits mode
8647 precision. Under targets where this is not the default it is required to
8648 call GNAT.Float_Control.Reset before using floating point numbers (this
8649 include float computation, float input and output) in the Ada code. A
8650 side effect is that this could be the wrong mode for the foreign code
8651 where floating point computation could be broken after this call.
8653 @node Binding Programs with No Main Subprogram
8654 @subsection Binding Programs with No Main Subprogram
8657 It is possible to have an Ada program which does not have a main
8658 subprogram. This program will call the elaboration routines of all the
8659 packages, then the finalization routines.
8661 The following switch is used to bind programs organized in this manner:
8664 @item ^-z^/ZERO_MAIN^
8665 @cindex @option{^-z^/ZERO_MAIN^} (@code{gnatbind})
8666 Normally the binder checks that the unit name given on the command line
8667 corresponds to a suitable main subprogram. When this switch is used,
8668 a list of ALI files can be given, and the execution of the program
8669 consists of elaboration of these units in an appropriate order. Note
8670 that the default wide character encoding method for standard Text_IO
8671 files is always set to Brackets if this switch is set (you can use
8673 @option{^-Wx^WIDE_CHARACTER_ENCODING^} to override this default).
8676 @node Command-Line Access
8677 @section Command-Line Access
8680 The package @code{Ada.Command_Line} provides access to the command-line
8681 arguments and program name. In order for this interface to operate
8682 correctly, the two variables
8694 are declared in one of the GNAT library routines. These variables must
8695 be set from the actual @code{argc} and @code{argv} values passed to the
8696 main program. With no @option{^n^/NOMAIN^} present, @code{gnatbind}
8697 generates the C main program to automatically set these variables.
8698 If the @option{^n^/NOMAIN^} switch is used, there is no automatic way to
8699 set these variables. If they are not set, the procedures in
8700 @code{Ada.Command_Line} will not be available, and any attempt to use
8701 them will raise @code{Constraint_Error}. If command line access is
8702 required, your main program must set @code{gnat_argc} and
8703 @code{gnat_argv} from the @code{argc} and @code{argv} values passed to
8706 @node Search Paths for gnatbind
8707 @section Search Paths for @code{gnatbind}
8710 The binder takes the name of an ALI file as its argument and needs to
8711 locate source files as well as other ALI files to verify object consistency.
8713 For source files, it follows exactly the same search rules as @command{gcc}
8714 (@pxref{Search Paths and the Run-Time Library (RTL)}). For ALI files the
8715 directories searched are:
8719 The directory containing the ALI file named in the command line, unless
8720 the switch @option{^-I-^/NOCURRENT_DIRECTORY^} is specified.
8723 All directories specified by @option{^-I^/SEARCH^}
8724 switches on the @code{gnatbind}
8725 command line, in the order given.
8728 @findex ADA_PRJ_OBJECTS_FILE
8729 Each of the directories listed in the text file whose name is given
8730 by the @env{ADA_PRJ_OBJECTS_FILE} ^environment variable^logical name^.
8733 @env{ADA_PRJ_OBJECTS_FILE} is normally set by gnatmake or by the ^gnat^GNAT^
8734 driver when project files are used. It should not normally be set
8738 @findex ADA_OBJECTS_PATH
8739 Each of the directories listed in the value of the
8740 @env{ADA_OBJECTS_PATH} ^environment variable^logical name^.
8742 Construct this value
8743 exactly as the @env{PATH} environment variable: a list of directory
8744 names separated by colons (semicolons when working with the NT version
8748 Normally, define this value as a logical name containing a comma separated
8749 list of directory names.
8751 This variable can also be defined by means of an environment string
8752 (an argument to the HP C exec* set of functions).
8756 DEFINE ANOTHER_PATH FOO:[BAG]
8757 DEFINE ADA_OBJECTS_PATH ANOTHER_PATH,FOO:[BAM],FOO:[BAR]
8760 By default, the path includes GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB]
8761 first, followed by the standard Ada
8762 libraries in GNU:[LIB.OPENVMS7_x.2_8_x.ADALIB].
8763 If this is not redefined, the user will obtain the HP Ada 83 IO packages
8764 (Text_IO, Sequential_IO, etc)
8765 instead of the standard Ada packages. Thus, in order to get the standard Ada
8766 packages by default, ADA_OBJECTS_PATH must be redefined.
8770 The content of the @file{ada_object_path} file which is part of the GNAT
8771 installation tree and is used to store standard libraries such as the
8772 GNAT Run Time Library (RTL) unless the switch @option{-nostdlib} is
8775 @ref{Installing a library}
8780 In the binder the switch @option{^-I^/SEARCH^}
8781 @cindex @option{^-I^/SEARCH^} (@command{gnatbind})
8782 is used to specify both source and
8783 library file paths. Use @option{^-aI^/SOURCE_SEARCH^}
8784 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatbind})
8785 instead if you want to specify
8786 source paths only, and @option{^-aO^/LIBRARY_SEARCH^}
8787 @cindex @option{^-aO^/LIBRARY_SEARCH^} (@command{gnatbind})
8788 if you want to specify library paths
8789 only. This means that for the binder
8790 @option{^-I^/SEARCH=^}@var{dir} is equivalent to
8791 @option{^-aI^/SOURCE_SEARCH=^}@var{dir}
8792 @option{^-aO^/OBJECT_SEARCH=^}@var{dir}.
8793 The binder generates the bind file (a C language source file) in the
8794 current working directory.
8800 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
8801 children make up the GNAT Run-Time Library, together with the package
8802 GNAT and its children, which contain a set of useful additional
8803 library functions provided by GNAT. The sources for these units are
8804 needed by the compiler and are kept together in one directory. The ALI
8805 files and object files generated by compiling the RTL are needed by the
8806 binder and the linker and are kept together in one directory, typically
8807 different from the directory containing the sources. In a normal
8808 installation, you need not specify these directory names when compiling
8809 or binding. Either the environment variables or the built-in defaults
8810 cause these files to be found.
8812 Besides simplifying access to the RTL, a major use of search paths is
8813 in compiling sources from multiple directories. This can make
8814 development environments much more flexible.
8816 @node Examples of gnatbind Usage
8817 @section Examples of @code{gnatbind} Usage
8820 This section contains a number of examples of using the GNAT binding
8821 utility @code{gnatbind}.
8824 @item gnatbind hello
8825 The main program @code{Hello} (source program in @file{hello.adb}) is
8826 bound using the standard switch settings. The generated main program is
8827 @file{b~hello.adb}. This is the normal, default use of the binder.
8830 @item gnatbind hello -o mainprog.adb
8833 @item gnatbind HELLO.ALI /OUTPUT=Mainprog.ADB
8835 The main program @code{Hello} (source program in @file{hello.adb}) is
8836 bound using the standard switch settings. The generated main program is
8837 @file{mainprog.adb} with the associated spec in
8838 @file{mainprog.ads}. Note that you must specify the body here not the
8839 spec. Note that if this option is used, then linking must be done manually,
8840 since gnatlink will not be able to find the generated file.
8843 @c ------------------------------------
8844 @node Linking with gnatlink
8845 @chapter Linking with @command{gnatlink}
8846 @c ------------------------------------
8850 This chapter discusses @command{gnatlink}, a tool that links
8851 an Ada program and builds an executable file. This utility
8852 invokes the system linker ^(via the @command{gcc} command)^^
8853 with a correct list of object files and library references.
8854 @command{gnatlink} automatically determines the list of files and
8855 references for the Ada part of a program. It uses the binder file
8856 generated by the @command{gnatbind} to determine this list.
8858 Note: to invoke @code{gnatlink} with a project file, use the @code{gnat}
8859 driver (see @ref{The GNAT Driver and Project Files}).
8862 * Running gnatlink::
8863 * Switches for gnatlink::
8866 @node Running gnatlink
8867 @section Running @command{gnatlink}
8870 The form of the @command{gnatlink} command is
8873 @c $ gnatlink @ovar{switches} @var{mainprog}@r{[}.ali@r{]}
8874 @c @ovar{non-Ada objects} @ovar{linker options}
8875 @c Expanding @ovar macro inline (explanation in macro def comments)
8876 $ gnatlink @r{[}@var{switches}@r{]} @var{mainprog}@r{[}.ali@r{]}
8877 @r{[}@var{non-Ada objects}@r{]} @r{[}@var{linker options}@r{]}
8882 The arguments of @command{gnatlink} (switches, main @file{ALI} file,
8884 or linker options) may be in any order, provided that no non-Ada object may
8885 be mistaken for a main @file{ALI} file.
8886 Any file name @file{F} without the @file{.ali}
8887 extension will be taken as the main @file{ALI} file if a file exists
8888 whose name is the concatenation of @file{F} and @file{.ali}.
8891 @file{@var{mainprog}.ali} references the ALI file of the main program.
8892 The @file{.ali} extension of this file can be omitted. From this
8893 reference, @command{gnatlink} locates the corresponding binder file
8894 @file{b~@var{mainprog}.adb} and, using the information in this file along
8895 with the list of non-Ada objects and linker options, constructs a
8896 linker command file to create the executable.
8898 The arguments other than the @command{gnatlink} switches and the main
8899 @file{ALI} file are passed to the linker uninterpreted.
8900 They typically include the names of
8901 object files for units written in other languages than Ada and any library
8902 references required to resolve references in any of these foreign language
8903 units, or in @code{Import} pragmas in any Ada units.
8905 @var{linker options} is an optional list of linker specific
8907 The default linker called by gnatlink is @command{gcc} which in
8908 turn calls the appropriate system linker.
8910 One useful option for the linker is @option{-s}: it reduces the size of the
8911 executable by removing all symbol table and relocation information from the
8914 Standard options for the linker such as @option{-lmy_lib} or
8915 @option{-Ldir} can be added as is.
8916 For options that are not recognized by
8917 @command{gcc} as linker options, use the @command{gcc} switches
8918 @option{-Xlinker} or @option{-Wl,}.
8920 Refer to the GCC documentation for
8923 Here is an example showing how to generate a linker map:
8926 $ ^gnatlink my_prog -Wl,-Map,MAPFILE^GNAT LINK my_prog.ali /MAP^
8929 Using @var{linker options} it is possible to set the program stack and
8932 See @ref{Setting Stack Size from gnatlink} and
8933 @ref{Setting Heap Size from gnatlink}.
8936 @command{gnatlink} determines the list of objects required by the Ada
8937 program and prepends them to the list of objects passed to the linker.
8938 @command{gnatlink} also gathers any arguments set by the use of
8939 @code{pragma Linker_Options} and adds them to the list of arguments
8940 presented to the linker.
8943 @command{gnatlink} accepts the following types of extra files on the command
8944 line: objects (@file{.OBJ}), libraries (@file{.OLB}), sharable images
8945 (@file{.EXE}), and options files (@file{.OPT}). These are recognized and
8946 handled according to their extension.
8949 @node Switches for gnatlink
8950 @section Switches for @command{gnatlink}
8953 The following switches are available with the @command{gnatlink} utility:
8959 @cindex @option{--version} @command{gnatlink}
8960 Display Copyright and version, then exit disregarding all other options.
8963 @cindex @option{--help} @command{gnatlink}
8964 If @option{--version} was not used, display usage, then exit disregarding
8967 @item ^-f^/FORCE_OBJECT_FILE_LIST^
8968 @cindex Command line length
8969 @cindex @option{^-f^/FORCE_OBJECT_FILE_LIST^} (@command{gnatlink})
8970 On some targets, the command line length is limited, and @command{gnatlink}
8971 will generate a separate file for the linker if the list of object files
8973 The @option{^-f^/FORCE_OBJECT_FILE_LIST^} switch forces this file
8974 to be generated even if
8975 the limit is not exceeded. This is useful in some cases to deal with
8976 special situations where the command line length is exceeded.
8979 @cindex Debugging information, including
8980 @cindex @option{^-g^/DEBUG^} (@command{gnatlink})
8981 The option to include debugging information causes the Ada bind file (in
8982 other words, @file{b~@var{mainprog}.adb}) to be compiled with
8983 @option{^-g^/DEBUG^}.
8984 In addition, the binder does not delete the @file{b~@var{mainprog}.adb},
8985 @file{b~@var{mainprog}.o} and @file{b~@var{mainprog}.ali} files.
8986 Without @option{^-g^/DEBUG^}, the binder removes these files by
8987 default. The same procedure apply if a C bind file was generated using
8988 @option{^-C^/BIND_FILE=C^} @code{gnatbind} option, in this case the filenames
8989 are @file{b_@var{mainprog}.c} and @file{b_@var{mainprog}.o}.
8991 @item ^-n^/NOCOMPILE^
8992 @cindex @option{^-n^/NOCOMPILE^} (@command{gnatlink})
8993 Do not compile the file generated by the binder. This may be used when
8994 a link is rerun with different options, but there is no need to recompile
8998 @cindex @option{^-v^/VERBOSE^} (@command{gnatlink})
8999 Causes additional information to be output, including a full list of the
9000 included object files. This switch option is most useful when you want
9001 to see what set of object files are being used in the link step.
9003 @item ^-v -v^/VERBOSE/VERBOSE^
9004 @cindex @option{^-v -v^/VERBOSE/VERBOSE^} (@command{gnatlink})
9005 Very verbose mode. Requests that the compiler operate in verbose mode when
9006 it compiles the binder file, and that the system linker run in verbose mode.
9008 @item ^-o ^/EXECUTABLE=^@var{exec-name}
9009 @cindex @option{^-o^/EXECUTABLE^} (@command{gnatlink})
9010 @var{exec-name} specifies an alternate name for the generated
9011 executable program. If this switch is omitted, the executable has the same
9012 name as the main unit. For example, @code{gnatlink try.ali} creates
9013 an executable called @file{^try^TRY.EXE^}.
9016 @item -b @var{target}
9017 @cindex @option{-b} (@command{gnatlink})
9018 Compile your program to run on @var{target}, which is the name of a
9019 system configuration. You must have a GNAT cross-compiler built if
9020 @var{target} is not the same as your host system.
9023 @cindex @option{-B} (@command{gnatlink})
9024 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
9025 from @var{dir} instead of the default location. Only use this switch
9026 when multiple versions of the GNAT compiler are available.
9027 @xref{Directory Options,,, gcc, The GNU Compiler Collection},
9028 for further details. You would normally use the @option{-b} or
9029 @option{-V} switch instead.
9032 When linking an executable, create a map file. The name of the map file
9033 has the same name as the executable with extension ".map".
9036 When linking an executable, create a map file. The name of the map file is
9039 @item --GCC=@var{compiler_name}
9040 @cindex @option{--GCC=compiler_name} (@command{gnatlink})
9041 Program used for compiling the binder file. The default is
9042 @command{gcc}. You need to use quotes around @var{compiler_name} if
9043 @code{compiler_name} contains spaces or other separator characters.
9044 As an example @option{--GCC="foo -x -y"} will instruct @command{gnatlink} to
9045 use @code{foo -x -y} as your compiler. Note that switch @option{-c} is always
9046 inserted after your command name. Thus in the above example the compiler
9047 command that will be used by @command{gnatlink} will be @code{foo -c -x -y}.
9048 A limitation of this syntax is that the name and path name of the executable
9049 itself must not include any embedded spaces. If the compiler executable is
9050 different from the default one (gcc or <prefix>-gcc), then the back-end
9051 switches in the ALI file are not used to compile the binder generated source.
9052 For example, this is the case with @option{--GCC="foo -x -y"}. But the back end
9053 switches will be used for @option{--GCC="gcc -gnatv"}. If several
9054 @option{--GCC=compiler_name} are used, only the last @var{compiler_name}
9055 is taken into account. However, all the additional switches are also taken
9057 @option{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
9058 @option{--GCC="bar -x -y -z -t"}.
9060 @item --LINK=@var{name}
9061 @cindex @option{--LINK=} (@command{gnatlink})
9062 @var{name} is the name of the linker to be invoked. This is especially
9063 useful in mixed language programs since languages such as C++ require
9064 their own linker to be used. When this switch is omitted, the default
9065 name for the linker is @command{gcc}. When this switch is used, the
9066 specified linker is called instead of @command{gcc} with exactly the same
9067 parameters that would have been passed to @command{gcc} so if the desired
9068 linker requires different parameters it is necessary to use a wrapper
9069 script that massages the parameters before invoking the real linker. It
9070 may be useful to control the exact invocation by using the verbose
9076 @item /DEBUG=TRACEBACK
9077 @cindex @code{/DEBUG=TRACEBACK} (@command{gnatlink})
9078 This qualifier causes sufficient information to be included in the
9079 executable file to allow a traceback, but does not include the full
9080 symbol information needed by the debugger.
9082 @item /IDENTIFICATION="<string>"
9083 @code{"<string>"} specifies the string to be stored in the image file
9084 identification field in the image header.
9085 It overrides any pragma @code{Ident} specified string.
9087 @item /NOINHIBIT-EXEC
9088 Generate the executable file even if there are linker warnings.
9090 @item /NOSTART_FILES
9091 Don't link in the object file containing the ``main'' transfer address.
9092 Used when linking with a foreign language main program compiled with an
9096 Prefer linking with object libraries over sharable images, even without
9102 @node The GNAT Make Program gnatmake
9103 @chapter The GNAT Make Program @command{gnatmake}
9107 * Running gnatmake::
9108 * Switches for gnatmake::
9109 * Mode Switches for gnatmake::
9110 * Notes on the Command Line::
9111 * How gnatmake Works::
9112 * Examples of gnatmake Usage::
9115 A typical development cycle when working on an Ada program consists of
9116 the following steps:
9120 Edit some sources to fix bugs.
9126 Compile all sources affected.
9136 The third step can be tricky, because not only do the modified files
9137 @cindex Dependency rules
9138 have to be compiled, but any files depending on these files must also be
9139 recompiled. The dependency rules in Ada can be quite complex, especially
9140 in the presence of overloading, @code{use} clauses, generics and inlined
9143 @command{gnatmake} automatically takes care of the third and fourth steps
9144 of this process. It determines which sources need to be compiled,
9145 compiles them, and binds and links the resulting object files.
9147 Unlike some other Ada make programs, the dependencies are always
9148 accurately recomputed from the new sources. The source based approach of
9149 the GNAT compilation model makes this possible. This means that if
9150 changes to the source program cause corresponding changes in
9151 dependencies, they will always be tracked exactly correctly by
9154 @node Running gnatmake
9155 @section Running @command{gnatmake}
9158 The usual form of the @command{gnatmake} command is
9161 @c $ gnatmake @ovar{switches} @var{file_name}
9162 @c @ovar{file_names} @ovar{mode_switches}
9163 @c Expanding @ovar macro inline (explanation in macro def comments)
9164 $ gnatmake @r{[}@var{switches}@r{]} @var{file_name}
9165 @r{[}@var{file_names}@r{]} @r{[}@var{mode_switches}@r{]}
9169 The only required argument is one @var{file_name}, which specifies
9170 a compilation unit that is a main program. Several @var{file_names} can be
9171 specified: this will result in several executables being built.
9172 If @code{switches} are present, they can be placed before the first
9173 @var{file_name}, between @var{file_names} or after the last @var{file_name}.
9174 If @var{mode_switches} are present, they must always be placed after
9175 the last @var{file_name} and all @code{switches}.
9177 If you are using standard file extensions (@file{.adb} and @file{.ads}), then the
9178 extension may be omitted from the @var{file_name} arguments. However, if
9179 you are using non-standard extensions, then it is required that the
9180 extension be given. A relative or absolute directory path can be
9181 specified in a @var{file_name}, in which case, the input source file will
9182 be searched for in the specified directory only. Otherwise, the input
9183 source file will first be searched in the directory where
9184 @command{gnatmake} was invoked and if it is not found, it will be search on
9185 the source path of the compiler as described in
9186 @ref{Search Paths and the Run-Time Library (RTL)}.
9188 All @command{gnatmake} output (except when you specify
9189 @option{^-M^/DEPENDENCIES_LIST^}) is to
9190 @file{stderr}. The output produced by the
9191 @option{^-M^/DEPENDENCIES_LIST^} switch is send to
9194 @node Switches for gnatmake
9195 @section Switches for @command{gnatmake}
9198 You may specify any of the following switches to @command{gnatmake}:
9204 @cindex @option{--version} @command{gnatmake}
9205 Display Copyright and version, then exit disregarding all other options.
9208 @cindex @option{--help} @command{gnatmake}
9209 If @option{--version} was not used, display usage, then exit disregarding
9213 @item --GCC=@var{compiler_name}
9214 @cindex @option{--GCC=compiler_name} (@command{gnatmake})
9215 Program used for compiling. The default is `@command{gcc}'. You need to use
9216 quotes around @var{compiler_name} if @code{compiler_name} contains
9217 spaces or other separator characters. As an example @option{--GCC="foo -x
9218 -y"} will instruct @command{gnatmake} to use @code{foo -x -y} as your
9219 compiler. A limitation of this syntax is that the name and path name of
9220 the executable itself must not include any embedded spaces. Note that
9221 switch @option{-c} is always inserted after your command name. Thus in the
9222 above example the compiler command that will be used by @command{gnatmake}
9223 will be @code{foo -c -x -y}. If several @option{--GCC=compiler_name} are
9224 used, only the last @var{compiler_name} is taken into account. However,
9225 all the additional switches are also taken into account. Thus,
9226 @option{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
9227 @option{--GCC="bar -x -y -z -t"}.
9229 @item --GNATBIND=@var{binder_name}
9230 @cindex @option{--GNATBIND=binder_name} (@command{gnatmake})
9231 Program used for binding. The default is `@code{gnatbind}'. You need to
9232 use quotes around @var{binder_name} if @var{binder_name} contains spaces
9233 or other separator characters. As an example @option{--GNATBIND="bar -x
9234 -y"} will instruct @command{gnatmake} to use @code{bar -x -y} as your
9235 binder. Binder switches that are normally appended by @command{gnatmake}
9236 to `@code{gnatbind}' are now appended to the end of @code{bar -x -y}.
9237 A limitation of this syntax is that the name and path name of the executable
9238 itself must not include any embedded spaces.
9240 @item --GNATLINK=@var{linker_name}
9241 @cindex @option{--GNATLINK=linker_name} (@command{gnatmake})
9242 Program used for linking. The default is `@command{gnatlink}'. You need to
9243 use quotes around @var{linker_name} if @var{linker_name} contains spaces
9244 or other separator characters. As an example @option{--GNATLINK="lan -x
9245 -y"} will instruct @command{gnatmake} to use @code{lan -x -y} as your
9246 linker. Linker switches that are normally appended by @command{gnatmake} to
9247 `@command{gnatlink}' are now appended to the end of @code{lan -x -y}.
9248 A limitation of this syntax is that the name and path name of the executable
9249 itself must not include any embedded spaces.
9253 @item ^--subdirs^/SUBDIRS^=subdir
9254 Actual object directory of each project file is the subdirectory subdir of the
9255 object directory specified or defaulted in the project file.
9257 @item ^--single-compile-per-obj-dir^/SINGLE_COMPILE_PER_OBJ_DIR^
9258 Disallow simultaneous compilations in the same object directory when
9259 project files are used.
9261 @item ^--unchecked-shared-lib-imports^/UNCHECKED_SHARED_LIB_IMPORTS^
9262 By default, shared library projects are not allowed to import static library
9263 projects. When this switch is used on the command line, this restriction is
9266 @item ^--source-info=<source info file>^/SRC_INFO=source-info-file^
9267 Specify a source info file. This switch is active only when project files
9268 are used. If the source info file is specified as a relative path, then it is
9269 relative to the object directory of the main project. If the source info file
9270 does not exist, then after the Project Manager has successfully parsed and
9271 processed the project files and found the sources, it creates the source info
9272 file. If the source info file already exists and can be read successfully,
9273 then the Project Manager will get all the needed information about the sources
9274 from the source info file and will not look for them. This reduces the time
9275 to process the project files, especially when looking for sources that take a
9276 long time. If the source info file exists but cannot be parsed successfully,
9277 the Project Manager will attempt to recreate it. If the Project Manager fails
9278 to create the source info file, a message is issued, but gnatmake does not
9279 fail. @command{gnatmake} "trusts" the source info file. This means that
9280 if the source files have changed (addition, deletion, moving to a different
9281 source directory), then the source info file need to be deleted and recreated.
9284 @item --create-map-file
9285 When linking an executable, create a map file. The name of the map file
9286 has the same name as the executable with extension ".map".
9288 @item --create-map-file=mapfile
9289 When linking an executable, create a map file. The name of the map file is
9294 @item ^-a^/ALL_FILES^
9295 @cindex @option{^-a^/ALL_FILES^} (@command{gnatmake})
9296 Consider all files in the make process, even the GNAT internal system
9297 files (for example, the predefined Ada library files), as well as any
9298 locked files. Locked files are files whose ALI file is write-protected.
9300 @command{gnatmake} does not check these files,
9301 because the assumption is that the GNAT internal files are properly up
9302 to date, and also that any write protected ALI files have been properly
9303 installed. Note that if there is an installation problem, such that one
9304 of these files is not up to date, it will be properly caught by the
9306 You may have to specify this switch if you are working on GNAT
9307 itself. The switch @option{^-a^/ALL_FILES^} is also useful
9308 in conjunction with @option{^-f^/FORCE_COMPILE^}
9309 if you need to recompile an entire application,
9310 including run-time files, using special configuration pragmas,
9311 such as a @code{Normalize_Scalars} pragma.
9314 @code{gnatmake ^-a^/ALL_FILES^} compiles all GNAT
9317 @code{gcc -c -gnatpg} rather than @code{gcc -c}.
9320 the @code{/CHECKS=SUPPRESS_ALL /STYLE_CHECKS=GNAT} switch.
9323 @item ^-b^/ACTIONS=BIND^
9324 @cindex @option{^-b^/ACTIONS=BIND^} (@command{gnatmake})
9325 Bind only. Can be combined with @option{^-c^/ACTIONS=COMPILE^} to do
9326 compilation and binding, but no link.
9327 Can be combined with @option{^-l^/ACTIONS=LINK^}
9328 to do binding and linking. When not combined with
9329 @option{^-c^/ACTIONS=COMPILE^}
9330 all the units in the closure of the main program must have been previously
9331 compiled and must be up to date. The root unit specified by @var{file_name}
9332 may be given without extension, with the source extension or, if no GNAT
9333 Project File is specified, with the ALI file extension.
9335 @item ^-c^/ACTIONS=COMPILE^
9336 @cindex @option{^-c^/ACTIONS=COMPILE^} (@command{gnatmake})
9337 Compile only. Do not perform binding, except when @option{^-b^/ACTIONS=BIND^}
9338 is also specified. Do not perform linking, except if both
9339 @option{^-b^/ACTIONS=BIND^} and
9340 @option{^-l^/ACTIONS=LINK^} are also specified.
9341 If the root unit specified by @var{file_name} is not a main unit, this is the
9342 default. Otherwise @command{gnatmake} will attempt binding and linking
9343 unless all objects are up to date and the executable is more recent than
9347 @cindex @option{^-C^/MAPPING^} (@command{gnatmake})
9348 Use a temporary mapping file. A mapping file is a way to communicate
9349 to the compiler two mappings: from unit names to file names (without
9350 any directory information) and from file names to path names (with
9351 full directory information). A mapping file can make the compiler's
9352 file searches faster, especially if there are many source directories,
9353 or the sources are read over a slow network connection. If
9354 @option{^-P^/PROJECT_FILE^} is used, a mapping file is always used, so
9355 @option{^-C^/MAPPING^} is unnecessary; in this case the mapping file
9356 is initially populated based on the project file. If
9357 @option{^-C^/MAPPING^} is used without
9358 @option{^-P^/PROJECT_FILE^},
9359 the mapping file is initially empty. Each invocation of the compiler
9360 will add any newly accessed sources to the mapping file.
9362 @item ^-C=^/USE_MAPPING_FILE=^@var{file}
9363 @cindex @option{^-C=^/USE_MAPPING^} (@command{gnatmake})
9364 Use a specific mapping file. The file, specified as a path name (absolute or
9365 relative) by this switch, should already exist, otherwise the switch is
9366 ineffective. The specified mapping file will be communicated to the compiler.
9367 This switch is not compatible with a project file
9368 (^-P^/PROJECT_FILE=^@var{file}) or with multiple compiling processes
9369 (^-j^/PROCESSES=^nnn, when nnn is greater than 1).
9371 @item ^-d^/DISPLAY_PROGRESS^
9372 @cindex @option{^-d^/DISPLAY_PROGRESS^} (@command{gnatmake})
9373 Display progress for each source, up to date or not, as a single line
9376 completed x out of y (zz%)
9379 If the file needs to be compiled this is displayed after the invocation of
9380 the compiler. These lines are displayed even in quiet output mode.
9382 @item ^-D ^/DIRECTORY_OBJECTS=^@var{dir}
9383 @cindex @option{^-D^/DIRECTORY_OBJECTS^} (@command{gnatmake})
9384 Put all object files and ALI file in directory @var{dir}.
9385 If the @option{^-D^/DIRECTORY_OBJECTS^} switch is not used, all object files
9386 and ALI files go in the current working directory.
9388 This switch cannot be used when using a project file.
9391 @cindex @option{-eI} (@command{gnatmake})
9392 Indicates that the main source is a multi-unit source and the rank of the unit
9393 in the source file is nnn. nnn needs to be a positive number and a valid
9394 index in the source. This switch cannot be used when @command{gnatmake} is
9395 invoked for several mains.
9399 @cindex @option{-eL} (@command{gnatmake})
9400 @cindex symbolic links
9401 Follow all symbolic links when processing project files.
9402 This should be used if your project uses symbolic links for files or
9403 directories, but is not needed in other cases.
9405 @cindex naming scheme
9406 This also assumes that no directory matches the naming scheme for files (for
9407 instance that you do not have a directory called "sources.ads" when using the
9408 default GNAT naming scheme).
9410 When you do not have to use this switch (i.e.@: by default), gnatmake is able to
9411 save a lot of system calls (several per source file and object file), which
9412 can result in a significant speed up to load and manipulate a project file,
9413 especially when using source files from a remote system.
9417 @item ^-eS^/STANDARD_OUTPUT_FOR_COMMANDS^
9418 @cindex @option{^-eS^/STANDARD_OUTPUT_FOR_COMMANDS^} (@command{gnatmake})
9419 Output the commands for the compiler, the binder and the linker
9420 on ^standard output^SYS$OUTPUT^,
9421 instead of ^standard error^SYS$ERROR^.
9423 @item ^-f^/FORCE_COMPILE^
9424 @cindex @option{^-f^/FORCE_COMPILE^} (@command{gnatmake})
9425 Force recompilations. Recompile all sources, even though some object
9426 files may be up to date, but don't recompile predefined or GNAT internal
9427 files or locked files (files with a write-protected ALI file),
9428 unless the @option{^-a^/ALL_FILES^} switch is also specified.
9430 @item ^-F^/FULL_PATH_IN_BRIEF_MESSAGES^
9431 @cindex @option{^-F^/FULL_PATH_IN_BRIEF_MESSAGES^} (@command{gnatmake})
9432 When using project files, if some errors or warnings are detected during
9433 parsing and verbose mode is not in effect (no use of switch
9434 ^-v^/VERBOSE^), then error lines start with the full path name of the project
9435 file, rather than its simple file name.
9438 @cindex @option{^-g^/DEBUG^} (@command{gnatmake})
9439 Enable debugging. This switch is simply passed to the compiler and to the
9442 @item ^-i^/IN_PLACE^
9443 @cindex @option{^-i^/IN_PLACE^} (@command{gnatmake})
9444 In normal mode, @command{gnatmake} compiles all object files and ALI files
9445 into the current directory. If the @option{^-i^/IN_PLACE^} switch is used,
9446 then instead object files and ALI files that already exist are overwritten
9447 in place. This means that once a large project is organized into separate
9448 directories in the desired manner, then @command{gnatmake} will automatically
9449 maintain and update this organization. If no ALI files are found on the
9450 Ada object path (@ref{Search Paths and the Run-Time Library (RTL)}),
9451 the new object and ALI files are created in the
9452 directory containing the source being compiled. If another organization
9453 is desired, where objects and sources are kept in different directories,
9454 a useful technique is to create dummy ALI files in the desired directories.
9455 When detecting such a dummy file, @command{gnatmake} will be forced to
9456 recompile the corresponding source file, and it will be put the resulting
9457 object and ALI files in the directory where it found the dummy file.
9459 @item ^-j^/PROCESSES=^@var{n}
9460 @cindex @option{^-j^/PROCESSES^} (@command{gnatmake})
9461 @cindex Parallel make
9462 Use @var{n} processes to carry out the (re)compilations. On a multiprocessor
9463 machine compilations will occur in parallel. If @var{n} is 0, then the
9464 maximum number of parallel compilations is the number of core processors
9465 on the platform. In the event of compilation errors, messages from various
9466 compilations might get interspersed (but @command{gnatmake} will give you the
9467 full ordered list of failing compiles at the end). If this is problematic,
9468 rerun the make process with n set to 1 to get a clean list of messages.
9470 @item ^-k^/CONTINUE_ON_ERROR^
9471 @cindex @option{^-k^/CONTINUE_ON_ERROR^} (@command{gnatmake})
9472 Keep going. Continue as much as possible after a compilation error. To
9473 ease the programmer's task in case of compilation errors, the list of
9474 sources for which the compile fails is given when @command{gnatmake}
9477 If @command{gnatmake} is invoked with several @file{file_names} and with this
9478 switch, if there are compilation errors when building an executable,
9479 @command{gnatmake} will not attempt to build the following executables.
9481 @item ^-l^/ACTIONS=LINK^
9482 @cindex @option{^-l^/ACTIONS=LINK^} (@command{gnatmake})
9483 Link only. Can be combined with @option{^-b^/ACTIONS=BIND^} to binding
9484 and linking. Linking will not be performed if combined with
9485 @option{^-c^/ACTIONS=COMPILE^}
9486 but not with @option{^-b^/ACTIONS=BIND^}.
9487 When not combined with @option{^-b^/ACTIONS=BIND^}
9488 all the units in the closure of the main program must have been previously
9489 compiled and must be up to date, and the main program needs to have been bound.
9490 The root unit specified by @var{file_name}
9491 may be given without extension, with the source extension or, if no GNAT
9492 Project File is specified, with the ALI file extension.
9494 @item ^-m^/MINIMAL_RECOMPILATION^
9495 @cindex @option{^-m^/MINIMAL_RECOMPILATION^} (@command{gnatmake})
9496 Specify that the minimum necessary amount of recompilations
9497 be performed. In this mode @command{gnatmake} ignores time
9498 stamp differences when the only
9499 modifications to a source file consist in adding/removing comments,
9500 empty lines, spaces or tabs. This means that if you have changed the
9501 comments in a source file or have simply reformatted it, using this
9502 switch will tell @command{gnatmake} not to recompile files that depend on it
9503 (provided other sources on which these files depend have undergone no
9504 semantic modifications). Note that the debugging information may be
9505 out of date with respect to the sources if the @option{-m} switch causes
9506 a compilation to be switched, so the use of this switch represents a
9507 trade-off between compilation time and accurate debugging information.
9509 @item ^-M^/DEPENDENCIES_LIST^
9510 @cindex Dependencies, producing list
9511 @cindex @option{^-M^/DEPENDENCIES_LIST^} (@command{gnatmake})
9512 Check if all objects are up to date. If they are, output the object
9513 dependences to @file{stdout} in a form that can be directly exploited in
9514 a @file{Makefile}. By default, each source file is prefixed with its
9515 (relative or absolute) directory name. This name is whatever you
9516 specified in the various @option{^-aI^/SOURCE_SEARCH^}
9517 and @option{^-I^/SEARCH^} switches. If you use
9518 @code{gnatmake ^-M^/DEPENDENCIES_LIST^}
9519 @option{^-q^/QUIET^}
9520 (see below), only the source file names,
9521 without relative paths, are output. If you just specify the
9522 @option{^-M^/DEPENDENCIES_LIST^}
9523 switch, dependencies of the GNAT internal system files are omitted. This
9524 is typically what you want. If you also specify
9525 the @option{^-a^/ALL_FILES^} switch,
9526 dependencies of the GNAT internal files are also listed. Note that
9527 dependencies of the objects in external Ada libraries (see switch
9528 @option{^-aL^/SKIP_MISSING=^}@var{dir} in the following list)
9531 @item ^-n^/DO_OBJECT_CHECK^
9532 @cindex @option{^-n^/DO_OBJECT_CHECK^} (@command{gnatmake})
9533 Don't compile, bind, or link. Checks if all objects are up to date.
9534 If they are not, the full name of the first file that needs to be
9535 recompiled is printed.
9536 Repeated use of this option, followed by compiling the indicated source
9537 file, will eventually result in recompiling all required units.
9539 @item ^-o ^/EXECUTABLE=^@var{exec_name}
9540 @cindex @option{^-o^/EXECUTABLE^} (@command{gnatmake})
9541 Output executable name. The name of the final executable program will be
9542 @var{exec_name}. If the @option{^-o^/EXECUTABLE^} switch is omitted the default
9543 name for the executable will be the name of the input file in appropriate form
9544 for an executable file on the host system.
9546 This switch cannot be used when invoking @command{gnatmake} with several
9549 @item ^-p or --create-missing-dirs^/CREATE_MISSING_DIRS^
9550 @cindex @option{^-p^/CREATE_MISSING_DIRS^} (@command{gnatmake})
9551 When using project files (^-P^/PROJECT_FILE=^@var{project}), create
9552 automatically missing object directories, library directories and exec
9555 @item ^-P^/PROJECT_FILE=^@var{project}
9556 @cindex @option{^-P^/PROJECT_FILE^} (@command{gnatmake})
9557 Use project file @var{project}. Only one such switch can be used.
9558 @xref{gnatmake and Project Files}.
9561 @cindex @option{^-q^/QUIET^} (@command{gnatmake})
9562 Quiet. When this flag is not set, the commands carried out by
9563 @command{gnatmake} are displayed.
9565 @item ^-s^/SWITCH_CHECK/^
9566 @cindex @option{^-s^/SWITCH_CHECK^} (@command{gnatmake})
9567 Recompile if compiler switches have changed since last compilation.
9568 All compiler switches but -I and -o are taken into account in the
9570 orders between different ``first letter'' switches are ignored, but
9571 orders between same switches are taken into account. For example,
9572 @option{-O -O2} is different than @option{-O2 -O}, but @option{-g -O}
9573 is equivalent to @option{-O -g}.
9575 This switch is recommended when Integrated Preprocessing is used.
9578 @cindex @option{^-u^/UNIQUE^} (@command{gnatmake})
9579 Unique. Recompile at most the main files. It implies -c. Combined with
9580 -f, it is equivalent to calling the compiler directly. Note that using
9581 ^-u^/UNIQUE^ with a project file and no main has a special meaning
9582 (@pxref{Project Files and Main Subprograms}).
9584 @item ^-U^/ALL_PROJECTS^
9585 @cindex @option{^-U^/ALL_PROJECTS^} (@command{gnatmake})
9586 When used without a project file or with one or several mains on the command
9587 line, is equivalent to ^-u^/UNIQUE^. When used with a project file and no main
9588 on the command line, all sources of all project files are checked and compiled
9589 if not up to date, and libraries are rebuilt, if necessary.
9592 @cindex @option{^-v^/REASONS^} (@command{gnatmake})
9593 Verbose. Display the reason for all recompilations @command{gnatmake}
9594 decides are necessary, with the highest verbosity level.
9596 @item ^-vl^/LOW_VERBOSITY^
9597 @cindex @option{^-vl^/LOW_VERBOSITY^} (@command{gnatmake})
9598 Verbosity level Low. Display fewer lines than in verbosity Medium.
9600 @item ^-vm^/MEDIUM_VERBOSITY^
9601 @cindex @option{^-vm^/MEDIUM_VERBOSITY^} (@command{gnatmake})
9602 Verbosity level Medium. Potentially display fewer lines than in verbosity High.
9604 @item ^-vh^/HIGH_VERBOSITY^
9605 @cindex @option{^-vm^/HIGH_VERBOSITY^} (@command{gnatmake})
9606 Verbosity level High. Equivalent to ^-v^/REASONS^.
9608 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
9609 Indicate the verbosity of the parsing of GNAT project files.
9610 @xref{Switches Related to Project Files}.
9612 @item ^-x^/NON_PROJECT_UNIT_COMPILATION^
9613 @cindex @option{^-x^/NON_PROJECT_UNIT_COMPILATION^} (@command{gnatmake})
9614 Indicate that sources that are not part of any Project File may be compiled.
9615 Normally, when using Project Files, only sources that are part of a Project
9616 File may be compile. When this switch is used, a source outside of all Project
9617 Files may be compiled. The ALI file and the object file will be put in the
9618 object directory of the main Project. The compilation switches used will only
9619 be those specified on the command line. Even when
9620 @option{^-x^/NON_PROJECT_UNIT_COMPILATION^} is used, mains specified on the
9621 command line need to be sources of a project file.
9623 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
9624 Indicate that external variable @var{name} has the value @var{value}.
9625 The Project Manager will use this value for occurrences of
9626 @code{external(name)} when parsing the project file.
9627 @xref{Switches Related to Project Files}.
9630 @cindex @option{^-z^/NOMAIN^} (@command{gnatmake})
9631 No main subprogram. Bind and link the program even if the unit name
9632 given on the command line is a package name. The resulting executable
9633 will execute the elaboration routines of the package and its closure,
9634 then the finalization routines.
9639 @item @command{gcc} @asis{switches}
9641 Any uppercase or multi-character switch that is not a @command{gnatmake} switch
9642 is passed to @command{gcc} (e.g.@: @option{-O}, @option{-gnato,} etc.)
9645 Any qualifier that cannot be recognized as a qualifier for @code{GNAT MAKE}
9646 but is recognizable as a valid qualifier for @code{GNAT COMPILE} is
9647 automatically treated as a compiler switch, and passed on to all
9648 compilations that are carried out.
9653 Source and library search path switches:
9657 @item ^-aI^/SOURCE_SEARCH=^@var{dir}
9658 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatmake})
9659 When looking for source files also look in directory @var{dir}.
9660 The order in which source files search is undertaken is
9661 described in @ref{Search Paths and the Run-Time Library (RTL)}.
9663 @item ^-aL^/SKIP_MISSING=^@var{dir}
9664 @cindex @option{^-aL^/SKIP_MISSING^} (@command{gnatmake})
9665 Consider @var{dir} as being an externally provided Ada library.
9666 Instructs @command{gnatmake} to skip compilation units whose @file{.ALI}
9667 files have been located in directory @var{dir}. This allows you to have
9668 missing bodies for the units in @var{dir} and to ignore out of date bodies
9669 for the same units. You still need to specify
9670 the location of the specs for these units by using the switches
9671 @option{^-aI^/SOURCE_SEARCH=^@var{dir}}
9672 or @option{^-I^/SEARCH=^@var{dir}}.
9673 Note: this switch is provided for compatibility with previous versions
9674 of @command{gnatmake}. The easier method of causing standard libraries
9675 to be excluded from consideration is to write-protect the corresponding
9678 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
9679 @cindex @option{^-aO^/OBJECT_SEARCH^} (@command{gnatmake})
9680 When searching for library and object files, look in directory
9681 @var{dir}. The order in which library files are searched is described in
9682 @ref{Search Paths for gnatbind}.
9684 @item ^-A^/CONDITIONAL_SOURCE_SEARCH=^@var{dir}
9685 @cindex Search paths, for @command{gnatmake}
9686 @cindex @option{^-A^/CONDITIONAL_SOURCE_SEARCH^} (@command{gnatmake})
9687 Equivalent to @option{^-aL^/SKIP_MISSING=^@var{dir}
9688 ^-aI^/SOURCE_SEARCH=^@var{dir}}.
9690 @item ^-I^/SEARCH=^@var{dir}
9691 @cindex @option{^-I^/SEARCH^} (@command{gnatmake})
9692 Equivalent to @option{^-aO^/OBJECT_SEARCH=^@var{dir}
9693 ^-aI^/SOURCE_SEARCH=^@var{dir}}.
9695 @item ^-I-^/NOCURRENT_DIRECTORY^
9696 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gnatmake})
9697 @cindex Source files, suppressing search
9698 Do not look for source files in the directory containing the source
9699 file named in the command line.
9700 Do not look for ALI or object files in the directory
9701 where @command{gnatmake} was invoked.
9703 @item ^-L^/LIBRARY_SEARCH=^@var{dir}
9704 @cindex @option{^-L^/LIBRARY_SEARCH^} (@command{gnatmake})
9705 @cindex Linker libraries
9706 Add directory @var{dir} to the list of directories in which the linker
9707 will search for libraries. This is equivalent to
9708 @option{-largs ^-L^/LIBRARY_SEARCH=^}@var{dir}.
9710 Furthermore, under Windows, the sources pointed to by the libraries path
9711 set in the registry are not searched for.
9715 @cindex @option{-nostdinc} (@command{gnatmake})
9716 Do not look for source files in the system default directory.
9719 @cindex @option{-nostdlib} (@command{gnatmake})
9720 Do not look for library files in the system default directory.
9722 @item --RTS=@var{rts-path}
9723 @cindex @option{--RTS} (@command{gnatmake})
9724 Specifies the default location of the runtime library. GNAT looks for the
9726 in the following directories, and stops as soon as a valid runtime is found
9727 (@file{adainclude} or @file{ada_source_path}, and @file{adalib} or
9728 @file{ada_object_path} present):
9731 @item <current directory>/$rts_path
9733 @item <default-search-dir>/$rts_path
9735 @item <default-search-dir>/rts-$rts_path
9739 The selected path is handled like a normal RTS path.
9743 @node Mode Switches for gnatmake
9744 @section Mode Switches for @command{gnatmake}
9747 The mode switches (referred to as @code{mode_switches}) allow the
9748 inclusion of switches that are to be passed to the compiler itself, the
9749 binder or the linker. The effect of a mode switch is to cause all
9750 subsequent switches up to the end of the switch list, or up to the next
9751 mode switch, to be interpreted as switches to be passed on to the
9752 designated component of GNAT.
9756 @item -cargs @var{switches}
9757 @cindex @option{-cargs} (@command{gnatmake})
9758 Compiler switches. Here @var{switches} is a list of switches
9759 that are valid switches for @command{gcc}. They will be passed on to
9760 all compile steps performed by @command{gnatmake}.
9762 @item -bargs @var{switches}
9763 @cindex @option{-bargs} (@command{gnatmake})
9764 Binder switches. Here @var{switches} is a list of switches
9765 that are valid switches for @code{gnatbind}. They will be passed on to
9766 all bind steps performed by @command{gnatmake}.
9768 @item -largs @var{switches}
9769 @cindex @option{-largs} (@command{gnatmake})
9770 Linker switches. Here @var{switches} is a list of switches
9771 that are valid switches for @command{gnatlink}. They will be passed on to
9772 all link steps performed by @command{gnatmake}.
9774 @item -margs @var{switches}
9775 @cindex @option{-margs} (@command{gnatmake})
9776 Make switches. The switches are directly interpreted by @command{gnatmake},
9777 regardless of any previous occurrence of @option{-cargs}, @option{-bargs}
9781 @node Notes on the Command Line
9782 @section Notes on the Command Line
9785 This section contains some additional useful notes on the operation
9786 of the @command{gnatmake} command.
9790 @cindex Recompilation, by @command{gnatmake}
9791 If @command{gnatmake} finds no ALI files, it recompiles the main program
9792 and all other units required by the main program.
9793 This means that @command{gnatmake}
9794 can be used for the initial compile, as well as during subsequent steps of
9795 the development cycle.
9798 If you enter @code{gnatmake @var{file}.adb}, where @file{@var{file}.adb}
9799 is a subunit or body of a generic unit, @command{gnatmake} recompiles
9800 @file{@var{file}.adb} (because it finds no ALI) and stops, issuing a
9804 In @command{gnatmake} the switch @option{^-I^/SEARCH^}
9805 is used to specify both source and
9806 library file paths. Use @option{^-aI^/SOURCE_SEARCH^}
9807 instead if you just want to specify
9808 source paths only and @option{^-aO^/OBJECT_SEARCH^}
9809 if you want to specify library paths
9813 @command{gnatmake} will ignore any files whose ALI file is write-protected.
9814 This may conveniently be used to exclude standard libraries from
9815 consideration and in particular it means that the use of the
9816 @option{^-f^/FORCE_COMPILE^} switch will not recompile these files
9817 unless @option{^-a^/ALL_FILES^} is also specified.
9820 @command{gnatmake} has been designed to make the use of Ada libraries
9821 particularly convenient. Assume you have an Ada library organized
9822 as follows: @i{^obj-dir^[OBJ_DIR]^} contains the objects and ALI files for
9823 of your Ada compilation units,
9824 whereas @i{^include-dir^[INCLUDE_DIR]^} contains the
9825 specs of these units, but no bodies. Then to compile a unit
9826 stored in @code{main.adb}, which uses this Ada library you would just type
9830 $ gnatmake -aI@var{include-dir} -aL@var{obj-dir} main
9833 $ gnatmake /SOURCE_SEARCH=@i{[INCLUDE_DIR]}
9834 /SKIP_MISSING=@i{[OBJ_DIR]} main
9839 Using @command{gnatmake} along with the
9840 @option{^-m (minimal recompilation)^/MINIMAL_RECOMPILATION^}
9841 switch provides a mechanism for avoiding unnecessary recompilations. Using
9843 you can update the comments/format of your
9844 source files without having to recompile everything. Note, however, that
9845 adding or deleting lines in a source files may render its debugging
9846 info obsolete. If the file in question is a spec, the impact is rather
9847 limited, as that debugging info will only be useful during the
9848 elaboration phase of your program. For bodies the impact can be more
9849 significant. In all events, your debugger will warn you if a source file
9850 is more recent than the corresponding object, and alert you to the fact
9851 that the debugging information may be out of date.
9854 @node How gnatmake Works
9855 @section How @command{gnatmake} Works
9858 Generally @command{gnatmake} automatically performs all necessary
9859 recompilations and you don't need to worry about how it works. However,
9860 it may be useful to have some basic understanding of the @command{gnatmake}
9861 approach and in particular to understand how it uses the results of
9862 previous compilations without incorrectly depending on them.
9864 First a definition: an object file is considered @dfn{up to date} if the
9865 corresponding ALI file exists and if all the source files listed in the
9866 dependency section of this ALI file have time stamps matching those in
9867 the ALI file. This means that neither the source file itself nor any
9868 files that it depends on have been modified, and hence there is no need
9869 to recompile this file.
9871 @command{gnatmake} works by first checking if the specified main unit is up
9872 to date. If so, no compilations are required for the main unit. If not,
9873 @command{gnatmake} compiles the main program to build a new ALI file that
9874 reflects the latest sources. Then the ALI file of the main unit is
9875 examined to find all the source files on which the main program depends,
9876 and @command{gnatmake} recursively applies the above procedure on all these
9879 This process ensures that @command{gnatmake} only trusts the dependencies
9880 in an existing ALI file if they are known to be correct. Otherwise it
9881 always recompiles to determine a new, guaranteed accurate set of
9882 dependencies. As a result the program is compiled ``upside down'' from what may
9883 be more familiar as the required order of compilation in some other Ada
9884 systems. In particular, clients are compiled before the units on which
9885 they depend. The ability of GNAT to compile in any order is critical in
9886 allowing an order of compilation to be chosen that guarantees that
9887 @command{gnatmake} will recompute a correct set of new dependencies if
9890 When invoking @command{gnatmake} with several @var{file_names}, if a unit is
9891 imported by several of the executables, it will be recompiled at most once.
9893 Note: when using non-standard naming conventions
9894 (@pxref{Using Other File Names}), changing through a configuration pragmas
9895 file the version of a source and invoking @command{gnatmake} to recompile may
9896 have no effect, if the previous version of the source is still accessible
9897 by @command{gnatmake}. It may be necessary to use the switch
9898 ^-f^/FORCE_COMPILE^.
9900 @node Examples of gnatmake Usage
9901 @section Examples of @command{gnatmake} Usage
9904 @item gnatmake hello.adb
9905 Compile all files necessary to bind and link the main program
9906 @file{hello.adb} (containing unit @code{Hello}) and bind and link the
9907 resulting object files to generate an executable file @file{^hello^HELLO.EXE^}.
9909 @item gnatmake main1 main2 main3
9910 Compile all files necessary to bind and link the main programs
9911 @file{main1.adb} (containing unit @code{Main1}), @file{main2.adb}
9912 (containing unit @code{Main2}) and @file{main3.adb}
9913 (containing unit @code{Main3}) and bind and link the resulting object files
9914 to generate three executable files @file{^main1^MAIN1.EXE^},
9915 @file{^main2^MAIN2.EXE^}
9916 and @file{^main3^MAIN3.EXE^}.
9919 @item gnatmake -q Main_Unit -cargs -O2 -bargs -l
9923 @item gnatmake Main_Unit /QUIET
9924 /COMPILER_QUALIFIERS /OPTIMIZE=ALL
9925 /BINDER_QUALIFIERS /ORDER_OF_ELABORATION
9927 Compile all files necessary to bind and link the main program unit
9928 @code{Main_Unit} (from file @file{main_unit.adb}). All compilations will
9929 be done with optimization level 2 and the order of elaboration will be
9930 listed by the binder. @command{gnatmake} will operate in quiet mode, not
9931 displaying commands it is executing.
9934 @c *************************
9935 @node Improving Performance
9936 @chapter Improving Performance
9937 @cindex Improving performance
9940 This chapter presents several topics related to program performance.
9941 It first describes some of the tradeoffs that need to be considered
9942 and some of the techniques for making your program run faster.
9943 It then documents the @command{gnatelim} tool and unused subprogram/data
9944 elimination feature, which can reduce the size of program executables.
9948 * Performance Considerations::
9949 * Text_IO Suggestions::
9950 * Reducing Size of Ada Executables with gnatelim::
9951 * Reducing Size of Executables with unused subprogram/data elimination::
9955 @c *****************************
9956 @node Performance Considerations
9957 @section Performance Considerations
9960 The GNAT system provides a number of options that allow a trade-off
9965 performance of the generated code
9968 speed of compilation
9971 minimization of dependences and recompilation
9974 the degree of run-time checking.
9978 The defaults (if no options are selected) aim at improving the speed
9979 of compilation and minimizing dependences, at the expense of performance
9980 of the generated code:
9987 no inlining of subprogram calls
9990 all run-time checks enabled except overflow and elaboration checks
9994 These options are suitable for most program development purposes. This
9995 chapter describes how you can modify these choices, and also provides
9996 some guidelines on debugging optimized code.
9999 * Controlling Run-Time Checks::
10000 * Use of Restrictions::
10001 * Optimization Levels::
10002 * Debugging Optimized Code::
10003 * Inlining of Subprograms::
10004 * Vectorization of loops::
10005 * Other Optimization Switches::
10006 * Optimization and Strict Aliasing::
10007 * Aliased Variables and Optimization::
10010 * Coverage Analysis::
10014 @node Controlling Run-Time Checks
10015 @subsection Controlling Run-Time Checks
10018 By default, GNAT generates all run-time checks, except integer overflow
10019 checks, stack overflow checks, and checks for access before elaboration on
10020 subprogram calls. The latter are not required in default mode, because all
10021 necessary checking is done at compile time.
10022 @cindex @option{-gnatp} (@command{gcc})
10023 @cindex @option{-gnato} (@command{gcc})
10024 Two gnat switches, @option{-gnatp} and @option{-gnato} allow this default to
10025 be modified. @xref{Run-Time Checks}.
10027 Our experience is that the default is suitable for most development
10030 We treat integer overflow specially because these
10031 are quite expensive and in our experience are not as important as other
10032 run-time checks in the development process. Note that division by zero
10033 is not considered an overflow check, and divide by zero checks are
10034 generated where required by default.
10036 Elaboration checks are off by default, and also not needed by default, since
10037 GNAT uses a static elaboration analysis approach that avoids the need for
10038 run-time checking. This manual contains a full chapter discussing the issue
10039 of elaboration checks, and if the default is not satisfactory for your use,
10040 you should read this chapter.
10042 For validity checks, the minimal checks required by the Ada Reference
10043 Manual (for case statements and assignments to array elements) are on
10044 by default. These can be suppressed by use of the @option{-gnatVn} switch.
10045 Note that in Ada 83, there were no validity checks, so if the Ada 83 mode
10046 is acceptable (or when comparing GNAT performance with an Ada 83 compiler),
10047 it may be reasonable to routinely use @option{-gnatVn}. Validity checks
10048 are also suppressed entirely if @option{-gnatp} is used.
10050 @cindex Overflow checks
10051 @cindex Checks, overflow
10054 @cindex pragma Suppress
10055 @cindex pragma Unsuppress
10056 Note that the setting of the switches controls the default setting of
10057 the checks. They may be modified using either @code{pragma Suppress} (to
10058 remove checks) or @code{pragma Unsuppress} (to add back suppressed
10059 checks) in the program source.
10061 @node Use of Restrictions
10062 @subsection Use of Restrictions
10065 The use of pragma Restrictions allows you to control which features are
10066 permitted in your program. Apart from the obvious point that if you avoid
10067 relatively expensive features like finalization (enforceable by the use
10068 of pragma Restrictions (No_Finalization), the use of this pragma does not
10069 affect the generated code in most cases.
10071 One notable exception to this rule is that the possibility of task abort
10072 results in some distributed overhead, particularly if finalization or
10073 exception handlers are used. The reason is that certain sections of code
10074 have to be marked as non-abortable.
10076 If you use neither the @code{abort} statement, nor asynchronous transfer
10077 of control (@code{select @dots{} then abort}), then this distributed overhead
10078 is removed, which may have a general positive effect in improving
10079 overall performance. Especially code involving frequent use of tasking
10080 constructs and controlled types will show much improved performance.
10081 The relevant restrictions pragmas are
10083 @smallexample @c ada
10084 pragma Restrictions (No_Abort_Statements);
10085 pragma Restrictions (Max_Asynchronous_Select_Nesting => 0);
10089 It is recommended that these restriction pragmas be used if possible. Note
10090 that this also means that you can write code without worrying about the
10091 possibility of an immediate abort at any point.
10093 @node Optimization Levels
10094 @subsection Optimization Levels
10095 @cindex @option{^-O^/OPTIMIZE^} (@command{gcc})
10098 Without any optimization ^option,^qualifier,^
10099 the compiler's goal is to reduce the cost of
10100 compilation and to make debugging produce the expected results.
10101 Statements are independent: if you stop the program with a breakpoint between
10102 statements, you can then assign a new value to any variable or change
10103 the program counter to any other statement in the subprogram and get exactly
10104 the results you would expect from the source code.
10106 Turning on optimization makes the compiler attempt to improve the
10107 performance and/or code size at the expense of compilation time and
10108 possibly the ability to debug the program.
10110 If you use multiple
10111 ^-O options, with or without level numbers,^/OPTIMIZE qualifiers,^
10112 the last such option is the one that is effective.
10115 The default is optimization off. This results in the fastest compile
10116 times, but GNAT makes absolutely no attempt to optimize, and the
10117 generated programs are considerably larger and slower than when
10118 optimization is enabled. You can use the
10120 @option{-O} switch (the permitted forms are @option{-O0}, @option{-O1}
10121 @option{-O2}, @option{-O3}, and @option{-Os})
10124 @code{OPTIMIZE} qualifier
10126 to @command{gcc} to control the optimization level:
10129 @item ^-O0^/OPTIMIZE=NONE^
10130 No optimization (the default);
10131 generates unoptimized code but has
10132 the fastest compilation time.
10134 Note that many other compilers do fairly extensive optimization
10135 even if ``no optimization'' is specified. With gcc, it is
10136 very unusual to use ^-O0^/OPTIMIZE=NONE^ for production if
10137 execution time is of any concern, since ^-O0^/OPTIMIZE=NONE^
10138 really does mean no optimization at all. This difference between
10139 gcc and other compilers should be kept in mind when doing
10140 performance comparisons.
10142 @item ^-O1^/OPTIMIZE=SOME^
10143 Moderate optimization;
10144 optimizes reasonably well but does not
10145 degrade compilation time significantly.
10147 @item ^-O2^/OPTIMIZE=ALL^
10149 @itemx /OPTIMIZE=DEVELOPMENT
10152 generates highly optimized code and has
10153 the slowest compilation time.
10155 @item ^-O3^/OPTIMIZE=INLINING^
10156 Full optimization as in @option{-O2};
10157 also uses more aggressive automatic inlining of subprograms within a unit
10158 (@pxref{Inlining of Subprograms}) and attempts to vectorize loops.
10160 @item ^-Os^/OPTIMIZE=SPACE^
10161 Optimize space usage (code and data) of resulting program.
10165 Higher optimization levels perform more global transformations on the
10166 program and apply more expensive analysis algorithms in order to generate
10167 faster and more compact code. The price in compilation time, and the
10168 resulting improvement in execution time,
10169 both depend on the particular application and the hardware environment.
10170 You should experiment to find the best level for your application.
10172 Since the precise set of optimizations done at each level will vary from
10173 release to release (and sometime from target to target), it is best to think
10174 of the optimization settings in general terms.
10175 @xref{Optimize Options,, Options That Control Optimization, gcc, Using
10176 the GNU Compiler Collection (GCC)}, for details about
10177 ^the @option{-O} settings and a number of @option{-f} options that^how to^
10178 individually enable or disable specific optimizations.
10180 Unlike some other compilation systems, ^@command{gcc}^GNAT^ has
10181 been tested extensively at all optimization levels. There are some bugs
10182 which appear only with optimization turned on, but there have also been
10183 bugs which show up only in @emph{unoptimized} code. Selecting a lower
10184 level of optimization does not improve the reliability of the code
10185 generator, which in practice is highly reliable at all optimization
10188 Note regarding the use of @option{-O3}: The use of this optimization level
10189 is generally discouraged with GNAT, since it often results in larger
10190 executables which may run more slowly. See further discussion of this point
10191 in @ref{Inlining of Subprograms}.
10193 @node Debugging Optimized Code
10194 @subsection Debugging Optimized Code
10195 @cindex Debugging optimized code
10196 @cindex Optimization and debugging
10199 Although it is possible to do a reasonable amount of debugging at
10201 nonzero optimization levels,
10202 the higher the level the more likely that
10205 @option{/OPTIMIZE} settings other than @code{NONE},
10206 such settings will make it more likely that
10208 source-level constructs will have been eliminated by optimization.
10209 For example, if a loop is strength-reduced, the loop
10210 control variable may be completely eliminated and thus cannot be
10211 displayed in the debugger.
10212 This can only happen at @option{-O2} or @option{-O3}.
10213 Explicit temporary variables that you code might be eliminated at
10214 ^level^setting^ @option{-O1} or higher.
10216 The use of the @option{^-g^/DEBUG^} switch,
10217 @cindex @option{^-g^/DEBUG^} (@command{gcc})
10218 which is needed for source-level debugging,
10219 affects the size of the program executable on disk,
10220 and indeed the debugging information can be quite large.
10221 However, it has no effect on the generated code (and thus does not
10222 degrade performance)
10224 Since the compiler generates debugging tables for a compilation unit before
10225 it performs optimizations, the optimizing transformations may invalidate some
10226 of the debugging data. You therefore need to anticipate certain
10227 anomalous situations that may arise while debugging optimized code.
10228 These are the most common cases:
10232 @i{The ``hopping Program Counter'':} Repeated @code{step} or @code{next}
10234 the PC bouncing back and forth in the code. This may result from any of
10235 the following optimizations:
10239 @i{Common subexpression elimination:} using a single instance of code for a
10240 quantity that the source computes several times. As a result you
10241 may not be able to stop on what looks like a statement.
10244 @i{Invariant code motion:} moving an expression that does not change within a
10245 loop, to the beginning of the loop.
10248 @i{Instruction scheduling:} moving instructions so as to
10249 overlap loads and stores (typically) with other code, or in
10250 general to move computations of values closer to their uses. Often
10251 this causes you to pass an assignment statement without the assignment
10252 happening and then later bounce back to the statement when the
10253 value is actually needed. Placing a breakpoint on a line of code
10254 and then stepping over it may, therefore, not always cause all the
10255 expected side-effects.
10259 @i{The ``big leap'':} More commonly known as @emph{cross-jumping}, in which
10260 two identical pieces of code are merged and the program counter suddenly
10261 jumps to a statement that is not supposed to be executed, simply because
10262 it (and the code following) translates to the same thing as the code
10263 that @emph{was} supposed to be executed. This effect is typically seen in
10264 sequences that end in a jump, such as a @code{goto}, a @code{return}, or
10265 a @code{break} in a C @code{^switch^switch^} statement.
10268 @i{The ``roving variable'':} The symptom is an unexpected value in a variable.
10269 There are various reasons for this effect:
10273 In a subprogram prologue, a parameter may not yet have been moved to its
10277 A variable may be dead, and its register re-used. This is
10278 probably the most common cause.
10281 As mentioned above, the assignment of a value to a variable may
10285 A variable may be eliminated entirely by value propagation or
10286 other means. In this case, GCC may incorrectly generate debugging
10287 information for the variable
10291 In general, when an unexpected value appears for a local variable or parameter
10292 you should first ascertain if that value was actually computed by
10293 your program, as opposed to being incorrectly reported by the debugger.
10295 array elements in an object designated by an access value
10296 are generally less of a problem, once you have ascertained that the access
10298 Typically, this means checking variables in the preceding code and in the
10299 calling subprogram to verify that the value observed is explainable from other
10300 values (one must apply the procedure recursively to those
10301 other values); or re-running the code and stopping a little earlier
10302 (perhaps before the call) and stepping to better see how the variable obtained
10303 the value in question; or continuing to step @emph{from} the point of the
10304 strange value to see if code motion had simply moved the variable's
10309 In light of such anomalies, a recommended technique is to use @option{-O0}
10310 early in the software development cycle, when extensive debugging capabilities
10311 are most needed, and then move to @option{-O1} and later @option{-O2} as
10312 the debugger becomes less critical.
10313 Whether to use the @option{^-g^/DEBUG^} switch in the release version is
10314 a release management issue.
10316 Note that if you use @option{-g} you can then use the @command{strip} program
10317 on the resulting executable,
10318 which removes both debugging information and global symbols.
10321 @node Inlining of Subprograms
10322 @subsection Inlining of Subprograms
10325 A call to a subprogram in the current unit is inlined if all the
10326 following conditions are met:
10330 The optimization level is at least @option{-O1}.
10333 The called subprogram is suitable for inlining: It must be small enough
10334 and not contain something that @command{gcc} cannot support in inlined
10338 @cindex pragma Inline
10340 Any one of the following applies: @code{pragma Inline} is applied to the
10341 subprogram and the @option{^-gnatn^/INLINE^} switch is specified; the
10342 subprogram is local to the unit and called once from within it; the
10343 subprogram is small and optimization level @option{-O2} is specified;
10344 optimization level @option{-O3} is specified.
10348 Calls to subprograms in @code{with}'ed units are normally not inlined.
10349 To achieve actual inlining (that is, replacement of the call by the code
10350 in the body of the subprogram), the following conditions must all be true:
10354 The optimization level is at least @option{-O1}.
10357 The called subprogram is suitable for inlining: It must be small enough
10358 and not contain something that @command{gcc} cannot support in inlined
10362 The call appears in a body (not in a package spec).
10365 There is a @code{pragma Inline} for the subprogram.
10368 The @option{^-gnatn^/INLINE^} switch is used on the command line.
10371 Even if all these conditions are met, it may not be possible for
10372 the compiler to inline the call, due to the length of the body,
10373 or features in the body that make it impossible for the compiler
10374 to do the inlining.
10376 Note that specifying the @option{-gnatn} switch causes additional
10377 compilation dependencies. Consider the following:
10379 @smallexample @c ada
10399 With the default behavior (no @option{-gnatn} switch specified), the
10400 compilation of the @code{Main} procedure depends only on its own source,
10401 @file{main.adb}, and the spec of the package in file @file{r.ads}. This
10402 means that editing the body of @code{R} does not require recompiling
10405 On the other hand, the call @code{R.Q} is not inlined under these
10406 circumstances. If the @option{-gnatn} switch is present when @code{Main}
10407 is compiled, the call will be inlined if the body of @code{Q} is small
10408 enough, but now @code{Main} depends on the body of @code{R} in
10409 @file{r.adb} as well as on the spec. This means that if this body is edited,
10410 the main program must be recompiled. Note that this extra dependency
10411 occurs whether or not the call is in fact inlined by @command{gcc}.
10413 The use of front end inlining with @option{-gnatN} generates similar
10414 additional dependencies.
10416 @cindex @option{^-fno-inline^/INLINE=SUPPRESS^} (@command{gcc})
10417 Note: The @option{^-fno-inline^/INLINE=SUPPRESS^} switch
10418 can be used to prevent
10419 all inlining. This switch overrides all other conditions and ensures
10420 that no inlining occurs. The extra dependences resulting from
10421 @option{-gnatn} will still be active, even if
10422 this switch is used to suppress the resulting inlining actions.
10424 @cindex @option{-fno-inline-functions} (@command{gcc})
10425 Note: The @option{-fno-inline-functions} switch can be used to prevent
10426 automatic inlining of subprograms if @option{-O3} is used.
10428 @cindex @option{-fno-inline-small-functions} (@command{gcc})
10429 Note: The @option{-fno-inline-small-functions} switch can be used to prevent
10430 automatic inlining of small subprograms if @option{-O2} is used.
10432 @cindex @option{-fno-inline-functions-called-once} (@command{gcc})
10433 Note: The @option{-fno-inline-functions-called-once} switch
10434 can be used to prevent inlining of subprograms local to the unit
10435 and called once from within it if @option{-O1} is used.
10437 Note regarding the use of @option{-O3}: @option{-gnatn} is made up of two
10438 sub-switches @option{-gnatn1} and @option{-gnatn2} that can be directly
10439 specified in lieu of it, @option{-gnatn} being translated into one of them
10440 based on the optimization level. With @option{-O2} or below, @option{-gnatn}
10441 is equivalent to @option{-gnatn1} which activates pragma @code{Inline} with
10442 moderate inlining across modules. With @option{-O3}, @option{-gnatn} is
10443 equivalent to @option{-gnatn2} which activates pragma @code{Inline} with
10444 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
10445 effect of inlining subprograms you did not think should be inlined. We have
10446 found that the use of @option{-O3} may slow down the compilation and increase
10447 the code size by performing excessive inlining, leading to increased
10448 instruction cache pressure from the increased code size and thus minor
10449 performance improvements. So the bottom line here is that you should not
10450 automatically assume that @option{-O3} is better than @option{-O2}, and
10451 indeed you should use @option{-O3} only if tests show that it actually
10452 improves performance for your program.
10454 @node Vectorization of loops
10455 @subsection Vectorization of loops
10456 @cindex Optimization Switches
10458 You can take advantage of the auto-vectorizer present in the @command{gcc}
10459 back end to vectorize loops with GNAT. The corresponding command line switch
10460 is @option{-ftree-vectorize} but, as it is enabled by default at @option{-O3}
10461 and other aggressive optimizations helpful for vectorization also are enabled
10462 by default at this level, using @option{-O3} directly is recommended.
10464 You also need to make sure that the target architecture features a supported
10465 SIMD instruction set. For example, for the x86 architecture, you should at
10466 least specify @option{-msse2} to get significant vectorization (but you don't
10467 need to specify it for x86-64 as it is part of the base 64-bit architecture).
10468 Similarly, for the PowerPC architecture, you should specify @option{-maltivec}.
10470 The preferred loop form for vectorization is the @code{for} iteration scheme.
10471 Loops with a @code{while} iteration scheme can also be vectorized if they are
10472 very simple, but the vectorizer will quickly give up otherwise. With either
10473 iteration scheme, the flow of control must be straight, in particular no
10474 @code{exit} statement may appear in the loop body. The loop may however
10475 contain a single nested loop, if it can be vectorized when considered alone:
10477 @smallexample @c ada
10479 A : array (1..4, 1..4) of Long_Float;
10480 S : array (1..4) of Long_Float;
10484 for I in A'Range(1) loop
10485 for J in A'Range(2) loop
10486 S (I) := S (I) + A (I, J);
10493 The vectorizable operations depend on the targeted SIMD instruction set, but
10494 the adding and some of the multiplying operators are generally supported, as
10495 well as the logical operators for modular types. Note that, in the former
10496 case, enabling overflow checks, for example with @option{-gnato}, totally
10497 disables vectorization. The other checks are not supposed to have the same
10498 definitive effect, although compiling with @option{-gnatp} might well reveal
10499 cases where some checks do thwart vectorization.
10501 Type conversions may also prevent vectorization if they involve semantics that
10502 are not directly supported by the code generator or the SIMD instruction set.
10503 A typical example is direct conversion from floating-point to integer types.
10504 The solution in this case is to use the following idiom:
10506 @smallexample @c ada
10507 Integer (S'Truncation (F))
10511 if @code{S} is the subtype of floating-point object @code{F}.
10513 In most cases, the vectorizable loops are loops that iterate over arrays.
10514 All kinds of array types are supported, i.e. constrained array types with
10517 @smallexample @c ada
10518 type Array_Type is array (1 .. 4) of Long_Float;
10522 constrained array types with dynamic bounds:
10524 @smallexample @c ada
10525 type Array_Type is array (1 .. Q.N) of Long_Float;
10527 type Array_Type is array (Q.K .. 4) of Long_Float;
10529 type Array_Type is array (Q.K .. Q.N) of Long_Float;
10533 or unconstrained array types:
10535 @smallexample @c ada
10536 type Array_Type is array (Positive range <>) of Long_Float;
10540 The quality of the generated code decreases when the dynamic aspect of the
10541 array type increases, the worst code being generated for unconstrained array
10542 types. This is so because, the less information the compiler has about the
10543 bounds of the array, the more fallback code it needs to generate in order to
10544 fix things up at run time.
10546 It is possible to specify that a given loop should be subject to vectorization
10547 preferably to other optimizations by means of pragma @code{Loop_Optimize}:
10549 @smallexample @c ada
10550 pragma Loop_Optimize (Vector);
10554 placed immediately within the loop will convey the appropriate hint to the
10555 compiler for this loop.
10557 You can obtain information about the vectorization performed by the compiler
10558 by specifying @option{-ftree-vectorizer-verbose=N}. For more details of
10559 this switch, see @ref{Debugging Options,,Options for Debugging Your Program
10560 or GCC, gcc, Using the GNU Compiler Collection (GCC)}.
10562 @node Other Optimization Switches
10563 @subsection Other Optimization Switches
10564 @cindex Optimization Switches
10566 Since @code{GNAT} uses the @command{gcc} back end, all the specialized
10567 @command{gcc} optimization switches are potentially usable. These switches
10568 have not been extensively tested with GNAT but can generally be expected
10569 to work. Examples of switches in this category are @option{-funroll-loops}
10570 and the various target-specific @option{-m} options (in particular, it has
10571 been observed that @option{-march=xxx} can significantly improve performance
10572 on appropriate machines). For full details of these switches, see
10573 @ref{Submodel Options,, Hardware Models and Configurations, gcc, Using
10574 the GNU Compiler Collection (GCC)}.
10576 @node Optimization and Strict Aliasing
10577 @subsection Optimization and Strict Aliasing
10579 @cindex Strict Aliasing
10580 @cindex No_Strict_Aliasing
10583 The strong typing capabilities of Ada allow an optimizer to generate
10584 efficient code in situations where other languages would be forced to
10585 make worst case assumptions preventing such optimizations. Consider
10586 the following example:
10588 @smallexample @c ada
10591 type Int1 is new Integer;
10592 type Int2 is new Integer;
10593 type Int1A is access Int1;
10594 type Int2A is access Int2;
10601 for J in Data'Range loop
10602 if Data (J) = Int1V.all then
10603 Int2V.all := Int2V.all + 1;
10612 In this example, since the variable @code{Int1V} can only access objects
10613 of type @code{Int1}, and @code{Int2V} can only access objects of type
10614 @code{Int2}, there is no possibility that the assignment to
10615 @code{Int2V.all} affects the value of @code{Int1V.all}. This means that
10616 the compiler optimizer can "know" that the value @code{Int1V.all} is constant
10617 for all iterations of the loop and avoid the extra memory reference
10618 required to dereference it each time through the loop.
10620 This kind of optimization, called strict aliasing analysis, is
10621 triggered by specifying an optimization level of @option{-O2} or
10622 higher or @option{-Os} and allows @code{GNAT} to generate more efficient code
10623 when access values are involved.
10625 However, although this optimization is always correct in terms of
10626 the formal semantics of the Ada Reference Manual, difficulties can
10627 arise if features like @code{Unchecked_Conversion} are used to break
10628 the typing system. Consider the following complete program example:
10630 @smallexample @c ada
10633 type int1 is new integer;
10634 type int2 is new integer;
10635 type a1 is access int1;
10636 type a2 is access int2;
10641 function to_a2 (Input : a1) return a2;
10644 with Unchecked_Conversion;
10646 function to_a2 (Input : a1) return a2 is
10648 new Unchecked_Conversion (a1, a2);
10650 return to_a2u (Input);
10656 with Text_IO; use Text_IO;
10658 v1 : a1 := new int1;
10659 v2 : a2 := to_a2 (v1);
10663 put_line (int1'image (v1.all));
10669 This program prints out 0 in @option{-O0} or @option{-O1}
10670 mode, but it prints out 1 in @option{-O2} mode. That's
10671 because in strict aliasing mode, the compiler can and
10672 does assume that the assignment to @code{v2.all} could not
10673 affect the value of @code{v1.all}, since different types
10676 This behavior is not a case of non-conformance with the standard, since
10677 the Ada RM specifies that an unchecked conversion where the resulting
10678 bit pattern is not a correct value of the target type can result in an
10679 abnormal value and attempting to reference an abnormal value makes the
10680 execution of a program erroneous. That's the case here since the result
10681 does not point to an object of type @code{int2}. This means that the
10682 effect is entirely unpredictable.
10684 However, although that explanation may satisfy a language
10685 lawyer, in practice an applications programmer expects an
10686 unchecked conversion involving pointers to create true
10687 aliases and the behavior of printing 1 seems plain wrong.
10688 In this case, the strict aliasing optimization is unwelcome.
10690 Indeed the compiler recognizes this possibility, and the
10691 unchecked conversion generates a warning:
10694 p2.adb:5:07: warning: possible aliasing problem with type "a2"
10695 p2.adb:5:07: warning: use -fno-strict-aliasing switch for references
10696 p2.adb:5:07: warning: or use "pragma No_Strict_Aliasing (a2);"
10700 Unfortunately the problem is recognized when compiling the body of
10701 package @code{p2}, but the actual "bad" code is generated while
10702 compiling the body of @code{m} and this latter compilation does not see
10703 the suspicious @code{Unchecked_Conversion}.
10705 As implied by the warning message, there are approaches you can use to
10706 avoid the unwanted strict aliasing optimization in a case like this.
10708 One possibility is to simply avoid the use of @option{-O2}, but
10709 that is a bit drastic, since it throws away a number of useful
10710 optimizations that do not involve strict aliasing assumptions.
10712 A less drastic approach is to compile the program using the
10713 option @option{-fno-strict-aliasing}. Actually it is only the
10714 unit containing the dereferencing of the suspicious pointer
10715 that needs to be compiled. So in this case, if we compile
10716 unit @code{m} with this switch, then we get the expected
10717 value of zero printed. Analyzing which units might need
10718 the switch can be painful, so a more reasonable approach
10719 is to compile the entire program with options @option{-O2}
10720 and @option{-fno-strict-aliasing}. If the performance is
10721 satisfactory with this combination of options, then the
10722 advantage is that the entire issue of possible "wrong"
10723 optimization due to strict aliasing is avoided.
10725 To avoid the use of compiler switches, the configuration
10726 pragma @code{No_Strict_Aliasing} with no parameters may be
10727 used to specify that for all access types, the strict
10728 aliasing optimization should be suppressed.
10730 However, these approaches are still overkill, in that they causes
10731 all manipulations of all access values to be deoptimized. A more
10732 refined approach is to concentrate attention on the specific
10733 access type identified as problematic.
10735 First, if a careful analysis of uses of the pointer shows
10736 that there are no possible problematic references, then
10737 the warning can be suppressed by bracketing the
10738 instantiation of @code{Unchecked_Conversion} to turn
10741 @smallexample @c ada
10742 pragma Warnings (Off);
10744 new Unchecked_Conversion (a1, a2);
10745 pragma Warnings (On);
10749 Of course that approach is not appropriate for this particular
10750 example, since indeed there is a problematic reference. In this
10751 case we can take one of two other approaches.
10753 The first possibility is to move the instantiation of unchecked
10754 conversion to the unit in which the type is declared. In
10755 this example, we would move the instantiation of
10756 @code{Unchecked_Conversion} from the body of package
10757 @code{p2} to the spec of package @code{p1}. Now the
10758 warning disappears. That's because any use of the
10759 access type knows there is a suspicious unchecked
10760 conversion, and the strict aliasing optimization
10761 is automatically suppressed for the type.
10763 If it is not practical to move the unchecked conversion to the same unit
10764 in which the destination access type is declared (perhaps because the
10765 source type is not visible in that unit), you may use pragma
10766 @code{No_Strict_Aliasing} for the type. This pragma must occur in the
10767 same declarative sequence as the declaration of the access type:
10769 @smallexample @c ada
10770 type a2 is access int2;
10771 pragma No_Strict_Aliasing (a2);
10775 Here again, the compiler now knows that the strict aliasing optimization
10776 should be suppressed for any reference to type @code{a2} and the
10777 expected behavior is obtained.
10779 Finally, note that although the compiler can generate warnings for
10780 simple cases of unchecked conversions, there are tricker and more
10781 indirect ways of creating type incorrect aliases which the compiler
10782 cannot detect. Examples are the use of address overlays and unchecked
10783 conversions involving composite types containing access types as
10784 components. In such cases, no warnings are generated, but there can
10785 still be aliasing problems. One safe coding practice is to forbid the
10786 use of address clauses for type overlaying, and to allow unchecked
10787 conversion only for primitive types. This is not really a significant
10788 restriction since any possible desired effect can be achieved by
10789 unchecked conversion of access values.
10791 The aliasing analysis done in strict aliasing mode can certainly
10792 have significant benefits. We have seen cases of large scale
10793 application code where the time is increased by up to 5% by turning
10794 this optimization off. If you have code that includes significant
10795 usage of unchecked conversion, you might want to just stick with
10796 @option{-O1} and avoid the entire issue. If you get adequate
10797 performance at this level of optimization level, that's probably
10798 the safest approach. If tests show that you really need higher
10799 levels of optimization, then you can experiment with @option{-O2}
10800 and @option{-O2 -fno-strict-aliasing} to see how much effect this
10801 has on size and speed of the code. If you really need to use
10802 @option{-O2} with strict aliasing in effect, then you should
10803 review any uses of unchecked conversion of access types,
10804 particularly if you are getting the warnings described above.
10806 @node Aliased Variables and Optimization
10807 @subsection Aliased Variables and Optimization
10809 There are scenarios in which programs may
10810 use low level techniques to modify variables
10811 that otherwise might be considered to be unassigned. For example,
10812 a variable can be passed to a procedure by reference, which takes
10813 the address of the parameter and uses the address to modify the
10814 variable's value, even though it is passed as an IN parameter.
10815 Consider the following example:
10817 @smallexample @c ada
10819 Max_Length : constant Natural := 16;
10820 type Char_Ptr is access all Character;
10822 procedure Get_String(Buffer: Char_Ptr; Size : Integer);
10823 pragma Import (C, Get_String, "get_string");
10825 Name : aliased String (1 .. Max_Length) := (others => ' ');
10828 function Addr (S : String) return Char_Ptr is
10829 function To_Char_Ptr is
10830 new Ada.Unchecked_Conversion (System.Address, Char_Ptr);
10832 return To_Char_Ptr (S (S'First)'Address);
10836 Temp := Addr (Name);
10837 Get_String (Temp, Max_Length);
10842 where Get_String is a C function that uses the address in Temp to
10843 modify the variable @code{Name}. This code is dubious, and arguably
10844 erroneous, and the compiler would be entitled to assume that
10845 @code{Name} is never modified, and generate code accordingly.
10847 However, in practice, this would cause some existing code that
10848 seems to work with no optimization to start failing at high
10849 levels of optimzization.
10851 What the compiler does for such cases is to assume that marking
10852 a variable as aliased indicates that some "funny business" may
10853 be going on. The optimizer recognizes the aliased keyword and
10854 inhibits optimizations that assume the value cannot be assigned.
10855 This means that the above example will in fact "work" reliably,
10856 that is, it will produce the expected results.
10859 @node Coverage Analysis
10860 @subsection Coverage Analysis
10863 GNAT supports the HP Performance Coverage Analyzer (PCA), which allows
10864 the user to determine the distribution of execution time across a program,
10865 @pxref{Profiling} for details of usage.
10869 @node Text_IO Suggestions
10870 @section @code{Text_IO} Suggestions
10871 @cindex @code{Text_IO} and performance
10874 The @code{Ada.Text_IO} package has fairly high overheads due in part to
10875 the requirement of maintaining page and line counts. If performance
10876 is critical, a recommendation is to use @code{Stream_IO} instead of
10877 @code{Text_IO} for volume output, since this package has less overhead.
10879 If @code{Text_IO} must be used, note that by default output to the standard
10880 output and standard error files is unbuffered (this provides better
10881 behavior when output statements are used for debugging, or if the
10882 progress of a program is observed by tracking the output, e.g. by
10883 using the Unix @command{tail -f} command to watch redirected output.
10885 If you are generating large volumes of output with @code{Text_IO} and
10886 performance is an important factor, use a designated file instead
10887 of the standard output file, or change the standard output file to
10888 be buffered using @code{Interfaces.C_Streams.setvbuf}.
10892 @node Reducing Size of Ada Executables with gnatelim
10893 @section Reducing Size of Ada Executables with @code{gnatelim}
10897 This section describes @command{gnatelim}, a tool which detects unused
10898 subprograms and helps the compiler to create a smaller executable for your
10903 * Running gnatelim::
10904 * Processing Precompiled Libraries::
10905 * Correcting the List of Eliminate Pragmas::
10906 * Making Your Executables Smaller::
10907 * Summary of the gnatelim Usage Cycle::
10910 @node About gnatelim
10911 @subsection About @code{gnatelim}
10914 When a program shares a set of Ada
10915 packages with other programs, it may happen that this program uses
10916 only a fraction of the subprograms defined in these packages. The code
10917 created for these unused subprograms increases the size of the executable.
10919 @code{gnatelim} tracks unused subprograms in an Ada program and
10920 outputs a list of GNAT-specific pragmas @code{Eliminate} marking all the
10921 subprograms that are declared but never called. By placing the list of
10922 @code{Eliminate} pragmas in the GNAT configuration file @file{gnat.adc} and
10923 recompiling your program, you may decrease the size of its executable,
10924 because the compiler will not generate the code for 'eliminated' subprograms.
10925 @xref{Pragma Eliminate,,, gnat_rm, GNAT Reference Manual}, for more
10926 information about this pragma.
10928 @code{gnatelim} needs as its input data the name of the main subprogram.
10930 If a set of source files is specified as @code{gnatelim} arguments, it
10931 treats these files as a complete set of sources making up a program to
10932 analyse, and analyses only these sources.
10934 After a full successful build of the main subprogram @code{gnatelim} can be
10935 called without specifying sources to analyse, in this case it computes
10936 the source closure of the main unit from the @file{ALI} files.
10938 The following command will create the set of @file{ALI} files needed for
10942 $ gnatmake ^-c Main_Prog^/ACTIONS=COMPILE MAIN_PROG^
10945 Note that @code{gnatelim} does not need object files.
10947 @node Running gnatelim
10948 @subsection Running @code{gnatelim}
10951 @code{gnatelim} has the following command-line interface:
10954 $ gnatelim [@var{switches}] ^-main^?MAIN^=@var{main_unit_name} @{@var{filename}@} @r{[}-cargs @var{gcc_switches}@r{]}
10958 @var{main_unit_name} should be a name of a source file that contains the main
10959 subprogram of a program (partition).
10961 Each @var{filename} is the name (including the extension) of a source
10962 file to process. ``Wildcards'' are allowed, and
10963 the file name may contain path information.
10965 @samp{@var{gcc_switches}} is a list of switches for
10966 @command{gcc}. They will be passed on to all compiler invocations made by
10967 @command{gnatelim} to generate the ASIS trees. Here you can provide
10968 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
10969 use the @option{-gnatec} switch to set the configuration file,
10970 use the @option{-gnat05} switch if sources should be compiled in
10973 @code{gnatelim} has the following switches:
10978 @cindex @option{--version} @command{gnatelim}
10979 Display Copyright and version, then exit disregarding all other options.
10982 @cindex @option{--help} @command{gnatelim}
10983 Display usage, then exit disregarding all other options.
10985 @item ^-files^/FILES^=@var{filename}
10986 @cindex @option{^-files^/FILES^} (@code{gnatelim})
10987 Take the argument source files from the specified file. This file should be an
10988 ordinary text file containing file names separated by spaces or
10989 line breaks. You can use this switch more than once in the same call to
10990 @command{gnatelim}. You also can combine this switch with
10991 an explicit list of files.
10994 @cindex @option{^-log^/LOG^} (@command{gnatelim})
10995 Duplicate all the output sent to @file{stderr} into a log file. The log file
10996 is named @file{gnatelim.log} and is located in the current directory.
10998 @item ^-log^/LOGFILE^=@var{filename}
10999 @cindex @option{^-log^/LOGFILE^} (@command{gnatelim})
11000 Duplicate all the output sent to @file{stderr} into a specified log file.
11002 @cindex @option{^--no-elim-dispatch^/NO_DISPATCH^} (@command{gnatelim})
11003 @item ^--no-elim-dispatch^/NO_DISPATCH^
11004 Do not generate pragmas for dispatching operations.
11006 @item ^--ignore^/IGNORE^=@var{filename}
11007 @cindex @option{^--ignore^/IGNORE^} (@command{gnatelim})
11008 Do not generate pragmas for subprograms declared in the sources
11009 listed in a specified file
11011 @cindex @option{^-o^/OUTPUT^} (@command{gnatelim})
11012 @item ^-o^/OUTPUT^=@var{report_file}
11013 Put @command{gnatelim} output into a specified file. If this file already exists,
11014 it is overridden. If this switch is not used, @command{gnatelim} outputs its results
11018 @cindex @option{^-q^/QUIET^} (@command{gnatelim})
11019 Quiet mode: by default @code{gnatelim} outputs to the standard error
11020 stream the number of program units left to be processed. This option turns
11023 @cindex @option{^-t^/TIME^} (@command{gnatelim})
11025 Print out execution time.
11027 @item ^-v^/VERBOSE^
11028 @cindex @option{^-v^/VERBOSE^} (@command{gnatelim})
11029 Verbose mode: @code{gnatelim} version information is printed as Ada
11030 comments to the standard output stream. Also, in addition to the number of
11031 program units left @code{gnatelim} will output the name of the current unit
11034 @item ^-wq^/WARNINGS=QUIET^
11035 @cindex @option{^-wq^/WARNINGS=QUIET^} (@command{gnatelim})
11036 Quiet warning mode - some warnings are suppressed. In particular warnings that
11037 indicate that the analysed set of sources is incomplete to make up a
11038 partition and that some subprogram bodies are missing are not generated.
11042 Note: to invoke @command{gnatelim} with a project file, use the @code{gnat}
11043 driver (see @ref{The GNAT Driver and Project Files}).
11045 @node Processing Precompiled Libraries
11046 @subsection Processing Precompiled Libraries
11049 If some program uses a precompiled Ada library, it can be processed by
11050 @code{gnatelim} in a usual way. @code{gnatelim} will newer generate an
11051 Eliminate pragma for a subprogram if the body of this subprogram has not
11052 been analysed, this is a typical case for subprograms from precompiled
11053 libraries. Switch @option{^-wq^/WARNINGS=QUIET^} may be used to suppress
11054 warnings about missing source files and non-analyzed subprogram bodies
11055 that can be generated when processing precompiled Ada libraries.
11057 @node Correcting the List of Eliminate Pragmas
11058 @subsection Correcting the List of Eliminate Pragmas
11061 In some rare cases @code{gnatelim} may try to eliminate
11062 subprograms that are actually called in the program. In this case, the
11063 compiler will generate an error message of the form:
11066 main.adb:4:08: cannot reference subprogram "P" eliminated at elim.out:5
11070 You will need to manually remove the wrong @code{Eliminate} pragmas from
11071 the configuration file indicated in the error message. You should recompile
11072 your program from scratch after that, because you need a consistent
11073 configuration file(s) during the entire compilation.
11075 @node Making Your Executables Smaller
11076 @subsection Making Your Executables Smaller
11079 In order to get a smaller executable for your program you now have to
11080 recompile the program completely with the configuration file containing
11081 pragmas Eliminate generated by gnatelim. If these pragmas are placed in
11082 @file{gnat.adc} file located in your current directory, just do:
11085 $ gnatmake ^-f main_prog^/FORCE_COMPILE MAIN_PROG^
11089 (Use the @option{^-f^/FORCE_COMPILE^} option for @command{gnatmake} to
11090 recompile everything
11091 with the set of pragmas @code{Eliminate} that you have obtained with
11092 @command{gnatelim}).
11094 Be aware that the set of @code{Eliminate} pragmas is specific to each
11095 program. It is not recommended to merge sets of @code{Eliminate}
11096 pragmas created for different programs in one configuration file.
11098 @node Summary of the gnatelim Usage Cycle
11099 @subsection Summary of the @code{gnatelim} Usage Cycle
11102 Here is a quick summary of the steps to be taken in order to reduce
11103 the size of your executables with @code{gnatelim}. You may use
11104 other GNAT options to control the optimization level,
11105 to produce the debugging information, to set search path, etc.
11109 Create a complete set of @file{ALI} files (if the program has not been
11113 $ gnatmake ^-c main_prog^/ACTIONS=COMPILE MAIN_PROG^
11117 Generate a list of @code{Eliminate} pragmas in default configuration file
11118 @file{gnat.adc} in the current directory
11121 $ PIPE GNAT ELIM MAIN_PROG > GNAT.ADC
11124 $ gnatelim main_prog >@r{[}>@r{]} gnat.adc
11129 Recompile the application
11132 $ gnatmake ^-f main_prog^/FORCE_COMPILE MAIN_PROG^
11137 @node Reducing Size of Executables with unused subprogram/data elimination
11138 @section Reducing Size of Executables with Unused Subprogram/Data Elimination
11139 @findex unused subprogram/data elimination
11142 This section describes how you can eliminate unused subprograms and data from
11143 your executable just by setting options at compilation time.
11146 * About unused subprogram/data elimination::
11147 * Compilation options::
11148 * Example of unused subprogram/data elimination::
11151 @node About unused subprogram/data elimination
11152 @subsection About unused subprogram/data elimination
11155 By default, an executable contains all code and data of its composing objects
11156 (directly linked or coming from statically linked libraries), even data or code
11157 never used by this executable.
11159 This feature will allow you to eliminate such unused code from your
11160 executable, making it smaller (in disk and in memory).
11162 This functionality is available on all Linux platforms except for the IA-64
11163 architecture and on all cross platforms using the ELF binary file format.
11164 In both cases GNU binutils version 2.16 or later are required to enable it.
11166 @node Compilation options
11167 @subsection Compilation options
11170 The operation of eliminating the unused code and data from the final executable
11171 is directly performed by the linker.
11173 In order to do this, it has to work with objects compiled with the
11175 @option{-ffunction-sections} @option{-fdata-sections}.
11176 @cindex @option{-ffunction-sections} (@command{gcc})
11177 @cindex @option{-fdata-sections} (@command{gcc})
11178 These options are usable with C and Ada files.
11179 They will place respectively each
11180 function or data in a separate section in the resulting object file.
11182 Once the objects and static libraries are created with these options, the
11183 linker can perform the dead code elimination. You can do this by setting
11184 the @option{-Wl,--gc-sections} option to gcc command or in the
11185 @option{-largs} section of @command{gnatmake}. This will perform a
11186 garbage collection of code and data never referenced.
11188 If the linker performs a partial link (@option{-r} ld linker option), then you
11189 will need to provide one or several entry point using the
11190 @option{-e} / @option{--entry} ld option.
11192 Note that objects compiled without the @option{-ffunction-sections} and
11193 @option{-fdata-sections} options can still be linked with the executable.
11194 However, no dead code elimination will be performed on those objects (they will
11197 The GNAT static library is now compiled with -ffunction-sections and
11198 -fdata-sections on some platforms. This allows you to eliminate the unused code
11199 and data of the GNAT library from your executable.
11201 @node Example of unused subprogram/data elimination
11202 @subsection Example of unused subprogram/data elimination
11205 Here is a simple example:
11207 @smallexample @c ada
11216 Used_Data : Integer;
11217 Unused_Data : Integer;
11219 procedure Used (Data : Integer);
11220 procedure Unused (Data : Integer);
11223 package body Aux is
11224 procedure Used (Data : Integer) is
11229 procedure Unused (Data : Integer) is
11231 Unused_Data := Data;
11237 @code{Unused} and @code{Unused_Data} are never referenced in this code
11238 excerpt, and hence they may be safely removed from the final executable.
11243 $ nm test | grep used
11244 020015f0 T aux__unused
11245 02005d88 B aux__unused_data
11246 020015cc T aux__used
11247 02005d84 B aux__used_data
11249 $ gnatmake test -cargs -fdata-sections -ffunction-sections \
11250 -largs -Wl,--gc-sections
11252 $ nm test | grep used
11253 02005350 T aux__used
11254 0201ffe0 B aux__used_data
11258 It can be observed that the procedure @code{Unused} and the object
11259 @code{Unused_Data} are removed by the linker when using the
11260 appropriate options.
11262 @c ********************************
11263 @node Renaming Files with gnatchop
11264 @chapter Renaming Files with @code{gnatchop}
11268 This chapter discusses how to handle files with multiple units by using
11269 the @code{gnatchop} utility. This utility is also useful in renaming
11270 files to meet the standard GNAT default file naming conventions.
11273 * Handling Files with Multiple Units::
11274 * Operating gnatchop in Compilation Mode::
11275 * Command Line for gnatchop::
11276 * Switches for gnatchop::
11277 * Examples of gnatchop Usage::
11280 @node Handling Files with Multiple Units
11281 @section Handling Files with Multiple Units
11284 The basic compilation model of GNAT requires that a file submitted to the
11285 compiler have only one unit and there be a strict correspondence
11286 between the file name and the unit name.
11288 The @code{gnatchop} utility allows both of these rules to be relaxed,
11289 allowing GNAT to process files which contain multiple compilation units
11290 and files with arbitrary file names. @code{gnatchop}
11291 reads the specified file and generates one or more output files,
11292 containing one unit per file. The unit and the file name correspond,
11293 as required by GNAT.
11295 If you want to permanently restructure a set of ``foreign'' files so that
11296 they match the GNAT rules, and do the remaining development using the
11297 GNAT structure, you can simply use @command{gnatchop} once, generate the
11298 new set of files and work with them from that point on.
11300 Alternatively, if you want to keep your files in the ``foreign'' format,
11301 perhaps to maintain compatibility with some other Ada compilation
11302 system, you can set up a procedure where you use @command{gnatchop} each
11303 time you compile, regarding the source files that it writes as temporary
11304 files that you throw away.
11306 Note that if your file containing multiple units starts with a byte order
11307 mark (BOM) specifying UTF-8 encoding, then the files generated by gnatchop
11308 will each start with a copy of this BOM, meaning that they can be compiled
11309 automatically in UTF-8 mode without needing to specify an explicit encoding.
11311 @node Operating gnatchop in Compilation Mode
11312 @section Operating gnatchop in Compilation Mode
11315 The basic function of @code{gnatchop} is to take a file with multiple units
11316 and split it into separate files. The boundary between files is reasonably
11317 clear, except for the issue of comments and pragmas. In default mode, the
11318 rule is that any pragmas between units belong to the previous unit, except
11319 that configuration pragmas always belong to the following unit. Any comments
11320 belong to the following unit. These rules
11321 almost always result in the right choice of
11322 the split point without needing to mark it explicitly and most users will
11323 find this default to be what they want. In this default mode it is incorrect to
11324 submit a file containing only configuration pragmas, or one that ends in
11325 configuration pragmas, to @code{gnatchop}.
11327 However, using a special option to activate ``compilation mode'',
11329 can perform another function, which is to provide exactly the semantics
11330 required by the RM for handling of configuration pragmas in a compilation.
11331 In the absence of configuration pragmas (at the main file level), this
11332 option has no effect, but it causes such configuration pragmas to be handled
11333 in a quite different manner.
11335 First, in compilation mode, if @code{gnatchop} is given a file that consists of
11336 only configuration pragmas, then this file is appended to the
11337 @file{gnat.adc} file in the current directory. This behavior provides
11338 the required behavior described in the RM for the actions to be taken
11339 on submitting such a file to the compiler, namely that these pragmas
11340 should apply to all subsequent compilations in the same compilation
11341 environment. Using GNAT, the current directory, possibly containing a
11342 @file{gnat.adc} file is the representation
11343 of a compilation environment. For more information on the
11344 @file{gnat.adc} file, see @ref{Handling of Configuration Pragmas}.
11346 Second, in compilation mode, if @code{gnatchop}
11347 is given a file that starts with
11348 configuration pragmas, and contains one or more units, then these
11349 configuration pragmas are prepended to each of the chopped files. This
11350 behavior provides the required behavior described in the RM for the
11351 actions to be taken on compiling such a file, namely that the pragmas
11352 apply to all units in the compilation, but not to subsequently compiled
11355 Finally, if configuration pragmas appear between units, they are appended
11356 to the previous unit. This results in the previous unit being illegal,
11357 since the compiler does not accept configuration pragmas that follow
11358 a unit. This provides the required RM behavior that forbids configuration
11359 pragmas other than those preceding the first compilation unit of a
11362 For most purposes, @code{gnatchop} will be used in default mode. The
11363 compilation mode described above is used only if you need exactly
11364 accurate behavior with respect to compilations, and you have files
11365 that contain multiple units and configuration pragmas. In this
11366 circumstance the use of @code{gnatchop} with the compilation mode
11367 switch provides the required behavior, and is for example the mode
11368 in which GNAT processes the ACVC tests.
11370 @node Command Line for gnatchop
11371 @section Command Line for @code{gnatchop}
11374 The @code{gnatchop} command has the form:
11377 @c $ gnatchop switches @var{file name} @r{[}@var{file name} @dots{}@r{]}
11378 @c @ovar{directory}
11379 @c Expanding @ovar macro inline (explanation in macro def comments)
11380 $ gnatchop switches @var{file name} @r{[}@var{file name} @dots{}@r{]}
11381 @r{[}@var{directory}@r{]}
11385 The only required argument is the file name of the file to be chopped.
11386 There are no restrictions on the form of this file name. The file itself
11387 contains one or more Ada units, in normal GNAT format, concatenated
11388 together. As shown, more than one file may be presented to be chopped.
11390 When run in default mode, @code{gnatchop} generates one output file in
11391 the current directory for each unit in each of the files.
11393 @var{directory}, if specified, gives the name of the directory to which
11394 the output files will be written. If it is not specified, all files are
11395 written to the current directory.
11397 For example, given a
11398 file called @file{hellofiles} containing
11400 @smallexample @c ada
11405 with Text_IO; use Text_IO;
11408 Put_Line ("Hello");
11418 $ gnatchop ^hellofiles^HELLOFILES.^
11422 generates two files in the current directory, one called
11423 @file{hello.ads} containing the single line that is the procedure spec,
11424 and the other called @file{hello.adb} containing the remaining text. The
11425 original file is not affected. The generated files can be compiled in
11429 When gnatchop is invoked on a file that is empty or that contains only empty
11430 lines and/or comments, gnatchop will not fail, but will not produce any
11433 For example, given a
11434 file called @file{toto.txt} containing
11436 @smallexample @c ada
11448 $ gnatchop ^toto.txt^TOT.TXT^
11452 will not produce any new file and will result in the following warnings:
11455 toto.txt:1:01: warning: empty file, contains no compilation units
11456 no compilation units found
11457 no source files written
11460 @node Switches for gnatchop
11461 @section Switches for @code{gnatchop}
11464 @command{gnatchop} recognizes the following switches:
11470 @cindex @option{--version} @command{gnatchop}
11471 Display Copyright and version, then exit disregarding all other options.
11474 @cindex @option{--help} @command{gnatchop}
11475 If @option{--version} was not used, display usage, then exit disregarding
11478 @item ^-c^/COMPILATION^
11479 @cindex @option{^-c^/COMPILATION^} (@code{gnatchop})
11480 Causes @code{gnatchop} to operate in compilation mode, in which
11481 configuration pragmas are handled according to strict RM rules. See
11482 previous section for a full description of this mode.
11485 @item -gnat@var{xxx}
11486 This passes the given @option{-gnat@var{xxx}} switch to @code{gnat} which is
11487 used to parse the given file. Not all @var{xxx} options make sense,
11488 but for example, the use of @option{-gnati2} allows @code{gnatchop} to
11489 process a source file that uses Latin-2 coding for identifiers.
11493 Causes @code{gnatchop} to generate a brief help summary to the standard
11494 output file showing usage information.
11496 @item ^-k@var{mm}^/FILE_NAME_MAX_LENGTH=@var{mm}^
11497 @cindex @option{^-k^/FILE_NAME_MAX_LENGTH^} (@code{gnatchop})
11498 Limit generated file names to the specified number @code{mm}
11500 This is useful if the
11501 resulting set of files is required to be interoperable with systems
11502 which limit the length of file names.
11504 If no value is given, or
11505 if no @code{/FILE_NAME_MAX_LENGTH} qualifier is given,
11506 a default of 39, suitable for OpenVMS Alpha
11507 Systems, is assumed
11510 No space is allowed between the @option{-k} and the numeric value. The numeric
11511 value may be omitted in which case a default of @option{-k8},
11513 with DOS-like file systems, is used. If no @option{-k} switch
11515 there is no limit on the length of file names.
11518 @item ^-p^/PRESERVE^
11519 @cindex @option{^-p^/PRESERVE^} (@code{gnatchop})
11520 Causes the file ^modification^creation^ time stamp of the input file to be
11521 preserved and used for the time stamp of the output file(s). This may be
11522 useful for preserving coherency of time stamps in an environment where
11523 @code{gnatchop} is used as part of a standard build process.
11526 @cindex @option{^-q^/QUIET^} (@code{gnatchop})
11527 Causes output of informational messages indicating the set of generated
11528 files to be suppressed. Warnings and error messages are unaffected.
11530 @item ^-r^/REFERENCE^
11531 @cindex @option{^-r^/REFERENCE^} (@code{gnatchop})
11532 @findex Source_Reference
11533 Generate @code{Source_Reference} pragmas. Use this switch if the output
11534 files are regarded as temporary and development is to be done in terms
11535 of the original unchopped file. This switch causes
11536 @code{Source_Reference} pragmas to be inserted into each of the
11537 generated files to refers back to the original file name and line number.
11538 The result is that all error messages refer back to the original
11540 In addition, the debugging information placed into the object file (when
11541 the @option{^-g^/DEBUG^} switch of @command{gcc} or @command{gnatmake} is
11543 also refers back to this original file so that tools like profilers and
11544 debuggers will give information in terms of the original unchopped file.
11546 If the original file to be chopped itself contains
11547 a @code{Source_Reference}
11548 pragma referencing a third file, then gnatchop respects
11549 this pragma, and the generated @code{Source_Reference} pragmas
11550 in the chopped file refer to the original file, with appropriate
11551 line numbers. This is particularly useful when @code{gnatchop}
11552 is used in conjunction with @code{gnatprep} to compile files that
11553 contain preprocessing statements and multiple units.
11555 @item ^-v^/VERBOSE^
11556 @cindex @option{^-v^/VERBOSE^} (@code{gnatchop})
11557 Causes @code{gnatchop} to operate in verbose mode. The version
11558 number and copyright notice are output, as well as exact copies of
11559 the gnat1 commands spawned to obtain the chop control information.
11561 @item ^-w^/OVERWRITE^
11562 @cindex @option{^-w^/OVERWRITE^} (@code{gnatchop})
11563 Overwrite existing file names. Normally @code{gnatchop} regards it as a
11564 fatal error if there is already a file with the same name as a
11565 file it would otherwise output, in other words if the files to be
11566 chopped contain duplicated units. This switch bypasses this
11567 check, and causes all but the last instance of such duplicated
11568 units to be skipped.
11571 @item --GCC=@var{xxxx}
11572 @cindex @option{--GCC=} (@code{gnatchop})
11573 Specify the path of the GNAT parser to be used. When this switch is used,
11574 no attempt is made to add the prefix to the GNAT parser executable.
11578 @node Examples of gnatchop Usage
11579 @section Examples of @code{gnatchop} Usage
11583 @item gnatchop /OVERWRITE HELLO_S.ADA [PRERELEASE.FILES]
11586 @item gnatchop -w hello_s.ada prerelease/files
11589 Chops the source file @file{hello_s.ada}. The output files will be
11590 placed in the directory @file{^prerelease/files^[PRERELEASE.FILES]^},
11592 files with matching names in that directory (no files in the current
11593 directory are modified).
11595 @item gnatchop ^archive^ARCHIVE.^
11596 Chops the source file @file{^archive^ARCHIVE.^}
11597 into the current directory. One
11598 useful application of @code{gnatchop} is in sending sets of sources
11599 around, for example in email messages. The required sources are simply
11600 concatenated (for example, using a ^Unix @code{cat}^VMS @code{APPEND/NEW}^
11602 @command{gnatchop} is used at the other end to reconstitute the original
11605 @item gnatchop file1 file2 file3 direc
11606 Chops all units in files @file{file1}, @file{file2}, @file{file3}, placing
11607 the resulting files in the directory @file{direc}. Note that if any units
11608 occur more than once anywhere within this set of files, an error message
11609 is generated, and no files are written. To override this check, use the
11610 @option{^-w^/OVERWRITE^} switch,
11611 in which case the last occurrence in the last file will
11612 be the one that is output, and earlier duplicate occurrences for a given
11613 unit will be skipped.
11616 @node Configuration Pragmas
11617 @chapter Configuration Pragmas
11618 @cindex Configuration pragmas
11619 @cindex Pragmas, configuration
11622 * Handling of Configuration Pragmas::
11623 * The Configuration Pragmas Files::
11627 Configuration pragmas include those pragmas described as
11628 such in the Ada Reference Manual, as well as
11629 implementation-dependent pragmas that are configuration pragmas.
11630 @xref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference Manual},
11631 for details on these additional GNAT-specific configuration pragmas.
11632 Most notably, the pragma @code{Source_File_Name}, which allows
11633 specifying non-default names for source files, is a configuration
11634 pragma. The following is a complete list of configuration pragmas
11635 recognized by GNAT:
11646 Assume_No_Invalid_Values
11651 Compile_Time_Warning
11653 Component_Alignment
11654 Convention_Identifier
11657 Default_Storage_Pool
11663 External_Name_Casing
11666 Float_Representation
11679 Priority_Specific_Dispatching
11682 Propagate_Exceptions
11685 Restricted_Run_Time
11687 Restrictions_Warnings
11689 Short_Circuit_And_Or
11691 Source_File_Name_Project
11695 Suppress_Exception_Locations
11696 Task_Dispatching_Policy
11702 Wide_Character_Encoding
11705 @node Handling of Configuration Pragmas
11706 @section Handling of Configuration Pragmas
11708 Configuration pragmas may either appear at the start of a compilation
11709 unit, or they can appear in a configuration pragma file to apply to
11710 all compilations performed in a given compilation environment.
11712 GNAT also provides the @code{gnatchop} utility to provide an automatic
11713 way to handle configuration pragmas following the semantics for
11714 compilations (that is, files with multiple units), described in the RM.
11715 See @ref{Operating gnatchop in Compilation Mode} for details.
11716 However, for most purposes, it will be more convenient to edit the
11717 @file{gnat.adc} file that contains configuration pragmas directly,
11718 as described in the following section.
11720 In the case of @code{Restrictions} pragmas appearing as configuration
11721 pragmas in individual compilation units, the exact handling depends on
11722 the type of restriction.
11724 Restrictions that require partition-wide consistency (like
11725 @code{No_Tasking}) are
11726 recognized wherever they appear
11727 and can be freely inherited, e.g. from a with'ed unit to the with'ing
11728 unit. This makes sense since the binder will in any case insist on seeing
11729 consistent use, so any unit not conforming to any restrictions that are
11730 anywhere in the partition will be rejected, and you might as well find
11731 that out at compile time rather than at bind time.
11733 For restrictions that do not require partition-wide consistency, e.g.
11734 SPARK or No_Implementation_Attributes, in general the restriction applies
11735 only to the unit in which the pragma appears, and not to any other units.
11737 The exception is No_Elaboration_Code which always applies to the entire
11738 object file from a compilation, i.e. to the body, spec, and all subunits.
11739 This restriction can be specified in a configuration pragma file, or it
11740 can be on the body and/or the spec (in eithe case it applies to all the
11741 relevant units). It can appear on a subunit only if it has previously
11742 appeared in the body of spec.
11744 @node The Configuration Pragmas Files
11745 @section The Configuration Pragmas Files
11746 @cindex @file{gnat.adc}
11749 In GNAT a compilation environment is defined by the current
11750 directory at the time that a compile command is given. This current
11751 directory is searched for a file whose name is @file{gnat.adc}. If
11752 this file is present, it is expected to contain one or more
11753 configuration pragmas that will be applied to the current compilation.
11754 However, if the switch @option{-gnatA} is used, @file{gnat.adc} is not
11757 Configuration pragmas may be entered into the @file{gnat.adc} file
11758 either by running @code{gnatchop} on a source file that consists only of
11759 configuration pragmas, or more conveniently by
11760 direct editing of the @file{gnat.adc} file, which is a standard format
11763 In addition to @file{gnat.adc}, additional files containing configuration
11764 pragmas may be applied to the current compilation using the switch
11765 @option{-gnatec}@var{path}. @var{path} must designate an existing file that
11766 contains only configuration pragmas. These configuration pragmas are
11767 in addition to those found in @file{gnat.adc} (provided @file{gnat.adc}
11768 is present and switch @option{-gnatA} is not used).
11770 It is allowed to specify several switches @option{-gnatec}, all of which
11771 will be taken into account.
11773 If you are using project file, a separate mechanism is provided using
11774 project attributes, see @ref{Specifying Configuration Pragmas} for more
11778 Of special interest to GNAT OpenVMS Alpha is the following
11779 configuration pragma:
11781 @smallexample @c ada
11783 pragma Extend_System (Aux_DEC);
11788 In the presence of this pragma, GNAT adds to the definition of the
11789 predefined package SYSTEM all the additional types and subprograms that are
11790 defined in HP Ada. See @ref{Compatibility with HP Ada} for details.
11793 @node Handling Arbitrary File Naming Conventions with gnatname
11794 @chapter Handling Arbitrary File Naming Conventions with @code{gnatname}
11795 @cindex Arbitrary File Naming Conventions
11798 * Arbitrary File Naming Conventions::
11799 * Running gnatname::
11800 * Switches for gnatname::
11801 * Examples of gnatname Usage::
11804 @node Arbitrary File Naming Conventions
11805 @section Arbitrary File Naming Conventions
11808 The GNAT compiler must be able to know the source file name of a compilation
11809 unit. When using the standard GNAT default file naming conventions
11810 (@code{.ads} for specs, @code{.adb} for bodies), the GNAT compiler
11811 does not need additional information.
11814 When the source file names do not follow the standard GNAT default file naming
11815 conventions, the GNAT compiler must be given additional information through
11816 a configuration pragmas file (@pxref{Configuration Pragmas})
11818 When the non-standard file naming conventions are well-defined,
11819 a small number of pragmas @code{Source_File_Name} specifying a naming pattern
11820 (@pxref{Alternative File Naming Schemes}) may be sufficient. However,
11821 if the file naming conventions are irregular or arbitrary, a number
11822 of pragma @code{Source_File_Name} for individual compilation units
11824 To help maintain the correspondence between compilation unit names and
11825 source file names within the compiler,
11826 GNAT provides a tool @code{gnatname} to generate the required pragmas for a
11829 @node Running gnatname
11830 @section Running @code{gnatname}
11833 The usual form of the @code{gnatname} command is
11836 @c $ gnatname @ovar{switches} @var{naming_pattern} @ovar{naming_patterns}
11837 @c @r{[}--and @ovar{switches} @var{naming_pattern} @ovar{naming_patterns}@r{]}
11838 @c Expanding @ovar macro inline (explanation in macro def comments)
11839 $ gnatname @r{[}@var{switches}@r{]} @var{naming_pattern} @r{[}@var{naming_patterns}@r{]}
11840 @r{[}--and @r{[}@var{switches}@r{]} @var{naming_pattern} @r{[}@var{naming_patterns}@r{]}@r{]}
11844 All of the arguments are optional. If invoked without any argument,
11845 @code{gnatname} will display its usage.
11848 When used with at least one naming pattern, @code{gnatname} will attempt to
11849 find all the compilation units in files that follow at least one of the
11850 naming patterns. To find these compilation units,
11851 @code{gnatname} will use the GNAT compiler in syntax-check-only mode on all
11855 One or several Naming Patterns may be given as arguments to @code{gnatname}.
11856 Each Naming Pattern is enclosed between double quotes (or single
11857 quotes on Windows).
11858 A Naming Pattern is a regular expression similar to the wildcard patterns
11859 used in file names by the Unix shells or the DOS prompt.
11862 @code{gnatname} may be called with several sections of directories/patterns.
11863 Sections are separated by switch @code{--and}. In each section, there must be
11864 at least one pattern. If no directory is specified in a section, the current
11865 directory (or the project directory is @code{-P} is used) is implied.
11866 The options other that the directory switches and the patterns apply globally
11867 even if they are in different sections.
11870 Examples of Naming Patterns are
11879 For a more complete description of the syntax of Naming Patterns,
11880 see the second kind of regular expressions described in @file{g-regexp.ads}
11881 (the ``Glob'' regular expressions).
11884 When invoked with no switch @code{-P}, @code{gnatname} will create a
11885 configuration pragmas file @file{gnat.adc} in the current working directory,
11886 with pragmas @code{Source_File_Name} for each file that contains a valid Ada
11889 @node Switches for gnatname
11890 @section Switches for @code{gnatname}
11893 Switches for @code{gnatname} must precede any specified Naming Pattern.
11896 You may specify any of the following switches to @code{gnatname}:
11902 @cindex @option{--version} @command{gnatname}
11903 Display Copyright and version, then exit disregarding all other options.
11906 @cindex @option{--help} @command{gnatname}
11907 If @option{--version} was not used, display usage, then exit disregarding
11910 @item --subdirs=<dir>
11911 Real object, library or exec directories are subdirectories <dir> of the
11915 Do not create a backup copy of an existing project file.
11918 Start another section of directories/patterns.
11920 @item ^-c^/CONFIG_FILE=^@file{file}
11921 @cindex @option{^-c^/CONFIG_FILE^} (@code{gnatname})
11922 Create a configuration pragmas file @file{file} (instead of the default
11925 There may be zero, one or more space between @option{-c} and
11928 @file{file} may include directory information. @file{file} must be
11929 writable. There may be only one switch @option{^-c^/CONFIG_FILE^}.
11930 When a switch @option{^-c^/CONFIG_FILE^} is
11931 specified, no switch @option{^-P^/PROJECT_FILE^} may be specified (see below).
11933 @item ^-d^/SOURCE_DIRS=^@file{dir}
11934 @cindex @option{^-d^/SOURCE_DIRS^} (@code{gnatname})
11935 Look for source files in directory @file{dir}. There may be zero, one or more
11936 spaces between @option{^-d^/SOURCE_DIRS=^} and @file{dir}.
11937 @file{dir} may end with @code{/**}, that is it may be of the form
11938 @code{root_dir/**}. In this case, the directory @code{root_dir} and all of its
11939 subdirectories, recursively, have to be searched for sources.
11940 When a switch @option{^-d^/SOURCE_DIRS^}
11941 is specified, the current working directory will not be searched for source
11942 files, unless it is explicitly specified with a @option{^-d^/SOURCE_DIRS^}
11943 or @option{^-D^/DIR_FILES^} switch.
11944 Several switches @option{^-d^/SOURCE_DIRS^} may be specified.
11945 If @file{dir} is a relative path, it is relative to the directory of
11946 the configuration pragmas file specified with switch
11947 @option{^-c^/CONFIG_FILE^},
11948 or to the directory of the project file specified with switch
11949 @option{^-P^/PROJECT_FILE^} or,
11950 if neither switch @option{^-c^/CONFIG_FILE^}
11951 nor switch @option{^-P^/PROJECT_FILE^} are specified, it is relative to the
11952 current working directory. The directory
11953 specified with switch @option{^-d^/SOURCE_DIRS^} must exist and be readable.
11955 @item ^-D^/DIRS_FILE=^@file{file}
11956 @cindex @option{^-D^/DIRS_FILE^} (@code{gnatname})
11957 Look for source files in all directories listed in text file @file{file}.
11958 There may be zero, one or more spaces between @option{^-D^/DIRS_FILE=^}
11960 @file{file} must be an existing, readable text file.
11961 Each nonempty line in @file{file} must be a directory.
11962 Specifying switch @option{^-D^/DIRS_FILE^} is equivalent to specifying as many
11963 switches @option{^-d^/SOURCE_DIRS^} as there are nonempty lines in
11967 Follow symbolic links when processing project files.
11969 @item ^-f^/FOREIGN_PATTERN=^@file{pattern}
11970 @cindex @option{^-f^/FOREIGN_PATTERN^} (@code{gnatname})
11971 Foreign patterns. Using this switch, it is possible to add sources of languages
11972 other than Ada to the list of sources of a project file.
11973 It is only useful if a ^-P^/PROJECT_FILE^ switch is used.
11976 gnatname ^-Pprj -f"*.c"^/PROJECT_FILE=PRJ /FOREIGN_PATTERN=*.C^ "*.ada"
11979 will look for Ada units in all files with the @file{.ada} extension,
11980 and will add to the list of file for project @file{prj.gpr} the C files
11981 with extension @file{.^c^C^}.
11984 @cindex @option{^-h^/HELP^} (@code{gnatname})
11985 Output usage (help) information. The output is written to @file{stdout}.
11987 @item ^-P^/PROJECT_FILE=^@file{proj}
11988 @cindex @option{^-P^/PROJECT_FILE^} (@code{gnatname})
11989 Create or update project file @file{proj}. There may be zero, one or more space
11990 between @option{-P} and @file{proj}. @file{proj} may include directory
11991 information. @file{proj} must be writable.
11992 There may be only one switch @option{^-P^/PROJECT_FILE^}.
11993 When a switch @option{^-P^/PROJECT_FILE^} is specified,
11994 no switch @option{^-c^/CONFIG_FILE^} may be specified.
11995 On all platforms, except on VMS, when @code{gnatname} is invoked for an
11996 existing project file <proj>.gpr, a backup copy of the project file is created
11997 in the project directory with file name <proj>.gpr.saved_x. 'x' is the first
11998 non negative number that makes this backup copy a new file.
12000 @item ^-v^/VERBOSE^
12001 @cindex @option{^-v^/VERBOSE^} (@code{gnatname})
12002 Verbose mode. Output detailed explanation of behavior to @file{stdout}.
12003 This includes name of the file written, the name of the directories to search
12004 and, for each file in those directories whose name matches at least one of
12005 the Naming Patterns, an indication of whether the file contains a unit,
12006 and if so the name of the unit.
12008 @item ^-v -v^/VERBOSE /VERBOSE^
12009 @cindex @option{^-v -v^/VERBOSE /VERBOSE^} (@code{gnatname})
12010 Very Verbose mode. In addition to the output produced in verbose mode,
12011 for each file in the searched directories whose name matches none of
12012 the Naming Patterns, an indication is given that there is no match.
12014 @item ^-x^/EXCLUDED_PATTERN=^@file{pattern}
12015 @cindex @option{^-x^/EXCLUDED_PATTERN^} (@code{gnatname})
12016 Excluded patterns. Using this switch, it is possible to exclude some files
12017 that would match the name patterns. For example,
12019 gnatname ^-x "*_nt.ada"^/EXCLUDED_PATTERN=*_nt.ada^ "*.ada"
12022 will look for Ada units in all files with the @file{.ada} extension,
12023 except those whose names end with @file{_nt.ada}.
12027 @node Examples of gnatname Usage
12028 @section Examples of @code{gnatname} Usage
12032 $ gnatname /CONFIG_FILE=[HOME.ME]NAMES.ADC /SOURCE_DIRS=SOURCES "[a-z]*.ada*"
12038 $ gnatname -c /home/me/names.adc -d sources "[a-z]*.ada*"
12043 In this example, the directory @file{^/home/me^[HOME.ME]^} must already exist
12044 and be writable. In addition, the directory
12045 @file{^/home/me/sources^[HOME.ME.SOURCES]^} (specified by
12046 @option{^-d sources^/SOURCE_DIRS=SOURCES^}) must exist and be readable.
12049 Note the optional spaces after @option{-c} and @option{-d}.
12054 $ gnatname -P/home/me/proj -x "*_nt_body.ada"
12055 -dsources -dsources/plus -Dcommon_dirs.txt "body_*" "spec_*"
12058 $ gnatname /PROJECT_FILE=[HOME.ME]PROJ
12059 /EXCLUDED_PATTERN=*_nt_body.ada
12060 /SOURCE_DIRS=(SOURCES,[SOURCES.PLUS])
12061 /DIRS_FILE=COMMON_DIRS.TXT "body_*" "spec_*"
12065 Note that several switches @option{^-d^/SOURCE_DIRS^} may be used,
12066 even in conjunction with one or several switches
12067 @option{^-D^/DIRS_FILE^}. Several Naming Patterns and one excluded pattern
12068 are used in this example.
12070 @c *****************************************
12071 @c * G N A T P r o j e c t M a n a g e r *
12072 @c *****************************************
12074 @c ------ macros for projects.texi
12075 @c These macros are needed when building the gprbuild documentation, but
12076 @c should have no effect in the gnat user's guide
12078 @macro CODESAMPLE{TXT}
12086 @macro PROJECTFILE{TXT}
12090 @c simulates a newline when in a @CODESAMPLE
12101 @macro TIPHTML{TXT}
12105 @macro IMPORTANT{TXT}
12120 @include projects.texi
12122 @c ---------------------------------------------
12123 @c Tools Supporting Project Files
12124 @c ---------------------------------------------
12126 @node Tools Supporting Project Files
12127 @chapter Tools Supporting Project Files
12132 * gnatmake and Project Files::
12133 * The GNAT Driver and Project Files::
12136 @c ---------------------------------------------
12137 @node gnatmake and Project Files
12138 @section gnatmake and Project Files
12139 @c ---------------------------------------------
12142 This section covers several topics related to @command{gnatmake} and
12143 project files: defining ^switches^switches^ for @command{gnatmake}
12144 and for the tools that it invokes; specifying configuration pragmas;
12145 the use of the @code{Main} attribute; building and rebuilding library project
12149 * Switches Related to Project Files::
12150 * Switches and Project Files::
12151 * Specifying Configuration Pragmas::
12152 * Project Files and Main Subprograms::
12153 * Library Project Files::
12156 @c ---------------------------------------------
12157 @node Switches Related to Project Files
12158 @subsection Switches Related to Project Files
12159 @c ---------------------------------------------
12162 The following switches are used by GNAT tools that support project files:
12166 @item ^-P^/PROJECT_FILE=^@var{project}
12167 @cindex @option{^-P^/PROJECT_FILE^} (any project-aware tool)
12168 Indicates the name of a project file. This project file will be parsed with
12169 the verbosity indicated by @option{^-vP^MESSAGE_PROJECT_FILES=^@emph{x}},
12170 if any, and using the external references indicated
12171 by @option{^-X^/EXTERNAL_REFERENCE^} switches, if any.
12173 There may zero, one or more spaces between @option{-P} and @var{project}.
12176 There must be only one @option{^-P^/PROJECT_FILE^} switch on the command line.
12178 Since the Project Manager parses the project file only after all the switches
12179 on the command line are checked, the order of the switches
12180 @option{^-P^/PROJECT_FILE^},
12181 @option{^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}}
12182 or @option{^-X^/EXTERNAL_REFERENCE^} is not significant.
12184 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
12185 @cindex @option{^-X^/EXTERNAL_REFERENCE^} (any project-aware tool)
12186 Indicates that external variable @var{name} has the value @var{value}.
12187 The Project Manager will use this value for occurrences of
12188 @code{external(name)} when parsing the project file.
12191 If @var{name} or @var{value} includes a space, then @var{name=value} should be
12192 put between quotes.
12199 Several @option{^-X^/EXTERNAL_REFERENCE^} switches can be used simultaneously.
12200 If several @option{^-X^/EXTERNAL_REFERENCE^} switches specify the same
12201 @var{name}, only the last one is used.
12203 An external variable specified with a @option{^-X^/EXTERNAL_REFERENCE^} switch
12204 takes precedence over the value of the same name in the environment.
12206 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
12207 @cindex @option{^-vP^/MESSAGES_PROJECT_FILE^} (any project-aware tool)
12208 Indicates the verbosity of the parsing of GNAT project files.
12211 @option{-vP0} means Default;
12212 @option{-vP1} means Medium;
12213 @option{-vP2} means High.
12217 There are three possible options for this qualifier: DEFAULT, MEDIUM and
12221 The default is ^Default^DEFAULT^: no output for syntactically correct
12223 If several @option{^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}} switches are present,
12224 only the last one is used.
12226 @item ^-aP^/ADD_PROJECT_SEARCH_DIR=^<dir>
12227 @cindex @option{^-aP^/ADD_PROJECT_SEARCH_DIR=^} (any project-aware tool)
12228 Add directory <dir> at the beginning of the project search path, in order,
12229 after the current working directory.
12233 @cindex @option{-eL} (any project-aware tool)
12234 Follow all symbolic links when processing project files.
12237 @item ^--subdirs^/SUBDIRS^=<subdir>
12238 @cindex @option{^--subdirs^/SUBDIRS^=} (gnatmake and gnatclean)
12239 This switch is recognized by @command{gnatmake} and @command{gnatclean}. It
12240 indicate that the real directories (except the source directories) are the
12241 subdirectories <subdir> of the directories specified in the project files.
12242 This applies in particular to object directories, library directories and
12243 exec directories. If the subdirectories do not exist, they are created
12248 @c ---------------------------------------------
12249 @node Switches and Project Files
12250 @subsection Switches and Project Files
12251 @c ---------------------------------------------
12255 It is not currently possible to specify VMS style qualifiers in the project
12256 files; only Unix style ^switches^switches^ may be specified.
12259 For each of the packages @code{Builder}, @code{Compiler}, @code{Binder}, and
12260 @code{Linker}, you can specify a @code{^Default_Switches^Default_Switches^}
12261 attribute, a @code{Switches} attribute, or both;
12262 as their names imply, these ^switch^switch^-related
12263 attributes affect the ^switches^switches^ that are used for each of these GNAT
12265 @command{gnatmake} is invoked. As will be explained below, these
12266 component-specific ^switches^switches^ precede
12267 the ^switches^switches^ provided on the @command{gnatmake} command line.
12269 The @code{^Default_Switches^Default_Switches^} attribute is an attribute
12270 indexed by language name (case insensitive) whose value is a string list.
12273 @smallexample @c projectfile
12275 package Compiler is
12276 for ^Default_Switches^Default_Switches^ ("Ada")
12277 use ("^-gnaty^-gnaty^",
12284 The @code{Switches} attribute is indexed on a file name (which may or may
12285 not be case sensitive, depending
12286 on the operating system) whose value is a string list. For example:
12288 @smallexample @c projectfile
12291 for Switches ("main1.adb")
12293 for Switches ("main2.adb")
12300 For the @code{Builder} package, the file names must designate source files
12301 for main subprograms. For the @code{Binder} and @code{Linker} packages, the
12302 file names must designate @file{ALI} or source files for main subprograms.
12303 In each case just the file name without an explicit extension is acceptable.
12305 For each tool used in a program build (@command{gnatmake}, the compiler, the
12306 binder, and the linker), the corresponding package @dfn{contributes} a set of
12307 ^switches^switches^ for each file on which the tool is invoked, based on the
12308 ^switch^switch^-related attributes defined in the package.
12309 In particular, the ^switches^switches^
12310 that each of these packages contributes for a given file @var{f} comprise:
12313 @item the value of attribute @code{Switches (@var{f})},
12314 if it is specified in the package for the given file,
12315 @item otherwise, the value of @code{^Default_Switches^Default_Switches^ ("Ada")},
12316 if it is specified in the package.
12321 If neither of these attributes is defined in the package, then the package does
12322 not contribute any ^switches^switches^ for the given file.
12324 When @command{gnatmake} is invoked on a file, the ^switches^switches^ comprise
12325 two sets, in the following order: those contributed for the file
12326 by the @code{Builder} package;
12327 and the switches passed on the command line.
12329 When @command{gnatmake} invokes a tool (compiler, binder, linker) on a file,
12330 the ^switches^switches^ passed to the tool comprise three sets,
12331 in the following order:
12335 the applicable ^switches^switches^ contributed for the file
12336 by the @code{Builder} package in the project file supplied on the command line;
12339 those contributed for the file by the package (in the relevant project file --
12340 see below) corresponding to the tool; and
12343 the applicable switches passed on the command line.
12346 The term @emph{applicable ^switches^switches^} reflects the fact that
12347 @command{gnatmake} ^switches^switches^ may or may not be passed to individual
12348 tools, depending on the individual ^switch^switch^.
12350 @command{gnatmake} may invoke the compiler on source files from different
12351 projects. The Project Manager will use the appropriate project file to
12352 determine the @code{Compiler} package for each source file being compiled.
12353 Likewise for the @code{Binder} and @code{Linker} packages.
12355 As an example, consider the following package in a project file:
12357 @smallexample @c projectfile
12360 package Compiler is
12361 for ^Default_Switches^Default_Switches^ ("Ada")
12363 for Switches ("a.adb")
12365 for Switches ("b.adb")
12367 "^-gnaty^-gnaty^");
12374 If @command{gnatmake} is invoked with this project file, and it needs to
12375 compile, say, the files @file{a.adb}, @file{b.adb}, and @file{c.adb}, then
12376 @file{a.adb} will be compiled with the ^switch^switch^
12377 @option{^-O1^-O1^},
12378 @file{b.adb} with ^switches^switches^
12380 and @option{^-gnaty^-gnaty^},
12381 and @file{c.adb} with @option{^-g^-g^}.
12383 The following example illustrates the ordering of the ^switches^switches^
12384 contributed by different packages:
12386 @smallexample @c projectfile
12390 for Switches ("main.adb")
12398 package Compiler is
12399 for Switches ("main.adb")
12407 If you issue the command:
12410 gnatmake ^-Pproj2^/PROJECT_FILE=PROJ2^ -O0 main
12414 then the compiler will be invoked on @file{main.adb} with the following
12415 sequence of ^switches^switches^
12418 ^-g -O1 -O2 -O0^-g -O1 -O2 -O0^
12422 with the last @option{^-O^-O^}
12423 ^switch^switch^ having precedence over the earlier ones;
12424 several other ^switches^switches^
12425 (such as @option{^-c^-c^}) are added implicitly.
12427 The ^switches^switches^
12429 and @option{^-O1^-O1^} are contributed by package
12430 @code{Builder}, @option{^-O2^-O2^} is contributed
12431 by the package @code{Compiler}
12432 and @option{^-O0^-O0^} comes from the command line.
12434 The @option{^-g^-g^}
12435 ^switch^switch^ will also be passed in the invocation of
12436 @command{Gnatlink.}
12438 A final example illustrates switch contributions from packages in different
12441 @smallexample @c projectfile
12444 for Source_Files use ("pack.ads", "pack.adb");
12445 package Compiler is
12446 for ^Default_Switches^Default_Switches^ ("Ada")
12447 use ("^-gnata^-gnata^");
12455 for Source_Files use ("foo_main.adb", "bar_main.adb");
12457 for Switches ("foo_main.adb")
12465 -- Ada source file:
12467 procedure Foo_Main is
12476 gnatmake ^-PProj4^/PROJECT_FILE=PROJ4^ foo_main.adb -cargs -gnato
12480 then the ^switches^switches^ passed to the compiler for @file{foo_main.adb} are
12481 @option{^-g^-g^} (contributed by the package @code{Proj4.Builder}) and
12482 @option{^-gnato^-gnato^} (passed on the command line).
12483 When the imported package @code{Pack} is compiled, the ^switches^switches^ used
12484 are @option{^-g^-g^} from @code{Proj4.Builder},
12485 @option{^-gnata^-gnata^} (contributed from package @code{Proj3.Compiler},
12486 and @option{^-gnato^-gnato^} from the command line.
12488 When using @command{gnatmake} with project files, some ^switches^switches^ or
12489 arguments may be expressed as relative paths. As the working directory where
12490 compilation occurs may change, these relative paths are converted to absolute
12491 paths. For the ^switches^switches^ found in a project file, the relative paths
12492 are relative to the project file directory, for the switches on the command
12493 line, they are relative to the directory where @command{gnatmake} is invoked.
12494 The ^switches^switches^ for which this occurs are:
12500 ^-aI^-aI^, as well as all arguments that are not switches (arguments to
12502 ^-o^-o^, object files specified in package @code{Linker} or after
12503 -largs on the command line). The exception to this rule is the ^switch^switch^
12504 ^--RTS=^--RTS=^ for which a relative path argument is never converted.
12506 @c ---------------------------------------------
12507 @node Specifying Configuration Pragmas
12508 @subsection Specifying Configuration Pragmas
12509 @c ---------------------------------------------
12512 When using @command{gnatmake} with project files, if there exists a file
12513 @file{gnat.adc} that contains configuration pragmas, this file will be
12516 Configuration pragmas can be defined by means of the following attributes in
12517 project files: @code{Global_Configuration_Pragmas} in package @code{Builder}
12518 and @code{Local_Configuration_Pragmas} in package @code{Compiler}.
12520 Both these attributes are single string attributes. Their values is the path
12521 name of a file containing configuration pragmas. If a path name is relative,
12522 then it is relative to the project directory of the project file where the
12523 attribute is defined.
12525 When compiling a source, the configuration pragmas used are, in order,
12526 those listed in the file designated by attribute
12527 @code{Global_Configuration_Pragmas} in package @code{Builder} of the main
12528 project file, if it is specified, and those listed in the file designated by
12529 attribute @code{Local_Configuration_Pragmas} in package @code{Compiler} of
12530 the project file of the source, if it exists.
12532 @c ---------------------------------------------
12533 @node Project Files and Main Subprograms
12534 @subsection Project Files and Main Subprograms
12535 @c ---------------------------------------------
12538 When using a project file, you can invoke @command{gnatmake}
12539 with one or several main subprograms, by specifying their source files on the
12543 gnatmake ^-P^/PROJECT_FILE=^prj main1.adb main2.adb main3.adb
12547 Each of these needs to be a source file of the same project, except
12548 when the switch ^-u^/UNIQUE^ is used.
12550 When ^-u^/UNIQUE^ is not used, all the mains need to be sources of the
12551 same project, one of the project in the tree rooted at the project specified
12552 on the command line. The package @code{Builder} of this common project, the
12553 "main project" is the one that is considered by @command{gnatmake}.
12555 When ^-u^/UNIQUE^ is used, the specified source files may be in projects
12556 imported directly or indirectly by the project specified on the command line.
12557 Note that if such a source file is not part of the project specified on the
12558 command line, the ^switches^switches^ found in package @code{Builder} of the
12559 project specified on the command line, if any, that are transmitted
12560 to the compiler will still be used, not those found in the project file of
12563 When using a project file, you can also invoke @command{gnatmake} without
12564 explicitly specifying any main, and the effect depends on whether you have
12565 defined the @code{Main} attribute. This attribute has a string list value,
12566 where each element in the list is the name of a source file (the file
12567 extension is optional) that contains a unit that can be a main subprogram.
12569 If the @code{Main} attribute is defined in a project file as a non-empty
12570 string list and the switch @option{^-u^/UNIQUE^} is not used on the command
12571 line, then invoking @command{gnatmake} with this project file but without any
12572 main on the command line is equivalent to invoking @command{gnatmake} with all
12573 the file names in the @code{Main} attribute on the command line.
12576 @smallexample @c projectfile
12579 for Main use ("main1.adb", "main2.adb", "main3.adb");
12585 With this project file, @code{"gnatmake ^-Pprj^/PROJECT_FILE=PRJ^"}
12587 @code{"gnatmake ^-Pprj^/PROJECT_FILE=PRJ^ main1.adb main2.adb main3.adb"}.
12589 When the project attribute @code{Main} is not specified, or is specified
12590 as an empty string list, or when the switch @option{-u} is used on the command
12591 line, then invoking @command{gnatmake} with no main on the command line will
12592 result in all immediate sources of the project file being checked, and
12593 potentially recompiled. Depending on the presence of the switch @option{-u},
12594 sources from other project files on which the immediate sources of the main
12595 project file depend are also checked and potentially recompiled. In other
12596 words, the @option{-u} switch is applied to all of the immediate sources of the
12599 When no main is specified on the command line and attribute @code{Main} exists
12600 and includes several mains, or when several mains are specified on the
12601 command line, the default ^switches^switches^ in package @code{Builder} will
12602 be used for all mains, even if there are specific ^switches^switches^
12603 specified for one or several mains.
12605 But the ^switches^switches^ from package @code{Binder} or @code{Linker} will be
12606 the specific ^switches^switches^ for each main, if they are specified.
12608 @c ---------------------------------------------
12609 @node Library Project Files
12610 @subsection Library Project Files
12611 @c ---------------------------------------------
12614 When @command{gnatmake} is invoked with a main project file that is a library
12615 project file, it is not allowed to specify one or more mains on the command
12618 When a library project file is specified, switches ^-b^/ACTION=BIND^ and
12619 ^-l^/ACTION=LINK^ have special meanings.
12622 @item ^-b^/ACTION=BIND^ is only allowed for stand-alone libraries. It indicates
12623 to @command{gnatmake} that @command{gnatbind} should be invoked for the
12626 @item ^-l^/ACTION=LINK^ may be used for all library projects. It indicates
12627 to @command{gnatmake} that the binder generated file should be compiled
12628 (in the case of a stand-alone library) and that the library should be built.
12631 @c ---------------------------------------------
12632 @node The GNAT Driver and Project Files
12633 @section The GNAT Driver and Project Files
12634 @c ---------------------------------------------
12637 A number of GNAT tools, other than @command{^gnatmake^gnatmake^}
12638 can benefit from project files:
12639 (@command{^gnatbind^gnatbind^},
12640 @command{^gnatcheck^gnatcheck^},
12641 @command{^gnatclean^gnatclean^},
12642 @command{^gnatelim^gnatelim^},
12643 @command{^gnatfind^gnatfind^},
12644 @command{^gnatlink^gnatlink^},
12645 @command{^gnatls^gnatls^},
12646 @command{^gnatmetric^gnatmetric^},
12647 @command{^gnatpp^gnatpp^},
12648 @command{^gnatstub^gnatstub^},
12649 and @command{^gnatxref^gnatxref^}). However, none of these tools can be invoked
12650 directly with a project file switch (@option{^-P^/PROJECT_FILE=^}).
12651 They must be invoked through the @command{gnat} driver.
12653 The @command{gnat} driver is a wrapper that accepts a number of commands and
12654 calls the corresponding tool. It was designed initially for VMS platforms (to
12655 convert VMS qualifiers to Unix-style switches), but it is now available on all
12658 On non-VMS platforms, the @command{gnat} driver accepts the following commands
12659 (case insensitive):
12662 @item BIND to invoke @command{^gnatbind^gnatbind^}
12663 @item CHOP to invoke @command{^gnatchop^gnatchop^}
12664 @item CLEAN to invoke @command{^gnatclean^gnatclean^}
12665 @item COMP or COMPILE to invoke the compiler
12666 @item ELIM to invoke @command{^gnatelim^gnatelim^}
12667 @item FIND to invoke @command{^gnatfind^gnatfind^}
12668 @item KR or KRUNCH to invoke @command{^gnatkr^gnatkr^}
12669 @item LINK to invoke @command{^gnatlink^gnatlink^}
12670 @item LS or LIST to invoke @command{^gnatls^gnatls^}
12671 @item MAKE to invoke @command{^gnatmake^gnatmake^}
12672 @item NAME to invoke @command{^gnatname^gnatname^}
12673 @item PREP or PREPROCESS to invoke @command{^gnatprep^gnatprep^}
12674 @item PP or PRETTY to invoke @command{^gnatpp^gnatpp^}
12675 @item METRIC to invoke @command{^gnatmetric^gnatmetric^}
12676 @item STUB to invoke @command{^gnatstub^gnatstub^}
12677 @item XREF to invoke @command{^gnatxref^gnatxref^}
12682 (note that the compiler is invoked using the command
12683 @command{^gnatmake -f -u -c^gnatmake -f -u -c^}).
12685 On non-VMS platforms, between @command{gnat} and the command, two
12686 special switches may be used:
12689 @item @command{-v} to display the invocation of the tool.
12690 @item @command{-dn} to prevent the @command{gnat} driver from removing
12691 the temporary files it has created. These temporary files are
12692 configuration files and temporary file list files.
12697 The command may be followed by switches and arguments for the invoked
12701 gnat bind -C main.ali
12707 Switches may also be put in text files, one switch per line, and the text
12708 files may be specified with their path name preceded by '@@'.
12711 gnat bind @@args.txt main.ali
12715 In addition, for commands BIND, COMP or COMPILE, FIND, ELIM, LS or LIST, LINK,
12716 METRIC, PP or PRETTY, STUB and XREF, the project file related switches
12717 (@option{^-P^/PROJECT_FILE^},
12718 @option{^-X^/EXTERNAL_REFERENCE^} and
12719 @option{^-vP^/MESSAGES_PROJECT_FILE=^x}) may be used in addition to
12720 the switches of the invoking tool.
12722 When GNAT PP or GNAT PRETTY is used with a project file, but with no source
12723 specified on the command line, it invokes @command{^gnatpp^gnatpp^} with all
12724 the immediate sources of the specified project file.
12726 When GNAT METRIC is used with a project file, but with no source
12727 specified on the command line, it invokes @command{^gnatmetric^gnatmetric^}
12728 with all the immediate sources of the specified project file and with
12729 @option{^-d^/DIRECTORY^} with the parameter pointing to the object directory
12732 In addition, when GNAT PP, GNAT PRETTY or GNAT METRIC is used with
12733 a project file, no source is specified on the command line and
12734 switch ^-U^/ALL_PROJECTS^ is specified on the command line, then
12735 the underlying tool (^gnatpp^gnatpp^ or
12736 ^gnatmetric^gnatmetric^) is invoked for all sources of all projects,
12737 not only for the immediate sources of the main project.
12739 (-U stands for Universal or Union of the project files of the project tree)
12742 For each of the following commands, there is optionally a corresponding
12743 package in the main project.
12746 @item package @code{Binder} for command BIND (invoking @code{^gnatbind^gnatbind^})
12748 @item package @code{Check} for command CHECK (invoking
12749 @code{^gnatcheck^gnatcheck^})
12751 @item package @code{Compiler} for command COMP or COMPILE (invoking the compiler)
12753 @item package @code{Cross_Reference} for command XREF (invoking
12754 @code{^gnatxref^gnatxref^})
12756 @item package @code{Eliminate} for command ELIM (invoking
12757 @code{^gnatelim^gnatelim^})
12759 @item package @code{Finder} for command FIND (invoking @code{^gnatfind^gnatfind^})
12761 @item package @code{Gnatls} for command LS or LIST (invoking @code{^gnatls^gnatls^})
12763 @item package @code{Gnatstub} for command STUB
12764 (invoking @code{^gnatstub^gnatstub^})
12766 @item package @code{Linker} for command LINK (invoking @code{^gnatlink^gnatlink^})
12768 @item package @code{Check} for command CHECK
12769 (invoking @code{^gnatcheck^gnatcheck^})
12771 @item package @code{Metrics} for command METRIC
12772 (invoking @code{^gnatmetric^gnatmetric^})
12774 @item package @code{Pretty_Printer} for command PP or PRETTY
12775 (invoking @code{^gnatpp^gnatpp^})
12780 Package @code{Gnatls} has a unique attribute @code{Switches},
12781 a simple variable with a string list value. It contains ^switches^switches^
12782 for the invocation of @code{^gnatls^gnatls^}.
12784 @smallexample @c projectfile
12797 All other packages have two attribute @code{Switches} and
12798 @code{^Default_Switches^Default_Switches^}.
12800 @code{Switches} is an indexed attribute, indexed by the
12801 source file name, that has a string list value: the ^switches^switches^ to be
12802 used when the tool corresponding to the package is invoked for the specific
12805 @code{^Default_Switches^Default_Switches^} is an attribute,
12806 indexed by the programming language that has a string list value.
12807 @code{^Default_Switches^Default_Switches^ ("Ada")} contains the
12808 ^switches^switches^ for the invocation of the tool corresponding
12809 to the package, except if a specific @code{Switches} attribute
12810 is specified for the source file.
12812 @smallexample @c projectfile
12816 for Source_Dirs use ("**");
12826 package Compiler is
12827 for ^Default_Switches^Default_Switches^ ("Ada")
12828 use ("^-gnatv^-gnatv^",
12829 "^-gnatwa^-gnatwa^");
12835 for ^Default_Switches^Default_Switches^ ("Ada")
12843 for ^Default_Switches^Default_Switches^ ("Ada")
12845 for Switches ("main.adb")
12854 for ^Default_Switches^Default_Switches^ ("Ada")
12861 package Cross_Reference is
12862 for ^Default_Switches^Default_Switches^ ("Ada")
12867 end Cross_Reference;
12873 With the above project file, commands such as
12876 ^gnat comp -Pproj main^GNAT COMP /PROJECT_FILE=PROJ MAIN^
12877 ^gnat ls -Pproj main^GNAT LIST /PROJECT_FILE=PROJ MAIN^
12878 ^gnat xref -Pproj main^GNAT XREF /PROJECT_FILE=PROJ MAIN^
12879 ^gnat bind -Pproj main.ali^GNAT BIND /PROJECT_FILE=PROJ MAIN.ALI^
12880 ^gnat link -Pproj main.ali^GNAT LINK /PROJECT_FILE=PROJ MAIN.ALI^
12884 will set up the environment properly and invoke the tool with the switches
12885 found in the package corresponding to the tool:
12886 @code{^Default_Switches^Default_Switches^ ("Ada")} for all tools,
12887 except @code{Switches ("main.adb")}
12888 for @code{^gnatlink^gnatlink^}.
12889 It is also possible to invoke some of the tools,
12890 (@code{^gnatcheck^gnatcheck^},
12891 @code{^gnatmetric^gnatmetric^},
12892 and @code{^gnatpp^gnatpp^})
12893 on a set of project units thanks to the combination of the switches
12894 @option{-P}, @option{-U} and possibly the main unit when one is interested
12895 in its closure. For instance,
12901 will compute the metrics for all the immediate units of project
12904 gnat metric -Pproj -U
12908 will compute the metrics for all the units of the closure of projects
12909 rooted at @code{proj}.
12911 gnat metric -Pproj -U main_unit
12915 will compute the metrics for the closure of units rooted at
12916 @code{main_unit}. This last possibility relies implicitly
12917 on @command{gnatbind}'s option @option{-R}. But if the argument files for the
12918 tool invoked by the @command{gnat} driver are explicitly specified
12919 either directly or through the tool @option{-files} option, then the tool
12920 is called only for these explicitly specified files.
12922 @c *****************************************
12923 @c * Cross-referencing tools
12924 @c *****************************************
12926 @node The Cross-Referencing Tools gnatxref and gnatfind
12927 @chapter The Cross-Referencing Tools @code{gnatxref} and @code{gnatfind}
12932 The compiler generates cross-referencing information (unless
12933 you set the @samp{-gnatx} switch), which are saved in the @file{.ali} files.
12934 This information indicates where in the source each entity is declared and
12935 referenced. Note that entities in package Standard are not included, but
12936 entities in all other predefined units are included in the output.
12938 Before using any of these two tools, you need to compile successfully your
12939 application, so that GNAT gets a chance to generate the cross-referencing
12942 The two tools @code{gnatxref} and @code{gnatfind} take advantage of this
12943 information to provide the user with the capability to easily locate the
12944 declaration and references to an entity. These tools are quite similar,
12945 the difference being that @code{gnatfind} is intended for locating
12946 definitions and/or references to a specified entity or entities, whereas
12947 @code{gnatxref} is oriented to generating a full report of all
12950 To use these tools, you must not compile your application using the
12951 @option{-gnatx} switch on the @command{gnatmake} command line
12952 (@pxref{The GNAT Make Program gnatmake}). Otherwise, cross-referencing
12953 information will not be generated.
12955 Note: to invoke @code{gnatxref} or @code{gnatfind} with a project file,
12956 use the @code{gnat} driver (see @ref{The GNAT Driver and Project Files}).
12959 * Switches for gnatxref::
12960 * Switches for gnatfind::
12961 * Project Files for gnatxref and gnatfind::
12962 * Regular Expressions in gnatfind and gnatxref::
12963 * Examples of gnatxref Usage::
12964 * Examples of gnatfind Usage::
12967 @node Switches for gnatxref
12968 @section @code{gnatxref} Switches
12971 The command invocation for @code{gnatxref} is:
12973 @c $ gnatxref @ovar{switches} @var{sourcefile1} @r{[}@var{sourcefile2} @dots{}@r{]}
12974 @c Expanding @ovar macro inline (explanation in macro def comments)
12975 $ gnatxref @r{[}@var{switches}@r{]} @var{sourcefile1} @r{[}@var{sourcefile2} @dots{}@r{]}
12984 identifies the source files for which a report is to be generated. The
12985 ``with''ed units will be processed too. You must provide at least one file.
12987 These file names are considered to be regular expressions, so for instance
12988 specifying @file{source*.adb} is the same as giving every file in the current
12989 directory whose name starts with @file{source} and whose extension is
12992 You shouldn't specify any directory name, just base names. @command{gnatxref}
12993 and @command{gnatfind} will be able to locate these files by themselves using
12994 the source path. If you specify directories, no result is produced.
12999 The switches can be:
13003 @cindex @option{--version} @command{gnatxref}
13004 Display Copyright and version, then exit disregarding all other options.
13007 @cindex @option{--help} @command{gnatxref}
13008 If @option{--version} was not used, display usage, then exit disregarding
13011 @item ^-a^/ALL_FILES^
13012 @cindex @option{^-a^/ALL_FILES^} (@command{gnatxref})
13013 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
13014 the read-only files found in the library search path. Otherwise, these files
13015 will be ignored. This option can be used to protect Gnat sources or your own
13016 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
13017 much faster, and their output much smaller. Read-only here refers to access
13018 or permissions status in the file system for the current user.
13021 @cindex @option{-aIDIR} (@command{gnatxref})
13022 When looking for source files also look in directory DIR. The order in which
13023 source file search is undertaken is the same as for @command{gnatmake}.
13026 @cindex @option{-aODIR} (@command{gnatxref})
13027 When searching for library and object files, look in directory
13028 DIR. The order in which library files are searched is the same as for
13029 @command{gnatmake}.
13032 @cindex @option{-nostdinc} (@command{gnatxref})
13033 Do not look for sources in the system default directory.
13036 @cindex @option{-nostdlib} (@command{gnatxref})
13037 Do not look for library files in the system default directory.
13039 @item --ext=@var{extension}
13040 @cindex @option{--ext} (@command{gnatxref})
13041 Specify an alternate ali file extension. The default is @code{ali} and other
13042 extensions (e.g. @code{sli} for SPARK library files) may be specified via this
13043 switch. Note that if this switch overrides the default, which means that only
13044 the new extension will be considered.
13046 @item --RTS=@var{rts-path}
13047 @cindex @option{--RTS} (@command{gnatxref})
13048 Specifies the default location of the runtime library. Same meaning as the
13049 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
13051 @item ^-d^/DERIVED_TYPES^
13052 @cindex @option{^-d^/DERIVED_TYPES^} (@command{gnatxref})
13053 If this switch is set @code{gnatxref} will output the parent type
13054 reference for each matching derived types.
13056 @item ^-f^/FULL_PATHNAME^
13057 @cindex @option{^-f^/FULL_PATHNAME^} (@command{gnatxref})
13058 If this switch is set, the output file names will be preceded by their
13059 directory (if the file was found in the search path). If this switch is
13060 not set, the directory will not be printed.
13062 @item ^-g^/IGNORE_LOCALS^
13063 @cindex @option{^-g^/IGNORE_LOCALS^} (@command{gnatxref})
13064 If this switch is set, information is output only for library-level
13065 entities, ignoring local entities. The use of this switch may accelerate
13066 @code{gnatfind} and @code{gnatxref}.
13069 @cindex @option{-IDIR} (@command{gnatxref})
13070 Equivalent to @samp{-aODIR -aIDIR}.
13073 @cindex @option{-pFILE} (@command{gnatxref})
13074 Specify a project file to use @xref{GNAT Project Manager}.
13075 If you need to use the @file{.gpr}
13076 project files, you should use gnatxref through the GNAT driver
13077 (@command{gnat xref -Pproject}).
13079 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
13080 project file in the current directory.
13082 If a project file is either specified or found by the tools, then the content
13083 of the source directory and object directory lines are added as if they
13084 had been specified respectively by @samp{^-aI^/SOURCE_SEARCH^}
13085 and @samp{^-aO^OBJECT_SEARCH^}.
13087 Output only unused symbols. This may be really useful if you give your
13088 main compilation unit on the command line, as @code{gnatxref} will then
13089 display every unused entity and 'with'ed package.
13093 Instead of producing the default output, @code{gnatxref} will generate a
13094 @file{tags} file that can be used by vi. For examples how to use this
13095 feature, see @ref{Examples of gnatxref Usage}. The tags file is output
13096 to the standard output, thus you will have to redirect it to a file.
13102 All these switches may be in any order on the command line, and may even
13103 appear after the file names. They need not be separated by spaces, thus
13104 you can say @samp{gnatxref ^-ag^/ALL_FILES/IGNORE_LOCALS^} instead of
13105 @samp{gnatxref ^-a -g^/ALL_FILES /IGNORE_LOCALS^}.
13107 @node Switches for gnatfind
13108 @section @code{gnatfind} Switches
13111 The command line for @code{gnatfind} is:
13114 @c $ gnatfind @ovar{switches} @var{pattern}@r{[}:@var{sourcefile}@r{[}:@var{line}@r{[}:@var{column}@r{]]]}
13115 @c @r{[}@var{file1} @var{file2} @dots{}]
13116 @c Expanding @ovar macro inline (explanation in macro def comments)
13117 $ gnatfind @r{[}@var{switches}@r{]} @var{pattern}@r{[}:@var{sourcefile}@r{[}:@var{line}@r{[}:@var{column}@r{]]]}
13118 @r{[}@var{file1} @var{file2} @dots{}@r{]}
13126 An entity will be output only if it matches the regular expression found
13127 in @var{pattern}, see @ref{Regular Expressions in gnatfind and gnatxref}.
13129 Omitting the pattern is equivalent to specifying @samp{*}, which
13130 will match any entity. Note that if you do not provide a pattern, you
13131 have to provide both a sourcefile and a line.
13133 Entity names are given in Latin-1, with uppercase/lowercase equivalence
13134 for matching purposes. At the current time there is no support for
13135 8-bit codes other than Latin-1, or for wide characters in identifiers.
13138 @code{gnatfind} will look for references, bodies or declarations
13139 of symbols referenced in @file{@var{sourcefile}}, at line @var{line}
13140 and column @var{column}. See @ref{Examples of gnatfind Usage}
13141 for syntax examples.
13144 is a decimal integer identifying the line number containing
13145 the reference to the entity (or entities) to be located.
13148 is a decimal integer identifying the exact location on the
13149 line of the first character of the identifier for the
13150 entity reference. Columns are numbered from 1.
13152 @item file1 file2 @dots{}
13153 The search will be restricted to these source files. If none are given, then
13154 the search will be done for every library file in the search path.
13155 These file must appear only after the pattern or sourcefile.
13157 These file names are considered to be regular expressions, so for instance
13158 specifying @file{source*.adb} is the same as giving every file in the current
13159 directory whose name starts with @file{source} and whose extension is
13162 The location of the spec of the entity will always be displayed, even if it
13163 isn't in one of @file{@var{file1}}, @file{@var{file2}},@enddots{} The
13164 occurrences of the entity in the separate units of the ones given on the
13165 command line will also be displayed.
13167 Note that if you specify at least one file in this part, @code{gnatfind} may
13168 sometimes not be able to find the body of the subprograms.
13173 At least one of 'sourcefile' or 'pattern' has to be present on
13176 The following switches are available:
13180 @cindex @option{--version} @command{gnatfind}
13181 Display Copyright and version, then exit disregarding all other options.
13184 @cindex @option{--help} @command{gnatfind}
13185 If @option{--version} was not used, display usage, then exit disregarding
13188 @item ^-a^/ALL_FILES^
13189 @cindex @option{^-a^/ALL_FILES^} (@command{gnatfind})
13190 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
13191 the read-only files found in the library search path. Otherwise, these files
13192 will be ignored. This option can be used to protect Gnat sources or your own
13193 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
13194 much faster, and their output much smaller. Read-only here refers to access
13195 or permission status in the file system for the current user.
13198 @cindex @option{-aIDIR} (@command{gnatfind})
13199 When looking for source files also look in directory DIR. The order in which
13200 source file search is undertaken is the same as for @command{gnatmake}.
13203 @cindex @option{-aODIR} (@command{gnatfind})
13204 When searching for library and object files, look in directory
13205 DIR. The order in which library files are searched is the same as for
13206 @command{gnatmake}.
13209 @cindex @option{-nostdinc} (@command{gnatfind})
13210 Do not look for sources in the system default directory.
13213 @cindex @option{-nostdlib} (@command{gnatfind})
13214 Do not look for library files in the system default directory.
13216 @item --ext=@var{extension}
13217 @cindex @option{--ext} (@command{gnatfind})
13218 Specify an alternate ali file extension. The default is @code{ali} and other
13219 extensions (e.g. @code{sli} for SPARK library files) may be specified via this
13220 switch. Note that if this switch overrides the default, which means that only
13221 the new extension will be considered.
13223 @item --RTS=@var{rts-path}
13224 @cindex @option{--RTS} (@command{gnatfind})
13225 Specifies the default location of the runtime library. Same meaning as the
13226 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
13228 @item ^-d^/DERIVED_TYPE_INFORMATION^
13229 @cindex @option{^-d^/DERIVED_TYPE_INFORMATION^} (@code{gnatfind})
13230 If this switch is set, then @code{gnatfind} will output the parent type
13231 reference for each matching derived types.
13233 @item ^-e^/EXPRESSIONS^
13234 @cindex @option{^-e^/EXPRESSIONS^} (@command{gnatfind})
13235 By default, @code{gnatfind} accept the simple regular expression set for
13236 @samp{pattern}. If this switch is set, then the pattern will be
13237 considered as full Unix-style regular expression.
13239 @item ^-f^/FULL_PATHNAME^
13240 @cindex @option{^-f^/FULL_PATHNAME^} (@command{gnatfind})
13241 If this switch is set, the output file names will be preceded by their
13242 directory (if the file was found in the search path). If this switch is
13243 not set, the directory will not be printed.
13245 @item ^-g^/IGNORE_LOCALS^
13246 @cindex @option{^-g^/IGNORE_LOCALS^} (@command{gnatfind})
13247 If this switch is set, information is output only for library-level
13248 entities, ignoring local entities. The use of this switch may accelerate
13249 @code{gnatfind} and @code{gnatxref}.
13252 @cindex @option{-IDIR} (@command{gnatfind})
13253 Equivalent to @samp{-aODIR -aIDIR}.
13256 @cindex @option{-pFILE} (@command{gnatfind})
13257 Specify a project file (@pxref{GNAT Project Manager}) to use.
13258 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
13259 project file in the current directory.
13261 If a project file is either specified or found by the tools, then the content
13262 of the source directory and object directory lines are added as if they
13263 had been specified respectively by @samp{^-aI^/SOURCE_SEARCH^} and
13264 @samp{^-aO^/OBJECT_SEARCH^}.
13266 @item ^-r^/REFERENCES^
13267 @cindex @option{^-r^/REFERENCES^} (@command{gnatfind})
13268 By default, @code{gnatfind} will output only the information about the
13269 declaration, body or type completion of the entities. If this switch is
13270 set, the @code{gnatfind} will locate every reference to the entities in
13271 the files specified on the command line (or in every file in the search
13272 path if no file is given on the command line).
13274 @item ^-s^/PRINT_LINES^
13275 @cindex @option{^-s^/PRINT_LINES^} (@command{gnatfind})
13276 If this switch is set, then @code{gnatfind} will output the content
13277 of the Ada source file lines were the entity was found.
13279 @item ^-t^/TYPE_HIERARCHY^
13280 @cindex @option{^-t^/TYPE_HIERARCHY^} (@command{gnatfind})
13281 If this switch is set, then @code{gnatfind} will output the type hierarchy for
13282 the specified type. It act like -d option but recursively from parent
13283 type to parent type. When this switch is set it is not possible to
13284 specify more than one file.
13289 All these switches may be in any order on the command line, and may even
13290 appear after the file names. They need not be separated by spaces, thus
13291 you can say @samp{gnatxref ^-ag^/ALL_FILES/IGNORE_LOCALS^} instead of
13292 @samp{gnatxref ^-a -g^/ALL_FILES /IGNORE_LOCALS^}.
13294 As stated previously, gnatfind will search in every directory in the
13295 search path. You can force it to look only in the current directory if
13296 you specify @code{*} at the end of the command line.
13298 @node Project Files for gnatxref and gnatfind
13299 @section Project Files for @command{gnatxref} and @command{gnatfind}
13302 Project files allow a programmer to specify how to compile its
13303 application, where to find sources, etc. These files are used
13305 primarily by GPS, but they can also be used
13308 @code{gnatxref} and @code{gnatfind}.
13310 A project file name must end with @file{.gpr}. If a single one is
13311 present in the current directory, then @code{gnatxref} and @code{gnatfind} will
13312 extract the information from it. If multiple project files are found, none of
13313 them is read, and you have to use the @samp{-p} switch to specify the one
13316 The following lines can be included, even though most of them have default
13317 values which can be used in most cases.
13318 The lines can be entered in any order in the file.
13319 Except for @file{src_dir} and @file{obj_dir}, you can only have one instance of
13320 each line. If you have multiple instances, only the last one is taken into
13325 [default: @code{"^./^[]^"}]
13326 specifies a directory where to look for source files. Multiple @code{src_dir}
13327 lines can be specified and they will be searched in the order they
13331 [default: @code{"^./^[]^"}]
13332 specifies a directory where to look for object and library files. Multiple
13333 @code{obj_dir} lines can be specified, and they will be searched in the order
13336 @item comp_opt=SWITCHES
13337 [default: @code{""}]
13338 creates a variable which can be referred to subsequently by using
13339 the @code{$@{comp_opt@}} notation. This is intended to store the default
13340 switches given to @command{gnatmake} and @command{gcc}.
13342 @item bind_opt=SWITCHES
13343 [default: @code{""}]
13344 creates a variable which can be referred to subsequently by using
13345 the @samp{$@{bind_opt@}} notation. This is intended to store the default
13346 switches given to @command{gnatbind}.
13348 @item link_opt=SWITCHES
13349 [default: @code{""}]
13350 creates a variable which can be referred to subsequently by using
13351 the @samp{$@{link_opt@}} notation. This is intended to store the default
13352 switches given to @command{gnatlink}.
13354 @item main=EXECUTABLE
13355 [default: @code{""}]
13356 specifies the name of the executable for the application. This variable can
13357 be referred to in the following lines by using the @samp{$@{main@}} notation.
13360 @item comp_cmd=COMMAND
13361 [default: @code{"GNAT COMPILE /SEARCH=$@{src_dir@} /DEBUG /TRY_SEMANTICS"}]
13364 @item comp_cmd=COMMAND
13365 [default: @code{"gcc -c -I$@{src_dir@} -g -gnatq"}]
13367 specifies the command used to compile a single file in the application.
13370 @item make_cmd=COMMAND
13371 [default: @code{"GNAT MAKE $@{main@}
13372 /SOURCE_SEARCH=$@{src_dir@} /OBJECT_SEARCH=$@{obj_dir@}
13373 /DEBUG /TRY_SEMANTICS /COMPILER_QUALIFIERS $@{comp_opt@}
13374 /BINDER_QUALIFIERS $@{bind_opt@} /LINKER_QUALIFIERS $@{link_opt@}"}]
13377 @item make_cmd=COMMAND
13378 [default: @code{"gnatmake $@{main@} -aI$@{src_dir@}
13379 -aO$@{obj_dir@} -g -gnatq -cargs $@{comp_opt@}
13380 -bargs $@{bind_opt@} -largs $@{link_opt@}"}]
13382 specifies the command used to recompile the whole application.
13384 @item run_cmd=COMMAND
13385 [default: @code{"$@{main@}"}]
13386 specifies the command used to run the application.
13388 @item debug_cmd=COMMAND
13389 [default: @code{"gdb $@{main@}"}]
13390 specifies the command used to debug the application
13395 @command{gnatxref} and @command{gnatfind} only take into account the
13396 @code{src_dir} and @code{obj_dir} lines, and ignore the others.
13398 @node Regular Expressions in gnatfind and gnatxref
13399 @section Regular Expressions in @code{gnatfind} and @code{gnatxref}
13402 As specified in the section about @command{gnatfind}, the pattern can be a
13403 regular expression. Actually, there are to set of regular expressions
13404 which are recognized by the program:
13407 @item globbing patterns
13408 These are the most usual regular expression. They are the same that you
13409 generally used in a Unix shell command line, or in a DOS session.
13411 Here is a more formal grammar:
13418 term ::= elmt -- matches elmt
13419 term ::= elmt elmt -- concatenation (elmt then elmt)
13420 term ::= * -- any string of 0 or more characters
13421 term ::= ? -- matches any character
13422 term ::= [char @{char@}] -- matches any character listed
13423 term ::= [char - char] -- matches any character in range
13427 @item full regular expression
13428 The second set of regular expressions is much more powerful. This is the
13429 type of regular expressions recognized by utilities such a @file{grep}.
13431 The following is the form of a regular expression, expressed in Ada
13432 reference manual style BNF is as follows
13439 regexp ::= term @{| term@} -- alternation (term or term @dots{})
13441 term ::= item @{item@} -- concatenation (item then item)
13443 item ::= elmt -- match elmt
13444 item ::= elmt * -- zero or more elmt's
13445 item ::= elmt + -- one or more elmt's
13446 item ::= elmt ? -- matches elmt or nothing
13449 elmt ::= nschar -- matches given character
13450 elmt ::= [nschar @{nschar@}] -- matches any character listed
13451 elmt ::= [^^^ nschar @{nschar@}] -- matches any character not listed
13452 elmt ::= [char - char] -- matches chars in given range
13453 elmt ::= \ char -- matches given character
13454 elmt ::= . -- matches any single character
13455 elmt ::= ( regexp ) -- parens used for grouping
13457 char ::= any character, including special characters
13458 nschar ::= any character except ()[].*+?^^^
13462 Following are a few examples:
13466 will match any of the two strings @samp{abcde} and @samp{fghi},
13469 will match any string like @samp{abd}, @samp{abcd}, @samp{abccd},
13470 @samp{abcccd}, and so on,
13473 will match any string which has only lowercase characters in it (and at
13474 least one character.
13479 @node Examples of gnatxref Usage
13480 @section Examples of @code{gnatxref} Usage
13482 @subsection General Usage
13485 For the following examples, we will consider the following units:
13487 @smallexample @c ada
13493 3: procedure Foo (B : in Integer);
13500 1: package body Main is
13501 2: procedure Foo (B : in Integer) is
13512 2: procedure Print (B : Integer);
13521 The first thing to do is to recompile your application (for instance, in
13522 that case just by doing a @samp{gnatmake main}, so that GNAT generates
13523 the cross-referencing information.
13524 You can then issue any of the following commands:
13526 @item gnatxref main.adb
13527 @code{gnatxref} generates cross-reference information for main.adb
13528 and every unit 'with'ed by main.adb.
13530 The output would be:
13538 Decl: main.ads 3:20
13539 Body: main.adb 2:20
13540 Ref: main.adb 4:13 5:13 6:19
13543 Ref: main.adb 6:8 7:8
13553 Decl: main.ads 3:15
13554 Body: main.adb 2:15
13557 Body: main.adb 1:14
13560 Ref: main.adb 6:12 7:12
13564 that is the entity @code{Main} is declared in main.ads, line 2, column 9,
13565 its body is in main.adb, line 1, column 14 and is not referenced any where.
13567 The entity @code{Print} is declared in bar.ads, line 2, column 15 and it
13568 is referenced in main.adb, line 6 column 12 and line 7 column 12.
13570 @item gnatxref package1.adb package2.ads
13571 @code{gnatxref} will generates cross-reference information for
13572 package1.adb, package2.ads and any other package 'with'ed by any
13578 @subsection Using gnatxref with vi
13580 @code{gnatxref} can generate a tags file output, which can be used
13581 directly from @command{vi}. Note that the standard version of @command{vi}
13582 will not work properly with overloaded symbols. Consider using another
13583 free implementation of @command{vi}, such as @command{vim}.
13586 $ gnatxref -v gnatfind.adb > tags
13590 will generate the tags file for @code{gnatfind} itself (if the sources
13591 are in the search path!).
13593 From @command{vi}, you can then use the command @samp{:tag @var{entity}}
13594 (replacing @var{entity} by whatever you are looking for), and vi will
13595 display a new file with the corresponding declaration of entity.
13598 @node Examples of gnatfind Usage
13599 @section Examples of @code{gnatfind} Usage
13603 @item gnatfind ^-f^/FULL_PATHNAME^ xyz:main.adb
13604 Find declarations for all entities xyz referenced at least once in
13605 main.adb. The references are search in every library file in the search
13608 The directories will be printed as well (as the @samp{^-f^/FULL_PATHNAME^}
13611 The output will look like:
13613 ^directory/^[directory]^main.ads:106:14: xyz <= declaration
13614 ^directory/^[directory]^main.adb:24:10: xyz <= body
13615 ^directory/^[directory]^foo.ads:45:23: xyz <= declaration
13619 that is to say, one of the entities xyz found in main.adb is declared at
13620 line 12 of main.ads (and its body is in main.adb), and another one is
13621 declared at line 45 of foo.ads
13623 @item gnatfind ^-fs^/FULL_PATHNAME/SOURCE_LINE^ xyz:main.adb
13624 This is the same command as the previous one, instead @code{gnatfind} will
13625 display the content of the Ada source file lines.
13627 The output will look like:
13630 ^directory/^[directory]^main.ads:106:14: xyz <= declaration
13632 ^directory/^[directory]^main.adb:24:10: xyz <= body
13634 ^directory/^[directory]^foo.ads:45:23: xyz <= declaration
13639 This can make it easier to find exactly the location your are looking
13642 @item gnatfind ^-r^/REFERENCES^ "*x*":main.ads:123 foo.adb
13643 Find references to all entities containing an x that are
13644 referenced on line 123 of main.ads.
13645 The references will be searched only in main.ads and foo.adb.
13647 @item gnatfind main.ads:123
13648 Find declarations and bodies for all entities that are referenced on
13649 line 123 of main.ads.
13651 This is the same as @code{gnatfind "*":main.adb:123}.
13653 @item gnatfind ^mydir/^[mydir]^main.adb:123:45
13654 Find the declaration for the entity referenced at column 45 in
13655 line 123 of file main.adb in directory mydir. Note that it
13656 is usual to omit the identifier name when the column is given,
13657 since the column position identifies a unique reference.
13659 The column has to be the beginning of the identifier, and should not
13660 point to any character in the middle of the identifier.
13664 @c *********************************
13665 @node The GNAT Pretty-Printer gnatpp
13666 @chapter The GNAT Pretty-Printer @command{gnatpp}
13668 @cindex Pretty-Printer
13671 * Switches for gnatpp::
13672 * Formatting Rules::
13676 ^The @command{gnatpp} tool^GNAT PRETTY^ is an ASIS-based utility
13677 for source reformatting / pretty-printing.
13678 It takes an Ada source file as input and generates a reformatted
13680 You can specify various style directives via switches; e.g.,
13681 identifier case conventions, rules of indentation, and comment layout.
13683 To produce a reformatted file, @command{gnatpp} generates and uses the ASIS
13684 tree for the input source and thus requires the input to be syntactically and
13685 semantically legal.
13686 If this condition is not met, @command{gnatpp} will terminate with an
13687 error message; no output file will be generated.
13689 @command{gnatpp} cannot process sources that contain
13690 preprocessing directives.
13692 If the compilation unit
13693 contained in the input source depends semantically upon units located
13694 outside the current directory, you have to provide the source search path
13695 when invoking @command{gnatpp}, if these units are contained in files with
13696 names that do not follow the GNAT file naming rules, you have to provide
13697 the configuration file describing the corresponding naming scheme;
13698 see the description of the @command{gnatpp}
13699 switches below. Another possibility is to use a project file and to
13700 call @command{gnatpp} through the @command{gnat} driver
13701 (see @ref{The GNAT Driver and Project Files}).
13703 The @command{gnatpp} command has the form
13706 @c $ gnatpp @ovar{switches} @var{filename}
13707 @c Expanding @ovar macro inline (explanation in macro def comments)
13708 $ gnatpp @r{[}@var{switches}@r{]} @var{filename} @r{[}-cargs @var{gcc_switches}@r{]}
13715 @var{switches} is an optional sequence of switches defining such properties as
13716 the formatting rules, the source search path, and the destination for the
13720 @var{filename} is the name (including the extension) of the source file to
13721 reformat; ``wildcards'' or several file names on the same gnatpp command are
13722 allowed. The file name may contain path information; it does not have to
13723 follow the GNAT file naming rules
13726 @samp{@var{gcc_switches}} is a list of switches for
13727 @command{gcc}. They will be passed on to all compiler invocations made by
13728 @command{gnatelim} to generate the ASIS trees. Here you can provide
13729 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
13730 use the @option{-gnatec} switch to set the configuration file,
13731 use the @option{-gnat05} switch if sources should be compiled in
13735 @node Switches for gnatpp
13736 @section Switches for @command{gnatpp}
13739 The following subsections describe the various switches accepted by
13740 @command{gnatpp}, organized by category.
13743 You specify a switch by supplying a name and generally also a value.
13744 In many cases the values for a switch with a given name are incompatible with
13746 (for example the switch that controls the casing of a reserved word may have
13747 exactly one value: upper case, lower case, or
13748 mixed case) and thus exactly one such switch can be in effect for an
13749 invocation of @command{gnatpp}.
13750 If more than one is supplied, the last one is used.
13751 However, some values for the same switch are mutually compatible.
13752 You may supply several such switches to @command{gnatpp}, but then
13753 each must be specified in full, with both the name and the value.
13754 Abbreviated forms (the name appearing once, followed by each value) are
13756 For example, to set
13757 the alignment of the assignment delimiter both in declarations and in
13758 assignment statements, you must write @option{-A2A3}
13759 (or @option{-A2 -A3}), but not @option{-A23}.
13763 In many cases the set of options for a given qualifier are incompatible with
13764 each other (for example the qualifier that controls the casing of a reserved
13765 word may have exactly one option, which specifies either upper case, lower
13766 case, or mixed case), and thus exactly one such option can be in effect for
13767 an invocation of @command{gnatpp}.
13768 If more than one is supplied, the last one is used.
13769 However, some qualifiers have options that are mutually compatible,
13770 and then you may then supply several such options when invoking
13774 In most cases, it is obvious whether or not the
13775 ^values for a switch with a given name^options for a given qualifier^
13776 are compatible with each other.
13777 When the semantics might not be evident, the summaries below explicitly
13778 indicate the effect.
13781 * Alignment Control::
13783 * Construct Layout Control::
13784 * General Text Layout Control::
13785 * Other Formatting Options::
13786 * Setting the Source Search Path::
13787 * Output File Control::
13788 * Other gnatpp Switches::
13791 @node Alignment Control
13792 @subsection Alignment Control
13793 @cindex Alignment control in @command{gnatpp}
13796 Programs can be easier to read if certain constructs are vertically aligned.
13797 By default all alignments are set ON.
13798 Through the @option{^-A0^/ALIGN=OFF^} switch you may reset the default to
13799 OFF, and then use one or more of the other
13800 ^@option{-A@var{n}} switches^@option{/ALIGN} options^
13801 to activate alignment for specific constructs.
13804 @cindex @option{^-A@var{n}^/ALIGN^} (@command{gnatpp})
13808 Set all alignments to ON
13811 @item ^-A0^/ALIGN=OFF^
13812 Set all alignments to OFF
13814 @item ^-A1^/ALIGN=COLONS^
13815 Align @code{:} in declarations
13817 @item ^-A2^/ALIGN=DECLARATIONS^
13818 Align @code{:=} in initializations in declarations
13820 @item ^-A3^/ALIGN=STATEMENTS^
13821 Align @code{:=} in assignment statements
13823 @item ^-A4^/ALIGN=ARROWS^
13824 Align @code{=>} in associations
13826 @item ^-A5^/ALIGN=COMPONENT_CLAUSES^
13827 Align @code{at} keywords in the component clauses in record
13828 representation clauses
13832 The @option{^-A^/ALIGN^} switches are mutually compatible; any combination
13835 @node Casing Control
13836 @subsection Casing Control
13837 @cindex Casing control in @command{gnatpp}
13840 @command{gnatpp} allows you to specify the casing for reserved words,
13841 pragma names, attribute designators and identifiers.
13842 For identifiers you may define a
13843 general rule for name casing but also override this rule
13844 via a set of dictionary files.
13846 Three types of casing are supported: lower case, upper case, and mixed case.
13847 Lower and upper case are self-explanatory (but since some letters in
13848 Latin1 and other GNAT-supported character sets
13849 exist only in lower-case form, an upper case conversion will have no
13851 ``Mixed case'' means that the first letter, and also each letter immediately
13852 following an underscore, are converted to their uppercase forms;
13853 all the other letters are converted to their lowercase forms.
13856 @cindex @option{^-a@var{x}^/ATTRIBUTE^} (@command{gnatpp})
13857 @item ^-aL^/ATTRIBUTE_CASING=LOWER_CASE^
13858 Attribute designators are lower case
13860 @item ^-aU^/ATTRIBUTE_CASING=UPPER_CASE^
13861 Attribute designators are upper case
13863 @item ^-aM^/ATTRIBUTE_CASING=MIXED_CASE^
13864 Attribute designators are mixed case (this is the default)
13866 @cindex @option{^-k@var{x}^/KEYWORD_CASING^} (@command{gnatpp})
13867 @item ^-kL^/KEYWORD_CASING=LOWER_CASE^
13868 Keywords (technically, these are known in Ada as @emph{reserved words}) are
13869 lower case (this is the default)
13871 @item ^-kU^/KEYWORD_CASING=UPPER_CASE^
13872 Keywords are upper case
13874 @cindex @option{^-n@var{x}^/NAME_CASING^} (@command{gnatpp})
13875 @item ^-nD^/NAME_CASING=AS_DECLARED^
13876 Name casing for defining occurrences are as they appear in the source file
13877 (this is the default)
13879 @item ^-nU^/NAME_CASING=UPPER_CASE^
13880 Names are in upper case
13882 @item ^-nL^/NAME_CASING=LOWER_CASE^
13883 Names are in lower case
13885 @item ^-nM^/NAME_CASING=MIXED_CASE^
13886 Names are in mixed case
13888 @cindex @option{^-ne@var{x}^/ENUM_CASING^} (@command{gnatpp})
13889 @item ^-neD^/ENUM_CASING=AS_DECLARED^
13890 Enumeration literal casing for defining occurrences are as they appear in the
13891 source file. Overrides ^-n^/NAME_CASING^ casing setting.
13893 @item ^-neU^/ENUM_CASING=UPPER_CASE^
13894 Enumeration literals are in upper case. Overrides ^-n^/NAME_CASING^ casing
13897 @item ^-neL^/ENUM_CASING=LOWER_CASE^
13898 Enumeration literals are in lower case. Overrides ^-n^/NAME_CASING^ casing
13901 @item ^-neM^/ENUM_CASING=MIXED_CASE^
13902 Enumeration literals are in mixed case. Overrides ^-n^/NAME_CASING^ casing
13905 @cindex @option{^-nt@var{x}^/TYPE_CASING^} (@command{gnatpp})
13906 @item ^-neD^/TYPE_CASING=AS_DECLARED^
13907 Names introduced by type and subtype declarations are always
13908 cased as they appear in the declaration in the source file.
13909 Overrides ^-n^/NAME_CASING^ casing setting.
13911 @item ^-ntU^/TYPE_CASING=UPPER_CASE^
13912 Names introduced by type and subtype declarations are always in
13913 upper case. Overrides ^-n^/NAME_CASING^ casing setting.
13915 @item ^-ntL^/TYPE_CASING=LOWER_CASE^
13916 Names introduced by type and subtype declarations are always in
13917 lower case. Overrides ^-n^/NAME_CASING^ casing setting.
13919 @item ^-ntM^/TYPE_CASING=MIXED_CASE^
13920 Names introduced by type and subtype declarations are always in
13921 mixed case. Overrides ^-n^/NAME_CASING^ casing setting.
13923 @item ^-nnU^/NUMBER_CASING=UPPER_CASE^
13924 Names introduced by number declarations are always in
13925 upper case. Overrides ^-n^/NAME_CASING^ casing setting.
13927 @item ^-nnL^/NUMBER_CASING=LOWER_CASE^
13928 Names introduced by number declarations are always in
13929 lower case. Overrides ^-n^/NAME_CASING^ casing setting.
13931 @item ^-nnM^/NUMBER_CASING=MIXED_CASE^
13932 Names introduced by number declarations are always in
13933 mixed case. Overrides ^-n^/NAME_CASING^ casing setting.
13935 @cindex @option{^-p@var{x}^/PRAGMA_CASING^} (@command{gnatpp})
13936 @item ^-pL^/PRAGMA_CASING=LOWER_CASE^
13937 Pragma names are lower case
13939 @item ^-pU^/PRAGMA_CASING=UPPER_CASE^
13940 Pragma names are upper case
13942 @item ^-pM^/PRAGMA_CASING=MIXED_CASE^
13943 Pragma names are mixed case (this is the default)
13945 @item ^-D@var{file}^/DICTIONARY=@var{file}^
13946 @cindex @option{^-D^/DICTIONARY^} (@command{gnatpp})
13947 Use @var{file} as a @emph{dictionary file} that defines
13948 the casing for a set of specified names,
13949 thereby overriding the effect on these names by
13950 any explicit or implicit
13951 ^-n^/NAME_CASING^ switch.
13952 To supply more than one dictionary file,
13953 use ^several @option{-D} switches^a list of files as options^.
13956 @option{gnatpp} implicitly uses a @emph{default dictionary file}
13957 to define the casing for the Ada predefined names and
13958 the names declared in the GNAT libraries.
13960 @item ^-D-^/SPECIFIC_CASING^
13961 @cindex @option{^-D-^/SPECIFIC_CASING^} (@command{gnatpp})
13962 Do not use the default dictionary file;
13963 instead, use the casing
13964 defined by a @option{^-n^/NAME_CASING^} switch and any explicit
13969 The structure of a dictionary file, and details on the conventions
13970 used in the default dictionary file, are defined in @ref{Name Casing}.
13972 The @option{^-D-^/SPECIFIC_CASING^} and
13973 @option{^-D@var{file}^/DICTIONARY=@var{file}^} switches are mutually
13976 @node Construct Layout Control
13977 @subsection Construct Layout Control
13978 @cindex Layout control in @command{gnatpp}
13981 This group of @command{gnatpp} switches controls the layout of comments and
13982 complex syntactic constructs. See @ref{Formatting Comments} for details
13986 @cindex @option{^-c@var{n}^/COMMENTS_LAYOUT^} (@command{gnatpp})
13987 @item ^-c0^/COMMENTS_LAYOUT=UNTOUCHED^
13988 All the comments remain unchanged
13990 @item ^-c1^/COMMENTS_LAYOUT=DEFAULT^
13991 GNAT-style comment line indentation (this is the default).
13993 @item ^-c2^/COMMENTS_LAYOUT=STANDARD_INDENT^
13994 Reference-manual comment line indentation.
13996 @item ^-c3^/COMMENTS_LAYOUT=GNAT_BEGINNING^
13997 GNAT-style comment beginning
13999 @item ^-c4^/COMMENTS_LAYOUT=REFORMAT^
14000 Reformat comment blocks
14002 @item ^-c5^/COMMENTS_LAYOUT=KEEP_SPECIAL^
14003 Keep unchanged special form comments
14005 @cindex @option{^-l@var{n}^/CONSTRUCT_LAYOUT^} (@command{gnatpp})
14006 @item ^-l1^/CONSTRUCT_LAYOUT=GNAT^
14007 GNAT-style layout (this is the default)
14009 @item ^-l2^/CONSTRUCT_LAYOUT=COMPACT^
14012 @item ^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^
14015 @cindex @option{^-N^/NOTABS^} (@command{gnatpp})
14017 All the VT characters are removed from the comment text. All the HT characters
14018 are expanded with the sequences of space characters to get to the next tab
14021 @cindex @option{^--no-separate-is^/NO_SEPARATE_IS^} (@command{gnatpp})
14022 @item ^--no-separate-is^/NO_SEPARATE_IS^
14023 Do not place the keyword @code{is} on a separate line in a subprogram body in
14024 case if the spec occupies more than one line.
14026 @cindex @option{^--separate-label^/SEPARATE_LABEL^} (@command{gnatpp})
14027 @item ^--separate-label^/SEPARATE_LABEL^
14028 Place statement label(s) on a separate line, with the following statement
14031 @cindex @option{^--separate-loop-then^/SEPARATE_LOOP_THEN^} (@command{gnatpp})
14032 @item ^--separate-loop-then^/SEPARATE_LOOP_THEN^
14033 Place the keyword @code{loop} in FOR and WHILE loop statements and the
14034 keyword @code{then} in IF statements on a separate line.
14036 @cindex @option{^--no-separate-loop-then^/NO_SEPARATE_LOOP_THEN^} (@command{gnatpp})
14037 @item ^--no-separate-loop-then^/NO_SEPARATE_LOOP_THEN^
14038 Do not place the keyword @code{loop} in FOR and WHILE loop statements and the
14039 keyword @code{then} in IF statements on a separate line. This option is
14040 incompatible with @option{^--separate-loop-then^/SEPARATE_LOOP_THEN^} option.
14042 @cindex @option{^--use-on-new-line^/USE_ON_NEW_LINE^} (@command{gnatpp})
14043 @item ^--use-on-new-line^/USE_ON_NEW_LINE^
14044 Start each USE clause in a context clause from a separate line.
14046 @cindex @option{^--separate-stmt-name^/STMT_NAME_ON_NEW_LINE^} (@command{gnatpp})
14047 @item ^--separate-stmt-name^/STMT_NAME_ON_NEW_LINE^
14048 Use a separate line for a loop or block statement name, but do not use an extra
14049 indentation level for the statement itself.
14055 The @option{-c1} and @option{-c2} switches are incompatible.
14056 The @option{-c3} and @option{-c4} switches are compatible with each other and
14057 also with @option{-c1} and @option{-c2}. The @option{-c0} switch disables all
14058 the other comment formatting switches.
14060 The @option{-l1}, @option{-l2}, and @option{-l3} switches are incompatible.
14065 For the @option{/COMMENTS_LAYOUT} qualifier:
14068 The @option{DEFAULT} and @option{STANDARD_INDENT} options are incompatible.
14070 The @option{GNAT_BEGINNING} and @option{REFORMAT} options are compatible with
14071 each other and also with @option{DEFAULT} and @option{STANDARD_INDENT}.
14075 The @option{GNAT}, @option{COMPACT}, and @option{UNCOMPACT} options for the
14076 @option{/CONSTRUCT_LAYOUT} qualifier are incompatible.
14079 @node General Text Layout Control
14080 @subsection General Text Layout Control
14083 These switches allow control over line length and indentation.
14086 @item ^-M@var{nnn}^/LINE_LENGTH_MAX=@var{nnn}^
14087 @cindex @option{^-M^/LINE_LENGTH^} (@command{gnatpp})
14088 Maximum line length, @var{nnn} from 32@dots{}256, the default value is 79
14090 @item ^-i@var{nnn}^/INDENTATION_LEVEL=@var{nnn}^
14091 @cindex @option{^-i^/INDENTATION_LEVEL^} (@command{gnatpp})
14092 Indentation level, @var{nnn} from 1@dots{}9, the default value is 3
14094 @item ^-cl@var{nnn}^/CONTINUATION_INDENT=@var{nnn}^
14095 @cindex @option{^-cl^/CONTINUATION_INDENT^} (@command{gnatpp})
14096 Indentation level for continuation lines (relative to the line being
14097 continued), @var{nnn} from 1@dots{}9.
14099 value is one less than the (normal) indentation level, unless the
14100 indentation is set to 1 (in which case the default value for continuation
14101 line indentation is also 1)
14104 @node Other Formatting Options
14105 @subsection Other Formatting Options
14108 These switches control the inclusion of missing end/exit labels, and
14109 the indentation level in @b{case} statements.
14112 @item ^-e^/NO_MISSED_LABELS^
14113 @cindex @option{^-e^/NO_MISSED_LABELS^} (@command{gnatpp})
14114 Do not insert missing end/exit labels. An end label is the name of
14115 a construct that may optionally be repeated at the end of the
14116 construct's declaration;
14117 e.g., the names of packages, subprograms, and tasks.
14118 An exit label is the name of a loop that may appear as target
14119 of an exit statement within the loop.
14120 By default, @command{gnatpp} inserts these end/exit labels when
14121 they are absent from the original source. This option suppresses such
14122 insertion, so that the formatted source reflects the original.
14124 @item ^-ff^/FORM_FEED_AFTER_PRAGMA_PAGE^
14125 @cindex @option{^-ff^/FORM_FEED_AFTER_PRAGMA_PAGE^} (@command{gnatpp})
14126 Insert a Form Feed character after a pragma Page.
14128 @item ^-T@var{nnn}^/MAX_INDENT=@var{nnn}^
14129 @cindex @option{^-T^/MAX_INDENT^} (@command{gnatpp})
14130 Do not use an additional indentation level for @b{case} alternatives
14131 and variants if there are @var{nnn} or more (the default
14133 If @var{nnn} is 0, an additional indentation level is
14134 used for @b{case} alternatives and variants regardless of their number.
14136 @item ^--call_threshold=@var{nnn}^/MAX_ACT=@var{nnn}^
14137 @cindex @option{^--call_threshold^/MAX_ACT^} (@command{gnatpp})
14138 If the number of parameter associations is greater than @var{nnn} and if at
14139 least one association uses named notation, start each association from
14140 a new line. If @var{nnn} is 0, no check for the number of associations
14141 is made, this is the default.
14143 @item ^--par_threshold=@var{nnn}^/MAX_PAR=@var{nnn}^
14144 @cindex @option{^--par_threshold^/MAX_PAR^} (@command{gnatpp})
14145 If the number of parameter specifications is greater than @var{nnn}
14146 (or equal to @var{nnn} in case of a function), start each specification from
14147 a new line. The default for @var{nnn} is 3.
14150 @node Setting the Source Search Path
14151 @subsection Setting the Source Search Path
14154 To define the search path for the input source file, @command{gnatpp}
14155 uses the same switches as the GNAT compiler, with the same effects.
14158 @item ^-I^/SEARCH=^@var{dir}
14159 @cindex @option{^-I^/SEARCH^} (@code{gnatpp})
14160 The same as the corresponding gcc switch
14162 @item ^-I-^/NOCURRENT_DIRECTORY^
14163 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatpp})
14164 The same as the corresponding gcc switch
14166 @item ^-gnatec^/CONFIGURATION_PRAGMAS_FILE^=@var{path}
14167 @cindex @option{^-gnatec^/CONFIGURATION_PRAGMAS_FILE^} (@code{gnatpp})
14168 The same as the corresponding gcc switch
14170 @item ^--RTS^/RUNTIME_SYSTEM^=@var{path}
14171 @cindex @option{^--RTS^/RUNTIME_SYSTEM^} (@code{gnatpp})
14172 The same as the corresponding gcc switch
14176 @node Output File Control
14177 @subsection Output File Control
14180 By default the output is sent to the file whose name is obtained by appending
14181 the ^@file{.pp}^@file{$PP}^ suffix to the name of the input file
14182 (if the file with this name already exists, it is unconditionally overwritten).
14183 Thus if the input file is @file{^my_ada_proc.adb^MY_ADA_PROC.ADB^} then
14184 @command{gnatpp} will produce @file{^my_ada_proc.adb.pp^MY_ADA_PROC.ADB$PP^}
14186 The output may be redirected by the following switches:
14189 @item ^-pipe^/STANDARD_OUTPUT^
14190 @cindex @option{^-pipe^/STANDARD_OUTPUT^} (@code{gnatpp})
14191 Send the output to @code{Standard_Output}
14193 @item ^-o @var{output_file}^/OUTPUT=@var{output_file}^
14194 @cindex @option{^-o^/OUTPUT^} (@code{gnatpp})
14195 Write the output into @var{output_file}.
14196 If @var{output_file} already exists, @command{gnatpp} terminates without
14197 reading or processing the input file.
14199 @item ^-of ^/FORCED_OUTPUT=^@var{output_file}
14200 @cindex @option{^-of^/FORCED_OUTPUT^} (@code{gnatpp})
14201 Write the output into @var{output_file}, overwriting the existing file
14202 (if one is present).
14204 @item ^-r^/REPLACE^
14205 @cindex @option{^-r^/REPLACE^} (@code{gnatpp})
14206 Replace the input source file with the reformatted output, and copy the
14207 original input source into the file whose name is obtained by appending the
14208 ^@file{.npp}^@file{$NPP}^ suffix to the name of the input file.
14209 If a file with this name already exists, @command{gnatpp} terminates without
14210 reading or processing the input file.
14212 @item ^-rf^/OVERRIDING_REPLACE^
14213 @cindex @option{^-rf^/OVERRIDING_REPLACE^} (@code{gnatpp})
14214 Like @option{^-r^/REPLACE^} except that if the file with the specified name
14215 already exists, it is overwritten.
14217 @item ^-rnb^/REPLACE_NO_BACKUP^
14218 @cindex @option{^-rnb^/REPLACE_NO_BACKUP^} (@code{gnatpp})
14219 Replace the input source file with the reformatted output without
14220 creating any backup copy of the input source.
14222 @item ^--eol=@var{xxx}^/END_OF_LINE=@var{xxx}^
14223 @cindex @option{^--eol^/END_OF_LINE^} (@code{gnatpp})
14224 Specifies the format of the reformatted output file. The @var{xxx}
14225 ^string specified with the switch^option^ may be either
14227 @item ``@option{^dos^DOS^}'' MS DOS style, lines end with CR LF characters
14228 @item ``@option{^crlf^CRLF^}''
14229 the same as @option{^crlf^CRLF^}
14230 @item ``@option{^unix^UNIX^}'' UNIX style, lines end with LF character
14231 @item ``@option{^lf^LF^}''
14232 the same as @option{^unix^UNIX^}
14235 @item ^-W^/RESULT_ENCODING=^@var{e}
14236 @cindex @option{^-W^/RESULT_ENCODING=^} (@command{gnatpp})
14237 Specify the wide character encoding method used to write the code in the
14239 @var{e} is one of the following:
14247 Upper half encoding
14249 @item ^s^SHIFT_JIS^
14259 Brackets encoding (default value)
14265 Options @option{^-pipe^/STANDARD_OUTPUT^},
14266 @option{^-o^/OUTPUT^} and
14267 @option{^-of^/FORCED_OUTPUT^} are allowed only if the call to gnatpp
14268 contains only one file to reformat.
14270 @option{^--eol^/END_OF_LINE^}
14272 @option{^-W^/RESULT_ENCODING^}
14273 cannot be used together
14274 with @option{^-pipe^/STANDARD_OUTPUT^} option.
14276 @node Other gnatpp Switches
14277 @subsection Other @code{gnatpp} Switches
14280 The additional @command{gnatpp} switches are defined in this subsection.
14284 @cindex @option{--version} @command{gnatpp}
14285 Display Copyright and version, then exit disregarding all other options.
14288 @cindex @option{--help} @command{gnatpp}
14289 Display usage, then exit disregarding all other options.
14291 @item ^-files @var{filename}^/FILES=@var{filename}^
14292 @cindex @option{^-files^/FILES^} (@code{gnatpp})
14293 Take the argument source files from the specified file. This file should be an
14294 ordinary text file containing file names separated by spaces or
14295 line breaks. You can use this switch more than once in the same call to
14296 @command{gnatpp}. You also can combine this switch with an explicit list of
14299 @item ^-v^/VERBOSE^
14300 @cindex @option{^-v^/VERBOSE^} (@code{gnatpp})
14302 @command{gnatpp} generates version information and then
14303 a trace of the actions it takes to produce or obtain the ASIS tree.
14305 @item ^-w^/WARNINGS^
14306 @cindex @option{^-w^/WARNINGS^} (@code{gnatpp})
14308 @command{gnatpp} generates a warning whenever it cannot provide
14309 a required layout in the result source.
14312 @node Formatting Rules
14313 @section Formatting Rules
14316 The following subsections show how @command{gnatpp} treats ``white space'',
14317 comments, program layout, and name casing.
14318 They provide the detailed descriptions of the switches shown above.
14321 * White Space and Empty Lines::
14322 * Formatting Comments::
14323 * Construct Layout::
14327 @node White Space and Empty Lines
14328 @subsection White Space and Empty Lines
14331 @command{gnatpp} does not have an option to control space characters.
14332 It will add or remove spaces according to the style illustrated by the
14333 examples in the @cite{Ada Reference Manual}.
14335 The only format effectors
14336 (see @cite{Ada Reference Manual}, paragraph 2.1(13))
14337 that will appear in the output file are platform-specific line breaks,
14338 and also format effectors within (but not at the end of) comments.
14339 In particular, each horizontal tab character that is not inside
14340 a comment will be treated as a space and thus will appear in the
14341 output file as zero or more spaces depending on
14342 the reformatting of the line in which it appears.
14343 The only exception is a Form Feed character, which is inserted after a
14344 pragma @code{Page} when @option{-ff} is set.
14346 The output file will contain no lines with trailing ``white space'' (spaces,
14349 Empty lines in the original source are preserved
14350 only if they separate declarations or statements.
14351 In such contexts, a
14352 sequence of two or more empty lines is replaced by exactly one empty line.
14353 Note that a blank line will be removed if it separates two ``comment blocks''
14354 (a comment block is a sequence of whole-line comments).
14355 In order to preserve a visual separation between comment blocks, use an
14356 ``empty comment'' (a line comprising only hyphens) rather than an empty line.
14357 Likewise, if for some reason you wish to have a sequence of empty lines,
14358 use a sequence of empty comments instead.
14360 @node Formatting Comments
14361 @subsection Formatting Comments
14364 Comments in Ada code are of two kinds:
14367 a @emph{whole-line comment}, which appears by itself (possibly preceded by
14368 ``white space'') on a line
14371 an @emph{end-of-line comment}, which follows some other Ada lexical element
14376 The indentation of a whole-line comment is that of either
14377 the preceding or following line in
14378 the formatted source, depending on switch settings as will be described below.
14380 For an end-of-line comment, @command{gnatpp} leaves the same number of spaces
14381 between the end of the preceding Ada lexical element and the beginning
14382 of the comment as appear in the original source,
14383 unless either the comment has to be split to
14384 satisfy the line length limitation, or else the next line contains a
14385 whole line comment that is considered a continuation of this end-of-line
14386 comment (because it starts at the same position).
14388 cases, the start of the end-of-line comment is moved right to the nearest
14389 multiple of the indentation level.
14390 This may result in a ``line overflow'' (the right-shifted comment extending
14391 beyond the maximum line length), in which case the comment is split as
14394 There is a difference between @option{^-c1^/COMMENTS_LAYOUT=DEFAULT^}
14395 (GNAT-style comment line indentation)
14396 and @option{^-c2^/COMMENTS_LAYOUT=STANDARD_INDENT^}
14397 (reference-manual comment line indentation).
14398 With reference-manual style, a whole-line comment is indented as if it
14399 were a declaration or statement at the same place
14400 (i.e., according to the indentation of the preceding line(s)).
14401 With GNAT style, a whole-line comment that is immediately followed by an
14402 @b{if} or @b{case} statement alternative, a record variant, or the reserved
14403 word @b{begin}, is indented based on the construct that follows it.
14406 @smallexample @c ada
14418 Reference-manual indentation produces:
14420 @smallexample @c ada
14432 while GNAT-style indentation produces:
14434 @smallexample @c ada
14446 The @option{^-c3^/COMMENTS_LAYOUT=GNAT_BEGINNING^} switch
14447 (GNAT style comment beginning) has the following
14452 For each whole-line comment that does not end with two hyphens,
14453 @command{gnatpp} inserts spaces if necessary after the starting two hyphens
14454 to ensure that there are at least two spaces between these hyphens and the
14455 first non-blank character of the comment.
14459 For an end-of-line comment, if in the original source the next line is a
14460 whole-line comment that starts at the same position
14461 as the end-of-line comment,
14462 then the whole-line comment (and all whole-line comments
14463 that follow it and that start at the same position)
14464 will start at this position in the output file.
14467 That is, if in the original source we have:
14469 @smallexample @c ada
14472 A := B + C; -- B must be in the range Low1..High1
14473 -- C must be in the range Low2..High2
14474 --B+C will be in the range Low1+Low2..High1+High2
14480 Then in the formatted source we get
14482 @smallexample @c ada
14485 A := B + C; -- B must be in the range Low1..High1
14486 -- C must be in the range Low2..High2
14487 -- B+C will be in the range Low1+Low2..High1+High2
14493 A comment that exceeds the line length limit will be split.
14495 @option{^-c4^/COMMENTS_LAYOUT=REFORMAT^} (reformat comment blocks) is set and
14496 the line belongs to a reformattable block, splitting the line generates a
14497 @command{gnatpp} warning.
14498 The @option{^-c4^/COMMENTS_LAYOUT=REFORMAT^} switch specifies that whole-line
14499 comments may be reformatted in typical
14500 word processor style (that is, moving words between lines and putting as
14501 many words in a line as possible).
14504 The @option{^-c5^/COMMENTS_LAYOUT=KEEP_SPECIAL^} switch specifies, that comments
14505 that has a special format (that is, a character that is neither a letter nor digit
14506 not white space nor line break immediately following the leading @code{--} of
14507 the comment) should be without any change moved from the argument source
14508 into reformatted source. This switch allows to preserve comments that are used
14509 as a special marks in the code (e.g.@: SPARK annotation).
14511 @node Construct Layout
14512 @subsection Construct Layout
14515 In several cases the suggested layout in the Ada Reference Manual includes
14516 an extra level of indentation that many programmers prefer to avoid. The
14517 affected cases include:
14521 @item Record type declaration (RM 3.8)
14523 @item Record representation clause (RM 13.5.1)
14525 @item Loop statement in case if a loop has a statement identifier (RM 5.6)
14527 @item Block statement in case if a block has a statement identifier (RM 5.6)
14531 In compact mode (when GNAT style layout or compact layout is set),
14532 the pretty printer uses one level of indentation instead
14533 of two. This is achieved in the record definition and record representation
14534 clause cases by putting the @code{record} keyword on the same line as the
14535 start of the declaration or representation clause, and in the block and loop
14536 case by putting the block or loop header on the same line as the statement
14540 The difference between GNAT style @option{^-l1^/CONSTRUCT_LAYOUT=GNAT^}
14541 and compact @option{^-l2^/CONSTRUCT_LAYOUT=COMPACT^}
14542 layout on the one hand, and uncompact layout
14543 @option{^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^} on the other hand,
14544 can be illustrated by the following examples:
14548 @multitable @columnfractions .5 .5
14549 @item @i{GNAT style, compact layout} @tab @i{Uncompact layout}
14552 @smallexample @c ada
14559 @smallexample @c ada
14568 @smallexample @c ada
14570 a at 0 range 0 .. 31;
14571 b at 4 range 0 .. 31;
14575 @smallexample @c ada
14578 a at 0 range 0 .. 31;
14579 b at 4 range 0 .. 31;
14584 @smallexample @c ada
14592 @smallexample @c ada
14602 @smallexample @c ada
14603 Clear : for J in 1 .. 10 loop
14608 @smallexample @c ada
14610 for J in 1 .. 10 loop
14621 GNAT style, compact layout Uncompact layout
14623 type q is record type q is
14624 a : integer; record
14625 b : integer; a : integer;
14626 end record; b : integer;
14629 for q use record for q use
14630 a at 0 range 0 .. 31; record
14631 b at 4 range 0 .. 31; a at 0 range 0 .. 31;
14632 end record; b at 4 range 0 .. 31;
14635 Block : declare Block :
14636 A : Integer := 3; declare
14637 begin A : Integer := 3;
14639 end Block; Proc (A, A);
14642 Clear : for J in 1 .. 10 loop Clear :
14643 A (J) := 0; for J in 1 .. 10 loop
14644 end loop Clear; A (J) := 0;
14651 A further difference between GNAT style layout and compact layout is that
14652 GNAT style layout inserts empty lines as separation for
14653 compound statements, return statements and bodies.
14655 Note that the layout specified by
14656 @option{^--separate-stmt-name^/STMT_NAME_ON_NEW_LINE^}
14657 for named block and loop statements overrides the layout defined by these
14658 constructs by @option{^-l1^/CONSTRUCT_LAYOUT=GNAT^},
14659 @option{^-l2^/CONSTRUCT_LAYOUT=COMPACT^} or
14660 @option{^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^} option.
14663 @subsection Name Casing
14666 @command{gnatpp} always converts the usage occurrence of a (simple) name to
14667 the same casing as the corresponding defining identifier.
14669 You control the casing for defining occurrences via the
14670 @option{^-n^/NAME_CASING^} switch.
14672 With @option{-nD} (``as declared'', which is the default),
14675 With @option{/NAME_CASING=AS_DECLARED}, which is the default,
14677 defining occurrences appear exactly as in the source file
14678 where they are declared.
14679 The other ^values for this switch^options for this qualifier^ ---
14680 @option{^-nU^UPPER_CASE^},
14681 @option{^-nL^LOWER_CASE^},
14682 @option{^-nM^MIXED_CASE^} ---
14684 ^upper, lower, or mixed case, respectively^the corresponding casing^.
14685 If @command{gnatpp} changes the casing of a defining
14686 occurrence, it analogously changes the casing of all the
14687 usage occurrences of this name.
14689 If the defining occurrence of a name is not in the source compilation unit
14690 currently being processed by @command{gnatpp}, the casing of each reference to
14691 this name is changed according to the value of the @option{^-n^/NAME_CASING^}
14692 switch (subject to the dictionary file mechanism described below).
14693 Thus @command{gnatpp} acts as though the @option{^-n^/NAME_CASING^} switch
14695 casing for the defining occurrence of the name.
14697 Some names may need to be spelled with casing conventions that are not
14698 covered by the upper-, lower-, and mixed-case transformations.
14699 You can arrange correct casing by placing such names in a
14700 @emph{dictionary file},
14701 and then supplying a @option{^-D^/DICTIONARY^} switch.
14702 The casing of names from dictionary files overrides
14703 any @option{^-n^/NAME_CASING^} switch.
14705 To handle the casing of Ada predefined names and the names from GNAT libraries,
14706 @command{gnatpp} assumes a default dictionary file.
14707 The name of each predefined entity is spelled with the same casing as is used
14708 for the entity in the @cite{Ada Reference Manual}.
14709 The name of each entity in the GNAT libraries is spelled with the same casing
14710 as is used in the declaration of that entity.
14712 The @w{@option{^-D-^/SPECIFIC_CASING^}} switch suppresses the use of the
14713 default dictionary file.
14714 Instead, the casing for predefined and GNAT-defined names will be established
14715 by the @option{^-n^/NAME_CASING^} switch or explicit dictionary files.
14716 For example, by default the names @code{Ada.Text_IO} and @code{GNAT.OS_Lib}
14717 will appear as just shown,
14718 even in the presence of a @option{^-nU^/NAME_CASING=UPPER_CASE^} switch.
14719 To ensure that even such names are rendered in uppercase,
14720 additionally supply the @w{@option{^-D-^/SPECIFIC_CASING^}} switch
14721 (or else, less conveniently, place these names in upper case in a dictionary
14724 A dictionary file is
14725 a plain text file; each line in this file can be either a blank line
14726 (containing only space characters and ASCII.HT characters), an Ada comment
14727 line, or the specification of exactly one @emph{casing schema}.
14729 A casing schema is a string that has the following syntax:
14733 @var{casing_schema} ::= @var{identifier} | *@var{simple_identifier}*
14735 @var{simple_identifier} ::= @var{letter}@{@var{letter_or_digit}@}
14740 (See @cite{Ada Reference Manual}, Section 2.3) for the definition of the
14741 @var{identifier} lexical element and the @var{letter_or_digit} category.)
14743 The casing schema string can be followed by white space and/or an Ada-style
14744 comment; any amount of white space is allowed before the string.
14746 If a dictionary file is passed as
14748 the value of a @option{-D@var{file}} switch
14751 an option to the @option{/DICTIONARY} qualifier
14754 simple name and every identifier, @command{gnatpp} checks if the dictionary
14755 defines the casing for the name or for some of its parts (the term ``subword''
14756 is used below to denote the part of a name which is delimited by ``_'' or by
14757 the beginning or end of the word and which does not contain any ``_'' inside):
14761 if the whole name is in the dictionary, @command{gnatpp} uses for this name
14762 the casing defined by the dictionary; no subwords are checked for this word
14765 for every subword @command{gnatpp} checks if the dictionary contains the
14766 corresponding string of the form @code{*@var{simple_identifier}*},
14767 and if it does, the casing of this @var{simple_identifier} is used
14771 if the whole name does not contain any ``_'' inside, and if for this name
14772 the dictionary contains two entries - one of the form @var{identifier},
14773 and another - of the form *@var{simple_identifier}*, then the first one
14774 is applied to define the casing of this name
14777 if more than one dictionary file is passed as @command{gnatpp} switches, each
14778 dictionary adds new casing exceptions and overrides all the existing casing
14779 exceptions set by the previous dictionaries
14782 when @command{gnatpp} checks if the word or subword is in the dictionary,
14783 this check is not case sensitive
14787 For example, suppose we have the following source to reformat:
14789 @smallexample @c ada
14792 name1 : integer := 1;
14793 name4_name3_name2 : integer := 2;
14794 name2_name3_name4 : Boolean;
14797 name2_name3_name4 := name4_name3_name2 > name1;
14803 And suppose we have two dictionaries:
14820 If @command{gnatpp} is called with the following switches:
14824 @command{gnatpp -nM -D dict1 -D dict2 test.adb}
14827 @command{gnatpp test.adb /NAME_CASING=MIXED_CASE /DICTIONARY=(dict1, dict2)}
14832 then we will get the following name casing in the @command{gnatpp} output:
14834 @smallexample @c ada
14837 NAME1 : Integer := 1;
14838 Name4_NAME3_Name2 : Integer := 2;
14839 Name2_NAME3_Name4 : Boolean;
14842 Name2_NAME3_Name4 := Name4_NAME3_Name2 > NAME1;
14848 @c *********************************
14849 @node The Ada-to-XML converter gnat2xml
14850 @chapter The Ada-to-XML converter @command{gnat2xml}
14852 @cindex XML generation
14855 The @command{gnat2xml} tool is an ASIS-based utility that converts
14856 Ada source code into XML.
14859 * Switches for gnat2xml::
14860 * Driving gnat2xml with gnatmake or gprbuild::
14862 * Structure of the XML::
14865 @node Switches for gnat2xml
14866 @section Switches for @command{gnat2xml}
14869 @command{gnat2xml} takes Ada source code as input, and produces XML
14870 that conforms to the schema.
14875 gnat2xml [options] files
14878 ``files'' are the Ada source file names.
14884 --help -- generate usage information and quit, ignoring all other options
14886 -mdir -- generate one .xml file for each Ada source file, in directory
14887 @file{dir}. (Default is to generate the XML to standard output.)
14889 -q -- debugging version, with interspersed source, and a more
14890 compact representation of "sloc". This version does not conform
14894 directories to search for dependencies
14895 You can also set the ADA_INCLUDE_PATH environment variable for this.
14897 -v -- verbose (print out the command line options, and the names of
14898 output files as they are generated).
14900 -t -- do not delete tree files when done (they are deleted by default).
14902 -cargs ... -- options to pass to gcc
14906 You can generate the ``tree files'' ahead of time using the -gnatct switch:
14909 gnatmake -gnat2012 -gnatct *.ad[sb]
14913 If tree files do not exist, @command{gnat2xml} will create them by running gcc.
14914 See the ASIS documentation for more information on tree files.
14920 gnat2xml -v -mxml-files *.ad[sb] -cargs -gnat2012
14924 The above will create *.xml files in the @file{xml-files} subdirectory.
14925 For example, if there is an Ada package Mumble.Dumble, whose spec and
14926 body source code lives in mumble-dumble.ads and mumble-dumble.adb,
14927 the above will produce xml-files/mumble-dumble.ads.xml and
14928 xml-files/mumble-dumble.adb.xml.
14930 @node Driving gnat2xml with gnatmake or gprbuild
14931 @section Driving @command{gnat2xml} with @command{gnatmake} or @command{gprbuild}
14934 You can use gnatmake or gprbuild to drive @command{gnat2xml} to get
14935 incremental updates of the XML files on a per-source-file basis. For
14936 example, if you already have a bunch of XML files, and then you change
14937 one source file, it will regenerate XML files only for that source
14938 file, and other source files that depend on it. Gnatmake and gprbuild
14939 take care of tracking inter-file dependencies. For example, if
14940 this.adb says @code{with That;}, then this.adb depends on that.ads.
14942 To do this, you tell gnatmake/gprbuild to pretend that
14943 @command{gnat2xml} is the Ada compiler (instead of using gcc as the
14944 Ada compiler, as is normal).
14946 To tell gnatmake to use @command{gnat2xml} instead of gcc as the
14947 ``compiler'', for example:
14950 gnatmake -gnatc *.adb --GCC="gnat2xml -t -mxml"
14954 The @option{--GCC=} switch tells gnatmake that the ``compiler'' to run
14955 is @command{gnat2xml -t -mxml}. The @option{-t} switch means to keep the tree
14956 files, so they can be reused on the next run. (@command{gnat2xml}
14957 deletes them by default.) As usual, @option{-mxml} means to put the
14958 XML files in the @file{xml} subdirectory.
14960 You must give the @option{-gnatc} switch to gnatmake, which means
14961 ``compile only; do not generate object code''. Otherwise, gnatmake will
14962 complain about missing object (*.o) files; @command{gnat2xml} of
14963 course does not generate *.o files.
14965 Using gprbuild is similar: you tell it to use @command{gnat2xml}
14966 instead of gcc. First write a project file, such as my_project.gpr:
14968 @smallexample @c projectfile
14969 project My_Project is
14971 package Compiler is
14972 for Driver ("ada") use "gnat2xml";
14973 -- Use gnat2xml instead of the usual gcc.
14975 for Default_Switches ("ada") use ("-t", "-mxml");
14976 -- Same switches as in the gnatmake case.
14985 @smallexample @c projectfile
14986 gprbuild --no-object-check -P my_project.gpr
14990 The @option{--no-object-check} switch serves the same purpose as
14991 @option{-gnatc} in the gnatmake case --- it tells gprbuild not to
14992 expect that the ``compiler'' (really @command{gnat2xml}) will produce
14995 See the gprbuild documentation for information on many other things
14996 you can put in the project file, such as telling it where to find
14999 @node Other Programs
15000 @section Other Programs
15003 The distribution includes two other programs that are related to
15004 @command{gnat2xml}:
15006 @command{gnat2xsd} is the schema generator, which generates the schema
15007 to standard output, based on the structure of Ada as encoded by
15008 ASIS. You don't need to run @command{gnat2xsd} in order to use
15009 @command{gnat2xml}. To generate the schema, type:
15012 gnat2xsd > ada-schema.xsd
15016 @command{gnat2xml} generates XML files that will validate against
15017 @file{ada-schema.xsd}.
15019 @command{xml2gnat} is a back-translator that translates the XML back
15020 into Ada source code. The Ada generated by @command{xml2gnat} has
15021 identical semantics to the original Ada code passed to
15022 @command{gnat2xml}. It is not textually identical, however --- for
15023 example, no attempt is made to preserve the original indentation.
15025 @node Structure of the XML
15026 @section Structure of the XML
15029 The primary documentation for the structure of the XML generated by
15030 @command{gnat2xml} is the schema (see @command{gnat2xsd} above). The
15031 following documentation gives additional details needed to understand
15032 the schema and therefore the XML.
15034 The elements listed under Defining Occurrences, Usage Occurrences, and
15035 Other Elements represent the syntactic structure of the Ada program.
15036 Element names are given in lower case, with the corresponding element
15037 type Capitalized_Like_This. The element and element type names are
15038 derived directly from the ASIS enumeration type Flat_Element_Kinds,
15039 declared in Asis.Extensions.Flat_Kinds, with the leading ``An_'' or ``A_''
15040 removed. For example, the ASIS enumeration literal
15041 An_Assignment_Statement corresponds to the XML element
15042 assignment_statement of XML type Assignment_Statement.
15044 To understand the details of the schema and the corresponding XML, it is
15045 necessary to understand the ASIS standard, as well as the GNAT-specific
15048 A defining occurrence is an identifier (or character literal or operator
15049 symbol) declared by a declaration. A usage occurrence is an identifier
15050 (or ...) that references such a declared entity. For example, in:
15053 type T is range 1..10;
15054 X, Y : constant T := 1;
15058 The first ``T'' is the defining occurrence of a type. The ``X'' is the
15059 defining occurrence of a constant, as is the ``Y'', and the second ``T'' is
15060 a usage occurrence referring to the defining occurrence of T.
15062 Each element has a 'sloc' (source location), and subelements for each
15063 syntactic subtree, reflecting the Ada grammar as implemented by ASIS.
15064 The types of subelements are as defined in the ASIS standard. For
15065 example, for the right-hand side of an assignment_statement we have
15066 the following comment in asis-statements.ads:
15069 ------------------------------------------------------------------------------
15070 -- 18.3 function Assignment_Expression
15071 ------------------------------------------------------------------------------
15073 function Assignment_Expression
15074 (Statement : Asis.Statement)
15075 return Asis.Expression;
15077 ------------------------------------------------------------------------------
15079 -- Returns the expression from the right hand side of the assignment.
15081 -- Returns Element_Kinds:
15086 The corresponding sub-element of type Assignment_Statement is:
15089 <xsd:element name="assignment_expression_q" type="Expression_Class"/>
15093 where Expression_Class is defined by an xsd:choice of all the
15094 various kinds of expression.
15096 The 'sloc' of each element indicates the starting and ending line and
15097 column numbers. Column numbers are character counts; that is, a tab
15098 counts as 1, not as however many spaces it might expand to.
15100 Subelements of type Element have names ending in ``_q'' (for ASIS
15101 ``Query''), and those of type Element_List end in ``_ql'' (``Query returning
15104 Some subelements are ``Boolean''. For example, Private_Type_Definition
15105 has has_abstract_q and has_limited_q, to indicate whether those
15106 keywords are present, as in @code{type T is abstract limited
15107 private;}. False is represented by a Nil_Element. True is represented
15108 by an element type specific to that query (for example, Abstract and
15111 The root of the tree is a Compilation_Unit, with attributes:
15115 unit_kind, unit_class, and unit_origin. These are strings that match the
15116 enumeration literals of types Unit_Kinds, Unit_Classes, and Unit_Origins
15120 unit_full_name is the full expanded name of the unit, starting from a
15121 root library unit. So for @code{package P.Q.R is ...},
15122 @code{unit_full_name="P.Q.R"}. Same for @code{separate (P.Q) package R is ...}.
15125 def_name is the same as unit_full_name for library units; for subunits,
15126 it is just the simple name.
15129 source_file is the name of the Ada source file. For example, for
15130 the spec of @code{P.Q.R}, @code{source_file="p-q-r.ads"}. This allows one to
15131 interpret the source locations --- the ``sloc'' of all elements
15132 within this Compilation_Unit refers to line and column numbers
15133 within the named file.
15137 Defining occurrences have these attributes:
15141 def_name is the simple name of the declared entity, as written in the Ada
15145 def is a unique URI of the form:
15147 ada://kind/fully/qualified/name
15151 kind indicates the kind of Ada entity being declared (see below), and
15153 fully/qualified/name, is the fully qualified name of the Ada
15154 entity, with each of ``fully'', ``qualified'', and ``name'' being
15155 mangled for uniqueness. We do not document the mangling
15156 algorithm, which is subject to change; we just guarantee that the
15157 names are unique in the face of overloading.
15160 type is the type of the declared object, or @code{null} for
15161 declarations of things other than objects.
15165 Usage occurrences have these attributes:
15169 ref_name is the same as the def_name of the corresponding defining
15170 occurrence. This attribute is not of much use, because of
15171 overloading; use ref for lookups, instead.
15174 ref is the same as the def of the corresponding defining
15179 In summary, @code{def_name} and @code{ref_name} are as in the source
15180 code of the declaration, possibly overloaded, whereas @code{def} and
15181 @code{ref} are unique-ified.
15183 Literal elements have this attribute:
15187 lit_val is the value of the literal as written in the source text,
15188 appropriately escaped (e.g. @code{"} ---> @code{"}). This applies
15189 only to numeric and string literals. Enumeration literals in Ada are
15190 not really "literals" in the usual sense; they are usage occurrences,
15191 and have ref_name and ref as described above. Note also that string
15192 literals used as operator symbols are treated as defining or usage
15193 occurrences, not as literals.
15197 Elements that can syntactically represent names and expressions (which
15198 includes usage occurrences, plus function calls and so forth) have this
15203 type. If the element represents an expression or the name of an object,
15204 'type' is the 'def' for the defining occurrence of the type of that
15205 expression or name. Names of other kinds of entities, such as package
15206 names and type names, do not have a type in Ada; these have type="null"
15211 Pragma elements have this attribute:
15215 pragma_name is the name of the pragma. For language-defined pragmas, the
15216 pragma name is redundant with the element kind (for example, an
15217 assert_pragma element necessarily has pragma_name="Assert"). However, all
15218 implementation-defined pragmas are lumped together in ASIS as a single
15219 element kind (for example, the GNAT-specific pragma Unreferenced is
15220 represented by an implementation_defined_pragma element with
15221 pragma_name="Unreferenced").
15225 Defining occurrences of formal parameters and generic formal objects have this
15230 mode indicates that the parameter is of mode 'in', 'in out', or 'out'.
15234 The "kind" part of the "def" and "ref" attributes is taken from the ASIS
15235 enumeration type Flat_Declaration_Kinds, declared in
15236 Asis.Extensions.Flat_Kinds, with the leading "An_" or "A_" removed, and
15237 any trailing "_Declaration" or "_Specification" removed. Thus, the
15238 possible kinds are as follows:
15245 tagged_incomplete_type
15256 enumeration_literal
15260 generalized_iterator
15270 expression_function
15278 generic_package_renaming
15279 generic_procedure_renaming
15280 generic_function_renaming
15286 procedure_body_stub
15290 protected_body_stub
15296 package_instantiation
15297 procedure_instantiation
15298 function_instantiation
15301 formal_incomplete_type
15305 formal_package_declaration_with_box
15309 @c *********************************
15310 @node The GNAT Metrics Tool gnatmetric
15311 @chapter The GNAT Metrics Tool @command{gnatmetric}
15313 @cindex Metric tool
15316 ^The @command{gnatmetric} tool^@command{GNAT METRIC}^ is an ASIS-based utility
15317 for computing various program metrics.
15318 It takes an Ada source file as input and generates a file containing the
15319 metrics data as output. Various switches control which
15320 metrics are computed and output.
15323 * Switches for gnatmetric::
15326 @command{gnatmetric} generates and uses the ASIS
15327 tree for the input source and thus requires the input to be syntactically and
15328 semantically legal.
15329 If this condition is not met, @command{gnatmetric} will generate
15330 an error message; no metric information for this file will be
15331 computed and reported.
15333 If the compilation unit contained in the input source depends semantically
15334 upon units in files located outside the current directory, you have to provide
15335 the source search path when invoking @command{gnatmetric}.
15336 If it depends semantically upon units that are contained
15337 in files with names that do not follow the GNAT file naming rules, you have to
15338 provide the configuration file describing the corresponding naming scheme (see
15339 the description of the @command{gnatmetric} switches below.)
15340 Alternatively, you may use a project file and invoke @command{gnatmetric}
15341 through the @command{gnat} driver (see @ref{The GNAT Driver and Project Files}).
15343 The @command{gnatmetric} command has the form
15346 @c $ gnatmetric @ovar{switches} @{@var{filename}@} @r{[}-cargs @var{gcc_switches}@r{]}
15347 @c Expanding @ovar macro inline (explanation in macro def comments)
15348 $ gnatmetric @r{[}@var{switches}@r{]} @{@var{filename}@} @r{[}-cargs @var{gcc_switches}@r{]}
15355 @var{switches} specify the metrics to compute and define the destination for
15359 Each @var{filename} is the name (including the extension) of a source
15360 file to process. ``Wildcards'' are allowed, and
15361 the file name may contain path information.
15362 If no @var{filename} is supplied, then the @var{switches} list must contain
15364 @option{-files} switch (@pxref{Other gnatmetric Switches}).
15365 Including both a @option{-files} switch and one or more
15366 @var{filename} arguments is permitted.
15369 @samp{@var{gcc_switches}} is a list of switches for
15370 @command{gcc}. They will be passed on to all compiler invocations made by
15371 @command{gnatmetric} to generate the ASIS trees. Here you can provide
15372 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
15373 and use the @option{-gnatec} switch to set the configuration file,
15374 use the @option{-gnat05} switch if sources should be compiled in
15378 @node Switches for gnatmetric
15379 @section Switches for @command{gnatmetric}
15382 The following subsections describe the various switches accepted by
15383 @command{gnatmetric}, organized by category.
15386 * Output Files Control::
15387 * Disable Metrics For Local Units::
15388 * Specifying a set of metrics to compute::
15389 * Other gnatmetric Switches::
15390 * Generate project-wide metrics::
15393 @node Output Files Control
15394 @subsection Output File Control
15395 @cindex Output file control in @command{gnatmetric}
15398 @command{gnatmetric} has two output formats. It can generate a
15399 textual (human-readable) form, and also XML. By default only textual
15400 output is generated.
15402 When generating the output in textual form, @command{gnatmetric} creates
15403 for each Ada source file a corresponding text file
15404 containing the computed metrics, except for the case when the set of metrics
15405 specified by gnatmetric parameters consists only of metrics that are computed
15406 for the whole set of analyzed sources, but not for each Ada source.
15407 By default, this file is placed in the same directory as where the source
15408 file is located, and its name is obtained
15409 by appending the ^@file{.metrix}^@file{$METRIX}^ suffix to the name of the
15412 All the output information generated in XML format is placed in a single
15413 file. By default this file is placed in the current directory and has the
15414 name ^@file{metrix.xml}^@file{METRIX$XML}^.
15416 Some of the computed metrics are summed over the units passed to
15417 @command{gnatmetric}; for example, the total number of lines of code.
15418 By default this information is sent to @file{stdout}, but a file
15419 can be specified with the @option{-og} switch.
15421 The following switches control the @command{gnatmetric} output:
15424 @cindex @option{^-x^/XML^} (@command{gnatmetric})
15426 Generate the XML output
15428 @cindex @option{^-xs^/XSD^} (@command{gnatmetric})
15430 Generate the XML output and the XML schema file that describes the structure
15431 of the XML metric report, this schema is assigned to the XML file. The schema
15432 file has the same name as the XML output file with @file{.xml} suffix replaced
15435 @cindex @option{^-nt^/NO_TEXT^} (@command{gnatmetric})
15436 @item ^-nt^/NO_TEXT^
15437 Do not generate the output in text form (implies @option{^-x^/XML^})
15439 @cindex @option{^-d^/DIRECTORY^} (@command{gnatmetric})
15440 @item ^-d @var{output_dir}^/DIRECTORY=@var{output_dir}^
15441 Put text files with detailed metrics into @var{output_dir}
15443 @cindex @option{^-o^/SUFFIX_DETAILS^} (@command{gnatmetric})
15444 @item ^-o @var{file_suffix}^/SUFFIX_DETAILS=@var{file_suffix}^
15445 Use @var{file_suffix}, instead of ^@file{.metrix}^@file{$METRIX}^
15446 in the name of the output file.
15448 @cindex @option{^-og^/GLOBAL_OUTPUT^} (@command{gnatmetric})
15449 @item ^-og @var{file_name}^/GLOBAL_OUTPUT=@var{file_name}^
15450 Put global metrics into @var{file_name}
15452 @cindex @option{^-ox^/XML_OUTPUT^} (@command{gnatmetric})
15453 @item ^-ox @var{file_name}^/XML_OUTPUT=@var{file_name}^
15454 Put the XML output into @var{file_name} (also implies @option{^-x^/XML^})
15456 @cindex @option{^-sfn^/SHORT_SOURCE_FILE_NAME^} (@command{gnatmetric})
15457 @item ^-sfn^/SHORT_SOURCE_FILE_NAME^
15458 Use ``short'' source file names in the output. (The @command{gnatmetric}
15459 output includes the name(s) of the Ada source file(s) from which the metrics
15460 are computed. By default each name includes the absolute path. The
15461 @option{^-sfn^/SHORT_SOURCE_FILE_NAME^} switch causes @command{gnatmetric}
15462 to exclude all directory information from the file names that are output.)
15466 @node Disable Metrics For Local Units
15467 @subsection Disable Metrics For Local Units
15468 @cindex Disable Metrics For Local Units in @command{gnatmetric}
15471 @command{gnatmetric} relies on the GNAT compilation model @minus{}
15473 unit per one source file. It computes line metrics for the whole source
15474 file, and it also computes syntax
15475 and complexity metrics for the file's outermost unit.
15477 By default, @command{gnatmetric} will also compute all metrics for certain
15478 kinds of locally declared program units:
15482 subprogram (and generic subprogram) bodies;
15485 package (and generic package) specs and bodies;
15488 task object and type specifications and bodies;
15491 protected object and type specifications and bodies.
15495 These kinds of entities will be referred to as
15496 @emph{eligible local program units}, or simply @emph{eligible local units},
15497 @cindex Eligible local unit (for @command{gnatmetric})
15498 in the discussion below.
15500 Note that a subprogram declaration, generic instantiation,
15501 or renaming declaration only receives metrics
15502 computation when it appear as the outermost entity
15505 Suppression of metrics computation for eligible local units can be
15506 obtained via the following switch:
15509 @cindex @option{^-n@var{x}^/SUPPRESS^} (@command{gnatmetric})
15510 @item ^-nolocal^/SUPPRESS=LOCAL_DETAILS^
15511 Do not compute detailed metrics for eligible local program units
15515 @node Specifying a set of metrics to compute
15516 @subsection Specifying a set of metrics to compute
15519 By default all the metrics are computed and reported. The switches
15520 described in this subsection allow you to control, on an individual
15521 basis, whether metrics are computed and
15522 reported. If at least one positive metric
15523 switch is specified (that is, a switch that defines that a given
15524 metric or set of metrics is to be computed), then only
15525 explicitly specified metrics are reported.
15528 * Line Metrics Control::
15529 * Syntax Metrics Control::
15530 * Complexity Metrics Control::
15531 * Coupling Metrics Control::
15534 @node Line Metrics Control
15535 @subsubsection Line Metrics Control
15536 @cindex Line metrics control in @command{gnatmetric}
15539 For any (legal) source file, and for each of its
15540 eligible local program units, @command{gnatmetric} computes the following
15545 the total number of lines;
15548 the total number of code lines (i.e., non-blank lines that are not comments)
15551 the number of comment lines
15554 the number of code lines containing end-of-line comments;
15557 the comment percentage: the ratio between the number of lines that contain
15558 comments and the number of all non-blank lines, expressed as a percentage;
15561 the number of empty lines and lines containing only space characters and/or
15562 format effectors (blank lines)
15565 the average number of code lines in subprogram bodies, task bodies, entry
15566 bodies and statement sequences in package bodies (this metric is only computed
15567 across the whole set of the analyzed units)
15572 @command{gnatmetric} sums the values of the line metrics for all the
15573 files being processed and then generates the cumulative results. The tool
15574 also computes for all the files being processed the average number of code
15577 You can use the following switches to select the specific line metrics
15578 to be computed and reported.
15581 @cindex @option{^--lines@var{x}^/LINE_COUNT_METRICS^} (@command{gnatmetric})
15584 @cindex @option{--no-lines@var{x}}
15587 @item ^--lines-all^/LINE_COUNT_METRICS=ALL^
15588 Report all the line metrics
15590 @item ^--no-lines-all^/LINE_COUNT_METRICS=NONE^
15591 Do not report any of line metrics
15593 @item ^--lines^/LINE_COUNT_METRICS=ALL_LINES^
15594 Report the number of all lines
15596 @item ^--no-lines^/LINE_COUNT_METRICS=NOALL_LINES^
15597 Do not report the number of all lines
15599 @item ^--lines-code^/LINE_COUNT_METRICS=CODE_LINES^
15600 Report the number of code lines
15602 @item ^--no-lines-code^/LINE_COUNT_METRICS=NOCODE_LINES^
15603 Do not report the number of code lines
15605 @item ^--lines-comment^/LINE_COUNT_METRICS=COMMENT_LINES^
15606 Report the number of comment lines
15608 @item ^--no-lines-comment^/LINE_COUNT_METRICS=NOCOMMENT_LINES^
15609 Do not report the number of comment lines
15611 @item ^--lines-eol-comment^/LINE_COUNT_METRICS=CODE_COMMENT_LINES^
15612 Report the number of code lines containing
15613 end-of-line comments
15615 @item ^--no-lines-eol-comment^/LINE_COUNT_METRICS=NOCODE_COMMENT_LINES^
15616 Do not report the number of code lines containing
15617 end-of-line comments
15619 @item ^--lines-ratio^/LINE_COUNT_METRICS=COMMENT_PERCENTAGE^
15620 Report the comment percentage in the program text
15622 @item ^--no-lines-ratio^/LINE_COUNT_METRICS=NOCOMMENT_PERCENTAGE^
15623 Do not report the comment percentage in the program text
15625 @item ^--lines-blank^/LINE_COUNT_METRICS=BLANK_LINES^
15626 Report the number of blank lines
15628 @item ^--no-lines-blank^/LINE_COUNT_METRICS=NOBLANK_LINES^
15629 Do not report the number of blank lines
15631 @item ^--lines-average^/LINE_COUNT_METRICS=AVERAGE_BODY_LINES^
15632 Report the average number of code lines in subprogram bodies, task bodies,
15633 entry bodies and statement sequences in package bodies. The metric is computed
15634 and reported for the whole set of processed Ada sources only.
15636 @item ^--no-lines-average^/LINE_COUNT_METRICS=NOAVERAGE_BODY_LINES^
15637 Do not report the average number of code lines in subprogram bodies,
15638 task bodies, entry bodies and statement sequences in package bodies.
15642 @node Syntax Metrics Control
15643 @subsubsection Syntax Metrics Control
15644 @cindex Syntax metrics control in @command{gnatmetric}
15647 @command{gnatmetric} computes various syntactic metrics for the
15648 outermost unit and for each eligible local unit:
15651 @item LSLOC (``Logical Source Lines Of Code'')
15652 The total number of declarations and the total number of statements. Note
15653 that the definition of declarations is the one given in the reference
15657 ``Each of the following is defined to be a declaration: any basic_declaration;
15658 an enumeration_literal_specification; a discriminant_specification;
15659 a component_declaration; a loop_parameter_specification; a
15660 parameter_specification; a subprogram_body; an entry_declaration;
15661 an entry_index_specification; a choice_parameter_specification;
15662 a generic_formal_parameter_declaration.''
15664 This means for example that each enumeration literal adds one to the count,
15665 as well as each subprogram parameter.
15667 Thus the results from this metric will be significantly greater than might
15668 be expected from a naive view of counting semicolons.
15670 @item Maximal static nesting level of inner program units
15672 @cite{Ada Reference Manual}, 10.1(1), ``A program unit is either a
15673 package, a task unit, a protected unit, a
15674 protected entry, a generic unit, or an explicitly declared subprogram other
15675 than an enumeration literal.''
15677 @item Maximal nesting level of composite syntactic constructs
15678 This corresponds to the notion of the
15679 maximum nesting level in the GNAT built-in style checks
15680 (@pxref{Style Checking})
15684 For the outermost unit in the file, @command{gnatmetric} additionally computes
15685 the following metrics:
15688 @item Public subprograms
15689 This metric is computed for package specs. It is the
15690 number of subprograms and generic subprograms declared in the visible
15691 part (including the visible part of nested packages, protected objects, and
15694 @item All subprograms
15695 This metric is computed for bodies and subunits. The
15696 metric is equal to a total number of subprogram bodies in the compilation
15698 Neither generic instantiations nor renamings-as-a-body nor body stubs
15699 are counted. Any subprogram body is counted, independently of its nesting
15700 level and enclosing constructs. Generic bodies and bodies of protected
15701 subprograms are counted in the same way as ``usual'' subprogram bodies.
15704 This metric is computed for package specs and
15705 generic package declarations. It is the total number of types
15706 that can be referenced from outside this compilation unit, plus the
15707 number of types from all the visible parts of all the visible generic
15708 packages. Generic formal types are not counted. Only types, not subtypes,
15712 Along with the total number of public types, the following
15713 types are counted and reported separately:
15720 Root tagged types (abstract, non-abstract, private, non-private). Type
15721 extensions are @emph{not} counted
15724 Private types (including private extensions)
15735 This metric is computed for any compilation unit. It is equal to the total
15736 number of the declarations of different types given in the compilation unit.
15737 The private and the corresponding full type declaration are counted as one
15738 type declaration. Incomplete type declarations and generic formal types
15740 No distinction is made among different kinds of types (abstract,
15741 private etc.); the total number of types is computed and reported.
15746 By default, all the syntax metrics are computed and reported. You can use the
15747 following switches to select specific syntax metrics.
15751 @cindex @option{^--syntax@var{x}^/SYNTAX_METRICS^} (@command{gnatmetric})
15754 @cindex @option{--no-syntax@var{x}} (@command{gnatmetric})
15757 @item ^--syntax-all^/SYNTAX_METRICS=ALL^
15758 Report all the syntax metrics
15760 @item ^--no-syntax-all^/SYNTAX_METRICS=NONE^
15761 Do not report any of syntax metrics
15763 @item ^--declarations^/SYNTAX_METRICS=DECLARATIONS^
15764 Report the total number of declarations
15766 @item ^--no-declarations^/SYNTAX_METRICS=NODECLARATIONS^
15767 Do not report the total number of declarations
15769 @item ^--statements^/SYNTAX_METRICS=STATEMENTS^
15770 Report the total number of statements
15772 @item ^--no-statements^/SYNTAX_METRICS=NOSTATEMENTS^
15773 Do not report the total number of statements
15775 @item ^--public-subprograms^/SYNTAX_METRICS=PUBLIC_SUBPROGRAMS^
15776 Report the number of public subprograms in a compilation unit
15778 @item ^--no-public-subprograms^/SYNTAX_METRICS=NOPUBLIC_SUBPROGRAMS^
15779 Do not report the number of public subprograms in a compilation unit
15781 @item ^--all-subprograms^/SYNTAX_METRICS=ALL_SUBPROGRAMS^
15782 Report the number of all the subprograms in a compilation unit
15784 @item ^--no-all-subprograms^/SYNTAX_METRICS=NOALL_SUBPROGRAMS^
15785 Do not report the number of all the subprograms in a compilation unit
15787 @item ^--public-types^/SYNTAX_METRICS=PUBLIC_TYPES^
15788 Report the number of public types in a compilation unit
15790 @item ^--no-public-types^/SYNTAX_METRICS=NOPUBLIC_TYPES^
15791 Do not report the number of public types in a compilation unit
15793 @item ^--all-types^/SYNTAX_METRICS=ALL_TYPES^
15794 Report the number of all the types in a compilation unit
15796 @item ^--no-all-types^/SYNTAX_METRICS=NOALL_TYPES^
15797 Do not report the number of all the types in a compilation unit
15799 @item ^--unit-nesting^/SYNTAX_METRICS=UNIT_NESTING^
15800 Report the maximal program unit nesting level
15802 @item ^--no-unit-nesting^/SYNTAX_METRICS=UNIT_NESTING_OFF^
15803 Do not report the maximal program unit nesting level
15805 @item ^--construct-nesting^/SYNTAX_METRICS=CONSTRUCT_NESTING^
15806 Report the maximal construct nesting level
15808 @item ^--no-construct-nesting^/SYNTAX_METRICS=NOCONSTRUCT_NESTING^
15809 Do not report the maximal construct nesting level
15813 @node Complexity Metrics Control
15814 @subsubsection Complexity Metrics Control
15815 @cindex Complexity metrics control in @command{gnatmetric}
15818 For a program unit that is an executable body (a subprogram body (including
15819 generic bodies), task body, entry body or a package body containing
15820 its own statement sequence) @command{gnatmetric} computes the following
15821 complexity metrics:
15825 McCabe cyclomatic complexity;
15828 McCabe essential complexity;
15831 maximal loop nesting level;
15834 extra exit points (for subprograms);
15838 The McCabe cyclomatic complexity metric is defined
15839 in @url{http://www.mccabe.com/pdf/mccabe-nist235r.pdf}
15841 According to McCabe, both control statements and short-circuit control forms
15842 should be taken into account when computing cyclomatic complexity.
15843 For Ada 2012 we have also take into account conditional expressions
15844 and quantified expressions. For each body, we compute three metric values:
15848 the complexity introduced by control
15849 statements only, without taking into account short-circuit forms,
15852 the complexity introduced by short-circuit control forms only, and
15856 cyclomatic complexity, which is the sum of these two values.
15861 The cyclomatic complexity is also computed for Ada 2012 expression functions.
15862 An expression function cannot have statements as its components, so only one
15863 metric value is computed as a cyclomatic complexity of an expression function.
15865 The origin of cyclomatic complexity metric is the need to estimate the number
15866 of independent paths in the control flow graph that in turn gives the number
15867 of tests needed to satisfy paths coverage testing completeness criterion.
15868 Considered from the testing point of view, a static Ada @code{loop} (that is,
15869 the @code{loop} statement having static subtype in loop parameter
15870 specification) does not add to cyclomatic complexity. By providing
15871 @option{^--no-static-loop^NO_STATIC_LOOP^} option a user
15872 may specify that such loops should not be counted when computing the
15873 cyclomatic complexity metric
15875 The Ada essential complexity metric is a McCabe cyclomatic complexity metric
15876 counted for the code that is reduced by excluding all the pure structural Ada
15877 control statements. An compound statement is considered as a non-structural
15878 if it contains a @code{raise} or @code{return} statement as it subcomponent,
15879 or if it contains a @code{goto} statement that transfers the control outside
15880 the operator. A selective accept statement with @code{terminate} alternative
15881 is considered as non-structural statement. When computing this metric,
15882 @code{exit} statements are treated in the same way as @code{goto}
15883 statements unless @option{^-ne^NO_EXITS_AS_GOTOS^} option is specified.
15885 The Ada essential complexity metric defined here is intended to quantify
15886 the extent to which the software is unstructured. It is adapted from
15887 the McCabe essential complexity metric defined in
15888 @url{http://www.mccabe.com/pdf/mccabe-nist235r.pdf} but is modified to be more
15889 suitable for typical Ada usage. For example, short circuit forms
15890 are not penalized as unstructured in the Ada essential complexity metric.
15892 When computing cyclomatic and essential complexity, @command{gnatmetric} skips
15893 the code in the exception handlers and in all the nested program units. The
15894 code of assertions and predicates (that is, subprogram preconditions and
15895 postconditions, subtype predicates and type invariants) is also skipped.
15897 By default, all the complexity metrics are computed and reported.
15898 For more fine-grained control you can use
15899 the following switches:
15902 @cindex @option{^-complexity@var{x}^/COMPLEXITY_METRICS^} (@command{gnatmetric})
15905 @cindex @option{--no-complexity@var{x}}
15908 @item ^--complexity-all^/COMPLEXITY_METRICS=ALL^
15909 Report all the complexity metrics
15911 @item ^--no-complexity-all^/COMPLEXITY_METRICS=NONE^
15912 Do not report any of complexity metrics
15914 @item ^--complexity-cyclomatic^/COMPLEXITY_METRICS=CYCLOMATIC^
15915 Report the McCabe Cyclomatic Complexity
15917 @item ^--no-complexity-cyclomatic^/COMPLEXITY_METRICS=NOCYCLOMATIC^
15918 Do not report the McCabe Cyclomatic Complexity
15920 @item ^--complexity-essential^/COMPLEXITY_METRICS=ESSENTIAL^
15921 Report the Essential Complexity
15923 @item ^--no-complexity-essential^/COMPLEXITY_METRICS=NOESSENTIAL^
15924 Do not report the Essential Complexity
15926 @item ^--loop-nesting^/COMPLEXITY_METRICS=LOOP_NESTING_ON^
15927 Report maximal loop nesting level
15929 @item ^--no-loop-nesting^/COMPLEXITY_METRICS=NOLOOP_NESTING^
15930 Do not report maximal loop nesting level
15932 @item ^--complexity-average^/COMPLEXITY_METRICS=AVERAGE_COMPLEXITY^
15933 Report the average McCabe Cyclomatic Complexity for all the subprogram bodies,
15934 task bodies, entry bodies and statement sequences in package bodies.
15935 The metric is computed and reported for whole set of processed Ada sources
15938 @item ^--no-complexity-average^/COMPLEXITY_METRICS=NOAVERAGE_COMPLEXITY^
15939 Do not report the average McCabe Cyclomatic Complexity for all the subprogram
15940 bodies, task bodies, entry bodies and statement sequences in package bodies
15942 @cindex @option{^-ne^/NO_EXITS_AS_GOTOS^} (@command{gnatmetric})
15943 @item ^-ne^/NO_EXITS_AS_GOTOS^
15944 Do not consider @code{exit} statements as @code{goto}s when
15945 computing Essential Complexity
15947 @cindex @option{^--no-static-loop^/NO_STATIC_LOOP^} (@command{gnatmetric})
15948 @item ^--no-static-loop^/NO_STATIC_LOOP^
15949 Do not consider static loops when computing cyclomatic complexity
15951 @item ^--extra-exit-points^/EXTRA_EXIT_POINTS^
15952 Report the extra exit points for subprogram bodies. As an exit point, this
15953 metric counts @code{return} statements and raise statements in case when the
15954 raised exception is not handled in the same body. In case of a function this
15955 metric subtracts 1 from the number of exit points, because a function body
15956 must contain at least one @code{return} statement.
15958 @item ^--no-extra-exit-points^/NOEXTRA_EXIT_POINTS^
15959 Do not report the extra exit points for subprogram bodies
15963 @node Coupling Metrics Control
15964 @subsubsection Coupling Metrics Control
15965 @cindex Coupling metrics control in @command{gnatmetric}
15968 @cindex Coupling metrics (in in @command{gnatmetric})
15969 Coupling metrics measure the dependencies between a given entity and other
15970 entities the program consists of. The goal of these metrics is to estimate the
15971 stability of the whole program considered as the collection of entities
15972 (modules, classes etc.).
15974 Gnatmetric computes the following coupling metrics:
15979 @emph{object-oriented coupling} - for classes in traditional object-oriented
15983 @emph{unit coupling} - for all the program units making up a program;
15986 @emph{control coupling} - this metric counts dependencies between a unit and
15987 only those units that define subprograms;
15991 Two kinds of coupling metrics are computed:
15994 @item fan-out coupling (efferent coupling)
15995 @cindex fan-out coupling
15996 @cindex efferent coupling
15997 the number of entities the given entity depends upon. It
15998 estimates in what extent the given entity depends on the changes in
16001 @item fan-in coupling (afferent coupling)
16002 @cindex fan-in coupling
16003 @cindex afferent coupling
16004 the number of entities that depend on a given entity.
16005 It estimates in what extent the ``external world'' depends on the changes in a
16011 Object-oriented coupling metrics are metrics that measure the dependencies
16012 between a given class (or a group of classes) and the other classes in the
16013 program. In this subsection the term ``class'' is used in its traditional
16014 object-oriented programming sense (an instantiable module that contains data
16015 and/or method members). A @emph{category} (of classes) is a group of closely
16016 related classes that are reused and/or modified together.
16018 A class @code{K}'s fan-out coupling is the number of classes
16019 that @code{K} depends upon.
16020 A category's fan-out coupling is the number of classes outside the
16021 category that the classes inside the category depend upon.
16023 A class @code{K}'s fan-in coupling is the number of classes
16024 that depend upon @code{K}.
16025 A category's fan-in coupling is the number of classes outside the
16026 category that depend on classes belonging to the category.
16028 Ada's implementation of the object-oriented paradigm does not use the
16029 traditional class notion, so the definition of the coupling
16030 metrics for Ada maps the class and class category notions
16031 onto Ada constructs.
16033 For the coupling metrics, several kinds of modules -- a library package,
16034 a library generic package, and a library generic package instantiation --
16035 that define a tagged type or an interface type are
16036 considered to be a class. A category consists of a library package (or
16037 a library generic package) that defines a tagged or an interface type,
16038 together with all its descendant (generic) packages that define tagged
16039 or interface types. That is a
16040 category is an Ada hierarchy of library-level program units. So class coupling
16041 in case of Ada is called as tagged coupling, and category coupling - as
16042 hierarchy coupling.
16044 For any package counted as a class, its body and subunits (if any) are
16045 considered together with its spec when counting the dependencies, and coupling
16046 metrics are reported for spec units only. For dependencies between classes,
16047 the Ada semantic dependencies are considered. For object-oriented coupling
16048 metrics, only dependencies on units that are considered as classes, are
16051 For unit and control coupling also not compilation units but program units are
16052 counted. That is, for a package, its spec, its body and its subunits (if any)
16053 are considered as making up one unit, and the dependencies that are counted
16054 are the dependencies of all these compilation units collected together as
16055 the dependencies as a (whole) unit. And metrics are reported for spec
16056 compilation units only (or for a subprogram body unit in case if there is no
16057 separate spec for the given subprogram).
16059 For unit coupling, dependencies between all kinds of program units are
16060 considered. For control coupling, for each unit the dependencies of this unit
16061 upon units that define subprograms are counted, so control fan-out coupling
16062 is reported for all units, but control fan-in coupling - only for the units
16063 that define subprograms.
16065 The following simple example illustrates the difference between unit coupling
16066 and control coupling metrics:
16068 @smallexample @c ada
16070 function F_1 (I : Integer) return Integer;
16074 type T_2 is new Integer;
16077 package body Lib_1 is
16078 function F_1 (I : Integer) return Integer is
16084 with Lib_2; use Lib_2;
16087 function Fun (I : Integer) return Integer;
16090 with Lib_1; use Lib_1;
16091 package body Pack is
16092 function Fun (I : Integer) return Integer is
16100 if we apply @command{gnatmetric} with @code{--coupling-all} option to these
16101 units, the result will be:
16106 Unit Lib_1 (C:\customers\662\L406-007\lib_1.ads)
16107 control fan-out coupling : 0
16108 control fan-in coupling : 1
16109 unit fan-out coupling : 0
16110 unit fan-in coupling : 1
16112 Unit Pack (C:\customers\662\L406-007\pack.ads)
16113 control fan-out coupling : 1
16114 control fan-in coupling : 0
16115 unit fan-out coupling : 2
16116 unit fan-in coupling : 0
16118 Unit Lib_2 (C:\customers\662\L406-007\lib_2.ads)
16119 control fan-out coupling : 0
16120 unit fan-out coupling : 0
16121 unit fan-in coupling : 1
16125 The result does not contain values for object-oriented
16126 coupling because none of the argument unit contains a tagged type and
16127 therefore none of these units can be treated as a class.
16129 @code{Pack} (considered as a program unit, that is spec+body) depends on two
16130 units - @code{Lib_1} @code{and Lib_2}, therefore it has unit fan-out coupling
16131 equals to 2. And nothing depend on it, so its unit fan-in coupling is 0 as
16132 well as control fan-in coupling. Only one of the units @code{Pack} depends
16133 upon defines a subprogram, so its control fan-out coupling is 1.
16135 @code{Lib_2} depends on nothing, so fan-out metrics for it are 0. It does
16136 not define a subprogram, so control fan-in metric cannot be applied to it,
16137 and there is one unit that depends on it (@code{Pack}), so it has
16138 unit fan-in coupling equals to 1.
16140 @code{Lib_1} is similar to @code{Lib_2}, but it does define a subprogram.
16141 So it has control fan-in coupling equals to 1 (because there is a unit
16144 When computing coupling metrics, @command{gnatmetric} counts only
16145 dependencies between units that are arguments of the @command{gnatmetric}
16146 call. Coupling metrics are program-wide (or project-wide) metrics, so to
16147 get a valid result, you should call @command{gnatmetric} for
16148 the whole set of sources that make up your program. It can be done
16149 by calling @command{gnatmetric} from the GNAT driver with @option{-U}
16150 option (see @ref{The GNAT Driver and Project Files} for details).
16152 By default, all the coupling metrics are disabled. You can use the following
16153 switches to specify the coupling metrics to be computed and reported:
16158 @cindex @option{--tagged-coupling@var{x}} (@command{gnatmetric})
16159 @cindex @option{--hierarchy-coupling@var{x}} (@command{gnatmetric})
16160 @cindex @option{--unit-coupling@var{x}} (@command{gnatmetric})
16161 @cindex @option{--control-coupling@var{x}} (@command{gnatmetric})
16165 @cindex @option{/COUPLING_METRICS} (@command{gnatmetric})
16168 @item ^--coupling-all^/COUPLING_METRICS=ALL^
16169 Report all the coupling metrics
16171 @item ^--tagged-coupling-out^/COUPLING_METRICS=TAGGED_OUT^
16172 Report tagged (class) fan-out coupling
16174 @item ^--tagged-coupling-in^/COUPLING_METRICS=TAGGED_IN^
16175 Report tagged (class) fan-in coupling
16177 @item ^--hierarchy-coupling-out^/COUPLING_METRICS=HIERARCHY_OUT^
16178 Report hierarchy (category) fan-out coupling
16180 @item ^--hierarchy-coupling-in^/COUPLING_METRICS=HIERARCHY_IN^
16181 Report hierarchy (category) fan-in coupling
16183 @item ^--unit-coupling-out^/COUPLING_METRICS=UNIT_OUT^
16184 Report unit fan-out coupling
16186 @item ^--unit-coupling-in^/COUPLING_METRICS=UNIT_IN^
16187 Report unit fan-in coupling
16189 @item ^--control-coupling-out^/COUPLING_METRICS=CONTROL_OUT^
16190 Report control fan-out coupling
16192 @item ^--control-coupling-in^/COUPLING_METRICS=CONTROL_IN^
16193 Report control fan-in coupling
16196 @node Other gnatmetric Switches
16197 @subsection Other @code{gnatmetric} Switches
16200 Additional @command{gnatmetric} switches are as follows:
16204 @cindex @option{--version} @command{gnatmetric}
16205 Display Copyright and version, then exit disregarding all other options.
16208 @cindex @option{--help} @command{gnatmetric}
16209 Display usage, then exit disregarding all other options.
16211 @item ^-files @var{filename}^/FILES=@var{filename}^
16212 @cindex @option{^-files^/FILES^} (@code{gnatmetric})
16213 Take the argument source files from the specified file. This file should be an
16214 ordinary text file containing file names separated by spaces or
16215 line breaks. You can use this switch more than once in the same call to
16216 @command{gnatmetric}. You also can combine this switch with
16217 an explicit list of files.
16219 @item ^-v^/VERBOSE^
16220 @cindex @option{^-v^/VERBOSE^} (@code{gnatmetric})
16222 @command{gnatmetric} generates version information and then
16223 a trace of sources being processed.
16226 @cindex @option{^-q^/QUIET^} (@code{gnatmetric})
16230 @node Generate project-wide metrics
16231 @subsection Generate project-wide metrics
16233 In order to compute metrics on all units of a given project, you can use
16234 the @command{gnat} driver along with the @option{-P} option:
16240 If the project @code{proj} depends upon other projects, you can compute
16241 the metrics on the project closure using the @option{-U} option:
16243 gnat metric -Pproj -U
16247 Finally, if not all the units are relevant to a particular main
16248 program in the project closure, you can generate metrics for the set
16249 of units needed to create a given main program (unit closure) using
16250 the @option{-U} option followed by the name of the main unit:
16252 gnat metric -Pproj -U main
16256 @c ***********************************
16257 @node File Name Krunching with gnatkr
16258 @chapter File Name Krunching with @code{gnatkr}
16262 This chapter discusses the method used by the compiler to shorten
16263 the default file names chosen for Ada units so that they do not
16264 exceed the maximum length permitted. It also describes the
16265 @code{gnatkr} utility that can be used to determine the result of
16266 applying this shortening.
16270 * Krunching Method::
16271 * Examples of gnatkr Usage::
16275 @section About @code{gnatkr}
16278 The default file naming rule in GNAT
16279 is that the file name must be derived from
16280 the unit name. The exact default rule is as follows:
16283 Take the unit name and replace all dots by hyphens.
16285 If such a replacement occurs in the
16286 second character position of a name, and the first character is
16287 ^@samp{a}, @samp{g}, @samp{s}, or @samp{i}, ^@samp{A}, @samp{G}, @samp{S}, or @samp{I},^
16288 then replace the dot by the character
16289 ^@samp{~} (tilde)^@samp{$} (dollar sign)^
16290 instead of a minus.
16292 The reason for this exception is to avoid clashes
16293 with the standard names for children of System, Ada, Interfaces,
16294 and GNAT, which use the prefixes
16295 ^@samp{s-}, @samp{a-}, @samp{i-}, and @samp{g-},^@samp{S-}, @samp{A-}, @samp{I-}, and @samp{G-},^
16298 The @option{^-gnatk^/FILE_NAME_MAX_LENGTH=^@var{nn}}
16299 switch of the compiler activates a ``krunching''
16300 circuit that limits file names to nn characters (where nn is a decimal
16301 integer). For example, using OpenVMS,
16302 where the maximum file name length is
16303 39, the value of nn is usually set to 39, but if you want to generate
16304 a set of files that would be usable if ported to a system with some
16305 different maximum file length, then a different value can be specified.
16306 The default value of 39 for OpenVMS need not be specified.
16308 The @code{gnatkr} utility can be used to determine the krunched name for
16309 a given file, when krunched to a specified maximum length.
16312 @section Using @code{gnatkr}
16315 The @code{gnatkr} command has the form
16319 @c $ gnatkr @var{name} @ovar{length}
16320 @c Expanding @ovar macro inline (explanation in macro def comments)
16321 $ gnatkr @var{name} @r{[}@var{length}@r{]}
16327 $ gnatkr @var{name} /COUNT=nn
16332 @var{name} is the uncrunched file name, derived from the name of the unit
16333 in the standard manner described in the previous section (i.e., in particular
16334 all dots are replaced by hyphens). The file name may or may not have an
16335 extension (defined as a suffix of the form period followed by arbitrary
16336 characters other than period). If an extension is present then it will
16337 be preserved in the output. For example, when krunching @file{hellofile.ads}
16338 to eight characters, the result will be hellofil.ads.
16340 Note: for compatibility with previous versions of @code{gnatkr} dots may
16341 appear in the name instead of hyphens, but the last dot will always be
16342 taken as the start of an extension. So if @code{gnatkr} is given an argument
16343 such as @file{Hello.World.adb} it will be treated exactly as if the first
16344 period had been a hyphen, and for example krunching to eight characters
16345 gives the result @file{hellworl.adb}.
16347 Note that the result is always all lower case (except on OpenVMS where it is
16348 all upper case). Characters of the other case are folded as required.
16350 @var{length} represents the length of the krunched name. The default
16351 when no argument is given is ^8^39^ characters. A length of zero stands for
16352 unlimited, in other words do not chop except for system files where the
16353 implied crunching length is always eight characters.
16356 The output is the krunched name. The output has an extension only if the
16357 original argument was a file name with an extension.
16359 @node Krunching Method
16360 @section Krunching Method
16363 The initial file name is determined by the name of the unit that the file
16364 contains. The name is formed by taking the full expanded name of the
16365 unit and replacing the separating dots with hyphens and
16366 using ^lowercase^uppercase^
16367 for all letters, except that a hyphen in the second character position is
16368 replaced by a ^tilde^dollar sign^ if the first character is
16369 ^@samp{a}, @samp{i}, @samp{g}, or @samp{s}^@samp{A}, @samp{I}, @samp{G}, or @samp{S}^.
16370 The extension is @code{.ads} for a
16371 spec and @code{.adb} for a body.
16372 Krunching does not affect the extension, but the file name is shortened to
16373 the specified length by following these rules:
16377 The name is divided into segments separated by hyphens, tildes or
16378 underscores and all hyphens, tildes, and underscores are
16379 eliminated. If this leaves the name short enough, we are done.
16382 If the name is too long, the longest segment is located (left-most
16383 if there are two of equal length), and shortened by dropping
16384 its last character. This is repeated until the name is short enough.
16386 As an example, consider the krunching of @*@file{our-strings-wide_fixed.adb}
16387 to fit the name into 8 characters as required by some operating systems.
16390 our-strings-wide_fixed 22
16391 our strings wide fixed 19
16392 our string wide fixed 18
16393 our strin wide fixed 17
16394 our stri wide fixed 16
16395 our stri wide fixe 15
16396 our str wide fixe 14
16397 our str wid fixe 13
16403 Final file name: oustwifi.adb
16407 The file names for all predefined units are always krunched to eight
16408 characters. The krunching of these predefined units uses the following
16409 special prefix replacements:
16413 replaced by @file{^a^A^-}
16416 replaced by @file{^g^G^-}
16419 replaced by @file{^i^I^-}
16422 replaced by @file{^s^S^-}
16425 These system files have a hyphen in the second character position. That
16426 is why normal user files replace such a character with a
16427 ^tilde^dollar sign^, to
16428 avoid confusion with system file names.
16430 As an example of this special rule, consider
16431 @*@file{ada-strings-wide_fixed.adb}, which gets krunched as follows:
16434 ada-strings-wide_fixed 22
16435 a- strings wide fixed 18
16436 a- string wide fixed 17
16437 a- strin wide fixed 16
16438 a- stri wide fixed 15
16439 a- stri wide fixe 14
16440 a- str wide fixe 13
16446 Final file name: a-stwifi.adb
16450 Of course no file shortening algorithm can guarantee uniqueness over all
16451 possible unit names, and if file name krunching is used then it is your
16452 responsibility to ensure that no name clashes occur. The utility
16453 program @code{gnatkr} is supplied for conveniently determining the
16454 krunched name of a file.
16456 @node Examples of gnatkr Usage
16457 @section Examples of @code{gnatkr} Usage
16464 $ gnatkr very_long_unit_name.ads --> velounna.ads
16465 $ gnatkr grandparent-parent-child.ads --> grparchi.ads
16466 $ gnatkr Grandparent.Parent.Child.ads --> grparchi.ads
16467 $ gnatkr grandparent-parent-child --> grparchi
16469 $ gnatkr very_long_unit_name.ads/count=6 --> vlunna.ads
16470 $ gnatkr very_long_unit_name.ads/count=0 --> very_long_unit_name.ads
16473 @node Preprocessing with gnatprep
16474 @chapter Preprocessing with @code{gnatprep}
16478 This chapter discusses how to use GNAT's @code{gnatprep} utility for simple
16480 Although designed for use with GNAT, @code{gnatprep} does not depend on any
16481 special GNAT features.
16482 For further discussion of conditional compilation in general, see
16483 @ref{Conditional Compilation}.
16486 * Preprocessing Symbols::
16488 * Switches for gnatprep::
16489 * Form of Definitions File::
16490 * Form of Input Text for gnatprep::
16493 @node Preprocessing Symbols
16494 @section Preprocessing Symbols
16497 Preprocessing symbols are defined in definition files and referred to in
16498 sources to be preprocessed. A Preprocessing symbol is an identifier, following
16499 normal Ada (case-insensitive) rules for its syntax, with the restriction that
16500 all characters need to be in the ASCII set (no accented letters).
16502 @node Using gnatprep
16503 @section Using @code{gnatprep}
16506 To call @code{gnatprep} use
16509 @c $ gnatprep @ovar{switches} @var{infile} @var{outfile} @ovar{deffile}
16510 @c Expanding @ovar macro inline (explanation in macro def comments)
16511 $ gnatprep @r{[}@var{switches}@r{]} @var{infile} @var{outfile} @r{[}@var{deffile}@r{]}
16518 is an optional sequence of switches as described in the next section.
16521 is the full name of the input file, which is an Ada source
16522 file containing preprocessor directives.
16525 is the full name of the output file, which is an Ada source
16526 in standard Ada form. When used with GNAT, this file name will
16527 normally have an ads or adb suffix.
16530 is the full name of a text file containing definitions of
16531 preprocessing symbols to be referenced by the preprocessor. This argument is
16532 optional, and can be replaced by the use of the @option{-D} switch.
16536 @node Switches for gnatprep
16537 @section Switches for @code{gnatprep}
16542 @item ^-b^/BLANK_LINES^
16543 @cindex @option{^-b^/BLANK_LINES^} (@command{gnatprep})
16544 Causes both preprocessor lines and the lines deleted by
16545 preprocessing to be replaced by blank lines in the output source file,
16546 preserving line numbers in the output file.
16548 @item ^-c^/COMMENTS^
16549 @cindex @option{^-c^/COMMENTS^} (@command{gnatprep})
16550 Causes both preprocessor lines and the lines deleted
16551 by preprocessing to be retained in the output source as comments marked
16552 with the special string @code{"--! "}. This option will result in line numbers
16553 being preserved in the output file.
16555 @item ^-C^/REPLACE_IN_COMMENTS^
16556 @cindex @option{^-C^/REPLACE_IN_COMMENTS^} (@command{gnatprep})
16557 Causes comments to be scanned. Normally comments are ignored by gnatprep.
16558 If this option is specified, then comments are scanned and any $symbol
16559 substitutions performed as in program text. This is particularly useful
16560 when structured comments are used (e.g., when writing programs in the
16561 SPARK dialect of Ada). Note that this switch is not available when
16562 doing integrated preprocessing (it would be useless in this context
16563 since comments are ignored by the compiler in any case).
16565 @item ^-Dsymbol=value^/ASSOCIATE="symbol=value"^
16566 @cindex @option{^-D^/ASSOCIATE^} (@command{gnatprep})
16567 Defines a new preprocessing symbol, associated with value. If no value is given
16568 on the command line, then symbol is considered to be @code{True}. This switch
16569 can be used in place of a definition file.
16573 @cindex @option{/REMOVE} (@command{gnatprep})
16574 This is the default setting which causes lines deleted by preprocessing
16575 to be entirely removed from the output file.
16578 @item ^-r^/REFERENCE^
16579 @cindex @option{^-r^/REFERENCE^} (@command{gnatprep})
16580 Causes a @code{Source_Reference} pragma to be generated that
16581 references the original input file, so that error messages will use
16582 the file name of this original file. The use of this switch implies
16583 that preprocessor lines are not to be removed from the file, so its
16584 use will force @option{^-b^/BLANK_LINES^} mode if
16585 @option{^-c^/COMMENTS^}
16586 has not been specified explicitly.
16588 Note that if the file to be preprocessed contains multiple units, then
16589 it will be necessary to @code{gnatchop} the output file from
16590 @code{gnatprep}. If a @code{Source_Reference} pragma is present
16591 in the preprocessed file, it will be respected by
16592 @code{gnatchop ^-r^/REFERENCE^}
16593 so that the final chopped files will correctly refer to the original
16594 input source file for @code{gnatprep}.
16596 @item ^-s^/SYMBOLS^
16597 @cindex @option{^-s^/SYMBOLS^} (@command{gnatprep})
16598 Causes a sorted list of symbol names and values to be
16599 listed on the standard output file.
16601 @item ^-u^/UNDEFINED^
16602 @cindex @option{^-u^/UNDEFINED^} (@command{gnatprep})
16603 Causes undefined symbols to be treated as having the value FALSE in the context
16604 of a preprocessor test. In the absence of this option, an undefined symbol in
16605 a @code{#if} or @code{#elsif} test will be treated as an error.
16611 Note: if neither @option{-b} nor @option{-c} is present,
16612 then preprocessor lines and
16613 deleted lines are completely removed from the output, unless -r is
16614 specified, in which case -b is assumed.
16617 @node Form of Definitions File
16618 @section Form of Definitions File
16621 The definitions file contains lines of the form
16628 where symbol is a preprocessing symbol, and value is one of the following:
16632 Empty, corresponding to a null substitution
16634 A string literal using normal Ada syntax
16636 Any sequence of characters from the set
16637 (letters, digits, period, underline).
16641 Comment lines may also appear in the definitions file, starting with
16642 the usual @code{--},
16643 and comments may be added to the definitions lines.
16645 @node Form of Input Text for gnatprep
16646 @section Form of Input Text for @code{gnatprep}
16649 The input text may contain preprocessor conditional inclusion lines,
16650 as well as general symbol substitution sequences.
16652 The preprocessor conditional inclusion commands have the form
16657 #if @i{expression} @r{[}then@r{]}
16659 #elsif @i{expression} @r{[}then@r{]}
16661 #elsif @i{expression} @r{[}then@r{]}
16672 In this example, @i{expression} is defined by the following grammar:
16674 @i{expression} ::= <symbol>
16675 @i{expression} ::= <symbol> = "<value>"
16676 @i{expression} ::= <symbol> = <symbol>
16677 @i{expression} ::= <symbol> 'Defined
16678 @i{expression} ::= not @i{expression}
16679 @i{expression} ::= @i{expression} and @i{expression}
16680 @i{expression} ::= @i{expression} or @i{expression}
16681 @i{expression} ::= @i{expression} and then @i{expression}
16682 @i{expression} ::= @i{expression} or else @i{expression}
16683 @i{expression} ::= ( @i{expression} )
16686 The following restriction exists: it is not allowed to have "and" or "or"
16687 following "not" in the same expression without parentheses. For example, this
16694 This should be one of the following:
16702 For the first test (@i{expression} ::= <symbol>) the symbol must have
16703 either the value true or false, that is to say the right-hand of the
16704 symbol definition must be one of the (case-insensitive) literals
16705 @code{True} or @code{False}. If the value is true, then the
16706 corresponding lines are included, and if the value is false, they are
16709 The test (@i{expression} ::= <symbol> @code{'Defined}) is true only if
16710 the symbol has been defined in the definition file or by a @option{-D}
16711 switch on the command line. Otherwise, the test is false.
16713 The equality tests are case insensitive, as are all the preprocessor lines.
16715 If the symbol referenced is not defined in the symbol definitions file,
16716 then the effect depends on whether or not switch @option{-u}
16717 is specified. If so, then the symbol is treated as if it had the value
16718 false and the test fails. If this switch is not specified, then
16719 it is an error to reference an undefined symbol. It is also an error to
16720 reference a symbol that is defined with a value other than @code{True}
16723 The use of the @code{not} operator inverts the sense of this logical test.
16724 The @code{not} operator cannot be combined with the @code{or} or @code{and}
16725 operators, without parentheses. For example, "if not X or Y then" is not
16726 allowed, but "if (not X) or Y then" and "if not (X or Y) then" are.
16728 The @code{then} keyword is optional as shown
16730 The @code{#} must be the first non-blank character on a line, but
16731 otherwise the format is free form. Spaces or tabs may appear between
16732 the @code{#} and the keyword. The keywords and the symbols are case
16733 insensitive as in normal Ada code. Comments may be used on a
16734 preprocessor line, but other than that, no other tokens may appear on a
16735 preprocessor line. Any number of @code{elsif} clauses can be present,
16736 including none at all. The @code{else} is optional, as in Ada.
16738 The @code{#} marking the start of a preprocessor line must be the first
16739 non-blank character on the line, i.e., it must be preceded only by
16740 spaces or horizontal tabs.
16742 Symbol substitution outside of preprocessor lines is obtained by using
16750 anywhere within a source line, except in a comment or within a
16751 string literal. The identifier
16752 following the @code{$} must match one of the symbols defined in the symbol
16753 definition file, and the result is to substitute the value of the
16754 symbol in place of @code{$symbol} in the output file.
16756 Note that although the substitution of strings within a string literal
16757 is not possible, it is possible to have a symbol whose defined value is
16758 a string literal. So instead of setting XYZ to @code{hello} and writing:
16761 Header : String := "$XYZ";
16765 you should set XYZ to @code{"hello"} and write:
16768 Header : String := $XYZ;
16772 and then the substitution will occur as desired.
16774 @node The GNAT Library Browser gnatls
16775 @chapter The GNAT Library Browser @code{gnatls}
16777 @cindex Library browser
16780 @code{gnatls} is a tool that outputs information about compiled
16781 units. It gives the relationship between objects, unit names and source
16782 files. It can also be used to check the source dependencies of a unit
16783 as well as various characteristics.
16785 Note: to invoke @code{gnatls} with a project file, use the @code{gnat}
16786 driver (see @ref{The GNAT Driver and Project Files}).
16790 * Switches for gnatls::
16791 * Examples of gnatls Usage::
16794 @node Running gnatls
16795 @section Running @code{gnatls}
16798 The @code{gnatls} command has the form
16801 $ gnatls switches @var{object_or_ali_file}
16805 The main argument is the list of object or @file{ali} files
16806 (@pxref{The Ada Library Information Files})
16807 for which information is requested.
16809 In normal mode, without additional option, @code{gnatls} produces a
16810 four-column listing. Each line represents information for a specific
16811 object. The first column gives the full path of the object, the second
16812 column gives the name of the principal unit in this object, the third
16813 column gives the status of the source and the fourth column gives the
16814 full path of the source representing this unit.
16815 Here is a simple example of use:
16819 ^./^[]^demo1.o demo1 DIF demo1.adb
16820 ^./^[]^demo2.o demo2 OK demo2.adb
16821 ^./^[]^hello.o h1 OK hello.adb
16822 ^./^[]^instr-child.o instr.child MOK instr-child.adb
16823 ^./^[]^instr.o instr OK instr.adb
16824 ^./^[]^tef.o tef DIF tef.adb
16825 ^./^[]^text_io_example.o text_io_example OK text_io_example.adb
16826 ^./^[]^tgef.o tgef DIF tgef.adb
16830 The first line can be interpreted as follows: the main unit which is
16832 object file @file{demo1.o} is demo1, whose main source is in
16833 @file{demo1.adb}. Furthermore, the version of the source used for the
16834 compilation of demo1 has been modified (DIF). Each source file has a status
16835 qualifier which can be:
16838 @item OK (unchanged)
16839 The version of the source file used for the compilation of the
16840 specified unit corresponds exactly to the actual source file.
16842 @item MOK (slightly modified)
16843 The version of the source file used for the compilation of the
16844 specified unit differs from the actual source file but not enough to
16845 require recompilation. If you use gnatmake with the qualifier
16846 @option{^-m (minimal recompilation)^/MINIMAL_RECOMPILATION^}, a file marked
16847 MOK will not be recompiled.
16849 @item DIF (modified)
16850 No version of the source found on the path corresponds to the source
16851 used to build this object.
16853 @item ??? (file not found)
16854 No source file was found for this unit.
16856 @item HID (hidden, unchanged version not first on PATH)
16857 The version of the source that corresponds exactly to the source used
16858 for compilation has been found on the path but it is hidden by another
16859 version of the same source that has been modified.
16863 @node Switches for gnatls
16864 @section Switches for @code{gnatls}
16867 @code{gnatls} recognizes the following switches:
16871 @cindex @option{--version} @command{gnatls}
16872 Display Copyright and version, then exit disregarding all other options.
16875 @cindex @option{--help} @command{gnatls}
16876 If @option{--version} was not used, display usage, then exit disregarding
16879 @item ^-a^/ALL_UNITS^
16880 @cindex @option{^-a^/ALL_UNITS^} (@code{gnatls})
16881 Consider all units, including those of the predefined Ada library.
16882 Especially useful with @option{^-d^/DEPENDENCIES^}.
16884 @item ^-d^/DEPENDENCIES^
16885 @cindex @option{^-d^/DEPENDENCIES^} (@code{gnatls})
16886 List sources from which specified units depend on.
16888 @item ^-h^/OUTPUT=OPTIONS^
16889 @cindex @option{^-h^/OUTPUT=OPTIONS^} (@code{gnatls})
16890 Output the list of options.
16892 @item ^-o^/OUTPUT=OBJECTS^
16893 @cindex @option{^-o^/OUTPUT=OBJECTS^} (@code{gnatls})
16894 Only output information about object files.
16896 @item ^-s^/OUTPUT=SOURCES^
16897 @cindex @option{^-s^/OUTPUT=SOURCES^} (@code{gnatls})
16898 Only output information about source files.
16900 @item ^-u^/OUTPUT=UNITS^
16901 @cindex @option{^-u^/OUTPUT=UNITS^} (@code{gnatls})
16902 Only output information about compilation units.
16904 @item ^-files^/FILES^=@var{file}
16905 @cindex @option{^-files^/FILES^} (@code{gnatls})
16906 Take as arguments the files listed in text file @var{file}.
16907 Text file @var{file} may contain empty lines that are ignored.
16908 Each nonempty line should contain the name of an existing file.
16909 Several such switches may be specified simultaneously.
16911 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
16912 @itemx ^-aI^/SOURCE_SEARCH=^@var{dir}
16913 @itemx ^-I^/SEARCH=^@var{dir}
16914 @itemx ^-I-^/NOCURRENT_DIRECTORY^
16916 @cindex @option{^-aO^/OBJECT_SEARCH^} (@code{gnatls})
16917 @cindex @option{^-aI^/SOURCE_SEARCH^} (@code{gnatls})
16918 @cindex @option{^-I^/SEARCH^} (@code{gnatls})
16919 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatls})
16920 Source path manipulation. Same meaning as the equivalent @command{gnatmake}
16921 flags (@pxref{Switches for gnatmake}).
16923 @item ^-aP^/ADD_PROJECT_SEARCH_DIR=^@var{dir}
16924 @cindex @option{^-aP^/ADD_PROJECT_SEARCH_DIR=^} (@code{gnatls})
16925 Add @var{dir} at the beginning of the project search dir.
16927 @item --RTS=@var{rts-path}
16928 @cindex @option{--RTS} (@code{gnatls})
16929 Specifies the default location of the runtime library. Same meaning as the
16930 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
16932 @item ^-v^/OUTPUT=VERBOSE^
16933 @cindex @option{^-v^/OUTPUT=VERBOSE^} (@code{gnatls})
16934 Verbose mode. Output the complete source, object and project paths. Do not use
16935 the default column layout but instead use long format giving as much as
16936 information possible on each requested units, including special
16937 characteristics such as:
16940 @item Preelaborable
16941 The unit is preelaborable in the Ada sense.
16944 No elaboration code has been produced by the compiler for this unit.
16947 The unit is pure in the Ada sense.
16949 @item Elaborate_Body
16950 The unit contains a pragma Elaborate_Body.
16953 The unit contains a pragma Remote_Types.
16955 @item Shared_Passive
16956 The unit contains a pragma Shared_Passive.
16959 This unit is part of the predefined environment and cannot be modified
16962 @item Remote_Call_Interface
16963 The unit contains a pragma Remote_Call_Interface.
16969 @node Examples of gnatls Usage
16970 @section Example of @code{gnatls} Usage
16974 Example of using the verbose switch. Note how the source and
16975 object paths are affected by the -I switch.
16978 $ gnatls -v -I.. demo1.o
16980 GNATLS 5.03w (20041123-34)
16981 Copyright 1997-2004 Free Software Foundation, Inc.
16983 Source Search Path:
16984 <Current_Directory>
16986 /home/comar/local/adainclude/
16988 Object Search Path:
16989 <Current_Directory>
16991 /home/comar/local/lib/gcc-lib/x86-linux/3.4.3/adalib/
16993 Project Search Path:
16994 <Current_Directory>
16995 /home/comar/local/lib/gnat/
17000 Kind => subprogram body
17001 Flags => No_Elab_Code
17002 Source => demo1.adb modified
17006 The following is an example of use of the dependency list.
17007 Note the use of the -s switch
17008 which gives a straight list of source files. This can be useful for
17009 building specialized scripts.
17012 $ gnatls -d demo2.o
17013 ./demo2.o demo2 OK demo2.adb
17019 $ gnatls -d -s -a demo1.o
17021 /home/comar/local/adainclude/ada.ads
17022 /home/comar/local/adainclude/a-finali.ads
17023 /home/comar/local/adainclude/a-filico.ads
17024 /home/comar/local/adainclude/a-stream.ads
17025 /home/comar/local/adainclude/a-tags.ads
17028 /home/comar/local/adainclude/gnat.ads
17029 /home/comar/local/adainclude/g-io.ads
17031 /home/comar/local/adainclude/system.ads
17032 /home/comar/local/adainclude/s-exctab.ads
17033 /home/comar/local/adainclude/s-finimp.ads
17034 /home/comar/local/adainclude/s-finroo.ads
17035 /home/comar/local/adainclude/s-secsta.ads
17036 /home/comar/local/adainclude/s-stalib.ads
17037 /home/comar/local/adainclude/s-stoele.ads
17038 /home/comar/local/adainclude/s-stratt.ads
17039 /home/comar/local/adainclude/s-tasoli.ads
17040 /home/comar/local/adainclude/s-unstyp.ads
17041 /home/comar/local/adainclude/unchconv.ads
17047 GNAT LIST /DEPENDENCIES /OUTPUT=SOURCES /ALL_UNITS DEMO1.ADB
17049 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]ada.ads
17050 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-finali.ads
17051 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-filico.ads
17052 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-stream.ads
17053 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-tags.ads
17057 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]gnat.ads
17058 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]g-io.ads
17060 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]system.ads
17061 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-exctab.ads
17062 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-finimp.ads
17063 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-finroo.ads
17064 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-secsta.ads
17065 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stalib.ads
17066 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stoele.ads
17067 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stratt.ads
17068 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-tasoli.ads
17069 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-unstyp.ads
17070 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]unchconv.ads
17074 @node Cleaning Up with gnatclean
17075 @chapter Cleaning Up with @code{gnatclean}
17077 @cindex Cleaning tool
17080 @code{gnatclean} is a tool that allows the deletion of files produced by the
17081 compiler, binder and linker, including ALI files, object files, tree files,
17082 expanded source files, library files, interface copy source files, binder
17083 generated files and executable files.
17086 * Running gnatclean::
17087 * Switches for gnatclean::
17088 @c * Examples of gnatclean Usage::
17091 @node Running gnatclean
17092 @section Running @code{gnatclean}
17095 The @code{gnatclean} command has the form:
17098 $ gnatclean switches @var{names}
17102 @var{names} is a list of source file names. Suffixes @code{.^ads^ADS^} and
17103 @code{^adb^ADB^} may be omitted. If a project file is specified using switch
17104 @code{^-P^/PROJECT_FILE=^}, then @var{names} may be completely omitted.
17107 In normal mode, @code{gnatclean} delete the files produced by the compiler and,
17108 if switch @code{^-c^/COMPILER_FILES_ONLY^} is not specified, by the binder and
17109 the linker. In informative-only mode, specified by switch
17110 @code{^-n^/NODELETE^}, the list of files that would have been deleted in
17111 normal mode is listed, but no file is actually deleted.
17113 @node Switches for gnatclean
17114 @section Switches for @code{gnatclean}
17117 @code{gnatclean} recognizes the following switches:
17121 @cindex @option{--version} @command{gnatclean}
17122 Display Copyright and version, then exit disregarding all other options.
17125 @cindex @option{--help} @command{gnatclean}
17126 If @option{--version} was not used, display usage, then exit disregarding
17129 @item ^--subdirs^/SUBDIRS^=subdir
17130 Actual object directory of each project file is the subdirectory subdir of the
17131 object directory specified or defaulted in the project file.
17133 @item ^--unchecked-shared-lib-imports^/UNCHECKED_SHARED_LIB_IMPORTS^
17134 By default, shared library projects are not allowed to import static library
17135 projects. When this switch is used on the command line, this restriction is
17138 @item ^-c^/COMPILER_FILES_ONLY^
17139 @cindex @option{^-c^/COMPILER_FILES_ONLY^} (@code{gnatclean})
17140 Only attempt to delete the files produced by the compiler, not those produced
17141 by the binder or the linker. The files that are not to be deleted are library
17142 files, interface copy files, binder generated files and executable files.
17144 @item ^-D ^/DIRECTORY_OBJECTS=^@var{dir}
17145 @cindex @option{^-D^/DIRECTORY_OBJECTS^} (@code{gnatclean})
17146 Indicate that ALI and object files should normally be found in directory
17149 @item ^-F^/FULL_PATH_IN_BRIEF_MESSAGES^
17150 @cindex @option{^-F^/FULL_PATH_IN_BRIEF_MESSAGES^} (@code{gnatclean})
17151 When using project files, if some errors or warnings are detected during
17152 parsing and verbose mode is not in effect (no use of switch
17153 ^-v^/VERBOSE^), then error lines start with the full path name of the project
17154 file, rather than its simple file name.
17157 @cindex @option{^-h^/HELP^} (@code{gnatclean})
17158 Output a message explaining the usage of @code{^gnatclean^gnatclean^}.
17160 @item ^-n^/NODELETE^
17161 @cindex @option{^-n^/NODELETE^} (@code{gnatclean})
17162 Informative-only mode. Do not delete any files. Output the list of the files
17163 that would have been deleted if this switch was not specified.
17165 @item ^-P^/PROJECT_FILE=^@var{project}
17166 @cindex @option{^-P^/PROJECT_FILE^} (@code{gnatclean})
17167 Use project file @var{project}. Only one such switch can be used.
17168 When cleaning a project file, the files produced by the compilation of the
17169 immediate sources or inherited sources of the project files are to be
17170 deleted. This is not depending on the presence or not of executable names
17171 on the command line.
17174 @cindex @option{^-q^/QUIET^} (@code{gnatclean})
17175 Quiet output. If there are no errors, do not output anything, except in
17176 verbose mode (switch ^-v^/VERBOSE^) or in informative-only mode
17177 (switch ^-n^/NODELETE^).
17179 @item ^-r^/RECURSIVE^
17180 @cindex @option{^-r^/RECURSIVE^} (@code{gnatclean})
17181 When a project file is specified (using switch ^-P^/PROJECT_FILE=^),
17182 clean all imported and extended project files, recursively. If this switch
17183 is not specified, only the files related to the main project file are to be
17184 deleted. This switch has no effect if no project file is specified.
17186 @item ^-v^/VERBOSE^
17187 @cindex @option{^-v^/VERBOSE^} (@code{gnatclean})
17190 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
17191 @cindex @option{^-vP^/MESSAGES_PROJECT_FILE^} (@code{gnatclean})
17192 Indicates the verbosity of the parsing of GNAT project files.
17193 @xref{Switches Related to Project Files}.
17195 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
17196 @cindex @option{^-X^/EXTERNAL_REFERENCE^} (@code{gnatclean})
17197 Indicates that external variable @var{name} has the value @var{value}.
17198 The Project Manager will use this value for occurrences of
17199 @code{external(name)} when parsing the project file.
17200 @xref{Switches Related to Project Files}.
17202 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
17203 @cindex @option{^-aO^/OBJECT_SEARCH^} (@code{gnatclean})
17204 When searching for ALI and object files, look in directory
17207 @item ^-I^/SEARCH=^@var{dir}
17208 @cindex @option{^-I^/SEARCH^} (@code{gnatclean})
17209 Equivalent to @option{^-aO^/OBJECT_SEARCH=^@var{dir}}.
17211 @item ^-I-^/NOCURRENT_DIRECTORY^
17212 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatclean})
17213 @cindex Source files, suppressing search
17214 Do not look for ALI or object files in the directory
17215 where @code{gnatclean} was invoked.
17219 @c @node Examples of gnatclean Usage
17220 @c @section Examples of @code{gnatclean} Usage
17223 @node GNAT and Libraries
17224 @chapter GNAT and Libraries
17225 @cindex Library, building, installing, using
17228 This chapter describes how to build and use libraries with GNAT, and also shows
17229 how to recompile the GNAT run-time library. You should be familiar with the
17230 Project Manager facility (@pxref{GNAT Project Manager}) before reading this
17234 * Introduction to Libraries in GNAT::
17235 * General Ada Libraries::
17236 * Stand-alone Ada Libraries::
17237 * Rebuilding the GNAT Run-Time Library::
17240 @node Introduction to Libraries in GNAT
17241 @section Introduction to Libraries in GNAT
17244 A library is, conceptually, a collection of objects which does not have its
17245 own main thread of execution, but rather provides certain services to the
17246 applications that use it. A library can be either statically linked with the
17247 application, in which case its code is directly included in the application,
17248 or, on platforms that support it, be dynamically linked, in which case
17249 its code is shared by all applications making use of this library.
17251 GNAT supports both types of libraries.
17252 In the static case, the compiled code can be provided in different ways. The
17253 simplest approach is to provide directly the set of objects resulting from
17254 compilation of the library source files. Alternatively, you can group the
17255 objects into an archive using whatever commands are provided by the operating
17256 system. For the latter case, the objects are grouped into a shared library.
17258 In the GNAT environment, a library has three types of components:
17264 @xref{The Ada Library Information Files}.
17266 Object files, an archive or a shared library.
17270 A GNAT library may expose all its source files, which is useful for
17271 documentation purposes. Alternatively, it may expose only the units needed by
17272 an external user to make use of the library. That is to say, the specs
17273 reflecting the library services along with all the units needed to compile
17274 those specs, which can include generic bodies or any body implementing an
17275 inlined routine. In the case of @emph{stand-alone libraries} those exposed
17276 units are called @emph{interface units} (@pxref{Stand-alone Ada Libraries}).
17278 All compilation units comprising an application, including those in a library,
17279 need to be elaborated in an order partially defined by Ada's semantics. GNAT
17280 computes the elaboration order from the @file{ALI} files and this is why they
17281 constitute a mandatory part of GNAT libraries.
17282 @emph{Stand-alone libraries} are the exception to this rule because a specific
17283 library elaboration routine is produced independently of the application(s)
17286 @node General Ada Libraries
17287 @section General Ada Libraries
17290 * Building a library::
17291 * Installing a library::
17292 * Using a library::
17295 @node Building a library
17296 @subsection Building a library
17299 The easiest way to build a library is to use the Project Manager,
17300 which supports a special type of project called a @emph{Library Project}
17301 (@pxref{Library Projects}).
17303 A project is considered a library project, when two project-level attributes
17304 are defined in it: @code{Library_Name} and @code{Library_Dir}. In order to
17305 control different aspects of library configuration, additional optional
17306 project-level attributes can be specified:
17309 This attribute controls whether the library is to be static or dynamic
17311 @item Library_Version
17312 This attribute specifies the library version; this value is used
17313 during dynamic linking of shared libraries to determine if the currently
17314 installed versions of the binaries are compatible.
17316 @item Library_Options
17318 These attributes specify additional low-level options to be used during
17319 library generation, and redefine the actual application used to generate
17324 The GNAT Project Manager takes full care of the library maintenance task,
17325 including recompilation of the source files for which objects do not exist
17326 or are not up to date, assembly of the library archive, and installation of
17327 the library (i.e., copying associated source, object and @file{ALI} files
17328 to the specified location).
17330 Here is a simple library project file:
17331 @smallexample @c ada
17333 for Source_Dirs use ("src1", "src2");
17334 for Object_Dir use "obj";
17335 for Library_Name use "mylib";
17336 for Library_Dir use "lib";
17337 for Library_Kind use "dynamic";
17342 and the compilation command to build and install the library:
17344 @smallexample @c ada
17345 $ gnatmake -Pmy_lib
17349 It is not entirely trivial to perform manually all the steps required to
17350 produce a library. We recommend that you use the GNAT Project Manager
17351 for this task. In special cases where this is not desired, the necessary
17352 steps are discussed below.
17354 There are various possibilities for compiling the units that make up the
17355 library: for example with a Makefile (@pxref{Using the GNU make Utility}) or
17356 with a conventional script. For simple libraries, it is also possible to create
17357 a dummy main program which depends upon all the packages that comprise the
17358 interface of the library. This dummy main program can then be given to
17359 @command{gnatmake}, which will ensure that all necessary objects are built.
17361 After this task is accomplished, you should follow the standard procedure
17362 of the underlying operating system to produce the static or shared library.
17364 Here is an example of such a dummy program:
17365 @smallexample @c ada
17367 with My_Lib.Service1;
17368 with My_Lib.Service2;
17369 with My_Lib.Service3;
17370 procedure My_Lib_Dummy is
17378 Here are the generic commands that will build an archive or a shared library.
17381 # compiling the library
17382 $ gnatmake -c my_lib_dummy.adb
17384 # we don't need the dummy object itself
17385 $ rm my_lib_dummy.o my_lib_dummy.ali
17387 # create an archive with the remaining objects
17388 $ ar rc libmy_lib.a *.o
17389 # some systems may require "ranlib" to be run as well
17391 # or create a shared library
17392 $ gcc -shared -o libmy_lib.so *.o
17393 # some systems may require the code to have been compiled with -fPIC
17395 # remove the object files that are now in the library
17398 # Make the ALI files read-only so that gnatmake will not try to
17399 # regenerate the objects that are in the library
17404 Please note that the library must have a name of the form @file{lib@var{xxx}.a}
17405 or @file{lib@var{xxx}.so} (or @file{lib@var{xxx}.dll} on Windows) in order to
17406 be accessed by the directive @option{-l@var{xxx}} at link time.
17408 @node Installing a library
17409 @subsection Installing a library
17410 @cindex @code{ADA_PROJECT_PATH}
17411 @cindex @code{GPR_PROJECT_PATH}
17414 If you use project files, library installation is part of the library build
17415 process (@pxref{Installing a library with project files}).
17417 When project files are not an option, it is also possible, but not recommended,
17418 to install the library so that the sources needed to use the library are on the
17419 Ada source path and the ALI files & libraries be on the Ada Object path (see
17420 @ref{Search Paths and the Run-Time Library (RTL)}. Alternatively, the system
17421 administrator can place general-purpose libraries in the default compiler
17422 paths, by specifying the libraries' location in the configuration files
17423 @file{ada_source_path} and @file{ada_object_path}. These configuration files
17424 must be located in the GNAT installation tree at the same place as the gcc spec
17425 file. The location of the gcc spec file can be determined as follows:
17431 The configuration files mentioned above have a simple format: each line
17432 must contain one unique directory name.
17433 Those names are added to the corresponding path
17434 in their order of appearance in the file. The names can be either absolute
17435 or relative; in the latter case, they are relative to where theses files
17438 The files @file{ada_source_path} and @file{ada_object_path} might not be
17440 GNAT installation, in which case, GNAT will look for its run-time library in
17441 the directories @file{adainclude} (for the sources) and @file{adalib} (for the
17442 objects and @file{ALI} files). When the files exist, the compiler does not
17443 look in @file{adainclude} and @file{adalib}, and thus the
17444 @file{ada_source_path} file
17445 must contain the location for the GNAT run-time sources (which can simply
17446 be @file{adainclude}). In the same way, the @file{ada_object_path} file must
17447 contain the location for the GNAT run-time objects (which can simply
17450 You can also specify a new default path to the run-time library at compilation
17451 time with the switch @option{--RTS=rts-path}. You can thus choose / change
17452 the run-time library you want your program to be compiled with. This switch is
17453 recognized by @command{gcc}, @command{gnatmake}, @command{gnatbind},
17454 @command{gnatls}, @command{gnatfind} and @command{gnatxref}.
17456 It is possible to install a library before or after the standard GNAT
17457 library, by reordering the lines in the configuration files. In general, a
17458 library must be installed before the GNAT library if it redefines
17461 @node Using a library
17462 @subsection Using a library
17464 @noindent Once again, the project facility greatly simplifies the use of
17465 libraries. In this context, using a library is just a matter of adding a
17466 @code{with} clause in the user project. For instance, to make use of the
17467 library @code{My_Lib} shown in examples in earlier sections, you can
17470 @smallexample @c projectfile
17477 Even if you have a third-party, non-Ada library, you can still use GNAT's
17478 Project Manager facility to provide a wrapper for it. For example, the
17479 following project, when @code{with}ed by your main project, will link with the
17480 third-party library @file{liba.a}:
17482 @smallexample @c projectfile
17485 for Externally_Built use "true";
17486 for Source_Files use ();
17487 for Library_Dir use "lib";
17488 for Library_Name use "a";
17489 for Library_Kind use "static";
17493 This is an alternative to the use of @code{pragma Linker_Options}. It is
17494 especially interesting in the context of systems with several interdependent
17495 static libraries where finding a proper linker order is not easy and best be
17496 left to the tools having visibility over project dependence information.
17499 In order to use an Ada library manually, you need to make sure that this
17500 library is on both your source and object path
17501 (see @ref{Search Paths and the Run-Time Library (RTL)}
17502 and @ref{Search Paths for gnatbind}). Furthermore, when the objects are grouped
17503 in an archive or a shared library, you need to specify the desired
17504 library at link time.
17506 For example, you can use the library @file{mylib} installed in
17507 @file{/dir/my_lib_src} and @file{/dir/my_lib_obj} with the following commands:
17510 $ gnatmake -aI/dir/my_lib_src -aO/dir/my_lib_obj my_appl \
17515 This can be expressed more simply:
17520 when the following conditions are met:
17523 @file{/dir/my_lib_src} has been added by the user to the environment
17524 variable @env{ADA_INCLUDE_PATH}, or by the administrator to the file
17525 @file{ada_source_path}
17527 @file{/dir/my_lib_obj} has been added by the user to the environment
17528 variable @env{ADA_OBJECTS_PATH}, or by the administrator to the file
17529 @file{ada_object_path}
17531 a pragma @code{Linker_Options} has been added to one of the sources.
17534 @smallexample @c ada
17535 pragma Linker_Options ("-lmy_lib");
17539 @node Stand-alone Ada Libraries
17540 @section Stand-alone Ada Libraries
17541 @cindex Stand-alone library, building, using
17544 * Introduction to Stand-alone Libraries::
17545 * Building a Stand-alone Library::
17546 * Creating a Stand-alone Library to be used in a non-Ada context::
17547 * Restrictions in Stand-alone Libraries::
17550 @node Introduction to Stand-alone Libraries
17551 @subsection Introduction to Stand-alone Libraries
17554 A Stand-alone Library (abbreviated ``SAL'') is a library that contains the
17556 elaborate the Ada units that are included in the library. In contrast with
17557 an ordinary library, which consists of all sources, objects and @file{ALI}
17559 library, a SAL may specify a restricted subset of compilation units
17560 to serve as a library interface. In this case, the fully
17561 self-sufficient set of files will normally consist of an objects
17562 archive, the sources of interface units' specs, and the @file{ALI}
17563 files of interface units.
17564 If an interface spec contains a generic unit or an inlined subprogram,
17566 source must also be provided; if the units that must be provided in the source
17567 form depend on other units, the source and @file{ALI} files of those must
17570 The main purpose of a SAL is to minimize the recompilation overhead of client
17571 applications when a new version of the library is installed. Specifically,
17572 if the interface sources have not changed, client applications do not need to
17573 be recompiled. If, furthermore, a SAL is provided in the shared form and its
17574 version, controlled by @code{Library_Version} attribute, is not changed,
17575 then the clients do not need to be relinked.
17577 SALs also allow the library providers to minimize the amount of library source
17578 text exposed to the clients. Such ``information hiding'' might be useful or
17579 necessary for various reasons.
17581 Stand-alone libraries are also well suited to be used in an executable whose
17582 main routine is not written in Ada.
17584 @node Building a Stand-alone Library
17585 @subsection Building a Stand-alone Library
17588 GNAT's Project facility provides a simple way of building and installing
17589 stand-alone libraries; see @ref{Stand-alone Library Projects}.
17590 To be a Stand-alone Library Project, in addition to the two attributes
17591 that make a project a Library Project (@code{Library_Name} and
17592 @code{Library_Dir}; see @ref{Library Projects}), the attribute
17593 @code{Library_Interface} must be defined. For example:
17595 @smallexample @c projectfile
17597 for Library_Dir use "lib_dir";
17598 for Library_Name use "dummy";
17599 for Library_Interface use ("int1", "int1.child");
17604 Attribute @code{Library_Interface} has a non-empty string list value,
17605 each string in the list designating a unit contained in an immediate source
17606 of the project file.
17608 When a Stand-alone Library is built, first the binder is invoked to build
17609 a package whose name depends on the library name
17610 (@file{^b~dummy.ads/b^B$DUMMY.ADS/B^} in the example above).
17611 This binder-generated package includes initialization and
17612 finalization procedures whose
17613 names depend on the library name (@code{dummyinit} and @code{dummyfinal}
17615 above). The object corresponding to this package is included in the library.
17617 You must ensure timely (e.g., prior to any use of interfaces in the SAL)
17618 calling of these procedures if a static SAL is built, or if a shared SAL
17620 with the project-level attribute @code{Library_Auto_Init} set to
17623 For a Stand-Alone Library, only the @file{ALI} files of the Interface Units
17624 (those that are listed in attribute @code{Library_Interface}) are copied to
17625 the Library Directory. As a consequence, only the Interface Units may be
17626 imported from Ada units outside of the library. If other units are imported,
17627 the binding phase will fail.
17630 It is also possible to build an encapsulated library where not only
17631 the code to elaborate and finalize the library is embedded but also
17632 ensuring that the library is linked only against static
17633 libraries. So an encapsulated library only depends on system
17634 libraries, all other code, including the GNAT runtime, is embedded. To
17635 build an encapsulated library the attribute
17636 @code{Library_Standalone} must be set to @code{encapsulated}:
17638 @smallexample @c projectfile
17640 for Library_Dir use "lib_dir";
17641 for Library_Name use "dummy";
17642 for Library_Kind use "dynamic";
17643 for Library_Interface use ("int1", "int1.child");
17644 for Library_Standalone use "encapsulated";
17649 The default value for this attribute is @code{standard} in which case
17650 a stand-alone library is built.
17652 The attribute @code{Library_Src_Dir} may be specified for a
17653 Stand-Alone Library. @code{Library_Src_Dir} is a simple attribute that has a
17654 single string value. Its value must be the path (absolute or relative to the
17655 project directory) of an existing directory. This directory cannot be the
17656 object directory or one of the source directories, but it can be the same as
17657 the library directory. The sources of the Interface
17658 Units of the library that are needed by an Ada client of the library will be
17659 copied to the designated directory, called the Interface Copy directory.
17660 These sources include the specs of the Interface Units, but they may also
17661 include bodies and subunits, when pragmas @code{Inline} or @code{Inline_Always}
17662 are used, or when there is a generic unit in the spec. Before the sources
17663 are copied to the Interface Copy directory, an attempt is made to delete all
17664 files in the Interface Copy directory.
17666 Building stand-alone libraries by hand is somewhat tedious, but for those
17667 occasions when it is necessary here are the steps that you need to perform:
17670 Compile all library sources.
17673 Invoke the binder with the switch @option{-n} (No Ada main program),
17674 with all the @file{ALI} files of the interfaces, and
17675 with the switch @option{-L} to give specific names to the @code{init}
17676 and @code{final} procedures. For example:
17678 gnatbind -n int1.ali int2.ali -Lsal1
17682 Compile the binder generated file:
17688 Link the dynamic library with all the necessary object files,
17689 indicating to the linker the names of the @code{init} (and possibly
17690 @code{final}) procedures for automatic initialization (and finalization).
17691 The built library should be placed in a directory different from
17692 the object directory.
17695 Copy the @code{ALI} files of the interface to the library directory,
17696 add in this copy an indication that it is an interface to a SAL
17697 (i.e., add a word @option{SL} on the line in the @file{ALI} file that starts
17698 with letter ``P'') and make the modified copy of the @file{ALI} file
17703 Using SALs is not different from using other libraries
17704 (see @ref{Using a library}).
17706 @node Creating a Stand-alone Library to be used in a non-Ada context
17707 @subsection Creating a Stand-alone Library to be used in a non-Ada context
17710 It is easy to adapt the SAL build procedure discussed above for use of a SAL in
17713 The only extra step required is to ensure that library interface subprograms
17714 are compatible with the main program, by means of @code{pragma Export}
17715 or @code{pragma Convention}.
17717 Here is an example of simple library interface for use with C main program:
17719 @smallexample @c ada
17720 package My_Package is
17722 procedure Do_Something;
17723 pragma Export (C, Do_Something, "do_something");
17725 procedure Do_Something_Else;
17726 pragma Export (C, Do_Something_Else, "do_something_else");
17732 On the foreign language side, you must provide a ``foreign'' view of the
17733 library interface; remember that it should contain elaboration routines in
17734 addition to interface subprograms.
17736 The example below shows the content of @code{mylib_interface.h} (note
17737 that there is no rule for the naming of this file, any name can be used)
17739 /* the library elaboration procedure */
17740 extern void mylibinit (void);
17742 /* the library finalization procedure */
17743 extern void mylibfinal (void);
17745 /* the interface exported by the library */
17746 extern void do_something (void);
17747 extern void do_something_else (void);
17751 Libraries built as explained above can be used from any program, provided
17752 that the elaboration procedures (named @code{mylibinit} in the previous
17753 example) are called before the library services are used. Any number of
17754 libraries can be used simultaneously, as long as the elaboration
17755 procedure of each library is called.
17757 Below is an example of a C program that uses the @code{mylib} library.
17760 #include "mylib_interface.h"
17765 /* First, elaborate the library before using it */
17768 /* Main program, using the library exported entities */
17770 do_something_else ();
17772 /* Library finalization at the end of the program */
17779 Note that invoking any library finalization procedure generated by
17780 @code{gnatbind} shuts down the Ada run-time environment.
17782 finalization of all Ada libraries must be performed at the end of the program.
17783 No call to these libraries or to the Ada run-time library should be made
17784 after the finalization phase.
17786 @node Restrictions in Stand-alone Libraries
17787 @subsection Restrictions in Stand-alone Libraries
17790 The pragmas listed below should be used with caution inside libraries,
17791 as they can create incompatibilities with other Ada libraries:
17793 @item pragma @code{Locking_Policy}
17794 @item pragma @code{Partition_Elaboration_Policy}
17795 @item pragma @code{Queuing_Policy}
17796 @item pragma @code{Task_Dispatching_Policy}
17797 @item pragma @code{Unreserve_All_Interrupts}
17801 When using a library that contains such pragmas, the user must make sure
17802 that all libraries use the same pragmas with the same values. Otherwise,
17803 @code{Program_Error} will
17804 be raised during the elaboration of the conflicting
17805 libraries. The usage of these pragmas and its consequences for the user
17806 should therefore be well documented.
17808 Similarly, the traceback in the exception occurrence mechanism should be
17809 enabled or disabled in a consistent manner across all libraries.
17810 Otherwise, Program_Error will be raised during the elaboration of the
17811 conflicting libraries.
17813 If the @code{Version} or @code{Body_Version}
17814 attributes are used inside a library, then you need to
17815 perform a @code{gnatbind} step that specifies all @file{ALI} files in all
17816 libraries, so that version identifiers can be properly computed.
17817 In practice these attributes are rarely used, so this is unlikely
17818 to be a consideration.
17820 @node Rebuilding the GNAT Run-Time Library
17821 @section Rebuilding the GNAT Run-Time Library
17822 @cindex GNAT Run-Time Library, rebuilding
17823 @cindex Building the GNAT Run-Time Library
17824 @cindex Rebuilding the GNAT Run-Time Library
17825 @cindex Run-Time Library, rebuilding
17828 It may be useful to recompile the GNAT library in various contexts, the
17829 most important one being the use of partition-wide configuration pragmas
17830 such as @code{Normalize_Scalars}. A special Makefile called
17831 @code{Makefile.adalib} is provided to that effect and can be found in
17832 the directory containing the GNAT library. The location of this
17833 directory depends on the way the GNAT environment has been installed and can
17834 be determined by means of the command:
17841 The last entry in the object search path usually contains the
17842 gnat library. This Makefile contains its own documentation and in
17843 particular the set of instructions needed to rebuild a new library and
17846 @node Using the GNU make Utility
17847 @chapter Using the GNU @code{make} Utility
17851 This chapter offers some examples of makefiles that solve specific
17852 problems. It does not explain how to write a makefile (@pxref{Top,, GNU
17853 make, make, GNU @code{make}}), nor does it try to replace the
17854 @command{gnatmake} utility (@pxref{The GNAT Make Program gnatmake}).
17856 All the examples in this section are specific to the GNU version of
17857 make. Although @command{make} is a standard utility, and the basic language
17858 is the same, these examples use some advanced features found only in
17862 * Using gnatmake in a Makefile::
17863 * Automatically Creating a List of Directories::
17864 * Generating the Command Line Switches::
17865 * Overcoming Command Line Length Limits::
17868 @node Using gnatmake in a Makefile
17869 @section Using gnatmake in a Makefile
17874 Complex project organizations can be handled in a very powerful way by
17875 using GNU make combined with gnatmake. For instance, here is a Makefile
17876 which allows you to build each subsystem of a big project into a separate
17877 shared library. Such a makefile allows you to significantly reduce the link
17878 time of very big applications while maintaining full coherence at
17879 each step of the build process.
17881 The list of dependencies are handled automatically by
17882 @command{gnatmake}. The Makefile is simply used to call gnatmake in each of
17883 the appropriate directories.
17885 Note that you should also read the example on how to automatically
17886 create the list of directories
17887 (@pxref{Automatically Creating a List of Directories})
17888 which might help you in case your project has a lot of subdirectories.
17893 @font@heightrm=cmr8
17896 ## This Makefile is intended to be used with the following directory
17898 ## - The sources are split into a series of csc (computer software components)
17899 ## Each of these csc is put in its own directory.
17900 ## Their name are referenced by the directory names.
17901 ## They will be compiled into shared library (although this would also work
17902 ## with static libraries
17903 ## - The main program (and possibly other packages that do not belong to any
17904 ## csc is put in the top level directory (where the Makefile is).
17905 ## toplevel_dir __ first_csc (sources) __ lib (will contain the library)
17906 ## \_ second_csc (sources) __ lib (will contain the library)
17908 ## Although this Makefile is build for shared library, it is easy to modify
17909 ## to build partial link objects instead (modify the lines with -shared and
17912 ## With this makefile, you can change any file in the system or add any new
17913 ## file, and everything will be recompiled correctly (only the relevant shared
17914 ## objects will be recompiled, and the main program will be re-linked).
17916 # The list of computer software component for your project. This might be
17917 # generated automatically.
17920 # Name of the main program (no extension)
17923 # If we need to build objects with -fPIC, uncomment the following line
17926 # The following variable should give the directory containing libgnat.so
17927 # You can get this directory through 'gnatls -v'. This is usually the last
17928 # directory in the Object_Path.
17931 # The directories for the libraries
17932 # (This macro expands the list of CSC to the list of shared libraries, you
17933 # could simply use the expanded form:
17934 # LIB_DIR=aa/lib/libaa.so bb/lib/libbb.so cc/lib/libcc.so
17935 LIB_DIR=$@{foreach dir,$@{CSC_LIST@},$@{dir@}/lib/lib$@{dir@}.so@}
17937 $@{MAIN@}: objects $@{LIB_DIR@}
17938 gnatbind $@{MAIN@} $@{CSC_LIST:%=-aO%/lib@} -shared
17939 gnatlink $@{MAIN@} $@{CSC_LIST:%=-l%@}
17942 # recompile the sources
17943 gnatmake -c -i $@{MAIN@}.adb $@{NEED_FPIC@} $@{CSC_LIST:%=-I%@}
17945 # Note: In a future version of GNAT, the following commands will be simplified
17946 # by a new tool, gnatmlib
17948 mkdir -p $@{dir $@@ @}
17949 cd $@{dir $@@ @} && gcc -shared -o $@{notdir $@@ @} ../*.o -L$@{GLIB@} -lgnat
17950 cd $@{dir $@@ @} && cp -f ../*.ali .
17952 # The dependencies for the modules
17953 # Note that we have to force the expansion of *.o, since in some cases
17954 # make won't be able to do it itself.
17955 aa/lib/libaa.so: $@{wildcard aa/*.o@}
17956 bb/lib/libbb.so: $@{wildcard bb/*.o@}
17957 cc/lib/libcc.so: $@{wildcard cc/*.o@}
17959 # Make sure all of the shared libraries are in the path before starting the
17962 LD_LIBRARY_PATH=`pwd`/aa/lib:`pwd`/bb/lib:`pwd`/cc/lib ./$@{MAIN@}
17965 $@{RM@} -rf $@{CSC_LIST:%=%/lib@}
17966 $@{RM@} $@{CSC_LIST:%=%/*.ali@}
17967 $@{RM@} $@{CSC_LIST:%=%/*.o@}
17968 $@{RM@} *.o *.ali $@{MAIN@}
17971 @node Automatically Creating a List of Directories
17972 @section Automatically Creating a List of Directories
17975 In most makefiles, you will have to specify a list of directories, and
17976 store it in a variable. For small projects, it is often easier to
17977 specify each of them by hand, since you then have full control over what
17978 is the proper order for these directories, which ones should be
17981 However, in larger projects, which might involve hundreds of
17982 subdirectories, it might be more convenient to generate this list
17985 The example below presents two methods. The first one, although less
17986 general, gives you more control over the list. It involves wildcard
17987 characters, that are automatically expanded by @command{make}. Its
17988 shortcoming is that you need to explicitly specify some of the
17989 organization of your project, such as for instance the directory tree
17990 depth, whether some directories are found in a separate tree, @enddots{}
17992 The second method is the most general one. It requires an external
17993 program, called @command{find}, which is standard on all Unix systems. All
17994 the directories found under a given root directory will be added to the
18000 @font@heightrm=cmr8
18003 # The examples below are based on the following directory hierarchy:
18004 # All the directories can contain any number of files
18005 # ROOT_DIRECTORY -> a -> aa -> aaa
18008 # -> b -> ba -> baa
18011 # This Makefile creates a variable called DIRS, that can be reused any time
18012 # you need this list (see the other examples in this section)
18014 # The root of your project's directory hierarchy
18018 # First method: specify explicitly the list of directories
18019 # This allows you to specify any subset of all the directories you need.
18022 DIRS := a/aa/ a/ab/ b/ba/
18025 # Second method: use wildcards
18026 # Note that the argument(s) to wildcard below should end with a '/'.
18027 # Since wildcards also return file names, we have to filter them out
18028 # to avoid duplicate directory names.
18029 # We thus use make's @code{dir} and @code{sort} functions.
18030 # It sets DIRs to the following value (note that the directories aaa and baa
18031 # are not given, unless you change the arguments to wildcard).
18032 # DIRS= ./a/a/ ./b/ ./a/aa/ ./a/ab/ ./a/ac/ ./b/ba/ ./b/bb/ ./b/bc/
18035 DIRS := $@{sort $@{dir $@{wildcard $@{ROOT_DIRECTORY@}/*/
18036 $@{ROOT_DIRECTORY@}/*/*/@}@}@}
18039 # Third method: use an external program
18040 # This command is much faster if run on local disks, avoiding NFS slowdowns.
18041 # This is the most complete command: it sets DIRs to the following value:
18042 # DIRS= ./a ./a/aa ./a/aa/aaa ./a/ab ./a/ac ./b ./b/ba ./b/ba/baa ./b/bb ./b/bc
18045 DIRS := $@{shell find $@{ROOT_DIRECTORY@} -type d -print@}
18049 @node Generating the Command Line Switches
18050 @section Generating the Command Line Switches
18053 Once you have created the list of directories as explained in the
18054 previous section (@pxref{Automatically Creating a List of Directories}),
18055 you can easily generate the command line arguments to pass to gnatmake.
18057 For the sake of completeness, this example assumes that the source path
18058 is not the same as the object path, and that you have two separate lists
18062 # see "Automatically creating a list of directories" to create
18067 GNATMAKE_SWITCHES := $@{patsubst %,-aI%,$@{SOURCE_DIRS@}@}
18068 GNATMAKE_SWITCHES += $@{patsubst %,-aO%,$@{OBJECT_DIRS@}@}
18071 gnatmake $@{GNATMAKE_SWITCHES@} main_unit
18074 @node Overcoming Command Line Length Limits
18075 @section Overcoming Command Line Length Limits
18078 One problem that might be encountered on big projects is that many
18079 operating systems limit the length of the command line. It is thus hard to give
18080 gnatmake the list of source and object directories.
18082 This example shows how you can set up environment variables, which will
18083 make @command{gnatmake} behave exactly as if the directories had been
18084 specified on the command line, but have a much higher length limit (or
18085 even none on most systems).
18087 It assumes that you have created a list of directories in your Makefile,
18088 using one of the methods presented in
18089 @ref{Automatically Creating a List of Directories}.
18090 For the sake of completeness, we assume that the object
18091 path (where the ALI files are found) is different from the sources patch.
18093 Note a small trick in the Makefile below: for efficiency reasons, we
18094 create two temporary variables (SOURCE_LIST and OBJECT_LIST), that are
18095 expanded immediately by @code{make}. This way we overcome the standard
18096 make behavior which is to expand the variables only when they are
18099 On Windows, if you are using the standard Windows command shell, you must
18100 replace colons with semicolons in the assignments to these variables.
18105 @font@heightrm=cmr8
18108 # In this example, we create both ADA_INCLUDE_PATH and ADA_OBJECTS_PATH.
18109 # This is the same thing as putting the -I arguments on the command line.
18110 # (the equivalent of using -aI on the command line would be to define
18111 # only ADA_INCLUDE_PATH, the equivalent of -aO is ADA_OBJECTS_PATH).
18112 # You can of course have different values for these variables.
18114 # Note also that we need to keep the previous values of these variables, since
18115 # they might have been set before running 'make' to specify where the GNAT
18116 # library is installed.
18118 # see "Automatically creating a list of directories" to create these
18124 space:=$@{empty@} $@{empty@}
18125 SOURCE_LIST := $@{subst $@{space@},:,$@{SOURCE_DIRS@}@}
18126 OBJECT_LIST := $@{subst $@{space@},:,$@{OBJECT_DIRS@}@}
18127 ADA_INCLUDE_PATH += $@{SOURCE_LIST@}
18128 ADA_OBJECTS_PATH += $@{OBJECT_LIST@}
18129 export ADA_INCLUDE_PATH
18130 export ADA_OBJECTS_PATH
18137 @node Memory Management Issues
18138 @chapter Memory Management Issues
18141 This chapter describes some useful memory pools provided in the GNAT library
18142 and in particular the GNAT Debug Pool facility, which can be used to detect
18143 incorrect uses of access values (including ``dangling references'').
18145 It also describes the @command{gnatmem} tool, which can be used to track down
18150 * Some Useful Memory Pools::
18151 * The GNAT Debug Pool Facility::
18153 * The gnatmem Tool::
18157 @node Some Useful Memory Pools
18158 @section Some Useful Memory Pools
18159 @findex Memory Pool
18160 @cindex storage, pool
18163 The @code{System.Pool_Global} package offers the Unbounded_No_Reclaim_Pool
18164 storage pool. Allocations use the standard system call @code{malloc} while
18165 deallocations use the standard system call @code{free}. No reclamation is
18166 performed when the pool goes out of scope. For performance reasons, the
18167 standard default Ada allocators/deallocators do not use any explicit storage
18168 pools but if they did, they could use this storage pool without any change in
18169 behavior. That is why this storage pool is used when the user
18170 manages to make the default implicit allocator explicit as in this example:
18171 @smallexample @c ada
18172 type T1 is access Something;
18173 -- no Storage pool is defined for T2
18174 type T2 is access Something_Else;
18175 for T2'Storage_Pool use T1'Storage_Pool;
18176 -- the above is equivalent to
18177 for T2'Storage_Pool use System.Pool_Global.Global_Pool_Object;
18181 The @code{System.Pool_Local} package offers the Unbounded_Reclaim_Pool storage
18182 pool. The allocation strategy is similar to @code{Pool_Local}'s
18183 except that the all
18184 storage allocated with this pool is reclaimed when the pool object goes out of
18185 scope. This pool provides a explicit mechanism similar to the implicit one
18186 provided by several Ada 83 compilers for allocations performed through a local
18187 access type and whose purpose was to reclaim memory when exiting the
18188 scope of a given local access. As an example, the following program does not
18189 leak memory even though it does not perform explicit deallocation:
18191 @smallexample @c ada
18192 with System.Pool_Local;
18193 procedure Pooloc1 is
18194 procedure Internal is
18195 type A is access Integer;
18196 X : System.Pool_Local.Unbounded_Reclaim_Pool;
18197 for A'Storage_Pool use X;
18200 for I in 1 .. 50 loop
18205 for I in 1 .. 100 loop
18212 The @code{System.Pool_Size} package implements the Stack_Bounded_Pool used when
18213 @code{Storage_Size} is specified for an access type.
18214 The whole storage for the pool is
18215 allocated at once, usually on the stack at the point where the access type is
18216 elaborated. It is automatically reclaimed when exiting the scope where the
18217 access type is defined. This package is not intended to be used directly by the
18218 user and it is implicitly used for each such declaration:
18220 @smallexample @c ada
18221 type T1 is access Something;
18222 for T1'Storage_Size use 10_000;
18225 @node The GNAT Debug Pool Facility
18226 @section The GNAT Debug Pool Facility
18228 @cindex storage, pool, memory corruption
18231 The use of unchecked deallocation and unchecked conversion can easily
18232 lead to incorrect memory references. The problems generated by such
18233 references are usually difficult to tackle because the symptoms can be
18234 very remote from the origin of the problem. In such cases, it is
18235 very helpful to detect the problem as early as possible. This is the
18236 purpose of the Storage Pool provided by @code{GNAT.Debug_Pools}.
18238 In order to use the GNAT specific debugging pool, the user must
18239 associate a debug pool object with each of the access types that may be
18240 related to suspected memory problems. See Ada Reference Manual 13.11.
18241 @smallexample @c ada
18242 type Ptr is access Some_Type;
18243 Pool : GNAT.Debug_Pools.Debug_Pool;
18244 for Ptr'Storage_Pool use Pool;
18248 @code{GNAT.Debug_Pools} is derived from a GNAT-specific kind of
18249 pool: the @code{Checked_Pool}. Such pools, like standard Ada storage pools,
18250 allow the user to redefine allocation and deallocation strategies. They
18251 also provide a checkpoint for each dereference, through the use of
18252 the primitive operation @code{Dereference} which is implicitly called at
18253 each dereference of an access value.
18255 Once an access type has been associated with a debug pool, operations on
18256 values of the type may raise four distinct exceptions,
18257 which correspond to four potential kinds of memory corruption:
18260 @code{GNAT.Debug_Pools.Accessing_Not_Allocated_Storage}
18262 @code{GNAT.Debug_Pools.Accessing_Deallocated_Storage}
18264 @code{GNAT.Debug_Pools.Freeing_Not_Allocated_Storage}
18266 @code{GNAT.Debug_Pools.Freeing_Deallocated_Storage }
18270 For types associated with a Debug_Pool, dynamic allocation is performed using
18271 the standard GNAT allocation routine. References to all allocated chunks of
18272 memory are kept in an internal dictionary. Several deallocation strategies are
18273 provided, whereupon the user can choose to release the memory to the system,
18274 keep it allocated for further invalid access checks, or fill it with an easily
18275 recognizable pattern for debug sessions. The memory pattern is the old IBM
18276 hexadecimal convention: @code{16#DEADBEEF#}.
18278 See the documentation in the file g-debpoo.ads for more information on the
18279 various strategies.
18281 Upon each dereference, a check is made that the access value denotes a
18282 properly allocated memory location. Here is a complete example of use of
18283 @code{Debug_Pools}, that includes typical instances of memory corruption:
18284 @smallexample @c ada
18288 with Gnat.Io; use Gnat.Io;
18289 with Unchecked_Deallocation;
18290 with Unchecked_Conversion;
18291 with GNAT.Debug_Pools;
18292 with System.Storage_Elements;
18293 with Ada.Exceptions; use Ada.Exceptions;
18294 procedure Debug_Pool_Test is
18296 type T is access Integer;
18297 type U is access all T;
18299 P : GNAT.Debug_Pools.Debug_Pool;
18300 for T'Storage_Pool use P;
18302 procedure Free is new Unchecked_Deallocation (Integer, T);
18303 function UC is new Unchecked_Conversion (U, T);
18306 procedure Info is new GNAT.Debug_Pools.Print_Info(Put_Line);
18316 Put_Line (Integer'Image(B.all));
18318 when E : others => Put_Line ("raised: " & Exception_Name (E));
18323 when E : others => Put_Line ("raised: " & Exception_Name (E));
18327 Put_Line (Integer'Image(B.all));
18329 when E : others => Put_Line ("raised: " & Exception_Name (E));
18334 when E : others => Put_Line ("raised: " & Exception_Name (E));
18337 end Debug_Pool_Test;
18341 The debug pool mechanism provides the following precise diagnostics on the
18342 execution of this erroneous program:
18345 Total allocated bytes : 0
18346 Total deallocated bytes : 0
18347 Current Water Mark: 0
18351 Total allocated bytes : 8
18352 Total deallocated bytes : 0
18353 Current Water Mark: 8
18356 raised: GNAT.DEBUG_POOLS.ACCESSING_DEALLOCATED_STORAGE
18357 raised: GNAT.DEBUG_POOLS.FREEING_DEALLOCATED_STORAGE
18358 raised: GNAT.DEBUG_POOLS.ACCESSING_NOT_ALLOCATED_STORAGE
18359 raised: GNAT.DEBUG_POOLS.FREEING_NOT_ALLOCATED_STORAGE
18361 Total allocated bytes : 8
18362 Total deallocated bytes : 4
18363 Current Water Mark: 4
18368 @node The gnatmem Tool
18369 @section The @command{gnatmem} Tool
18373 The @code{gnatmem} utility monitors dynamic allocation and
18374 deallocation activity in a program, and displays information about
18375 incorrect deallocations and possible sources of memory leaks.
18376 It is designed to work in association with a static runtime library
18377 only and in this context provides three types of information:
18380 General information concerning memory management, such as the total
18381 number of allocations and deallocations, the amount of allocated
18382 memory and the high water mark, i.e.@: the largest amount of allocated
18383 memory in the course of program execution.
18386 Backtraces for all incorrect deallocations, that is to say deallocations
18387 which do not correspond to a valid allocation.
18390 Information on each allocation that is potentially the origin of a memory
18395 * Running gnatmem::
18396 * Switches for gnatmem::
18397 * Example of gnatmem Usage::
18400 @node Running gnatmem
18401 @subsection Running @code{gnatmem}
18404 @code{gnatmem} makes use of the output created by the special version of
18405 allocation and deallocation routines that record call information. This
18406 allows to obtain accurate dynamic memory usage history at a minimal cost to
18407 the execution speed. Note however, that @code{gnatmem} is not supported on
18408 all platforms (currently, it is supported on AIX, HP-UX, GNU/Linux,
18409 Solaris and Windows NT/2000/XP (x86).
18412 The @code{gnatmem} command has the form
18415 @c $ gnatmem @ovar{switches} user_program
18416 @c Expanding @ovar macro inline (explanation in macro def comments)
18417 $ gnatmem @r{[}@var{switches}@r{]} @var{user_program}
18421 The program must have been linked with the instrumented version of the
18422 allocation and deallocation routines. This is done by linking with the
18423 @file{libgmem.a} library. For correct symbolic backtrace information,
18424 the user program should be compiled with debugging options
18425 (see @ref{Switches for gcc}). For example to build @file{my_program}:
18428 $ gnatmake -g my_program -largs -lgmem
18432 As library @file{libgmem.a} contains an alternate body for package
18433 @code{System.Memory}, @file{s-memory.adb} should not be compiled and linked
18434 when an executable is linked with library @file{libgmem.a}. It is then not
18435 recommended to use @command{gnatmake} with switch @option{^-a^/ALL_FILES^}.
18438 When @file{my_program} is executed, the file @file{gmem.out} is produced.
18439 This file contains information about all allocations and deallocations
18440 performed by the program. It is produced by the instrumented allocations and
18441 deallocations routines and will be used by @code{gnatmem}.
18443 In order to produce symbolic backtrace information for allocations and
18444 deallocations performed by the GNAT run-time library, you need to use a
18445 version of that library that has been compiled with the @option{-g} switch
18446 (see @ref{Rebuilding the GNAT Run-Time Library}).
18448 Gnatmem must be supplied with the @file{gmem.out} file and the executable to
18449 examine. If the location of @file{gmem.out} file was not explicitly supplied by
18450 @option{-i} switch, gnatmem will assume that this file can be found in the
18451 current directory. For example, after you have executed @file{my_program},
18452 @file{gmem.out} can be analyzed by @code{gnatmem} using the command:
18455 $ gnatmem my_program
18459 This will produce the output with the following format:
18461 *************** debut cc
18463 $ gnatmem my_program
18467 Total number of allocations : 45
18468 Total number of deallocations : 6
18469 Final Water Mark (non freed mem) : 11.29 Kilobytes
18470 High Water Mark : 11.40 Kilobytes
18475 Allocation Root # 2
18476 -------------------
18477 Number of non freed allocations : 11
18478 Final Water Mark (non freed mem) : 1.16 Kilobytes
18479 High Water Mark : 1.27 Kilobytes
18481 my_program.adb:23 my_program.alloc
18487 The first block of output gives general information. In this case, the
18488 Ada construct ``@code{@b{new}}'' was executed 45 times, and only 6 calls to an
18489 Unchecked_Deallocation routine occurred.
18492 Subsequent paragraphs display information on all allocation roots.
18493 An allocation root is a specific point in the execution of the program
18494 that generates some dynamic allocation, such as a ``@code{@b{new}}''
18495 construct. This root is represented by an execution backtrace (or subprogram
18496 call stack). By default the backtrace depth for allocations roots is 1, so
18497 that a root corresponds exactly to a source location. The backtrace can
18498 be made deeper, to make the root more specific.
18500 @node Switches for gnatmem
18501 @subsection Switches for @code{gnatmem}
18504 @code{gnatmem} recognizes the following switches:
18509 @cindex @option{-q} (@code{gnatmem})
18510 Quiet. Gives the minimum output needed to identify the origin of the
18511 memory leaks. Omits statistical information.
18514 @cindex @var{N} (@code{gnatmem})
18515 N is an integer literal (usually between 1 and 10) which controls the
18516 depth of the backtraces defining allocation root. The default value for
18517 N is 1. The deeper the backtrace, the more precise the localization of
18518 the root. Note that the total number of roots can depend on this
18519 parameter. This parameter must be specified @emph{before} the name of the
18520 executable to be analyzed, to avoid ambiguity.
18523 @cindex @option{-b} (@code{gnatmem})
18524 This switch has the same effect as just depth parameter.
18526 @item -i @var{file}
18527 @cindex @option{-i} (@code{gnatmem})
18528 Do the @code{gnatmem} processing starting from @file{file}, rather than
18529 @file{gmem.out} in the current directory.
18532 @cindex @option{-m} (@code{gnatmem})
18533 This switch causes @code{gnatmem} to mask the allocation roots that have less
18534 than n leaks. The default value is 1. Specifying the value of 0 will allow to
18535 examine even the roots that didn't result in leaks.
18538 @cindex @option{-s} (@code{gnatmem})
18539 This switch causes @code{gnatmem} to sort the allocation roots according to the
18540 specified order of sort criteria, each identified by a single letter. The
18541 currently supported criteria are @code{n, h, w} standing respectively for
18542 number of unfreed allocations, high watermark, and final watermark
18543 corresponding to a specific root. The default order is @code{nwh}.
18547 @node Example of gnatmem Usage
18548 @subsection Example of @code{gnatmem} Usage
18551 The following example shows the use of @code{gnatmem}
18552 on a simple memory-leaking program.
18553 Suppose that we have the following Ada program:
18555 @smallexample @c ada
18558 with Unchecked_Deallocation;
18559 procedure Test_Gm is
18561 type T is array (1..1000) of Integer;
18562 type Ptr is access T;
18563 procedure Free is new Unchecked_Deallocation (T, Ptr);
18566 procedure My_Alloc is
18571 procedure My_DeAlloc is
18579 for I in 1 .. 5 loop
18580 for J in I .. 5 loop
18591 The program needs to be compiled with debugging option and linked with
18592 @code{gmem} library:
18595 $ gnatmake -g test_gm -largs -lgmem
18599 Then we execute the program as usual:
18606 Then @code{gnatmem} is invoked simply with
18612 which produces the following output (result may vary on different platforms):
18617 Total number of allocations : 18
18618 Total number of deallocations : 5
18619 Final Water Mark (non freed mem) : 53.00 Kilobytes
18620 High Water Mark : 56.90 Kilobytes
18622 Allocation Root # 1
18623 -------------------
18624 Number of non freed allocations : 11
18625 Final Water Mark (non freed mem) : 42.97 Kilobytes
18626 High Water Mark : 46.88 Kilobytes
18628 test_gm.adb:11 test_gm.my_alloc
18630 Allocation Root # 2
18631 -------------------
18632 Number of non freed allocations : 1
18633 Final Water Mark (non freed mem) : 10.02 Kilobytes
18634 High Water Mark : 10.02 Kilobytes
18636 s-secsta.adb:81 system.secondary_stack.ss_init
18638 Allocation Root # 3
18639 -------------------
18640 Number of non freed allocations : 1
18641 Final Water Mark (non freed mem) : 12 Bytes
18642 High Water Mark : 12 Bytes
18644 s-secsta.adb:181 system.secondary_stack.ss_init
18648 Note that the GNAT run time contains itself a certain number of
18649 allocations that have no corresponding deallocation,
18650 as shown here for root #2 and root
18651 #3. This is a normal behavior when the number of non-freed allocations
18652 is one, it allocates dynamic data structures that the run time needs for
18653 the complete lifetime of the program. Note also that there is only one
18654 allocation root in the user program with a single line back trace:
18655 test_gm.adb:11 test_gm.my_alloc, whereas a careful analysis of the
18656 program shows that 'My_Alloc' is called at 2 different points in the
18657 source (line 21 and line 24). If those two allocation roots need to be
18658 distinguished, the backtrace depth parameter can be used:
18661 $ gnatmem 3 test_gm
18665 which will give the following output:
18670 Total number of allocations : 18
18671 Total number of deallocations : 5
18672 Final Water Mark (non freed mem) : 53.00 Kilobytes
18673 High Water Mark : 56.90 Kilobytes
18675 Allocation Root # 1
18676 -------------------
18677 Number of non freed allocations : 10
18678 Final Water Mark (non freed mem) : 39.06 Kilobytes
18679 High Water Mark : 42.97 Kilobytes
18681 test_gm.adb:11 test_gm.my_alloc
18682 test_gm.adb:24 test_gm
18683 b_test_gm.c:52 main
18685 Allocation Root # 2
18686 -------------------
18687 Number of non freed allocations : 1
18688 Final Water Mark (non freed mem) : 10.02 Kilobytes
18689 High Water Mark : 10.02 Kilobytes
18691 s-secsta.adb:81 system.secondary_stack.ss_init
18692 s-secsta.adb:283 <system__secondary_stack___elabb>
18693 b_test_gm.c:33 adainit
18695 Allocation Root # 3
18696 -------------------
18697 Number of non freed allocations : 1
18698 Final Water Mark (non freed mem) : 3.91 Kilobytes
18699 High Water Mark : 3.91 Kilobytes
18701 test_gm.adb:11 test_gm.my_alloc
18702 test_gm.adb:21 test_gm
18703 b_test_gm.c:52 main
18705 Allocation Root # 4
18706 -------------------
18707 Number of non freed allocations : 1
18708 Final Water Mark (non freed mem) : 12 Bytes
18709 High Water Mark : 12 Bytes
18711 s-secsta.adb:181 system.secondary_stack.ss_init
18712 s-secsta.adb:283 <system__secondary_stack___elabb>
18713 b_test_gm.c:33 adainit
18717 The allocation root #1 of the first example has been split in 2 roots #1
18718 and #3 thanks to the more precise associated backtrace.
18722 @node Stack Related Facilities
18723 @chapter Stack Related Facilities
18726 This chapter describes some useful tools associated with stack
18727 checking and analysis. In
18728 particular, it deals with dynamic and static stack usage measurements.
18731 * Stack Overflow Checking::
18732 * Static Stack Usage Analysis::
18733 * Dynamic Stack Usage Analysis::
18736 @node Stack Overflow Checking
18737 @section Stack Overflow Checking
18738 @cindex Stack Overflow Checking
18739 @cindex -fstack-check
18742 For most operating systems, @command{gcc} does not perform stack overflow
18743 checking by default. This means that if the main environment task or
18744 some other task exceeds the available stack space, then unpredictable
18745 behavior will occur. Most native systems offer some level of protection by
18746 adding a guard page at the end of each task stack. This mechanism is usually
18747 not enough for dealing properly with stack overflow situations because
18748 a large local variable could ``jump'' above the guard page.
18749 Furthermore, when the
18750 guard page is hit, there may not be any space left on the stack for executing
18751 the exception propagation code. Enabling stack checking avoids
18754 To activate stack checking, compile all units with the gcc option
18755 @option{-fstack-check}. For example:
18758 gcc -c -fstack-check package1.adb
18762 Units compiled with this option will generate extra instructions to check
18763 that any use of the stack (for procedure calls or for declaring local
18764 variables in declare blocks) does not exceed the available stack space.
18765 If the space is exceeded, then a @code{Storage_Error} exception is raised.
18767 For declared tasks, the stack size is controlled by the size
18768 given in an applicable @code{Storage_Size} pragma or by the value specified
18769 at bind time with @option{-d} (@pxref{Switches for gnatbind}) or is set to
18770 the default size as defined in the GNAT runtime otherwise.
18772 For the environment task, the stack size depends on
18773 system defaults and is unknown to the compiler. Stack checking
18774 may still work correctly if a fixed
18775 size stack is allocated, but this cannot be guaranteed.
18777 To ensure that a clean exception is signalled for stack
18778 overflow, set the environment variable
18779 @env{GNAT_STACK_LIMIT} to indicate the maximum
18780 stack area that can be used, as in:
18781 @cindex GNAT_STACK_LIMIT
18784 SET GNAT_STACK_LIMIT 1600
18788 The limit is given in kilobytes, so the above declaration would
18789 set the stack limit of the environment task to 1.6 megabytes.
18790 Note that the only purpose of this usage is to limit the amount
18791 of stack used by the environment task. If it is necessary to
18792 increase the amount of stack for the environment task, then this
18793 is an operating systems issue, and must be addressed with the
18794 appropriate operating systems commands.
18797 To have a fixed size stack in the environment task, the stack must be put
18798 in the P0 address space and its size specified. Use these switches to
18802 gnatmake my_progs -largs "-Wl,--opt=STACK=4000,/p0image"
18806 The quotes are required to keep case. The number after @samp{STACK=} is the
18807 size of the environmental task stack in pagelets (512 bytes). In this example
18808 the stack size is about 2 megabytes.
18811 A consequence of the @option{/p0image} qualifier is also to makes RMS buffers
18812 be placed in P0 space. Refer to @cite{HP OpenVMS Linker Utility Manual} for
18813 more details about the @option{/p0image} qualifier and the @option{stack}
18817 On Itanium platforms, you can instead assign the @samp{GNAT_STACK_SIZE} and
18818 @samp{GNAT_RBS_SIZE} logicals to the size of the primary and register
18819 stack in kilobytes. For example:
18822 $ define GNAT_RBS_SIZE 1024 ! Limit the RBS size to 1MB.
18826 @node Static Stack Usage Analysis
18827 @section Static Stack Usage Analysis
18828 @cindex Static Stack Usage Analysis
18829 @cindex -fstack-usage
18832 A unit compiled with @option{-fstack-usage} will generate an extra file
18834 the maximum amount of stack used, on a per-function basis.
18835 The file has the same
18836 basename as the target object file with a @file{.su} extension.
18837 Each line of this file is made up of three fields:
18841 The name of the function.
18845 One or more qualifiers: @code{static}, @code{dynamic}, @code{bounded}.
18848 The second field corresponds to the size of the known part of the function
18851 The qualifier @code{static} means that the function frame size
18853 It usually means that all local variables have a static size.
18854 In this case, the second field is a reliable measure of the function stack
18857 The qualifier @code{dynamic} means that the function frame size is not static.
18858 It happens mainly when some local variables have a dynamic size. When this
18859 qualifier appears alone, the second field is not a reliable measure
18860 of the function stack analysis. When it is qualified with @code{bounded}, it
18861 means that the second field is a reliable maximum of the function stack
18864 A unit compiled with @option{-Wstack-usage} will issue a warning for each
18865 subprogram whose stack usage might be larger than the specified amount of
18866 bytes. The wording is in keeping with the qualifier documented above.
18868 @node Dynamic Stack Usage Analysis
18869 @section Dynamic Stack Usage Analysis
18872 It is possible to measure the maximum amount of stack used by a task, by
18873 adding a switch to @command{gnatbind}, as:
18876 $ gnatbind -u0 file
18880 With this option, at each task termination, its stack usage is output on
18882 It is not always convenient to output the stack usage when the program
18883 is still running. Hence, it is possible to delay this output until program
18884 termination. for a given number of tasks specified as the argument of the
18885 @option{-u} option. For instance:
18888 $ gnatbind -u100 file
18892 will buffer the stack usage information of the first 100 tasks to terminate and
18893 output this info at program termination. Results are displayed in four
18897 Index | Task Name | Stack Size | Stack Usage
18904 is a number associated with each task.
18907 is the name of the task analyzed.
18910 is the maximum size for the stack.
18913 is the measure done by the stack analyzer. In order to prevent overflow, the stack
18914 is not entirely analyzed, and it's not possible to know exactly how
18915 much has actually been used.
18920 The environment task stack, e.g., the stack that contains the main unit, is
18921 only processed when the environment variable GNAT_STACK_LIMIT is set.
18924 The package @code{GNAT.Task_Stack_Usage} provides facilities to get
18925 stack usage reports at run-time. See its body for the details.
18927 @c *********************************
18929 @c *********************************
18930 @node Verifying Properties with gnatcheck
18931 @chapter Verifying Properties with @command{gnatcheck}
18933 @cindex @command{gnatcheck}
18936 The @command{gnatcheck} tool is an ASIS-based utility that checks properties
18937 of Ada source files according to a given set of semantic rules.
18940 In order to check compliance with a given rule, @command{gnatcheck} has to
18941 semantically analyze the Ada sources.
18942 Therefore, checks can only be performed on
18943 legal Ada units. Moreover, when a unit depends semantically upon units located
18944 outside the current directory, the source search path has to be provided when
18945 calling @command{gnatcheck}, either through a specified project file or
18946 through @command{gnatcheck} switches.
18948 For full details, refer to @cite{GNATcheck Reference Manual} document.
18951 @c *********************************
18952 @node Creating Sample Bodies with gnatstub
18953 @chapter Creating Sample Bodies with @command{gnatstub}
18957 @command{gnatstub} creates body stubs, that is, empty but compilable bodies
18958 for library unit declarations.
18960 Note: to invoke @code{gnatstub} with a project file, use the @code{gnat}
18961 driver (see @ref{The GNAT Driver and Project Files}).
18963 To create a body stub, @command{gnatstub} has to compile the library
18964 unit declaration. Therefore, bodies can be created only for legal
18965 library units. Moreover, if a library unit depends semantically upon
18966 units located outside the current directory, you have to provide
18967 the source search path when calling @command{gnatstub}, see the description
18968 of @command{gnatstub} switches below.
18970 By default, all the program unit body stubs generated by @code{gnatstub}
18971 raise the predefined @code{Program_Error} exception, which will catch
18972 accidental calls of generated stubs. This behavior can be changed with
18973 option @option{^--no-exception^/NO_EXCEPTION^} (see below).
18976 * Running gnatstub::
18977 * Switches for gnatstub::
18980 @node Running gnatstub
18981 @section Running @command{gnatstub}
18984 @command{gnatstub} has a command-line interface of the form:
18987 @c $ gnatstub @ovar{switches} @var{filename} @ovar{directory}
18988 @c Expanding @ovar macro inline (explanation in macro def comments)
18989 $ gnatstub @r{[}@var{switches}@r{]} @var{filename} @r{[}@var{directory}@r{]} @r{[}-cargs @var{gcc_switches}@r{]}
18996 is the name of the source file that contains a library unit declaration
18997 for which a body must be created. The file name may contain the path
18999 The file name does not have to follow the GNAT file name conventions. If the
19001 does not follow GNAT file naming conventions, the name of the body file must
19003 explicitly as the value of the @option{^-o^/BODY=^@var{body-name}} option.
19004 If the file name follows the GNAT file naming
19005 conventions and the name of the body file is not provided,
19008 of the body file from the argument file name by replacing the @file{.ads}
19010 with the @file{.adb} suffix.
19013 indicates the directory in which the body stub is to be placed (the default
19017 @item @samp{@var{gcc_switches}} is a list of switches for
19018 @command{gcc}. They will be passed on to all compiler invocations made by
19019 @command{gnatstub} to generate the ASIS trees. Here you can provide
19020 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
19021 use the @option{-gnatec} switch to set the configuration file,
19022 use the @option{-gnat05} switch if sources should be compiled in
19026 is an optional sequence of switches as described in the next section
19029 @node Switches for gnatstub
19030 @section Switches for @command{gnatstub}
19036 @cindex @option{--version} @command{gnatstub}
19037 Display Copyright and version, then exit disregarding all other options.
19040 @cindex @option{--help} @command{gnatstub}
19041 Display usage, then exit disregarding all other options.
19044 @cindex @option{^-f^/FULL^} (@command{gnatstub})
19045 If the destination directory already contains a file with the name of the
19047 for the argument spec file, replace it with the generated body stub.
19049 @item ^-hs^/HEADER=SPEC^
19050 @cindex @option{^-hs^/HEADER=SPEC^} (@command{gnatstub})
19051 Put the comment header (i.e., all the comments preceding the
19052 compilation unit) from the source of the library unit declaration
19053 into the body stub.
19055 @item ^-hg^/HEADER=GENERAL^
19056 @cindex @option{^-hg^/HEADER=GENERAL^} (@command{gnatstub})
19057 Put a sample comment header into the body stub.
19059 @item ^--header-file=@var{filename}^/FROM_HEADER_FILE=@var{filename}^
19060 @cindex @option{^--header-file^/FROM_HEADER_FILE=^} (@command{gnatstub})
19061 Use the content of the file as the comment header for a generated body stub.
19065 @cindex @option{-IDIR} (@command{gnatstub})
19067 @cindex @option{-I-} (@command{gnatstub})
19070 @item /NOCURRENT_DIRECTORY
19071 @cindex @option{/NOCURRENT_DIRECTORY} (@command{gnatstub})
19073 ^These switches have ^This switch has^ the same meaning as in calls to
19075 ^They define ^It defines ^ the source search path in the call to
19076 @command{gcc} issued
19077 by @command{gnatstub} to compile an argument source file.
19079 @item ^-gnatec^/CONFIGURATION_PRAGMAS_FILE=^@var{PATH}
19080 @cindex @option{^-gnatec^/CONFIGURATION_PRAGMAS_FILE^} (@command{gnatstub})
19081 This switch has the same meaning as in calls to @command{gcc}.
19082 It defines the additional configuration file to be passed to the call to
19083 @command{gcc} issued
19084 by @command{gnatstub} to compile an argument source file.
19086 @item ^-gnatyM^/MAX_LINE_LENGTH=^@var{n}
19087 @cindex @option{^-gnatyM^/MAX_LINE_LENGTH^} (@command{gnatstub})
19088 (@var{n} is a non-negative integer). Set the maximum line length that is
19089 allowed in a source file. The default is 79. The maximum value that can be
19090 specified is 32767. Note that in the special case of configuration
19091 pragma files, the maximum is always 32767 regardless of whether or
19092 not this switch appears.
19094 @item ^-gnaty^/STYLE_CHECKS=^@var{n}
19095 @cindex @option{^-gnaty^/STYLE_CHECKS=^} (@command{gnatstub})
19096 (@var{n} is a non-negative integer from 1 to 9). Set the indentation level in
19097 the generated body sample to @var{n}.
19098 The default indentation is 3.
19100 @item ^-gnatyo^/ORDERED_SUBPROGRAMS^
19101 @cindex @option{^-gnatyo^/ORDERED_SUBPROGRAMS^} (@command{gnatstub})
19102 Order local bodies alphabetically. (By default local bodies are ordered
19103 in the same way as the corresponding local specs in the argument spec file.)
19105 @item ^-i^/INDENTATION=^@var{n}
19106 @cindex @option{^-i^/INDENTATION^} (@command{gnatstub})
19107 Same as @option{^-gnaty^/STYLE_CHECKS=^@var{n}}
19109 @item ^-k^/TREE_FILE=SAVE^
19110 @cindex @option{^-k^/TREE_FILE=SAVE^} (@command{gnatstub})
19111 Do not remove the tree file (i.e., the snapshot of the compiler internal
19112 structures used by @command{gnatstub}) after creating the body stub.
19114 @item ^-l^/LINE_LENGTH=^@var{n}
19115 @cindex @option{^-l^/LINE_LENGTH^} (@command{gnatstub})
19116 Same as @option{^-gnatyM^/MAX_LINE_LENGTH=^@var{n}}
19118 @item ^--no-exception^/NO_EXCEPTION^
19119 @cindex @option{^--no-exception^/NO_EXCEPTION^} (@command{gnatstub})
19120 Avoid raising PROGRAM_ERROR in the generated bodies of program unit stubs.
19121 This is not always possible for function stubs.
19123 @item ^--no-local-header^/NO_LOCAL_HEADER^
19124 @cindex @option{^--no-local-header^/NO_LOCAL_HEADER^} (@command{gnatstub})
19125 Do not place local comment header with unit name before body stub for a
19128 @item ^-o ^/BODY=^@var{body-name}
19129 @cindex @option{^-o^/BODY^} (@command{gnatstub})
19130 Body file name. This should be set if the argument file name does not
19132 the GNAT file naming
19133 conventions. If this switch is omitted the default name for the body will be
19135 from the argument file name according to the GNAT file naming conventions.
19138 @cindex @option{^-q^/QUIET^} (@command{gnatstub})
19139 Quiet mode: do not generate a confirmation when a body is
19140 successfully created, and do not generate a message when a body is not
19144 @item ^-r^/TREE_FILE=REUSE^
19145 @cindex @option{^-r^/TREE_FILE=REUSE^} (@command{gnatstub})
19146 Reuse the tree file (if it exists) instead of creating it. Instead of
19147 creating the tree file for the library unit declaration, @command{gnatstub}
19148 tries to find it in the current directory and use it for creating
19149 a body. If the tree file is not found, no body is created. This option
19150 also implies @option{^-k^/SAVE^}, whether or not
19151 the latter is set explicitly.
19153 @item ^-t^/TREE_FILE=OVERWRITE^
19154 @cindex @option{^-t^/TREE_FILE=OVERWRITE^} (@command{gnatstub})
19155 Overwrite the existing tree file. If the current directory already
19156 contains the file which, according to the GNAT file naming rules should
19157 be considered as a tree file for the argument source file,
19159 will refuse to create the tree file needed to create a sample body
19160 unless this option is set.
19162 @item ^-v^/VERBOSE^
19163 @cindex @option{^-v^/VERBOSE^} (@command{gnatstub})
19164 Verbose mode: generate version information.
19168 @c *********************************
19169 @node Creating Unit Tests with gnattest
19170 @chapter Creating Unit Tests with @command{gnattest}
19174 @command{gnattest} is an ASIS-based utility that creates unit-test skeletons
19175 as well as a test driver infrastructure (harness). @command{gnattest} creates
19176 a skeleton for each visible subprogram in the packages under consideration when
19177 they do not exist already.
19179 In order to process source files from a project, @command{gnattest} has to
19180 semantically analyze the sources. Therefore, test skeletons can only be
19181 generated for legal Ada units. If a unit is dependent on other units,
19182 those units should be among the source files of the project or of other projects
19183 imported by this one.
19185 Generated skeletons and harnesses are based on the AUnit testing framework.
19186 AUnit is an Ada adaptation of the xxxUnit testing frameworks, similar to JUnit
19187 for Java or CppUnit for C++. While it is advised that gnattest users read
19188 the AUnit manual, deep knowledge of AUnit is not necessary for using gnattest.
19189 For correct operation of @command{gnattest}, AUnit should be installed and
19190 aunit.gpr must be on the project path. This happens automatically when Aunit
19191 is installed at its default location.
19193 * Running gnattest::
19194 * Switches for gnattest::
19195 * Project Attributes for gnattest::
19197 * Setting Up and Tearing Down the Testing Environment::
19198 * Regenerating Tests::
19199 * Default Test Behavior::
19200 * Testing Primitive Operations of Tagged Types::
19201 * Testing Inheritance::
19202 * Tagged Types Substitutability Testing::
19203 * Testing with Contracts::
19204 * Additional Tests::
19206 * Support for other platforms/run-times::
19208 * Current Limitations::
19211 @node Running gnattest
19212 @section Running @command{gnattest}
19215 @command{gnattest} has a command-line interface of the form
19218 @c $ gnattest @var{-Pprojname} @ovar{switches} @ovar{filename} @ovar{directory}
19219 @c Expanding @ovar macro inline (explanation in macro def comments)
19220 $ gnattest @var{-Pprojname} @r{[}@var{--harness-dir=dirname}@r{]} @r{[}@var{switches}@r{]} @r{[}@var{filename}@r{]} @r{[}-cargs @var{gcc_switches}@r{]}
19228 specifies the project defining the location of source files. When no
19229 file names are provided on the command line, all sources in the project
19230 are used as input. This switch is required.
19233 is the name of the source file containing the library unit package declaration
19234 for which a test package will be created. The file name may be given with a
19237 @item @samp{@var{gcc_switches}}
19238 is a list of switches for
19239 @command{gcc}. These switches will be passed on to all compiler invocations
19240 made by @command{gnattest} to generate a set of ASIS trees. Here you can provide
19241 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
19242 use the @option{-gnatec} switch to set the configuration file,
19243 use the @option{-gnat05} switch if sources should be compiled in
19244 Ada 2005 mode, etc.
19247 is an optional sequence of switches as described in the next section.
19251 @command{gnattest} results can be found in two different places.
19254 @item automatic harness:
19255 the harness code, which is located by default in "gnattest/harness" directory
19256 that is created in the object directory of corresponding project file. All of
19257 this code is generated completely automatically and can be destroyed and
19258 regenerated at will. It is not recommended to modify this code manually, since
19259 it could easily be overridden by mistake. The entry point in the harness code is
19260 the project file named @command{test_driver.gpr}. Tests can be compiled and run
19261 using a command such as:
19264 gnatmake -P<harness-dir>/test_driver
19268 Note that you might need to specify the necessary values of scenario variables
19269 when you are not using the AUnit defaults.
19271 @item actual unit test skeletons:
19272 a test skeleton for each visible subprogram is created in a separate file, if it
19273 doesn't exist already. By default, those separate test files are located in a
19274 "gnattest/tests" directory that is created in the object directory of
19275 corresponding project file. For example, if a source file my_unit.ads in
19276 directory src contains a visible subprogram Proc, then the corresponding unit
19277 test will be found in file src/tests/my_unit-test_data-tests-proc_<code>.adb.
19278 <code> is a signature encoding used to differentiate test names in case of
19281 Note that if the project already has both my_unit.ads and my_unit-test_data.ads,
19282 this will cause a name conflict with the generated test package.
19285 @node Switches for gnattest
19286 @section Switches for @command{gnattest}
19291 @item --harness-only
19292 @cindex @option{--harness-only} (@command{gnattest})
19293 When this option is given, @command{gnattest} creates a harness for all
19294 sources, treating them as test packages.
19296 @item --additional-tests=@var{projname}
19297 @cindex @option{--additional-tests} (@command{gnattest})
19298 Sources described in @var{projname} are considered potential additional
19299 manual tests to be added to the test suite.
19302 @cindex @option{-r} (@command{gnattest})
19303 Recursively consider all sources from all projects.
19305 @item -X@var{name=value}
19306 @cindex @option{-X} (@command{gnattest})
19307 Indicate that external variable @var{name} has the value @var{value}.
19310 @cindex @option{-q} (@command{gnattest})
19311 Suppresses noncritical output messages.
19314 @cindex @option{-v} (@command{gnattest})
19315 Verbose mode: generates version information.
19317 @item --validate-type-extensions
19318 @cindex @option{--validate-type-extensions} (@command{gnattest})
19319 Enables substitution check: run all tests from all parents in order
19320 to check substitutability.
19322 @item --skeleton-default=@var{val}
19323 @cindex @option{--skeleton-default} (@command{gnattest})
19324 Specifies the default behavior of generated skeletons. @var{val} can be either
19325 "fail" or "pass", "fail" being the default.
19327 @item --tests-root=@var{dirname}
19328 @cindex @option{--tests-root} (@command{gnattest})
19329 The directory hierarchy of tested sources is recreated in the @var{dirname}
19330 directory, and test packages are placed in corresponding directories.
19331 If the @var{dirname} is a relative path, it is considered relative to the object
19332 directory of the project file. When all sources from all projects are taken
19333 recursively from all projects, directory hierarchies of tested sources are
19334 recreated for each project in their object directories and test packages are
19335 placed accordingly.
19337 @item --subdir=@var{dirname}
19338 @cindex @option{--subdir} (@command{gnattest})
19339 Test packages are placed in subdirectories.
19341 @item --tests-dir=@var{dirname}
19342 @cindex @option{--tests-dir} (@command{gnattest})
19343 All test packages are placed in the @var{dirname} directory.
19344 If the @var{dirname} is a relative path, it is considered relative to the object
19345 directory of the project file. When all sources from all projects are taken
19346 recursively from all projects, @var{dirname} directories are created for each
19347 project in their object directories and test packages are placed accordingly.
19349 @item --harness-dir=@var{dirname}
19350 @cindex @option{--harness-dir} (@command{gnattest})
19351 specifies the directory that will hold the harness packages and project file
19352 for the test driver. If the @var{dirname} is a relative path, it is considered
19353 relative to the object directory of the project file.
19356 @cindex @option{--separates} (@command{gnattest})
19357 Bodies of all test routines are generated as separates. Note that this mode is
19358 kept for compatibility reasons only and it is not advised to use it due to
19359 possible problems with hash in names of test skeletons when using an
19360 inconsistent casing. Separate test skeletons can be incorporated to monolith
19361 test package with improved hash being used by using @option{--transition}
19366 @cindex @option{--transition} (@command{gnattest})
19367 This allows transition from separate test routines to monolith test packages.
19368 All matching test routines are overwritten with contents of corresponding
19369 separates. Note that if separate test routines had any manually added with
19370 clauses they will be moved to the test package body as is and have to be moved
19375 @option{--tests_root}, @option{--subdir} and @option{--tests-dir} switches are
19376 mutually exclusive.
19378 @node Project Attributes for gnattest
19379 @section Project Attributes for @command{gnattest}
19383 Most of the command-line options can also be passed to the tool by adding
19384 special attributes to the project file. Those attributes should be put in
19385 package gnattest. Here is the list of attributes:
19390 is used to select the same output mode as with the --tests-root option.
19391 This attribute cannot be used together with Subdir or Tests_Dir.
19394 is used to select the same output mode as with the --subdir option.
19395 This attribute cannot be used together with Tests_Root or Tests_Dir.
19398 is used to select the same output mode as with the --tests-dir option.
19399 This attribute cannot be used together with Subdir or Tests_Root.
19402 is used to specify the directory in which to place harness packages and project
19403 file for the test driver, otherwise specified by --harness-dir.
19405 @item Additional_Tests
19406 is used to specify the project file, otherwise given by
19407 --additional-tests switch.
19409 @item Skeletons_Default
19410 is used to specify the default behaviour of test skeletons, otherwise
19411 specified by --skeleton-default option. The value of this attribute
19412 should be either "pass" or "fail".
19416 Each of those attributes can be overridden from the command line if needed.
19417 Other @command{gnattest} switches can also be passed via the project
19418 file as an attribute list called GNATtest_Switches.
19420 @node Simple Example
19421 @section Simple Example
19425 Let's take a very simple example using the first @command{gnattest} example
19429 <install_prefix>/share/examples/gnattest/simple
19432 This project contains a simple package containing one subprogram. By running gnattest:
19435 $ gnattest --harness-dir=driver -Psimple.gpr
19438 a test driver is created in directory "driver". It can be compiled and run:
19442 $ gnatmake -Ptest_driver
19446 One failed test with diagnosis "test not implemented" is reported.
19447 Since no special output option was specified, the test package Simple.Tests
19451 <install_prefix>/share/examples/gnattest/simple/obj/gnattest/tests
19454 For each package containing visible subprograms, a child test package is
19455 generated. It contains one test routine per tested subprogram. Each
19456 declaration of a test subprogram has a comment specifying which tested
19457 subprogram it corresponds to. Bodies of test routines are placed in test package
19458 bodies and are surrounded by special comment sections. Those comment sections
19459 should not be removed or modified in order for gnattest to be able to regenerate
19460 test packages and keep already written tests in place.
19461 The test routine Test_Inc_5eaee3 located at simple-test_data-tests.adb contains
19462 a single statement: a call to procedure Assert. It has two arguments:
19463 the Boolean expression we want to check and the diagnosis message to display if
19464 the condition is false.
19466 That is where actual testing code should be written after a proper setup.
19467 An actual check can be performed by replacing the Assert call with:
19469 @smallexample @c ada
19470 Assert (Inc (1) = 2, "wrong incrementation");
19473 After recompiling and running the test driver, one successfully passed test
19476 @node Setting Up and Tearing Down the Testing Environment
19477 @section Setting Up and Tearing Down the Testing Environment
19481 Besides test routines themselves, each test package has a parent package
19482 Test_Data that has two procedures: Set_Up and Tear_Down. This package is never
19483 overwritten by the tool. Set_Up is called before each test routine of the
19484 package and Tear_Down is called after each test routine. Those two procedures
19485 can be used to perform necessary initialization and finalization,
19486 memory allocation, etc. Test type declared in Test_Data package is parent type
19487 for the test type of test package and can have user-defined components whose
19488 values can be set by Set_Up routine and used in test routines afterwards.
19490 @node Regenerating Tests
19491 @section Regenerating Tests
19495 Bodies of test routines and test_data packages are never overridden after they
19496 have been created once. As long as the name of the subprogram, full expanded Ada
19497 names, and the order of its parameters is the same, and comment sections are
19498 intact the old test routine will fit in its place and no test skeleton will be
19499 generated for the subprogram.
19501 This can be demonstrated with the previous example. By uncommenting declaration
19502 and body of function Dec in simple.ads and simple.adb, running
19503 @command{gnattest} on the project, and then running the test driver:
19506 gnattest --harness-dir=driver -Psimple.gpr
19508 gnatmake -Ptest_driver
19512 the old test is not replaced with a stub, nor is it lost, but a new test
19513 skeleton is created for function Dec.
19515 The only way of regenerating tests skeletons is to remove the previously created
19516 tests together with corresponding comment sections.
19518 @node Default Test Behavior
19519 @section Default Test Behavior
19523 The generated test driver can treat unimplemented tests in two ways:
19524 either count them all as failed (this is useful to see which tests are still
19525 left to implement) or as passed (to sort out unimplemented ones from those
19528 The test driver accepts a switch to specify this behavior:
19529 --skeleton-default=val, where val is either "pass" or "fail" (exactly as for
19530 @command{gnattest}).
19532 The default behavior of the test driver is set with the same switch
19533 as passed to gnattest when generating the test driver.
19535 Passing it to the driver generated on the first example:
19538 test_runner --skeleton-default=pass
19541 makes both tests pass, even the unimplemented one.
19543 @node Testing Primitive Operations of Tagged Types
19544 @section Testing Primitive Operations of Tagged Types
19548 Creation of test skeletons for primitive operations of tagged types entails
19549 a number of features. Test routines for all primitives of a given tagged type
19550 are placed in a separate child package named according to the tagged type. For
19551 example, if you have tagged type T in package P, all tests for primitives
19552 of T will be in P.T_Test_Data.T_Tests.
19554 Consider running gnattest on the second example (note: actual tests for this
19555 example already exist, so there's no need to worry if the tool reports that
19556 no new stubs were generated):
19559 cd <install_prefix>/share/examples/gnattest/tagged_rec
19560 gnattest --harness-dir=driver -Ptagged_rec.gpr
19563 Taking a closer look at the test type declared in the test package
19564 Speed1.Controller_Test_Data is necessary. It is declared in:
19567 <install_prefix>/share/examples/gnattest/tagged_rec/obj/gnattest/tests
19570 Test types are direct or indirect descendants of
19571 AUnit.Test_Fixtures.Test_Fixture type. In the case of nonprimitive tested
19572 subprograms, the user doesn't need to be concerned with them. However,
19573 when generating test packages for primitive operations, there are some things
19574 the user needs to know.
19576 Type Test_Controller has components that allow assignment of various
19577 derivations of type Controller. And if you look at the specification of
19578 package Speed2.Auto_Controller, you will see that Test_Auto_Controller
19579 actually derives from Test_Controller rather than AUnit type Test_Fixture.
19580 Thus, test types mirror the hierarchy of tested types.
19582 The Set_Up procedure of Test_Data package corresponding to a test package
19583 of primitive operations of type T assigns to Fixture a reference to an
19584 object of that exact type T. Notice, however, that if the tagged type has
19585 discriminants, the Set_Up only has a commented template for setting
19586 up the fixture, since filling the discriminant with actual value is up
19589 The knowledge of the structure of test types allows additional testing
19590 without additional effort. Those possibilities are described below.
19592 @node Testing Inheritance
19593 @section Testing Inheritance
19597 Since the test type hierarchy mimics the hierarchy of tested types, the
19598 inheritance of tests takes place. An example of such inheritance can be
19599 seen by running the test driver generated for the second example. As previously
19600 mentioned, actual tests are already written for this example.
19604 gnatmake -Ptest_driver
19608 There are 6 passed tests while there are only 5 testable subprograms. The test
19609 routine for function Speed has been inherited and run against objects of the
19612 @node Tagged Types Substitutability Testing
19613 @section Tagged Types Substitutability Testing
19617 Tagged Types Substitutability Testing is a way of verifying the global type
19618 consistency by testing. Global type consistency is a principle stating that if
19619 S is a subtype of T (in Ada, S is a derived type of tagged type T),
19620 then objects of type T may be replaced with objects of type S (that is,
19621 objects of type S may be substituted for objects of type T), without
19622 altering any of the desirable properties of the program. When the properties
19623 of the program are expressed in the form of subprogram preconditions and
19624 postconditions (let's call them pre and post), the principle is formulated as
19625 relations between the pre and post of primitive operations and the pre and post
19626 of their derived operations. The pre of a derived operation should not be
19627 stronger than the original pre, and the post of the derived operation should
19628 not be weaker than the original post. Those relations ensure that verifying if
19629 a dispatching call is safe can be done just by using the pre and post of the
19632 Verifying global type consistency by testing consists of running all the unit
19633 tests associated with the primitives of a given tagged type with objects of its
19636 In the example used in the previous section, there was clearly a violation of
19637 type consistency. The overriding primitive Adjust_Speed in package Speed2
19638 removes the functionality of the overridden primitive and thus doesn't respect
19639 the consistency principle.
19640 Gnattest has a special option to run overridden parent tests against objects
19641 of the type which have overriding primitives:
19644 gnattest --harness-dir=driver --validate-type-extensions -Ptagged_rec.gpr
19646 gnatmake -Ptest_driver
19650 While all the tests pass by themselves, the parent test for Adjust_Speed fails
19651 against objects of the derived type.
19653 Non-overridden tests are already inherited for derived test types, so the
19654 --validate-type-extensions enables the application of overriden tests to objects
19657 @node Testing with Contracts
19658 @section Testing with Contracts
19662 @command{gnattest} supports pragmas Precondition, Postcondition, and Test_Case,
19663 as well as corresponding aspects.
19664 Test routines are generated, one per each Test_Case associated with a tested
19665 subprogram. Those test routines have special wrappers for tested functions
19666 that have composition of pre- and postcondition of the subprogram with
19667 "requires" and "ensures" of the Test_Case (depending on the mode, pre and post
19668 either count for Nominal mode or do not count for Robustness mode).
19670 The third example demonstrates how this works:
19673 cd <install_prefix>/share/examples/gnattest/contracts
19674 gnattest --harness-dir=driver -Pcontracts.gpr
19677 Putting actual checks within the range of the contract does not cause any
19678 error reports. For example, for the test routine which corresponds to
19681 @smallexample @c ada
19682 Assert (Sqrt (9.0) = 3.0, "wrong sqrt");
19685 and for the test routine corresponding to test case 2:
19687 @smallexample @c ada
19688 Assert (Sqrt (-5.0) = -1.0, "wrong error indication");
19695 gnatmake -Ptest_driver
19699 However, by changing 9.0 to 25.0 and 3.0 to 5.0, for example, you can get
19700 a precondition violation for test case one. Also, by using any otherwise
19701 correct but positive pair of numbers in the second test routine, you can also
19702 get a precondition violation. Postconditions are checked and reported
19705 @node Additional Tests
19706 @section Additional Tests
19709 @command{gnattest} can add user-written tests to the main suite of the test
19710 driver. @command{gnattest} traverses the given packages and searches for test
19711 routines. All procedures with a single in out parameter of a type which is
19712 derived from AUnit.Test_Fixtures.Test_Fixture and that are declared in package
19713 specifications are added to the suites and are then executed by the test driver.
19714 (Set_Up and Tear_Down are filtered out.)
19716 An example illustrates two ways of creating test harnesses for user-written
19717 tests. Directory additional_tests contains an AUnit-based test driver written
19721 <install_prefix>/share/examples/gnattest/additional_tests/
19724 To create a test driver for already-written tests, use the --harness-only
19728 gnattest -Padditional/harness/harness.gpr --harness-dir=harness_only \
19730 gnatmake -Pharness_only/test_driver.gpr
19731 harness_only/test_runner
19734 Additional tests can also be executed together with generated tests:
19737 gnattest -Psimple.gpr --additional-tests=additional/harness/harness.gpr \
19738 --harness-dir=mixing
19739 gnatmake -Pmixing/test_driver.gpr
19744 @node Support for other platforms/run-times
19745 @section Support for other platforms/run-times
19748 @command{gnattest} can be used to generate the test harness for platforms
19749 and run-time libraries others than the default native target with the
19750 default full run-time. For example, when using a limited run-time library
19751 such as Zero FootPrint (ZFP), a simplified harness is generated.
19753 Two variables are used to tell the underlying AUnit framework how to generate
19754 the test harness: @code{PLATFORM}, which identifies the target, and
19755 @code{RUNTIME}, used to determine the run-time library for which the harness
19756 is generated. Corresponding prefix should also be used when calling
19757 @command{gnattest} for non-native targets. For example, the following options
19758 are used to generate the AUnit test harness for a PowerPC ELF target using
19759 the ZFP run-time library:
19762 powerpc-elf-gnattest -Psimple.gpr -XPLATFORM=powerpc-elf -XRUNTIME=zfp
19766 @node Current Limitations
19767 @section Current Limitations
19771 The tool currently does not support following features:
19774 @item generic tests for generic packages and package instantiations
19775 @item tests for protected subprograms and entries
19779 @c *********************************
19780 @node Performing Dimensionality Analysis in GNAT
19781 @chapter Performing Dimensionality Analysis in GNAT
19783 The GNAT compiler now supports dimensionality checking. The user can
19784 specify physical units for objects, and the compiler will verify that uses
19785 of these objects are compatible with their dimensions, in a fashion that is
19786 familiar to engineering practice. The dimensions of algebraic expressions
19787 (including powers with static exponents) are computed from their consistuents.
19789 This feature depends on Ada 2012 aspect specifications, and is available from
19790 version 7.0.1 of GNAT onwards. The GNAT-specific aspect Dimension_System allows
19791 you to define a system of units; the aspect Dimension then allows the user
19792 to declare dimensioned quantities within a given system.
19794 The major advantage of this model is that it does not require the declaration of
19795 multiple operators for all possible combinations of types: it is only necessary
19796 to use the proper subtypes in object declarations.
19798 The simplest way to impose dimensionality checking on a computation is to make
19799 use of the package System.Dim.Mks, which is part of the GNAT library. This
19800 package defines a floating-point type MKS_Type, 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 s-dimmks.ads.
19805 @smallexample @c ada
19806 type Mks_Type is new Long_Long_Float
19808 Dimension_System => (
19809 (Unit_Name => Meter, Unit_Symbol => 'm', Dim_Symbol => 'L'),
19810 (Unit_Name => Kilogram, Unit_Symbol => "kg", Dim_Symbol => 'M'),
19811 (Unit_Name => Second, Unit_Symbol => 's', Dim_Symbol => 'T'),
19812 (Unit_Name => Ampere, Unit_Symbol => 'A', Dim_Symbol => 'I'),
19813 (Unit_Name => Kelvin, Unit_Symbol => 'K', Dim_Symbol => "Theta"),
19814 (Unit_Name => Mole, Unit_Symbol => "mol", Dim_Symbol => 'N'),
19815 (Unit_Name => Candela, Unit_Symbol => "cd", Dim_Symbol => 'J'));
19819 The package then defines a series of subtypes that correspond to these
19820 conventional units. For example:
19821 @smallexample @c ada
19822 subtype Length is Mks_Type
19824 Dimension => (Symbol => 'm', Meter => 1, others => 0);
19827 and similarly for Mass, Time, Electric_Current, Thermodynamic_Temperature,
19828 Amount_Of_Substance, and Luminous_Intensity (the standard set of units of
19831 The package also defines conventional names for values of each unit, for
19834 @smallexample @c ada
19835 m : constant Length := 1.0;
19836 kg : constant Mass := 1.0;
19837 s : constant Time := 1.0;
19838 A : constant Electric_Current := 1.0;
19842 as well as useful multiples of these units:
19844 @smallexample @c ada
19845 cm : constant Length := 1.0E-02;
19846 g : constant Mass := 1.0E-03;
19847 min : constant Time := 60.0;
19848 day : constant TIme := 60.0 * 24.0 * min;
19853 Using this package, you can then define a derived unit by
19854 providing the aspect that
19855 specifies its dimensions within the MKS system, as well as the string to
19856 be used for output of a value of that unit:
19858 @smallexample @c ada
19859 subtype Acceleration is Mks_Type
19860 with Dimension => ("m/sec^^^2",
19867 Here is a complete example of use:
19869 @smallexample @c ada
19870 with System.Dim.MKS; use System.Dim.Mks;
19871 with System.Dim.Mks_IO; use System.Dim.Mks_IO;
19872 with Text_IO; use Text_IO;
19873 procedure Free_Fall is
19874 subtype Acceleration is Mks_Type
19875 with Dimension => ("m/sec^^^2", 1, 0, -2, others => 0);
19876 G : constant acceleration := 9.81 * m / (s ** 2);
19877 T : Time := 10.0*s;
19880 Put ("Gravitational constant: ");
19881 Put (G, Aft => 2, Exp => 0); Put_Line ("");
19882 Distance := 0.5 * G * T ** 2;
19883 Put ("distance travelled in 10 seconds of free fall ");
19884 Put (Distance, Aft => 2, Exp => 0);
19890 Execution of this program yields:
19892 Gravitational constant: 9.81 m/sec^^^2
19893 distance travelled in 10 seconds of free fall 490.50 m
19897 However, incorrect assignments such as:
19899 @smallexample @c ada
19901 Distance := 5.0 * kg:
19905 are rejected with the following diagnoses:
19909 >>> dimensions mismatch in assignment
19910 >>> left-hand side has dimension [L]
19911 >>> right-hand side is dimensionless
19913 Distance := 5.0 * kg:
19914 >>> dimensions mismatch in assignment
19915 >>> left-hand side has dimension [L]
19916 >>> right-hand side has dimension [M]
19920 The dimensions of an expression are properly displayed, even if there is
19921 no explicit subtype for it. If we add to the program:
19923 @smallexample @c ada
19924 Put ("Final velocity: ");
19925 Put (G * T, Aft =>2, Exp =>0);
19930 then the output includes:
19932 Final velocity: 98.10 m.s**(-1)
19935 @c *********************************
19936 @node Generating Ada Bindings for C and C++ headers
19937 @chapter Generating Ada Bindings for C and C++ headers
19941 GNAT now comes with a binding generator for C and C++ headers which is
19942 intended to do 95% of the tedious work of generating Ada specs from C
19943 or C++ header files.
19945 Note that this capability is not intended to generate 100% correct Ada specs,
19946 and will is some cases require manual adjustments, although it can often
19947 be used out of the box in practice.
19949 Some of the known limitations include:
19952 @item only very simple character constant macros are translated into Ada
19953 constants. Function macros (macros with arguments) are partially translated
19954 as comments, to be completed manually if needed.
19955 @item some extensions (e.g. vector types) are not supported
19956 @item pointers to pointers or complex structures are mapped to System.Address
19957 @item identifiers with identical name (except casing) will generate compilation
19958 errors (e.g. @code{shm_get} vs @code{SHM_GET}).
19961 The code generated is using the Ada 2005 syntax, which makes it
19962 easier to interface with other languages than previous versions of Ada.
19965 * Running the binding generator::
19966 * Generating bindings for C++ headers::
19970 @node Running the binding generator
19971 @section Running the binding generator
19974 The binding generator is part of the @command{gcc} compiler and can be
19975 invoked via the @option{-fdump-ada-spec} switch, which will generate Ada
19976 spec files for the header files specified on the command line, and all
19977 header files needed by these files transitively. For example:
19980 $ g++ -c -fdump-ada-spec -C /usr/include/time.h
19981 $ gcc -c -gnat05 *.ads
19984 will generate, under GNU/Linux, the following files: @file{time_h.ads},
19985 @file{bits_time_h.ads}, @file{stddef_h.ads}, @file{bits_types_h.ads} which
19986 correspond to the files @file{/usr/include/time.h},
19987 @file{/usr/include/bits/time.h}, etc@dots{}, and will then compile in Ada 2005
19988 mode these Ada specs.
19990 The @code{-C} switch tells @command{gcc} to extract comments from headers,
19991 and will attempt to generate corresponding Ada comments.
19993 If you want to generate a single Ada file and not the transitive closure, you
19994 can use instead the @option{-fdump-ada-spec-slim} switch.
19996 You can optionally specify a parent unit, of which all generated units will
19997 be children, using @code{-fada-spec-parent=}@var{unit}.
19999 Note that we recommend when possible to use the @command{g++} driver to
20000 generate bindings, even for most C headers, since this will in general
20001 generate better Ada specs. For generating bindings for C++ headers, it is
20002 mandatory to use the @command{g++} command, or @command{gcc -x c++} which
20003 is equivalent in this case. If @command{g++} cannot work on your C headers
20004 because of incompatibilities between C and C++, then you can fallback to
20005 @command{gcc} instead.
20007 For an example of better bindings generated from the C++ front-end,
20008 the name of the parameters (when available) are actually ignored by the C
20009 front-end. Consider the following C header:
20012 extern void foo (int variable);
20015 with the C front-end, @code{variable} is ignored, and the above is handled as:
20018 extern void foo (int);
20021 generating a generic:
20024 procedure foo (param1 : int);
20027 with the C++ front-end, the name is available, and we generate:
20030 procedure foo (variable : int);
20033 In some cases, the generated bindings will be more complete or more meaningful
20034 when defining some macros, which you can do via the @option{-D} switch. This
20035 is for example the case with @file{Xlib.h} under GNU/Linux:
20038 g++ -c -fdump-ada-spec -DXLIB_ILLEGAL_ACCESS -C /usr/include/X11/Xlib.h
20041 The above will generate more complete bindings than a straight call without
20042 the @option{-DXLIB_ILLEGAL_ACCESS} switch.
20044 In other cases, it is not possible to parse a header file in a stand-alone
20045 manner, because other include files need to be included first. In this
20046 case, the solution is to create a small header file including the needed
20047 @code{#include} and possible @code{#define} directives. For example, to
20048 generate Ada bindings for @file{readline/readline.h}, you need to first
20049 include @file{stdio.h}, so you can create a file with the following two
20050 lines in e.g. @file{readline1.h}:
20054 #include <readline/readline.h>
20057 and then generate Ada bindings from this file:
20060 $ g++ -c -fdump-ada-spec readline1.h
20063 @node Generating bindings for C++ headers
20064 @section Generating bindings for C++ headers
20067 Generating bindings for C++ headers is done using the same options, always
20068 with the @command{g++} compiler.
20070 In this mode, C++ classes will be mapped to Ada tagged types, constructors
20071 will be mapped using the @code{CPP_Constructor} pragma, and when possible,
20072 multiple inheritance of abstract classes will be mapped to Ada interfaces
20073 (@xref{Interfacing to C++,,,gnat_rm, GNAT Reference Manual}, for additional
20074 information on interfacing to C++).
20076 For example, given the following C++ header file:
20083 virtual int Number_Of_Teeth () = 0;
20088 virtual void Set_Owner (char* Name) = 0;
20094 virtual void Set_Age (int New_Age);
20097 class Dog : Animal, Carnivore, Domestic @{
20102 virtual int Number_Of_Teeth ();
20103 virtual void Set_Owner (char* Name);
20111 The corresponding Ada code is generated:
20113 @smallexample @c ada
20116 package Class_Carnivore is
20117 type Carnivore is limited interface;
20118 pragma Import (CPP, Carnivore);
20120 function Number_Of_Teeth (this : access Carnivore) return int is abstract;
20122 use Class_Carnivore;
20124 package Class_Domestic is
20125 type Domestic is limited interface;
20126 pragma Import (CPP, Domestic);
20128 procedure Set_Owner
20129 (this : access Domestic;
20130 Name : Interfaces.C.Strings.chars_ptr) is abstract;
20132 use Class_Domestic;
20134 package Class_Animal is
20135 type Animal is tagged limited record
20136 Age_Count : aliased int;
20138 pragma Import (CPP, Animal);
20140 procedure Set_Age (this : access Animal; New_Age : int);
20141 pragma Import (CPP, Set_Age, "_ZN6Animal7Set_AgeEi");
20145 package Class_Dog is
20146 type Dog is new Animal and Carnivore and Domestic with record
20147 Tooth_Count : aliased int;
20148 Owner : Interfaces.C.Strings.chars_ptr;
20150 pragma Import (CPP, Dog);
20152 function Number_Of_Teeth (this : access Dog) return int;
20153 pragma Import (CPP, Number_Of_Teeth, "_ZN3Dog15Number_Of_TeethEv");
20155 procedure Set_Owner
20156 (this : access Dog; Name : Interfaces.C.Strings.chars_ptr);
20157 pragma Import (CPP, Set_Owner, "_ZN3Dog9Set_OwnerEPc");
20159 function New_Dog return Dog;
20160 pragma CPP_Constructor (New_Dog);
20161 pragma Import (CPP, New_Dog, "_ZN3DogC1Ev");
20172 @item -fdump-ada-spec
20173 @cindex @option{-fdump-ada-spec} (@command{gcc})
20174 Generate Ada spec files for the given header files transitively (including
20175 all header files that these headers depend upon).
20177 @item -fdump-ada-spec-slim
20178 @cindex @option{-fdump-ada-spec-slim} (@command{gcc})
20179 Generate Ada spec files for the header files specified on the command line
20182 @item -fada-spec-parent=@var{unit}
20183 @cindex -fada-spec-parent (@command{gcc})
20184 Specifies that all files generated by @option{-fdump-ada-spec*} are
20185 to be child units of the specified parent unit.
20188 @cindex @option{-C} (@command{gcc})
20189 Extract comments from headers and generate Ada comments in the Ada spec files.
20192 @node Other Utility Programs
20193 @chapter Other Utility Programs
20196 This chapter discusses some other utility programs available in the Ada
20200 * Using Other Utility Programs with GNAT::
20201 * The External Symbol Naming Scheme of GNAT::
20202 * Converting Ada Files to html with gnathtml::
20203 * Installing gnathtml::
20210 @node Using Other Utility Programs with GNAT
20211 @section Using Other Utility Programs with GNAT
20214 The object files generated by GNAT are in standard system format and in
20215 particular the debugging information uses this format. This means
20216 programs generated by GNAT can be used with existing utilities that
20217 depend on these formats.
20220 In general, any utility program that works with C will also often work with
20221 Ada programs generated by GNAT. This includes software utilities such as
20222 gprof (a profiling program), @code{gdb} (the FSF debugger), and utilities such
20226 @node The External Symbol Naming Scheme of GNAT
20227 @section The External Symbol Naming Scheme of GNAT
20230 In order to interpret the output from GNAT, when using tools that are
20231 originally intended for use with other languages, it is useful to
20232 understand the conventions used to generate link names from the Ada
20235 All link names are in all lowercase letters. With the exception of library
20236 procedure names, the mechanism used is simply to use the full expanded
20237 Ada name with dots replaced by double underscores. For example, suppose
20238 we have the following package spec:
20240 @smallexample @c ada
20251 The variable @code{MN} has a full expanded Ada name of @code{QRS.MN}, so
20252 the corresponding link name is @code{qrs__mn}.
20254 Of course if a @code{pragma Export} is used this may be overridden:
20256 @smallexample @c ada
20261 pragma Export (Var1, C, External_Name => "var1_name");
20263 pragma Export (Var2, C, Link_Name => "var2_link_name");
20270 In this case, the link name for @var{Var1} is whatever link name the
20271 C compiler would assign for the C function @var{var1_name}. This typically
20272 would be either @var{var1_name} or @var{_var1_name}, depending on operating
20273 system conventions, but other possibilities exist. The link name for
20274 @var{Var2} is @var{var2_link_name}, and this is not operating system
20278 One exception occurs for library level procedures. A potential ambiguity
20279 arises between the required name @code{_main} for the C main program,
20280 and the name we would otherwise assign to an Ada library level procedure
20281 called @code{Main} (which might well not be the main program).
20283 To avoid this ambiguity, we attach the prefix @code{_ada_} to such
20284 names. So if we have a library level procedure such as
20286 @smallexample @c ada
20289 procedure Hello (S : String);
20295 the external name of this procedure will be @var{_ada_hello}.
20298 @node Converting Ada Files to html with gnathtml
20299 @section Converting Ada Files to HTML with @code{gnathtml}
20302 This @code{Perl} script allows Ada source files to be browsed using
20303 standard Web browsers. For installation procedure, see the section
20304 @xref{Installing gnathtml}.
20306 Ada reserved keywords are highlighted in a bold font and Ada comments in
20307 a blue font. Unless your program was compiled with the gcc @option{-gnatx}
20308 switch to suppress the generation of cross-referencing information, user
20309 defined variables and types will appear in a different color; you will
20310 be able to click on any identifier and go to its declaration.
20312 The command line is as follow:
20314 @c $ perl gnathtml.pl @ovar{^switches^options^} @var{ada-files}
20315 @c Expanding @ovar macro inline (explanation in macro def comments)
20316 $ perl gnathtml.pl @r{[}@var{^switches^options^}@r{]} @var{ada-files}
20320 You can pass it as many Ada files as you want. @code{gnathtml} will generate
20321 an html file for every ada file, and a global file called @file{index.htm}.
20322 This file is an index of every identifier defined in the files.
20324 The available ^switches^options^ are the following ones:
20328 @cindex @option{-83} (@code{gnathtml})
20329 Only the Ada 83 subset of keywords will be highlighted.
20331 @item -cc @var{color}
20332 @cindex @option{-cc} (@code{gnathtml})
20333 This option allows you to change the color used for comments. The default
20334 value is green. The color argument can be any name accepted by html.
20337 @cindex @option{-d} (@code{gnathtml})
20338 If the Ada files depend on some other files (for instance through
20339 @code{with} clauses, the latter files will also be converted to html.
20340 Only the files in the user project will be converted to html, not the files
20341 in the run-time library itself.
20344 @cindex @option{-D} (@code{gnathtml})
20345 This command is the same as @option{-d} above, but @command{gnathtml} will
20346 also look for files in the run-time library, and generate html files for them.
20348 @item -ext @var{extension}
20349 @cindex @option{-ext} (@code{gnathtml})
20350 This option allows you to change the extension of the generated HTML files.
20351 If you do not specify an extension, it will default to @file{htm}.
20354 @cindex @option{-f} (@code{gnathtml})
20355 By default, gnathtml will generate html links only for global entities
20356 ('with'ed units, global variables and types,@dots{}). If you specify
20357 @option{-f} on the command line, then links will be generated for local
20360 @item -l @var{number}
20361 @cindex @option{-l} (@code{gnathtml})
20362 If this ^switch^option^ is provided and @var{number} is not 0, then
20363 @code{gnathtml} will number the html files every @var{number} line.
20366 @cindex @option{-I} (@code{gnathtml})
20367 Specify a directory to search for library files (@file{.ALI} files) and
20368 source files. You can provide several -I switches on the command line,
20369 and the directories will be parsed in the order of the command line.
20372 @cindex @option{-o} (@code{gnathtml})
20373 Specify the output directory for html files. By default, gnathtml will
20374 saved the generated html files in a subdirectory named @file{html/}.
20376 @item -p @var{file}
20377 @cindex @option{-p} (@code{gnathtml})
20378 If you are using Emacs and the most recent Emacs Ada mode, which provides
20379 a full Integrated Development Environment for compiling, checking,
20380 running and debugging applications, you may use @file{.gpr} files
20381 to give the directories where Emacs can find sources and object files.
20383 Using this ^switch^option^, you can tell gnathtml to use these files.
20384 This allows you to get an html version of your application, even if it
20385 is spread over multiple directories.
20387 @item -sc @var{color}
20388 @cindex @option{-sc} (@code{gnathtml})
20389 This ^switch^option^ allows you to change the color used for symbol
20391 The default value is red. The color argument can be any name accepted by html.
20393 @item -t @var{file}
20394 @cindex @option{-t} (@code{gnathtml})
20395 This ^switch^option^ provides the name of a file. This file contains a list of
20396 file names to be converted, and the effect is exactly as though they had
20397 appeared explicitly on the command line. This
20398 is the recommended way to work around the command line length limit on some
20403 @node Installing gnathtml
20404 @section Installing @code{gnathtml}
20407 @code{Perl} needs to be installed on your machine to run this script.
20408 @code{Perl} is freely available for almost every architecture and
20409 Operating System via the Internet.
20411 On Unix systems, you may want to modify the first line of the script
20412 @code{gnathtml}, to explicitly tell the Operating system where Perl
20413 is. The syntax of this line is:
20415 #!full_path_name_to_perl
20419 Alternatively, you may run the script using the following command line:
20422 @c $ perl gnathtml.pl @ovar{switches} @var{files}
20423 @c Expanding @ovar macro inline (explanation in macro def comments)
20424 $ perl gnathtml.pl @r{[}@var{switches}@r{]} @var{files}
20433 The GNAT distribution provides an Ada 95 template for the HP Language
20434 Sensitive Editor (LSE), a component of DECset. In order to
20435 access it, invoke LSE with the qualifier /ENVIRONMENT=GNU:[LIB]ADA95.ENV.
20442 GNAT supports The HP Performance Coverage Analyzer (PCA), a component
20443 of DECset. To use it proceed as outlined under ``HELP PCA'', except for running
20444 the collection phase with the /DEBUG qualifier.
20447 $ GNAT MAKE /DEBUG <PROGRAM_NAME>
20448 $ DEFINE LIB$DEBUG PCA$COLLECTOR
20449 $ RUN/DEBUG <PROGRAM_NAME>
20455 @c ******************************
20456 @node Code Coverage and Profiling
20457 @chapter Code Coverage and Profiling
20458 @cindex Code Coverage
20462 This chapter describes how to use @code{gcov} - coverage testing tool - and
20463 @code{gprof} - profiler tool - on your Ada programs.
20466 * Code Coverage of Ada Programs with gcov::
20467 * Profiling an Ada Program with gprof::
20470 @node Code Coverage of Ada Programs with gcov
20471 @section Code Coverage of Ada Programs with gcov
20473 @cindex -fprofile-arcs
20474 @cindex -ftest-coverage
20476 @cindex Code Coverage
20479 @code{gcov} is a test coverage program: it analyzes the execution of a given
20480 program on selected tests, to help you determine the portions of the program
20481 that are still untested.
20483 @code{gcov} is part of the GCC suite, and is described in detail in the GCC
20484 User's Guide. You can refer to this documentation for a more complete
20487 This chapter provides a quick startup guide, and
20488 details some Gnat-specific features.
20491 * Quick startup guide::
20495 @node Quick startup guide
20496 @subsection Quick startup guide
20498 In order to perform coverage analysis of a program using @code{gcov}, 3
20503 Code instrumentation during the compilation process
20505 Execution of the instrumented program
20507 Execution of the @code{gcov} tool to generate the result.
20510 The code instrumentation needed by gcov is created at the object level:
20511 The source code is not modified in any way, because the instrumentation code is
20512 inserted by gcc during the compilation process. To compile your code with code
20513 coverage activated, you need to recompile your whole project using the
20515 @code{-fprofile-arcs} and @code{-ftest-coverage}, and link it using
20516 @code{-fprofile-arcs}.
20519 $ gnatmake -P my_project.gpr -f -cargs -fprofile-arcs -ftest-coverage \
20520 -largs -fprofile-arcs
20523 This compilation process will create @file{.gcno} files together with
20524 the usual object files.
20526 Once the program is compiled with coverage instrumentation, you can
20527 run it as many times as needed - on portions of a test suite for
20528 example. The first execution will produce @file{.gcda} files at the
20529 same location as the @file{.gcno} files. The following executions
20530 will update those files, so that a cumulative result of the covered
20531 portions of the program is generated.
20533 Finally, you need to call the @code{gcov} tool. The different options of
20534 @code{gcov} are available in the GCC User's Guide, section 'Invoking gcov'.
20536 This will create annotated source files with a @file{.gcov} extension:
20537 @file{my_main.adb} file will be analysed in @file{my_main.adb.gcov}.
20539 @node Gnat specifics
20540 @subsection Gnat specifics
20542 Because Ada semantics, portions of the source code may be shared among
20543 several object files. This is the case for example when generics are
20544 involved, when inlining is active or when declarations generate initialisation
20545 calls. In order to take
20546 into account this shared code, you need to call @code{gcov} on all
20547 source files of the tested program at once.
20549 The list of source files might exceed the system's maximum command line
20550 length. In order to bypass this limitation, a new mechanism has been
20551 implemented in @code{gcov}: you can now list all your project's files into a
20552 text file, and provide this file to gcov as a parameter, preceded by a @@
20553 (e.g. @samp{gcov @@mysrclist.txt}).
20555 Note that on AIX compiling a static library with @code{-fprofile-arcs} is
20556 not supported as there can be unresolved symbols during the final link.
20558 @node Profiling an Ada Program with gprof
20559 @section Profiling an Ada Program with gprof
20565 This section is not meant to be an exhaustive documentation of @code{gprof}.
20566 Full documentation for it can be found in the GNU Profiler User's Guide
20567 documentation that is part of this GNAT distribution.
20569 Profiling a program helps determine the parts of a program that are executed
20570 most often, and are therefore the most time-consuming.
20572 @code{gprof} is the standard GNU profiling tool; it has been enhanced to
20573 better handle Ada programs and multitasking.
20574 It is currently supported on the following platforms
20579 solaris sparc/sparc64/x86
20585 In order to profile a program using @code{gprof}, 3 steps are needed:
20589 Code instrumentation, requiring a full recompilation of the project with the
20592 Execution of the program under the analysis conditions, i.e. with the desired
20595 Analysis of the results using the @code{gprof} tool.
20599 The following sections detail the different steps, and indicate how
20600 to interpret the results:
20602 * Compilation for profiling::
20603 * Program execution::
20605 * Interpretation of profiling results::
20608 @node Compilation for profiling
20609 @subsection Compilation for profiling
20613 In order to profile a program the first step is to tell the compiler
20614 to generate the necessary profiling information. The compiler switch to be used
20615 is @code{-pg}, which must be added to other compilation switches. This
20616 switch needs to be specified both during compilation and link stages, and can
20617 be specified once when using gnatmake:
20620 gnatmake -f -pg -P my_project
20624 Note that only the objects that were compiled with the @samp{-pg} switch will
20625 be profiled; if you need to profile your whole project, use the @samp{-f}
20626 gnatmake switch to force full recompilation.
20628 @node Program execution
20629 @subsection Program execution
20632 Once the program has been compiled for profiling, you can run it as usual.
20634 The only constraint imposed by profiling is that the program must terminate
20635 normally. An interrupted program (via a Ctrl-C, kill, etc.) will not be
20638 Once the program completes execution, a data file called @file{gmon.out} is
20639 generated in the directory where the program was launched from. If this file
20640 already exists, it will be overwritten.
20642 @node Running gprof
20643 @subsection Running gprof
20646 The @code{gprof} tool is called as follow:
20649 gprof my_prog gmon.out
20660 The complete form of the gprof command line is the following:
20663 gprof [^switches^options^] [executable [data-file]]
20667 @code{gprof} supports numerous ^switch^options^. The order of these
20668 ^switch^options^ does not matter. The full list of options can be found in
20669 the GNU Profiler User's Guide documentation that comes with this documentation.
20671 The following is the subset of those switches that is most relevant:
20675 @item --demangle[=@var{style}]
20676 @itemx --no-demangle
20677 @cindex @option{--demangle} (@code{gprof})
20678 These options control whether symbol names should be demangled when
20679 printing output. The default is to demangle C++ symbols. The
20680 @code{--no-demangle} option may be used to turn off demangling. Different
20681 compilers have different mangling styles. The optional demangling style
20682 argument can be used to choose an appropriate demangling style for your
20683 compiler, in particular Ada symbols generated by GNAT can be demangled using
20684 @code{--demangle=gnat}.
20686 @item -e @var{function_name}
20687 @cindex @option{-e} (@code{gprof})
20688 The @samp{-e @var{function}} option tells @code{gprof} not to print
20689 information about the function @var{function_name} (and its
20690 children@dots{}) in the call graph. The function will still be listed
20691 as a child of any functions that call it, but its index number will be
20692 shown as @samp{[not printed]}. More than one @samp{-e} option may be
20693 given; only one @var{function_name} may be indicated with each @samp{-e}
20696 @item -E @var{function_name}
20697 @cindex @option{-E} (@code{gprof})
20698 The @code{-E @var{function}} option works like the @code{-e} option, but
20699 execution time spent in the function (and children who were not called from
20700 anywhere else), will not be used to compute the percentages-of-time for
20701 the call graph. More than one @samp{-E} option may be given; only one
20702 @var{function_name} may be indicated with each @samp{-E} option.
20704 @item -f @var{function_name}
20705 @cindex @option{-f} (@code{gprof})
20706 The @samp{-f @var{function}} option causes @code{gprof} to limit the
20707 call graph to the function @var{function_name} and its children (and
20708 their children@dots{}). More than one @samp{-f} option may be given;
20709 only one @var{function_name} may be indicated with each @samp{-f}
20712 @item -F @var{function_name}
20713 @cindex @option{-F} (@code{gprof})
20714 The @samp{-F @var{function}} option works like the @code{-f} option, but
20715 only time spent in the function and its children (and their
20716 children@dots{}) will be used to determine total-time and
20717 percentages-of-time for the call graph. More than one @samp{-F} option
20718 may be given; only one @var{function_name} may be indicated with each
20719 @samp{-F} option. The @samp{-F} option overrides the @samp{-E} option.
20723 @node Interpretation of profiling results
20724 @subsection Interpretation of profiling results
20728 The results of the profiling analysis are represented by two arrays: the
20729 'flat profile' and the 'call graph'. Full documentation of those outputs
20730 can be found in the GNU Profiler User's Guide.
20732 The flat profile shows the time spent in each function of the program, and how
20733 many time it has been called. This allows you to locate easily the most
20734 time-consuming functions.
20736 The call graph shows, for each subprogram, the subprograms that call it,
20737 and the subprograms that it calls. It also provides an estimate of the time
20738 spent in each of those callers/called subprograms.
20741 @c ******************************
20742 @node Running and Debugging Ada Programs
20743 @chapter Running and Debugging Ada Programs
20747 This chapter discusses how to debug Ada programs.
20749 It applies to GNAT on the Alpha OpenVMS platform;
20750 for I64 OpenVMS please refer to the @cite{OpenVMS Debugger Manual},
20751 since HP has implemented Ada support in the OpenVMS debugger on I64.
20754 An incorrect Ada program may be handled in three ways by the GNAT compiler:
20758 The illegality may be a violation of the static semantics of Ada. In
20759 that case GNAT diagnoses the constructs in the program that are illegal.
20760 It is then a straightforward matter for the user to modify those parts of
20764 The illegality may be a violation of the dynamic semantics of Ada. In
20765 that case the program compiles and executes, but may generate incorrect
20766 results, or may terminate abnormally with some exception.
20769 When presented with a program that contains convoluted errors, GNAT
20770 itself may terminate abnormally without providing full diagnostics on
20771 the incorrect user program.
20775 * The GNAT Debugger GDB::
20777 * Introduction to GDB Commands::
20778 * Using Ada Expressions::
20779 * Calling User-Defined Subprograms::
20780 * Using the Next Command in a Function::
20783 * Debugging Generic Units::
20784 * Remote Debugging with gdbserver::
20785 * GNAT Abnormal Termination or Failure to Terminate::
20786 * Naming Conventions for GNAT Source Files::
20787 * Getting Internal Debugging Information::
20788 * Stack Traceback::
20794 @node The GNAT Debugger GDB
20795 @section The GNAT Debugger GDB
20798 @code{GDB} is a general purpose, platform-independent debugger that
20799 can be used to debug mixed-language programs compiled with @command{gcc},
20800 and in particular is capable of debugging Ada programs compiled with
20801 GNAT. The latest versions of @code{GDB} are Ada-aware and can handle
20802 complex Ada data structures.
20804 @xref{Top,, Debugging with GDB, gdb, Debugging with GDB},
20806 located in the GNU:[DOCS] directory,
20808 for full details on the usage of @code{GDB}, including a section on
20809 its usage on programs. This manual should be consulted for full
20810 details. The section that follows is a brief introduction to the
20811 philosophy and use of @code{GDB}.
20813 When GNAT programs are compiled, the compiler optionally writes debugging
20814 information into the generated object file, including information on
20815 line numbers, and on declared types and variables. This information is
20816 separate from the generated code. It makes the object files considerably
20817 larger, but it does not add to the size of the actual executable that
20818 will be loaded into memory, and has no impact on run-time performance. The
20819 generation of debug information is triggered by the use of the
20820 ^-g^/DEBUG^ switch in the @command{gcc} or @command{gnatmake} command
20821 used to carry out the compilations. It is important to emphasize that
20822 the use of these options does not change the generated code.
20824 The debugging information is written in standard system formats that
20825 are used by many tools, including debuggers and profilers. The format
20826 of the information is typically designed to describe C types and
20827 semantics, but GNAT implements a translation scheme which allows full
20828 details about Ada types and variables to be encoded into these
20829 standard C formats. Details of this encoding scheme may be found in
20830 the file exp_dbug.ads in the GNAT source distribution. However, the
20831 details of this encoding are, in general, of no interest to a user,
20832 since @code{GDB} automatically performs the necessary decoding.
20834 When a program is bound and linked, the debugging information is
20835 collected from the object files, and stored in the executable image of
20836 the program. Again, this process significantly increases the size of
20837 the generated executable file, but it does not increase the size of
20838 the executable program itself. Furthermore, if this program is run in
20839 the normal manner, it runs exactly as if the debug information were
20840 not present, and takes no more actual memory.
20842 However, if the program is run under control of @code{GDB}, the
20843 debugger is activated. The image of the program is loaded, at which
20844 point it is ready to run. If a run command is given, then the program
20845 will run exactly as it would have if @code{GDB} were not present. This
20846 is a crucial part of the @code{GDB} design philosophy. @code{GDB} is
20847 entirely non-intrusive until a breakpoint is encountered. If no
20848 breakpoint is ever hit, the program will run exactly as it would if no
20849 debugger were present. When a breakpoint is hit, @code{GDB} accesses
20850 the debugging information and can respond to user commands to inspect
20851 variables, and more generally to report on the state of execution.
20855 @section Running GDB
20858 This section describes how to initiate the debugger.
20859 @c The above sentence is really just filler, but it was otherwise
20860 @c clumsy to get the first paragraph nonindented given the conditional
20861 @c nature of the description
20864 The debugger can be launched from a @code{GPS} menu or
20865 directly from the command line. The description below covers the latter use.
20866 All the commands shown can be used in the @code{GPS} debug console window,
20867 but there are usually more GUI-based ways to achieve the same effect.
20870 The command to run @code{GDB} is
20873 $ ^gdb program^GDB PROGRAM^
20877 where @code{^program^PROGRAM^} is the name of the executable file. This
20878 activates the debugger and results in a prompt for debugger commands.
20879 The simplest command is simply @code{run}, which causes the program to run
20880 exactly as if the debugger were not present. The following section
20881 describes some of the additional commands that can be given to @code{GDB}.
20883 @c *******************************
20884 @node Introduction to GDB Commands
20885 @section Introduction to GDB Commands
20888 @code{GDB} contains a large repertoire of commands. @xref{Top,,
20889 Debugging with GDB, gdb, Debugging with GDB},
20891 located in the GNU:[DOCS] directory,
20893 for extensive documentation on the use
20894 of these commands, together with examples of their use. Furthermore,
20895 the command @command{help} invoked from within GDB activates a simple help
20896 facility which summarizes the available commands and their options.
20897 In this section we summarize a few of the most commonly
20898 used commands to give an idea of what @code{GDB} is about. You should create
20899 a simple program with debugging information and experiment with the use of
20900 these @code{GDB} commands on the program as you read through the
20904 @item set args @var{arguments}
20905 The @var{arguments} list above is a list of arguments to be passed to
20906 the program on a subsequent run command, just as though the arguments
20907 had been entered on a normal invocation of the program. The @code{set args}
20908 command is not needed if the program does not require arguments.
20911 The @code{run} command causes execution of the program to start from
20912 the beginning. If the program is already running, that is to say if
20913 you are currently positioned at a breakpoint, then a prompt will ask
20914 for confirmation that you want to abandon the current execution and
20917 @item breakpoint @var{location}
20918 The breakpoint command sets a breakpoint, that is to say a point at which
20919 execution will halt and @code{GDB} will await further
20920 commands. @var{location} is
20921 either a line number within a file, given in the format @code{file:linenumber},
20922 or it is the name of a subprogram. If you request that a breakpoint be set on
20923 a subprogram that is overloaded, a prompt will ask you to specify on which of
20924 those subprograms you want to breakpoint. You can also
20925 specify that all of them should be breakpointed. If the program is run
20926 and execution encounters the breakpoint, then the program
20927 stops and @code{GDB} signals that the breakpoint was encountered by
20928 printing the line of code before which the program is halted.
20930 @item catch exception @var{name}
20931 This command causes the program execution to stop whenever exception
20932 @var{name} is raised. If @var{name} is omitted, then the execution is
20933 suspended when any exception is raised.
20935 @item print @var{expression}
20936 This will print the value of the given expression. Most simple
20937 Ada expression formats are properly handled by @code{GDB}, so the expression
20938 can contain function calls, variables, operators, and attribute references.
20941 Continues execution following a breakpoint, until the next breakpoint or the
20942 termination of the program.
20945 Executes a single line after a breakpoint. If the next statement
20946 is a subprogram call, execution continues into (the first statement of)
20947 the called subprogram.
20950 Executes a single line. If this line is a subprogram call, executes and
20951 returns from the call.
20954 Lists a few lines around the current source location. In practice, it
20955 is usually more convenient to have a separate edit window open with the
20956 relevant source file displayed. Successive applications of this command
20957 print subsequent lines. The command can be given an argument which is a
20958 line number, in which case it displays a few lines around the specified one.
20961 Displays a backtrace of the call chain. This command is typically
20962 used after a breakpoint has occurred, to examine the sequence of calls that
20963 leads to the current breakpoint. The display includes one line for each
20964 activation record (frame) corresponding to an active subprogram.
20967 At a breakpoint, @code{GDB} can display the values of variables local
20968 to the current frame. The command @code{up} can be used to
20969 examine the contents of other active frames, by moving the focus up
20970 the stack, that is to say from callee to caller, one frame at a time.
20973 Moves the focus of @code{GDB} down from the frame currently being
20974 examined to the frame of its callee (the reverse of the previous command),
20976 @item frame @var{n}
20977 Inspect the frame with the given number. The value 0 denotes the frame
20978 of the current breakpoint, that is to say the top of the call stack.
20983 The above list is a very short introduction to the commands that
20984 @code{GDB} provides. Important additional capabilities, including conditional
20985 breakpoints, the ability to execute command sequences on a breakpoint,
20986 the ability to debug at the machine instruction level and many other
20987 features are described in detail in @ref{Top,, Debugging with GDB, gdb,
20988 Debugging with GDB}. Note that most commands can be abbreviated
20989 (for example, c for continue, bt for backtrace).
20991 @node Using Ada Expressions
20992 @section Using Ada Expressions
20993 @cindex Ada expressions
20996 @code{GDB} supports a fairly large subset of Ada expression syntax, with some
20997 extensions. The philosophy behind the design of this subset is
21001 That @code{GDB} should provide basic literals and access to operations for
21002 arithmetic, dereferencing, field selection, indexing, and subprogram calls,
21003 leaving more sophisticated computations to subprograms written into the
21004 program (which therefore may be called from @code{GDB}).
21007 That type safety and strict adherence to Ada language restrictions
21008 are not particularly important to the @code{GDB} user.
21011 That brevity is important to the @code{GDB} user.
21015 Thus, for brevity, the debugger acts as if there were
21016 implicit @code{with} and @code{use} clauses in effect for all user-written
21017 packages, thus making it unnecessary to fully qualify most names with
21018 their packages, regardless of context. Where this causes ambiguity,
21019 @code{GDB} asks the user's intent.
21021 For details on the supported Ada syntax, see @ref{Top,, Debugging with
21022 GDB, gdb, Debugging with GDB}.
21024 @node Calling User-Defined Subprograms
21025 @section Calling User-Defined Subprograms
21028 An important capability of @code{GDB} is the ability to call user-defined
21029 subprograms while debugging. This is achieved simply by entering
21030 a subprogram call statement in the form:
21033 call subprogram-name (parameters)
21037 The keyword @code{call} can be omitted in the normal case where the
21038 @code{subprogram-name} does not coincide with any of the predefined
21039 @code{GDB} commands.
21041 The effect is to invoke the given subprogram, passing it the
21042 list of parameters that is supplied. The parameters can be expressions and
21043 can include variables from the program being debugged. The
21044 subprogram must be defined
21045 at the library level within your program, and @code{GDB} will call the
21046 subprogram within the environment of your program execution (which
21047 means that the subprogram is free to access or even modify variables
21048 within your program).
21050 The most important use of this facility is in allowing the inclusion of
21051 debugging routines that are tailored to particular data structures
21052 in your program. Such debugging routines can be written to provide a suitably
21053 high-level description of an abstract type, rather than a low-level dump
21054 of its physical layout. After all, the standard
21055 @code{GDB print} command only knows the physical layout of your
21056 types, not their abstract meaning. Debugging routines can provide information
21057 at the desired semantic level and are thus enormously useful.
21059 For example, when debugging GNAT itself, it is crucial to have access to
21060 the contents of the tree nodes used to represent the program internally.
21061 But tree nodes are represented simply by an integer value (which in turn
21062 is an index into a table of nodes).
21063 Using the @code{print} command on a tree node would simply print this integer
21064 value, which is not very useful. But the PN routine (defined in file
21065 treepr.adb in the GNAT sources) takes a tree node as input, and displays
21066 a useful high level representation of the tree node, which includes the
21067 syntactic category of the node, its position in the source, the integers
21068 that denote descendant nodes and parent node, as well as varied
21069 semantic information. To study this example in more detail, you might want to
21070 look at the body of the PN procedure in the stated file.
21072 @node Using the Next Command in a Function
21073 @section Using the Next Command in a Function
21076 When you use the @code{next} command in a function, the current source
21077 location will advance to the next statement as usual. A special case
21078 arises in the case of a @code{return} statement.
21080 Part of the code for a return statement is the ``epilog'' of the function.
21081 This is the code that returns to the caller. There is only one copy of
21082 this epilog code, and it is typically associated with the last return
21083 statement in the function if there is more than one return. In some
21084 implementations, this epilog is associated with the first statement
21087 The result is that if you use the @code{next} command from a return
21088 statement that is not the last return statement of the function you
21089 may see a strange apparent jump to the last return statement or to
21090 the start of the function. You should simply ignore this odd jump.
21091 The value returned is always that from the first return statement
21092 that was stepped through.
21094 @node Ada Exceptions
21095 @section Stopping when Ada Exceptions are Raised
21099 You can set catchpoints that stop the program execution when your program
21100 raises selected exceptions.
21103 @item catch exception
21104 Set a catchpoint that stops execution whenever (any task in the) program
21105 raises any exception.
21107 @item catch exception @var{name}
21108 Set a catchpoint that stops execution whenever (any task in the) program
21109 raises the exception @var{name}.
21111 @item catch exception unhandled
21112 Set a catchpoint that stops executing whenever (any task in the) program
21113 raises an exception for which there is no handler.
21115 @item info exceptions
21116 @itemx info exceptions @var{regexp}
21117 The @code{info exceptions} command permits the user to examine all defined
21118 exceptions within Ada programs. With a regular expression, @var{regexp}, as
21119 argument, prints out only those exceptions whose name matches @var{regexp}.
21127 @code{GDB} allows the following task-related commands:
21131 This command shows a list of current Ada tasks, as in the following example:
21138 ID TID P-ID Thread Pri State Name
21139 1 8088000 0 807e000 15 Child Activation Wait main_task
21140 2 80a4000 1 80ae000 15 Accept/Select Wait b
21141 3 809a800 1 80a4800 15 Child Activation Wait a
21142 * 4 80ae800 3 80b8000 15 Running c
21146 In this listing, the asterisk before the first task indicates it to be the
21147 currently running task. The first column lists the task ID that is used
21148 to refer to tasks in the following commands.
21150 @item break @var{linespec} task @var{taskid}
21151 @itemx break @var{linespec} task @var{taskid} if @dots{}
21152 @cindex Breakpoints and tasks
21153 These commands are like the @code{break @dots{} thread @dots{}}.
21154 @var{linespec} specifies source lines.
21156 Use the qualifier @samp{task @var{taskid}} with a breakpoint command
21157 to specify that you only want @code{GDB} to stop the program when a
21158 particular Ada task reaches this breakpoint. @var{taskid} is one of the
21159 numeric task identifiers assigned by @code{GDB}, shown in the first
21160 column of the @samp{info tasks} display.
21162 If you do not specify @samp{task @var{taskid}} when you set a
21163 breakpoint, the breakpoint applies to @emph{all} tasks of your
21166 You can use the @code{task} qualifier on conditional breakpoints as
21167 well; in this case, place @samp{task @var{taskid}} before the
21168 breakpoint condition (before the @code{if}).
21170 @item task @var{taskno}
21171 @cindex Task switching
21173 This command allows to switch to the task referred by @var{taskno}. In
21174 particular, This allows to browse the backtrace of the specified
21175 task. It is advised to switch back to the original task before
21176 continuing execution otherwise the scheduling of the program may be
21181 For more detailed information on the tasking support,
21182 see @ref{Top,, Debugging with GDB, gdb, Debugging with GDB}.
21184 @node Debugging Generic Units
21185 @section Debugging Generic Units
21186 @cindex Debugging Generic Units
21190 GNAT always uses code expansion for generic instantiation. This means that
21191 each time an instantiation occurs, a complete copy of the original code is
21192 made, with appropriate substitutions of formals by actuals.
21194 It is not possible to refer to the original generic entities in
21195 @code{GDB}, but it is always possible to debug a particular instance of
21196 a generic, by using the appropriate expanded names. For example, if we have
21198 @smallexample @c ada
21203 generic package k is
21204 procedure kp (v1 : in out integer);
21208 procedure kp (v1 : in out integer) is
21214 package k1 is new k;
21215 package k2 is new k;
21217 var : integer := 1;
21230 Then to break on a call to procedure kp in the k2 instance, simply
21234 (gdb) break g.k2.kp
21238 When the breakpoint occurs, you can step through the code of the
21239 instance in the normal manner and examine the values of local variables, as for
21242 @node Remote Debugging with gdbserver
21243 @section Remote Debugging with gdbserver
21244 @cindex Remote Debugging with gdbserver
21247 On platforms where gdbserver is supported, it is possible to use this tool
21248 to debug your application remotely. This can be useful in situations
21249 where the program needs to be run on a target host that is different
21250 from the host used for development, particularly when the target has
21251 a limited amount of resources (either CPU and/or memory).
21253 To do so, start your program using gdbserver on the target machine.
21254 gdbserver then automatically suspends the execution of your program
21255 at its entry point, waiting for a debugger to connect to it. The
21256 following commands starts an application and tells gdbserver to
21257 wait for a connection with the debugger on localhost port 4444.
21260 $ gdbserver localhost:4444 program
21261 Process program created; pid = 5685
21262 Listening on port 4444
21265 Once gdbserver has started listening, we can tell the debugger to establish
21266 a connection with this gdbserver, and then start the same debugging session
21267 as if the program was being debugged on the same host, directly under
21268 the control of GDB.
21272 (gdb) target remote targethost:4444
21273 Remote debugging using targethost:4444
21274 0x00007f29936d0af0 in ?? () from /lib64/ld-linux-x86-64.so.
21276 Breakpoint 1 at 0x401f0c: file foo.adb, line 3.
21280 Breakpoint 1, foo () at foo.adb:4
21284 It is also possible to use gdbserver to attach to an already running
21285 program, in which case the execution of that program is simply suspended
21286 until the connection between the debugger and gdbserver is established.
21288 For more information on how to use gdbserver, @ref{Top, Server, Using
21289 the gdbserver Program, gdb, Debugging with GDB}. @value{EDITION} provides support
21290 for gdbserver on x86-linux, x86-windows and x86_64-linux.
21292 @node GNAT Abnormal Termination or Failure to Terminate
21293 @section GNAT Abnormal Termination or Failure to Terminate
21294 @cindex GNAT Abnormal Termination or Failure to Terminate
21297 When presented with programs that contain serious errors in syntax
21299 GNAT may on rare occasions experience problems in operation, such
21301 segmentation fault or illegal memory access, raising an internal
21302 exception, terminating abnormally, or failing to terminate at all.
21303 In such cases, you can activate
21304 various features of GNAT that can help you pinpoint the construct in your
21305 program that is the likely source of the problem.
21307 The following strategies are presented in increasing order of
21308 difficulty, corresponding to your experience in using GNAT and your
21309 familiarity with compiler internals.
21313 Run @command{gcc} with the @option{-gnatf}. This first
21314 switch causes all errors on a given line to be reported. In its absence,
21315 only the first error on a line is displayed.
21317 The @option{-gnatdO} switch causes errors to be displayed as soon as they
21318 are encountered, rather than after compilation is terminated. If GNAT
21319 terminates prematurely or goes into an infinite loop, the last error
21320 message displayed may help to pinpoint the culprit.
21323 Run @command{gcc} with the @option{^-v (verbose)^/VERBOSE^} switch. In this
21324 mode, @command{gcc} produces ongoing information about the progress of the
21325 compilation and provides the name of each procedure as code is
21326 generated. This switch allows you to find which Ada procedure was being
21327 compiled when it encountered a code generation problem.
21330 @cindex @option{-gnatdc} switch
21331 Run @command{gcc} with the @option{-gnatdc} switch. This is a GNAT specific
21332 switch that does for the front-end what @option{^-v^VERBOSE^} does
21333 for the back end. The system prints the name of each unit,
21334 either a compilation unit or nested unit, as it is being analyzed.
21336 Finally, you can start
21337 @code{gdb} directly on the @code{gnat1} executable. @code{gnat1} is the
21338 front-end of GNAT, and can be run independently (normally it is just
21339 called from @command{gcc}). You can use @code{gdb} on @code{gnat1} as you
21340 would on a C program (but @pxref{The GNAT Debugger GDB} for caveats). The
21341 @code{where} command is the first line of attack; the variable
21342 @code{lineno} (seen by @code{print lineno}), used by the second phase of
21343 @code{gnat1} and by the @command{gcc} backend, indicates the source line at
21344 which the execution stopped, and @code{input_file name} indicates the name of
21348 @node Naming Conventions for GNAT Source Files
21349 @section Naming Conventions for GNAT Source Files
21352 In order to examine the workings of the GNAT system, the following
21353 brief description of its organization may be helpful:
21357 Files with prefix @file{^sc^SC^} contain the lexical scanner.
21360 All files prefixed with @file{^par^PAR^} are components of the parser. The
21361 numbers correspond to chapters of the Ada Reference Manual. For example,
21362 parsing of select statements can be found in @file{par-ch9.adb}.
21365 All files prefixed with @file{^sem^SEM^} perform semantic analysis. The
21366 numbers correspond to chapters of the Ada standard. For example, all
21367 issues involving context clauses can be found in @file{sem_ch10.adb}. In
21368 addition, some features of the language require sufficient special processing
21369 to justify their own semantic files: sem_aggr for aggregates, sem_disp for
21370 dynamic dispatching, etc.
21373 All files prefixed with @file{^exp^EXP^} perform normalization and
21374 expansion of the intermediate representation (abstract syntax tree, or AST).
21375 these files use the same numbering scheme as the parser and semantics files.
21376 For example, the construction of record initialization procedures is done in
21377 @file{exp_ch3.adb}.
21380 The files prefixed with @file{^bind^BIND^} implement the binder, which
21381 verifies the consistency of the compilation, determines an order of
21382 elaboration, and generates the bind file.
21385 The files @file{atree.ads} and @file{atree.adb} detail the low-level
21386 data structures used by the front-end.
21389 The files @file{sinfo.ads} and @file{sinfo.adb} detail the structure of
21390 the abstract syntax tree as produced by the parser.
21393 The files @file{einfo.ads} and @file{einfo.adb} detail the attributes of
21394 all entities, computed during semantic analysis.
21397 Library management issues are dealt with in files with prefix
21403 Ada files with the prefix @file{^a-^A-^} are children of @code{Ada}, as
21404 defined in Annex A.
21409 Files with prefix @file{^i-^I-^} are children of @code{Interfaces}, as
21410 defined in Annex B.
21414 Files with prefix @file{^s-^S-^} are children of @code{System}. This includes
21415 both language-defined children and GNAT run-time routines.
21419 Files with prefix @file{^g-^G-^} are children of @code{GNAT}. These are useful
21420 general-purpose packages, fully documented in their specs. All
21421 the other @file{.c} files are modifications of common @command{gcc} files.
21424 @node Getting Internal Debugging Information
21425 @section Getting Internal Debugging Information
21428 Most compilers have internal debugging switches and modes. GNAT
21429 does also, except GNAT internal debugging switches and modes are not
21430 secret. A summary and full description of all the compiler and binder
21431 debug flags are in the file @file{debug.adb}. You must obtain the
21432 sources of the compiler to see the full detailed effects of these flags.
21434 The switches that print the source of the program (reconstructed from
21435 the internal tree) are of general interest for user programs, as are the
21437 the full internal tree, and the entity table (the symbol table
21438 information). The reconstructed source provides a readable version of the
21439 program after the front-end has completed analysis and expansion,
21440 and is useful when studying the performance of specific constructs.
21441 For example, constraint checks are indicated, complex aggregates
21442 are replaced with loops and assignments, and tasking primitives
21443 are replaced with run-time calls.
21445 @node Stack Traceback
21446 @section Stack Traceback
21448 @cindex stack traceback
21449 @cindex stack unwinding
21452 Traceback is a mechanism to display the sequence of subprogram calls that
21453 leads to a specified execution point in a program. Often (but not always)
21454 the execution point is an instruction at which an exception has been raised.
21455 This mechanism is also known as @i{stack unwinding} because it obtains
21456 its information by scanning the run-time stack and recovering the activation
21457 records of all active subprograms. Stack unwinding is one of the most
21458 important tools for program debugging.
21460 The first entry stored in traceback corresponds to the deepest calling level,
21461 that is to say the subprogram currently executing the instruction
21462 from which we want to obtain the traceback.
21464 Note that there is no runtime performance penalty when stack traceback
21465 is enabled, and no exception is raised during program execution.
21468 * Non-Symbolic Traceback::
21469 * Symbolic Traceback::
21472 @node Non-Symbolic Traceback
21473 @subsection Non-Symbolic Traceback
21474 @cindex traceback, non-symbolic
21477 Note: this feature is not supported on all platforms. See
21478 @file{GNAT.Traceback spec in g-traceb.ads} for a complete list of supported
21482 * Tracebacks From an Unhandled Exception::
21483 * Tracebacks From Exception Occurrences (non-symbolic)::
21484 * Tracebacks From Anywhere in a Program (non-symbolic)::
21487 @node Tracebacks From an Unhandled Exception
21488 @subsubsection Tracebacks From an Unhandled Exception
21491 A runtime non-symbolic traceback is a list of addresses of call instructions.
21492 To enable this feature you must use the @option{-E}
21493 @code{gnatbind}'s option. With this option a stack traceback is stored as part
21494 of exception information. You can retrieve this information using the
21495 @code{addr2line} tool.
21497 Here is a simple example:
21499 @smallexample @c ada
21505 raise Constraint_Error;
21520 $ gnatmake stb -bargs -E
21523 Execution terminated by unhandled exception
21524 Exception name: CONSTRAINT_ERROR
21526 Call stack traceback locations:
21527 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
21531 As we see the traceback lists a sequence of addresses for the unhandled
21532 exception @code{CONSTRAINT_ERROR} raised in procedure P1. It is easy to
21533 guess that this exception come from procedure P1. To translate these
21534 addresses into the source lines where the calls appear, the
21535 @code{addr2line} tool, described below, is invaluable. The use of this tool
21536 requires the program to be compiled with debug information.
21539 $ gnatmake -g stb -bargs -E
21542 Execution terminated by unhandled exception
21543 Exception name: CONSTRAINT_ERROR
21545 Call stack traceback locations:
21546 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
21548 $ addr2line --exe=stb 0x401373 0x40138b 0x40139c 0x401335 0x4011c4
21549 0x4011f1 0x77e892a4
21551 00401373 at d:/stb/stb.adb:5
21552 0040138B at d:/stb/stb.adb:10
21553 0040139C at d:/stb/stb.adb:14
21554 00401335 at d:/stb/b~stb.adb:104
21555 004011C4 at /build/@dots{}/crt1.c:200
21556 004011F1 at /build/@dots{}/crt1.c:222
21557 77E892A4 in ?? at ??:0
21561 The @code{addr2line} tool has several other useful options:
21565 to get the function name corresponding to any location
21567 @item --demangle=gnat
21568 to use the gnat decoding mode for the function names. Note that
21569 for binutils version 2.9.x the option is simply @option{--demangle}.
21573 $ addr2line --exe=stb --functions --demangle=gnat 0x401373 0x40138b
21574 0x40139c 0x401335 0x4011c4 0x4011f1
21576 00401373 in stb.p1 at d:/stb/stb.adb:5
21577 0040138B in stb.p2 at d:/stb/stb.adb:10
21578 0040139C in stb at d:/stb/stb.adb:14
21579 00401335 in main at d:/stb/b~stb.adb:104
21580 004011C4 in <__mingw_CRTStartup> at /build/@dots{}/crt1.c:200
21581 004011F1 in <mainCRTStartup> at /build/@dots{}/crt1.c:222
21585 From this traceback we can see that the exception was raised in
21586 @file{stb.adb} at line 5, which was reached from a procedure call in
21587 @file{stb.adb} at line 10, and so on. The @file{b~std.adb} is the binder file,
21588 which contains the call to the main program.
21589 @xref{Running gnatbind}. The remaining entries are assorted runtime routines,
21590 and the output will vary from platform to platform.
21592 It is also possible to use @code{GDB} with these traceback addresses to debug
21593 the program. For example, we can break at a given code location, as reported
21594 in the stack traceback:
21600 Furthermore, this feature is not implemented inside Windows DLL. Only
21601 the non-symbolic traceback is reported in this case.
21604 (gdb) break *0x401373
21605 Breakpoint 1 at 0x401373: file stb.adb, line 5.
21609 It is important to note that the stack traceback addresses
21610 do not change when debug information is included. This is particularly useful
21611 because it makes it possible to release software without debug information (to
21612 minimize object size), get a field report that includes a stack traceback
21613 whenever an internal bug occurs, and then be able to retrieve the sequence
21614 of calls with the same program compiled with debug information.
21616 @node Tracebacks From Exception Occurrences (non-symbolic)
21617 @subsubsection Tracebacks From Exception Occurrences
21620 Non-symbolic tracebacks are obtained by using the @option{-E} binder argument.
21621 The stack traceback is attached to the exception information string, and can
21622 be retrieved in an exception handler within the Ada program, by means of the
21623 Ada facilities defined in @code{Ada.Exceptions}. Here is a simple example:
21625 @smallexample @c ada
21627 with Ada.Exceptions;
21632 use Ada.Exceptions;
21640 Text_IO.Put_Line (Exception_Information (E));
21654 This program will output:
21659 Exception name: CONSTRAINT_ERROR
21660 Message: stb.adb:12
21661 Call stack traceback locations:
21662 0x4015e4 0x401633 0x401644 0x401461 0x4011c4 0x4011f1 0x77e892a4
21665 @node Tracebacks From Anywhere in a Program (non-symbolic)
21666 @subsubsection Tracebacks From Anywhere in a Program
21669 It is also possible to retrieve a stack traceback from anywhere in a
21670 program. For this you need to
21671 use the @code{GNAT.Traceback} API. This package includes a procedure called
21672 @code{Call_Chain} that computes a complete stack traceback, as well as useful
21673 display procedures described below. It is not necessary to use the
21674 @option{-E gnatbind} option in this case, because the stack traceback mechanism
21675 is invoked explicitly.
21678 In the following example we compute a traceback at a specific location in
21679 the program, and we display it using @code{GNAT.Debug_Utilities.Image} to
21680 convert addresses to strings:
21682 @smallexample @c ada
21684 with GNAT.Traceback;
21685 with GNAT.Debug_Utilities;
21691 use GNAT.Traceback;
21694 TB : Tracebacks_Array (1 .. 10);
21695 -- We are asking for a maximum of 10 stack frames.
21697 -- Len will receive the actual number of stack frames returned.
21699 Call_Chain (TB, Len);
21701 Text_IO.Put ("In STB.P1 : ");
21703 for K in 1 .. Len loop
21704 Text_IO.Put (Debug_Utilities.Image (TB (K)));
21725 In STB.P1 : 16#0040_F1E4# 16#0040_14F2# 16#0040_170B# 16#0040_171C#
21726 16#0040_1461# 16#0040_11C4# 16#0040_11F1# 16#77E8_92A4#
21730 You can then get further information by invoking the @code{addr2line}
21731 tool as described earlier (note that the hexadecimal addresses
21732 need to be specified in C format, with a leading ``0x'').
21734 @node Symbolic Traceback
21735 @subsection Symbolic Traceback
21736 @cindex traceback, symbolic
21739 A symbolic traceback is a stack traceback in which procedure names are
21740 associated with each code location.
21743 Note that this feature is not supported on all platforms. See
21744 @file{GNAT.Traceback.Symbolic spec in g-trasym.ads} for a complete
21745 list of currently supported platforms.
21748 Note that the symbolic traceback requires that the program be compiled
21749 with debug information. If it is not compiled with debug information
21750 only the non-symbolic information will be valid.
21753 * Tracebacks From Exception Occurrences (symbolic)::
21754 * Tracebacks From Anywhere in a Program (symbolic)::
21757 @node Tracebacks From Exception Occurrences (symbolic)
21758 @subsubsection Tracebacks From Exception Occurrences
21760 @smallexample @c ada
21762 with GNAT.Traceback.Symbolic;
21768 raise Constraint_Error;
21785 Ada.Text_IO.Put_Line (GNAT.Traceback.Symbolic.Symbolic_Traceback (E));
21790 $ gnatmake -g .\stb -bargs -E
21793 0040149F in stb.p1 at stb.adb:8
21794 004014B7 in stb.p2 at stb.adb:13
21795 004014CF in stb.p3 at stb.adb:18
21796 004015DD in ada.stb at stb.adb:22
21797 00401461 in main at b~stb.adb:168
21798 004011C4 in __mingw_CRTStartup at crt1.c:200
21799 004011F1 in mainCRTStartup at crt1.c:222
21800 77E892A4 in ?? at ??:0
21804 In the above example the ``.\'' syntax in the @command{gnatmake} command
21805 is currently required by @command{addr2line} for files that are in
21806 the current working directory.
21807 Moreover, the exact sequence of linker options may vary from platform
21809 The above @option{-largs} section is for Windows platforms. By contrast,
21810 under Unix there is no need for the @option{-largs} section.
21811 Differences across platforms are due to details of linker implementation.
21813 @node Tracebacks From Anywhere in a Program (symbolic)
21814 @subsubsection Tracebacks From Anywhere in a Program
21817 It is possible to get a symbolic stack traceback
21818 from anywhere in a program, just as for non-symbolic tracebacks.
21819 The first step is to obtain a non-symbolic
21820 traceback, and then call @code{Symbolic_Traceback} to compute the symbolic
21821 information. Here is an example:
21823 @smallexample @c ada
21825 with GNAT.Traceback;
21826 with GNAT.Traceback.Symbolic;
21831 use GNAT.Traceback;
21832 use GNAT.Traceback.Symbolic;
21835 TB : Tracebacks_Array (1 .. 10);
21836 -- We are asking for a maximum of 10 stack frames.
21838 -- Len will receive the actual number of stack frames returned.
21840 Call_Chain (TB, Len);
21841 Text_IO.Put_Line (Symbolic_Traceback (TB (1 .. Len)));
21854 @c ******************************
21856 @node Compatibility with HP Ada
21857 @chapter Compatibility with HP Ada
21858 @cindex Compatibility
21863 @cindex Compatibility between GNAT and HP Ada
21864 This chapter compares HP Ada (formerly known as ``DEC Ada'')
21865 for OpenVMS Alpha and GNAT for OpenVMS for Alpha and for I64.
21866 GNAT is highly compatible
21867 with HP Ada, and it should generally be straightforward to port code
21868 from the HP Ada environment to GNAT. However, there are a few language
21869 and implementation differences of which the user must be aware. These
21870 differences are discussed in this chapter. In
21871 addition, the operating environment and command structure for the
21872 compiler are different, and these differences are also discussed.
21874 For further details on these and other compatibility issues,
21875 see Appendix E of the HP publication
21876 @cite{HP Ada, Technical Overview and Comparison on HP Platforms}.
21878 Except where otherwise indicated, the description of GNAT for OpenVMS
21879 applies to both the Alpha and I64 platforms.
21881 For information on porting Ada code from GNAT on Alpha OpenVMS to GNAT on
21882 I64 OpenVMS, see @ref{Transitioning to 64-Bit GNAT for OpenVMS}.
21884 The discussion in this chapter addresses specifically the implementation
21885 of Ada 83 for HP OpenVMS Alpha Systems. In cases where the implementation
21886 of HP Ada differs between OpenVMS Alpha Systems and OpenVMS VAX Systems,
21887 GNAT always follows the Alpha implementation.
21889 For GNAT running on other than VMS systems, all the HP Ada 83 pragmas and
21890 attributes are recognized, although only a subset of them can sensibly
21891 be implemented. The description of pragmas in
21892 @xref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference Manual},
21893 indicates whether or not they are applicable to non-VMS systems.
21896 * Ada Language Compatibility::
21897 * Differences in the Definition of Package System::
21898 * Language-Related Features::
21899 * The Package STANDARD::
21900 * The Package SYSTEM::
21901 * Tasking and Task-Related Features::
21902 * Pragmas and Pragma-Related Features::
21903 * Library of Predefined Units::
21905 * Main Program Definition::
21906 * Implementation-Defined Attributes::
21907 * Compiler and Run-Time Interfacing::
21908 * Program Compilation and Library Management::
21910 * Implementation Limits::
21911 * Tools and Utilities::
21914 @node Ada Language Compatibility
21915 @section Ada Language Compatibility
21918 GNAT handles Ada 95 and Ada 2005 as well as Ada 83, whereas HP Ada is only
21919 for Ada 83. Ada 95 and Ada 2005 are almost completely upwards compatible
21920 with Ada 83, and therefore Ada 83 programs will compile
21921 and run under GNAT with
21922 no changes or only minor changes. The @cite{Annotated Ada Reference Manual}
21923 provides details on specific incompatibilities.
21925 GNAT provides the switch @option{/83} on the @command{GNAT COMPILE} command,
21926 as well as the pragma @code{ADA_83}, to force the compiler to
21927 operate in Ada 83 mode. This mode does not guarantee complete
21928 conformance to Ada 83, but in practice is sufficient to
21929 eliminate most sources of incompatibilities.
21930 In particular, it eliminates the recognition of the
21931 additional Ada 95 and Ada 2005 keywords, so that their use as identifiers
21932 in Ada 83 programs is legal, and handles the cases of packages
21933 with optional bodies, and generics that instantiate unconstrained
21934 types without the use of @code{(<>)}.
21936 @node Differences in the Definition of Package System
21937 @section Differences in the Definition of Package @code{System}
21940 An Ada compiler is allowed to add
21941 implementation-dependent declarations to package @code{System}.
21943 GNAT does not take advantage of this permission, and the version of
21944 @code{System} provided by GNAT exactly matches that defined in the Ada
21947 However, HP Ada adds an extensive set of declarations to package
21949 as fully documented in the HP Ada manuals. To minimize changes required
21950 for programs that make use of these extensions, GNAT provides the pragma
21951 @code{Extend_System} for extending the definition of package System. By using:
21952 @cindex pragma @code{Extend_System}
21953 @cindex @code{Extend_System} pragma
21955 @smallexample @c ada
21958 pragma Extend_System (Aux_DEC);
21964 the set of definitions in @code{System} is extended to include those in
21965 package @code{System.Aux_DEC}.
21966 @cindex @code{System.Aux_DEC} package
21967 @cindex @code{Aux_DEC} package (child of @code{System})
21968 These definitions are incorporated directly into package @code{System},
21969 as though they had been declared there. For a
21970 list of the declarations added, see the spec of this package,
21971 which can be found in the file @file{s-auxdec.ads} in the GNAT library.
21972 @cindex @file{s-auxdec.ads} file
21973 The pragma @code{Extend_System} is a configuration pragma, which means that
21974 it can be placed in the file @file{gnat.adc}, so that it will automatically
21975 apply to all subsequent compilations. See @ref{Configuration Pragmas},
21976 for further details.
21978 An alternative approach that avoids the use of the non-standard
21979 @code{Extend_System} pragma is to add a context clause to the unit that
21980 references these facilities:
21982 @smallexample @c ada
21984 with System.Aux_DEC;
21985 use System.Aux_DEC;
21990 The effect is not quite semantically identical to incorporating
21991 the declarations directly into package @code{System},
21992 but most programs will not notice a difference
21993 unless they use prefix notation (e.g.@: @code{System.Integer_8})
21994 to reference the entities directly in package @code{System}.
21995 For units containing such references,
21996 the prefixes must either be removed, or the pragma @code{Extend_System}
21999 @node Language-Related Features
22000 @section Language-Related Features
22003 The following sections highlight differences in types,
22004 representations of types, operations, alignment, and
22008 * Integer Types and Representations::
22009 * Floating-Point Types and Representations::
22010 * Pragmas Float_Representation and Long_Float::
22011 * Fixed-Point Types and Representations::
22012 * Record and Array Component Alignment::
22013 * Address Clauses::
22014 * Other Representation Clauses::
22017 @node Integer Types and Representations
22018 @subsection Integer Types and Representations
22021 The set of predefined integer types is identical in HP Ada and GNAT.
22022 Furthermore the representation of these integer types is also identical,
22023 including the capability of size clauses forcing biased representation.
22026 HP Ada for OpenVMS Alpha systems has defined the
22027 following additional integer types in package @code{System}:
22044 @code{LARGEST_INTEGER}
22048 In GNAT, the first four of these types may be obtained from the
22049 standard Ada package @code{Interfaces}.
22050 Alternatively, by use of the pragma @code{Extend_System}, identical
22051 declarations can be referenced directly in package @code{System}.
22052 On both GNAT and HP Ada, the maximum integer size is 64 bits.
22054 @node Floating-Point Types and Representations
22055 @subsection Floating-Point Types and Representations
22056 @cindex Floating-Point types
22059 The set of predefined floating-point types is identical in HP Ada and GNAT.
22060 Furthermore the representation of these floating-point
22061 types is also identical. One important difference is that the default
22062 representation for HP Ada is @code{VAX_Float}, but the default representation
22065 Specific types may be declared to be @code{VAX_Float} or IEEE, using the
22066 pragma @code{Float_Representation} as described in the HP Ada
22068 For example, the declarations:
22070 @smallexample @c ada
22072 type F_Float is digits 6;
22073 pragma Float_Representation (VAX_Float, F_Float);
22078 declares a type @code{F_Float} that will be represented in @code{VAX_Float}
22080 This set of declarations actually appears in @code{System.Aux_DEC},
22082 the full set of additional floating-point declarations provided in
22083 the HP Ada version of package @code{System}.
22084 This and similar declarations may be accessed in a user program
22085 by using pragma @code{Extend_System}. The use of this
22086 pragma, and the related pragma @code{Long_Float} is described in further
22087 detail in the following section.
22089 @node Pragmas Float_Representation and Long_Float
22090 @subsection Pragmas @code{Float_Representation} and @code{Long_Float}
22093 HP Ada provides the pragma @code{Float_Representation}, which
22094 acts as a program library switch to allow control over
22095 the internal representation chosen for the predefined
22096 floating-point types declared in the package @code{Standard}.
22097 The format of this pragma is as follows:
22099 @smallexample @c ada
22101 pragma Float_Representation(VAX_Float | IEEE_Float);
22106 This pragma controls the representation of floating-point
22111 @code{VAX_Float} specifies that floating-point
22112 types are represented by default with the VAX system hardware types
22113 @code{F-floating}, @code{D-floating}, @code{G-floating}.
22114 Note that the @code{H-floating}
22115 type was available only on VAX systems, and is not available
22116 in either HP Ada or GNAT.
22119 @code{IEEE_Float} specifies that floating-point
22120 types are represented by default with the IEEE single and
22121 double floating-point types.
22125 GNAT provides an identical implementation of the pragma
22126 @code{Float_Representation}, except that it functions as a
22127 configuration pragma. Note that the
22128 notion of configuration pragma corresponds closely to the
22129 HP Ada notion of a program library switch.
22131 When no pragma is used in GNAT, the default is @code{IEEE_Float},
22133 from HP Ada 83, where the default is @code{VAX_Float}. In addition, the
22134 predefined libraries in GNAT are built using @code{IEEE_Float}, so it is not
22135 advisable to change the format of numbers passed to standard library
22136 routines, and if necessary explicit type conversions may be needed.
22138 The use of @code{IEEE_Float} is recommended in GNAT since it is more
22139 efficient, and (given that it conforms to an international standard)
22140 potentially more portable.
22141 The situation in which @code{VAX_Float} may be useful is in interfacing
22142 to existing code and data that expect the use of @code{VAX_Float}.
22143 In such a situation use the predefined @code{VAX_Float}
22144 types in package @code{System}, as extended by
22145 @code{Extend_System}. For example, use @code{System.F_Float}
22146 to specify the 32-bit @code{F-Float} format.
22149 On OpenVMS systems, HP Ada provides the pragma @code{Long_Float}
22150 to allow control over the internal representation chosen
22151 for the predefined type @code{Long_Float} and for floating-point
22152 type declarations with digits specified in the range 7 .. 15.
22153 The format of this pragma is as follows:
22155 @smallexample @c ada
22157 pragma Long_Float (D_FLOAT | G_FLOAT);
22161 @node Fixed-Point Types and Representations
22162 @subsection Fixed-Point Types and Representations
22165 On HP Ada for OpenVMS Alpha systems, rounding is
22166 away from zero for both positive and negative numbers.
22167 Therefore, @code{+0.5} rounds to @code{1},
22168 and @code{-0.5} rounds to @code{-1}.
22170 On GNAT the results of operations
22171 on fixed-point types are in accordance with the Ada
22172 rules. In particular, results of operations on decimal
22173 fixed-point types are truncated.
22175 @node Record and Array Component Alignment
22176 @subsection Record and Array Component Alignment
22179 On HP Ada for OpenVMS Alpha, all non-composite components
22180 are aligned on natural boundaries. For example, 1-byte
22181 components are aligned on byte boundaries, 2-byte
22182 components on 2-byte boundaries, 4-byte components on 4-byte
22183 byte boundaries, and so on. The OpenVMS Alpha hardware
22184 runs more efficiently with naturally aligned data.
22186 On GNAT, alignment rules are compatible
22187 with HP Ada for OpenVMS Alpha.
22189 @node Address Clauses
22190 @subsection Address Clauses
22193 In HP Ada and GNAT, address clauses are supported for
22194 objects and imported subprograms.
22195 The predefined type @code{System.Address} is a private type
22196 in both compilers on Alpha OpenVMS, with the same representation
22197 (it is simply a machine pointer). Addition, subtraction, and comparison
22198 operations are available in the standard Ada package
22199 @code{System.Storage_Elements}, or in package @code{System}
22200 if it is extended to include @code{System.Aux_DEC} using a
22201 pragma @code{Extend_System} as previously described.
22203 Note that code that @code{with}'s both this extended package @code{System}
22204 and the package @code{System.Storage_Elements} should not @code{use}
22205 both packages, or ambiguities will result. In general it is better
22206 not to mix these two sets of facilities. The Ada package was
22207 designed specifically to provide the kind of features that HP Ada
22208 adds directly to package @code{System}.
22210 The type @code{System.Address} is a 64-bit integer type in GNAT for
22211 I64 OpenVMS. For more information,
22212 see @ref{Transitioning to 64-Bit GNAT for OpenVMS}.
22214 GNAT is compatible with HP Ada in its handling of address
22215 clauses, except for some limitations in
22216 the form of address clauses for composite objects with
22217 initialization. Such address clauses are easily replaced
22218 by the use of an explicitly-defined constant as described
22219 in the Ada Reference Manual (13.1(22)). For example, the sequence
22222 @smallexample @c ada
22224 X, Y : Integer := Init_Func;
22225 Q : String (X .. Y) := "abc";
22227 for Q'Address use Compute_Address;
22232 will be rejected by GNAT, since the address cannot be computed at the time
22233 that @code{Q} is declared. To achieve the intended effect, write instead:
22235 @smallexample @c ada
22238 X, Y : Integer := Init_Func;
22239 Q_Address : constant Address := Compute_Address;
22240 Q : String (X .. Y) := "abc";
22242 for Q'Address use Q_Address;
22248 which will be accepted by GNAT (and other Ada compilers), and is also
22249 compatible with Ada 83. A fuller description of the restrictions
22250 on address specifications is found in @ref{Top, GNAT Reference Manual,
22251 About This Guide, gnat_rm, GNAT Reference Manual}.
22253 @node Other Representation Clauses
22254 @subsection Other Representation Clauses
22257 GNAT implements in a compatible manner all the representation
22258 clauses supported by HP Ada. In addition, GNAT
22259 implements the representation clause forms that were introduced in Ada 95,
22260 including @code{COMPONENT_SIZE} and @code{SIZE} clauses for objects.
22262 @node The Package STANDARD
22263 @section The Package @code{STANDARD}
22266 The package @code{STANDARD}, as implemented by HP Ada, is fully
22267 described in the @cite{Ada Reference Manual} and in the
22268 @cite{HP Ada Language Reference Manual}. As implemented by GNAT, the
22269 package @code{STANDARD} is described in the @cite{Ada Reference Manual}.
22271 In addition, HP Ada supports the Latin-1 character set in
22272 the type @code{CHARACTER}. GNAT supports the Latin-1 character set
22273 in the type @code{CHARACTER} and also Unicode (ISO 10646 BMP) in
22274 the type @code{WIDE_CHARACTER}.
22276 The floating-point types supported by GNAT are those
22277 supported by HP Ada, but the defaults are different, and are controlled by
22278 pragmas. See @ref{Floating-Point Types and Representations}, for details.
22280 @node The Package SYSTEM
22281 @section The Package @code{SYSTEM}
22284 HP Ada provides a specific version of the package
22285 @code{SYSTEM} for each platform on which the language is implemented.
22286 For the complete spec of the package @code{SYSTEM}, see
22287 Appendix F of the @cite{HP Ada Language Reference Manual}.
22289 On HP Ada, the package @code{SYSTEM} includes the following conversion
22292 @item @code{TO_ADDRESS(INTEGER)}
22294 @item @code{TO_ADDRESS(UNSIGNED_LONGWORD)}
22296 @item @code{TO_ADDRESS(}@i{universal_integer}@code{)}
22298 @item @code{TO_INTEGER(ADDRESS)}
22300 @item @code{TO_UNSIGNED_LONGWORD(ADDRESS)}
22302 @item Function @code{IMPORT_VALUE return UNSIGNED_LONGWORD} and the
22303 functions @code{IMPORT_ADDRESS} and @code{IMPORT_LARGEST_VALUE}
22307 By default, GNAT supplies a version of @code{SYSTEM} that matches
22308 the definition given in the @cite{Ada Reference Manual}.
22310 is a subset of the HP system definitions, which is as
22311 close as possible to the original definitions. The only difference
22312 is that the definition of @code{SYSTEM_NAME} is different:
22314 @smallexample @c ada
22316 type Name is (SYSTEM_NAME_GNAT);
22317 System_Name : constant Name := SYSTEM_NAME_GNAT;
22322 Also, GNAT adds the Ada declarations for
22323 @code{BIT_ORDER} and @code{DEFAULT_BIT_ORDER}.
22325 However, the use of the following pragma causes GNAT
22326 to extend the definition of package @code{SYSTEM} so that it
22327 encompasses the full set of HP-specific extensions,
22328 including the functions listed above:
22330 @smallexample @c ada
22332 pragma Extend_System (Aux_DEC);
22337 The pragma @code{Extend_System} is a configuration pragma that
22338 is most conveniently placed in the @file{gnat.adc} file. @xref{Pragma
22339 Extend_System,,, gnat_rm, GNAT Reference Manual}, for further details.
22341 HP Ada does not allow the recompilation of the package
22342 @code{SYSTEM}. Instead HP Ada provides several pragmas
22343 (@code{SYSTEM_NAME}, @code{STORAGE_UNIT}, and @code{MEMORY_SIZE})
22344 to modify values in the package @code{SYSTEM}.
22345 On OpenVMS Alpha systems, the pragma
22346 @code{SYSTEM_NAME} takes the enumeration literal @code{OPENVMS_AXP} as
22347 its single argument.
22349 GNAT does permit the recompilation of package @code{SYSTEM} using
22350 the special switch @option{-gnatg}, and this switch can be used if
22351 it is necessary to modify the definitions in @code{SYSTEM}. GNAT does
22352 not permit the specification of @code{SYSTEM_NAME}, @code{STORAGE_UNIT}
22353 or @code{MEMORY_SIZE} by any other means.
22355 On GNAT systems, the pragma @code{SYSTEM_NAME} takes the
22356 enumeration literal @code{SYSTEM_NAME_GNAT}.
22358 The definitions provided by the use of
22360 @smallexample @c ada
22361 pragma Extend_System (AUX_Dec);
22365 are virtually identical to those provided by the HP Ada 83 package
22366 @code{SYSTEM}. One important difference is that the name of the
22368 function for type @code{UNSIGNED_LONGWORD} is changed to
22369 @code{TO_ADDRESS_LONG}.
22370 @xref{Address Clauses,,, gnat_rm, GNAT Reference Manual}, for a
22371 discussion of why this change was necessary.
22374 The version of @code{TO_ADDRESS} taking a @i{universal_integer} argument
22376 an extension to Ada 83 not strictly compatible with the reference manual.
22377 GNAT, in order to be exactly compatible with the standard,
22378 does not provide this capability. In HP Ada 83, the
22379 point of this definition is to deal with a call like:
22381 @smallexample @c ada
22382 TO_ADDRESS (16#12777#);
22386 Normally, according to Ada 83 semantics, one would expect this to be
22387 ambiguous, since it matches both the @code{INTEGER} and
22388 @code{UNSIGNED_LONGWORD} forms of @code{TO_ADDRESS}.
22389 However, in HP Ada 83, there is no ambiguity, since the
22390 definition using @i{universal_integer} takes precedence.
22392 In GNAT, since the version with @i{universal_integer} cannot be supplied,
22394 not possible to be 100% compatible. Since there are many programs using
22395 numeric constants for the argument to @code{TO_ADDRESS}, the decision in
22397 to change the name of the function in the @code{UNSIGNED_LONGWORD} case,
22398 so the declarations provided in the GNAT version of @code{AUX_Dec} are:
22400 @smallexample @c ada
22401 function To_Address (X : Integer) return Address;
22402 pragma Pure_Function (To_Address);
22404 function To_Address_Long (X : Unsigned_Longword) return Address;
22405 pragma Pure_Function (To_Address_Long);
22409 This means that programs using @code{TO_ADDRESS} for
22410 @code{UNSIGNED_LONGWORD} must change the name to @code{TO_ADDRESS_LONG}.
22412 @node Tasking and Task-Related Features
22413 @section Tasking and Task-Related Features
22416 This section compares the treatment of tasking in GNAT
22417 and in HP Ada for OpenVMS Alpha.
22418 The GNAT description applies to both Alpha and I64 OpenVMS.
22419 For detailed information on tasking in
22420 HP Ada, see the @cite{HP Ada Language Reference Manual} and the
22421 relevant run-time reference manual.
22424 * Implementation of Tasks in HP Ada for OpenVMS Alpha Systems::
22425 * Assigning Task IDs::
22426 * Task IDs and Delays::
22427 * Task-Related Pragmas::
22428 * Scheduling and Task Priority::
22430 * External Interrupts::
22433 @node Implementation of Tasks in HP Ada for OpenVMS Alpha Systems
22434 @subsection Implementation of Tasks in HP Ada for OpenVMS Alpha Systems
22437 On OpenVMS Alpha systems, each Ada task (except a passive
22438 task) is implemented as a single stream of execution
22439 that is created and managed by the kernel. On these
22440 systems, HP Ada tasking support is based on DECthreads,
22441 an implementation of the POSIX standard for threads.
22443 Also, on OpenVMS Alpha systems, HP Ada tasks and foreign
22444 code that calls DECthreads routines can be used together.
22445 The interaction between Ada tasks and DECthreads routines
22446 can have some benefits. For example when on OpenVMS Alpha,
22447 HP Ada can call C code that is already threaded.
22449 GNAT uses the facilities of DECthreads,
22450 and Ada tasks are mapped to threads.
22452 @node Assigning Task IDs
22453 @subsection Assigning Task IDs
22456 The HP Ada Run-Time Library always assigns @code{%TASK 1} to
22457 the environment task that executes the main program. On
22458 OpenVMS Alpha systems, @code{%TASK 0} is often used for tasks
22459 that have been created but are not yet activated.
22461 On OpenVMS Alpha systems, task IDs are assigned at
22462 activation. On GNAT systems, task IDs are also assigned at
22463 task creation but do not have the same form or values as
22464 task ID values in HP Ada. There is no null task, and the
22465 environment task does not have a specific task ID value.
22467 @node Task IDs and Delays
22468 @subsection Task IDs and Delays
22471 On OpenVMS Alpha systems, tasking delays are implemented
22472 using Timer System Services. The Task ID is used for the
22473 identification of the timer request (the @code{REQIDT} parameter).
22474 If Timers are used in the application take care not to use
22475 @code{0} for the identification, because cancelling such a timer
22476 will cancel all timers and may lead to unpredictable results.
22478 @node Task-Related Pragmas
22479 @subsection Task-Related Pragmas
22482 Ada supplies the pragma @code{TASK_STORAGE}, which allows
22483 specification of the size of the guard area for a task
22484 stack. (The guard area forms an area of memory that has no
22485 read or write access and thus helps in the detection of
22486 stack overflow.) On OpenVMS Alpha systems, if the pragma
22487 @code{TASK_STORAGE} specifies a value of zero, a minimal guard
22488 area is created. In the absence of a pragma @code{TASK_STORAGE},
22489 a default guard area is created.
22491 GNAT supplies the following task-related pragmas:
22494 @item @code{TASK_INFO}
22496 This pragma appears within a task definition and
22497 applies to the task in which it appears. The argument
22498 must be of type @code{SYSTEM.TASK_INFO.TASK_INFO_TYPE}.
22500 @item @code{TASK_STORAGE}
22502 GNAT implements pragma @code{TASK_STORAGE} in the same way as HP Ada.
22503 Both HP Ada and GNAT supply the pragmas @code{PASSIVE},
22504 @code{SUPPRESS}, and @code{VOLATILE}.
22506 @node Scheduling and Task Priority
22507 @subsection Scheduling and Task Priority
22510 HP Ada implements the Ada language requirement that
22511 when two tasks are eligible for execution and they have
22512 different priorities, the lower priority task does not
22513 execute while the higher priority task is waiting. The HP
22514 Ada Run-Time Library keeps a task running until either the
22515 task is suspended or a higher priority task becomes ready.
22517 On OpenVMS Alpha systems, the default strategy is round-
22518 robin with preemption. Tasks of equal priority take turns
22519 at the processor. A task is run for a certain period of
22520 time and then placed at the tail of the ready queue for
22521 its priority level.
22523 HP Ada provides the implementation-defined pragma @code{TIME_SLICE},
22524 which can be used to enable or disable round-robin
22525 scheduling of tasks with the same priority.
22526 See the relevant HP Ada run-time reference manual for
22527 information on using the pragmas to control HP Ada task
22530 GNAT follows the scheduling rules of Annex D (Real-Time
22531 Annex) of the @cite{Ada Reference Manual}. In general, this
22532 scheduling strategy is fully compatible with HP Ada
22533 although it provides some additional constraints (as
22534 fully documented in Annex D).
22535 GNAT implements time slicing control in a manner compatible with
22536 HP Ada 83, by means of the pragma @code{Time_Slice}, whose semantics
22537 are identical to the HP Ada 83 pragma of the same name.
22538 Note that it is not possible to mix GNAT tasking and
22539 HP Ada 83 tasking in the same program, since the two run-time
22540 libraries are not compatible.
22542 @node The Task Stack
22543 @subsection The Task Stack
22546 In HP Ada, a task stack is allocated each time a
22547 non-passive task is activated. As soon as the task is
22548 terminated, the storage for the task stack is deallocated.
22549 If you specify a size of zero (bytes) with @code{T'STORAGE_SIZE},
22550 a default stack size is used. Also, regardless of the size
22551 specified, some additional space is allocated for task
22552 management purposes. On OpenVMS Alpha systems, at least
22553 one page is allocated.
22555 GNAT handles task stacks in a similar manner. In accordance with
22556 the Ada rules, it provides the pragma @code{STORAGE_SIZE} as
22557 an alternative method for controlling the task stack size.
22558 The specification of the attribute @code{T'STORAGE_SIZE} is also
22559 supported in a manner compatible with HP Ada.
22561 @node External Interrupts
22562 @subsection External Interrupts
22565 On HP Ada, external interrupts can be associated with task entries.
22566 GNAT is compatible with HP Ada in its handling of external interrupts.
22568 @node Pragmas and Pragma-Related Features
22569 @section Pragmas and Pragma-Related Features
22572 Both HP Ada and GNAT supply all language-defined pragmas
22573 as specified by the Ada 83 standard. GNAT also supplies all
22574 language-defined pragmas introduced by Ada 95 and Ada 2005.
22575 In addition, GNAT implements the implementation-defined pragmas
22579 @item @code{AST_ENTRY}
22581 @item @code{COMMON_OBJECT}
22583 @item @code{COMPONENT_ALIGNMENT}
22585 @item @code{EXPORT_EXCEPTION}
22587 @item @code{EXPORT_FUNCTION}
22589 @item @code{EXPORT_OBJECT}
22591 @item @code{EXPORT_PROCEDURE}
22593 @item @code{EXPORT_VALUED_PROCEDURE}
22595 @item @code{FLOAT_REPRESENTATION}
22599 @item @code{IMPORT_EXCEPTION}
22601 @item @code{IMPORT_FUNCTION}
22603 @item @code{IMPORT_OBJECT}
22605 @item @code{IMPORT_PROCEDURE}
22607 @item @code{IMPORT_VALUED_PROCEDURE}
22609 @item @code{INLINE_GENERIC}
22611 @item @code{INTERFACE_NAME}
22613 @item @code{LONG_FLOAT}
22615 @item @code{MAIN_STORAGE}
22617 @item @code{PASSIVE}
22619 @item @code{PSECT_OBJECT}
22621 @item @code{SHARE_GENERIC}
22623 @item @code{SUPPRESS_ALL}
22625 @item @code{TASK_STORAGE}
22627 @item @code{TIME_SLICE}
22633 These pragmas are all fully implemented, with the exception of @code{TITLE},
22634 @code{PASSIVE}, and @code{SHARE_GENERIC}, which are
22635 recognized, but which have no
22636 effect in GNAT. The effect of @code{PASSIVE} may be obtained by the
22637 use of Ada protected objects. In GNAT, all generics are inlined.
22639 Unlike HP Ada, the GNAT ``@code{EXPORT_}@i{subprogram}'' pragmas require
22640 a separate subprogram specification which must appear before the
22643 GNAT also supplies a number of implementation-defined pragmas including the
22647 @item @code{ABORT_DEFER}
22649 @item @code{ADA_83}
22651 @item @code{ADA_95}
22653 @item @code{ADA_05}
22655 @item @code{Ada_2005}
22657 @item @code{Ada_12}
22659 @item @code{Ada_2012}
22661 @item @code{ANNOTATE}
22663 @item @code{ASSERT}
22665 @item @code{C_PASS_BY_COPY}
22667 @item @code{CPP_CLASS}
22669 @item @code{CPP_CONSTRUCTOR}
22671 @item @code{CPP_DESTRUCTOR}
22675 @item @code{EXTEND_SYSTEM}
22677 @item @code{LINKER_ALIAS}
22679 @item @code{LINKER_SECTION}
22681 @item @code{MACHINE_ATTRIBUTE}
22683 @item @code{NO_RETURN}
22685 @item @code{PURE_FUNCTION}
22687 @item @code{SOURCE_FILE_NAME}
22689 @item @code{SOURCE_REFERENCE}
22691 @item @code{TASK_INFO}
22693 @item @code{UNCHECKED_UNION}
22695 @item @code{UNIMPLEMENTED_UNIT}
22697 @item @code{UNIVERSAL_DATA}
22699 @item @code{UNSUPPRESS}
22701 @item @code{WARNINGS}
22703 @item @code{WEAK_EXTERNAL}
22707 For full details on these and other GNAT implementation-defined pragmas,
22708 see @ref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference
22712 * Restrictions on the Pragma INLINE::
22713 * Restrictions on the Pragma INTERFACE::
22714 * Restrictions on the Pragma SYSTEM_NAME::
22717 @node Restrictions on the Pragma INLINE
22718 @subsection Restrictions on Pragma @code{INLINE}
22721 HP Ada enforces the following restrictions on the pragma @code{INLINE}:
22723 @item Parameters cannot have a task type.
22725 @item Function results cannot be task types, unconstrained
22726 array types, or unconstrained types with discriminants.
22728 @item Bodies cannot declare the following:
22730 @item Subprogram body or stub (imported subprogram is allowed)
22734 @item Generic declarations
22736 @item Instantiations
22740 @item Access types (types derived from access types allowed)
22742 @item Array or record types
22744 @item Dependent tasks
22746 @item Direct recursive calls of subprogram or containing
22747 subprogram, directly or via a renaming
22753 In GNAT, the only restriction on pragma @code{INLINE} is that the
22754 body must occur before the call if both are in the same
22755 unit, and the size must be appropriately small. There are
22756 no other specific restrictions which cause subprograms to
22757 be incapable of being inlined.
22759 @node Restrictions on the Pragma INTERFACE
22760 @subsection Restrictions on Pragma @code{INTERFACE}
22763 The following restrictions on pragma @code{INTERFACE}
22764 are enforced by both HP Ada and GNAT:
22766 @item Languages accepted: Ada, Bliss, C, Fortran, Default.
22767 Default is the default on OpenVMS Alpha systems.
22769 @item Parameter passing: Language specifies default
22770 mechanisms but can be overridden with an @code{EXPORT} pragma.
22773 @item Ada: Use internal Ada rules.
22775 @item Bliss, C: Parameters must be mode @code{in}; cannot be
22776 record or task type. Result cannot be a string, an
22777 array, or a record.
22779 @item Fortran: Parameters cannot have a task type. Result cannot
22780 be a string, an array, or a record.
22785 GNAT is entirely upwards compatible with HP Ada, and in addition allows
22786 record parameters for all languages.
22788 @node Restrictions on the Pragma SYSTEM_NAME
22789 @subsection Restrictions on Pragma @code{SYSTEM_NAME}
22792 For HP Ada for OpenVMS Alpha, the enumeration literal
22793 for the type @code{NAME} is @code{OPENVMS_AXP}.
22794 In GNAT, the enumeration
22795 literal for the type @code{NAME} is @code{SYSTEM_NAME_GNAT}.
22797 @node Library of Predefined Units
22798 @section Library of Predefined Units
22801 A library of predefined units is provided as part of the
22802 HP Ada and GNAT implementations. HP Ada does not provide
22803 the package @code{MACHINE_CODE} but instead recommends importing
22806 The GNAT versions of the HP Ada Run-Time Library (@code{ADA$PREDEFINED:})
22807 units are taken from the OpenVMS Alpha version, not the OpenVMS VAX
22809 The HP Ada Predefined Library units are modified to remove post-Ada 83
22810 incompatibilities and to make them interoperable with GNAT
22811 (@pxref{Changes to DECLIB}, for details).
22812 The units are located in the @file{DECLIB} directory.
22814 The GNAT RTL is contained in
22815 the @file{ADALIB} directory, and
22816 the default search path is set up to find @code{DECLIB} units in preference
22817 to @code{ADALIB} units with the same name (@code{TEXT_IO},
22818 @code{SEQUENTIAL_IO}, and @code{DIRECT_IO}, for example).
22821 * Changes to DECLIB::
22824 @node Changes to DECLIB
22825 @subsection Changes to @code{DECLIB}
22828 The changes made to the HP Ada predefined library for GNAT and post-Ada 83
22829 compatibility are minor and include the following:
22832 @item Adjusting the location of pragmas and record representation
22833 clauses to obey Ada 95 (and thus Ada 2005) rules
22835 @item Adding the proper notation to generic formal parameters
22836 that take unconstrained types in instantiation
22838 @item Adding pragma @code{ELABORATE_BODY} to package specs
22839 that have package bodies not otherwise allowed
22841 @item Replacing occurrences of the identifier ``@code{PROTECTED}'' by
22842 ``@code{PROTECTD}''.
22843 Currently these are found only in the @code{STARLET} package spec.
22845 @item Changing @code{SYSTEM.ADDRESS} to @code{SYSTEM.SHORT_ADDRESS}
22846 where the address size is constrained to 32 bits.
22850 None of the above changes is visible to users.
22856 On OpenVMS Alpha, HP Ada provides the following strongly-typed bindings:
22859 @item Command Language Interpreter (CLI interface)
22861 @item DECtalk Run-Time Library (DTK interface)
22863 @item Librarian utility routines (LBR interface)
22865 @item General Purpose Run-Time Library (LIB interface)
22867 @item Math Run-Time Library (MTH interface)
22869 @item National Character Set Run-Time Library (NCS interface)
22871 @item Compiled Code Support Run-Time Library (OTS interface)
22873 @item Parallel Processing Run-Time Library (PPL interface)
22875 @item Screen Management Run-Time Library (SMG interface)
22877 @item Sort Run-Time Library (SOR interface)
22879 @item String Run-Time Library (STR interface)
22881 @item STARLET System Library
22884 @item X Window System Version 11R4 and 11R5 (X, XLIB interface)
22886 @item X Windows Toolkit (XT interface)
22888 @item X/Motif Version 1.1.3 and 1.2 (XM interface)
22892 GNAT provides implementations of these HP bindings in the @code{DECLIB}
22893 directory, on both the Alpha and I64 OpenVMS platforms.
22895 The X components of DECLIB compatibility package are located in a separate
22896 library, called XDECGNAT, which is not linked with by default; this library
22897 must be explicitly linked with any application that makes use of any X facilities,
22898 with a command similar to
22900 @code{GNAT MAKE USE_X /LINK /LIBRARY=XDECGNAT}
22902 The X/Motif bindings used to build @code{DECLIB} are whatever versions are
22904 HP Ada @file{ADA$PREDEFINED} directory with extension @file{.ADC}.
22905 A pragma @code{Linker_Options} has been added to packages @code{Xm},
22906 @code{Xt}, and @code{X_Lib}
22907 causing the default X/Motif sharable image libraries to be linked in. This
22908 is done via options files named @file{xm.opt}, @file{xt.opt}, and
22909 @file{x_lib.opt} (also located in the @file{DECLIB} directory).
22911 It may be necessary to edit these options files to update or correct the
22912 library names if, for example, the newer X/Motif bindings from
22913 @file{ADA$EXAMPLES}
22914 had been (previous to installing GNAT) copied and renamed to supersede the
22915 default @file{ADA$PREDEFINED} versions.
22918 * Shared Libraries and Options Files::
22919 * Interfaces to C::
22922 @node Shared Libraries and Options Files
22923 @subsection Shared Libraries and Options Files
22926 When using the HP Ada
22927 predefined X and Motif bindings, the linking with their sharable images is
22928 done automatically by @command{GNAT LINK}.
22929 When using other X and Motif bindings, you need
22930 to add the corresponding sharable images to the command line for
22931 @code{GNAT LINK}. When linking with shared libraries, or with
22932 @file{.OPT} files, you must
22933 also add them to the command line for @command{GNAT LINK}.
22935 A shared library to be used with GNAT is built in the same way as other
22936 libraries under VMS. The VMS Link command can be used in standard fashion.
22938 @node Interfaces to C
22939 @subsection Interfaces to C
22943 provides the following Ada types and operations:
22946 @item C types package (@code{C_TYPES})
22948 @item C strings (@code{C_TYPES.NULL_TERMINATED})
22950 @item Other_types (@code{SHORT_INT})
22954 Interfacing to C with GNAT, you can use the above approach
22955 described for HP Ada or the facilities of Annex B of
22956 the @cite{Ada Reference Manual} (packages @code{INTERFACES.C},
22957 @code{INTERFACES.C.STRINGS} and @code{INTERFACES.C.POINTERS}). For more
22958 information, see @ref{Interfacing to C,,, gnat_rm, GNAT Reference Manual}.
22960 The @option{-gnatF} qualifier forces default and explicit
22961 @code{External_Name} parameters in pragmas @code{Import} and @code{Export}
22962 to be uppercased for compatibility with the default behavior
22963 of HP C. The qualifier has no effect on @code{Link_Name} parameters.
22965 @node Main Program Definition
22966 @section Main Program Definition
22969 The following section discusses differences in the
22970 definition of main programs on HP Ada and GNAT.
22971 On HP Ada, main programs are defined to meet the
22972 following conditions:
22974 @item Procedure with no formal parameters (returns @code{0} upon
22977 @item Procedure with no formal parameters (returns @code{42} when
22978 an unhandled exception is raised)
22980 @item Function with no formal parameters whose returned value
22981 is of a discrete type
22983 @item Procedure with one @code{out} formal of a discrete type for
22984 which a specification of pragma @code{EXPORT_VALUED_PROCEDURE} is given.
22989 When declared with the pragma @code{EXPORT_VALUED_PROCEDURE},
22990 a main function or main procedure returns a discrete
22991 value whose size is less than 64 bits (32 on VAX systems),
22992 the value is zero- or sign-extended as appropriate.
22993 On GNAT, main programs are defined as follows:
22995 @item Must be a non-generic, parameterless subprogram that
22996 is either a procedure or function returning an Ada
22997 @code{STANDARD.INTEGER} (the predefined type)
22999 @item Cannot be a generic subprogram or an instantiation of a
23003 @node Implementation-Defined Attributes
23004 @section Implementation-Defined Attributes
23007 GNAT provides all HP Ada implementation-defined
23010 @node Compiler and Run-Time Interfacing
23011 @section Compiler and Run-Time Interfacing
23014 HP Ada provides the following qualifiers to pass options to the linker
23017 @item @option{/WAIT} and @option{/SUBMIT}
23019 @item @option{/COMMAND}
23021 @item @option{/@r{[}NO@r{]}MAP}
23023 @item @option{/OUTPUT=@var{file-spec}}
23025 @item @option{/@r{[}NO@r{]}DEBUG} and @option{/@r{[}NO@r{]}TRACEBACK}
23029 To pass options to the linker, GNAT provides the following
23033 @item @option{/EXECUTABLE=@var{exec-name}}
23035 @item @option{/VERBOSE}
23037 @item @option{/@r{[}NO@r{]}DEBUG} and @option{/@r{[}NO@r{]}TRACEBACK}
23041 For more information on these switches, see
23042 @ref{Switches for gnatlink}.
23043 In HP Ada, the command-line switch @option{/OPTIMIZE} is available
23044 to control optimization. HP Ada also supplies the
23047 @item @code{OPTIMIZE}
23049 @item @code{INLINE}
23051 @item @code{INLINE_GENERIC}
23053 @item @code{SUPPRESS_ALL}
23055 @item @code{PASSIVE}
23059 In GNAT, optimization is controlled strictly by command
23060 line parameters, as described in the corresponding section of this guide.
23061 The HP pragmas for control of optimization are
23062 recognized but ignored.
23064 Note that in GNAT, the default is optimization off, whereas in HP Ada
23065 the default is that optimization is turned on.
23067 @node Program Compilation and Library Management
23068 @section Program Compilation and Library Management
23071 HP Ada and GNAT provide a comparable set of commands to
23072 build programs. HP Ada also provides a program library,
23073 which is a concept that does not exist on GNAT. Instead,
23074 GNAT provides directories of sources that are compiled as
23077 The following table summarizes
23078 the HP Ada commands and provides
23079 equivalent GNAT commands. In this table, some GNAT
23080 equivalents reflect the fact that GNAT does not use the
23081 concept of a program library. Instead, it uses a model
23082 in which collections of source and object files are used
23083 in a manner consistent with other languages like C and
23084 Fortran. Therefore, standard system file commands are used
23085 to manipulate these elements. Those GNAT commands are marked with
23087 Note that, unlike HP Ada, none of the GNAT commands accepts wild cards.
23090 @multitable @columnfractions .35 .65
23092 @item @emph{HP Ada Command}
23093 @tab @emph{GNAT Equivalent / Description}
23095 @item @command{ADA}
23096 @tab @command{GNAT COMPILE}@*
23097 Invokes the compiler to compile one or more Ada source files.
23099 @item @command{ACS ATTACH}@*
23100 @tab [No equivalent]@*
23101 Switches control of terminal from current process running the program
23104 @item @command{ACS CHECK}
23105 @tab @command{GNAT MAKE /DEPENDENCY_LIST}@*
23106 Forms the execution closure of one
23107 or more compiled units and checks completeness and currency.
23109 @item @command{ACS COMPILE}
23110 @tab @command{GNAT MAKE /ACTIONS=COMPILE}@*
23111 Forms the execution closure of one or
23112 more specified units, checks completeness and currency,
23113 identifies units that have revised source files, compiles same,
23114 and recompiles units that are or will become obsolete.
23115 Also completes incomplete generic instantiations.
23117 @item @command{ACS COPY FOREIGN}
23119 Copies a foreign object file into the program library as a
23122 @item @command{ACS COPY UNIT}
23124 Copies a compiled unit from one program library to another.
23126 @item @command{ACS CREATE LIBRARY}
23127 @tab Create /directory (*)@*
23128 Creates a program library.
23130 @item @command{ACS CREATE SUBLIBRARY}
23131 @tab Create /directory (*)@*
23132 Creates a program sublibrary.
23134 @item @command{ACS DELETE LIBRARY}
23136 Deletes a program library and its contents.
23138 @item @command{ACS DELETE SUBLIBRARY}
23140 Deletes a program sublibrary and its contents.
23142 @item @command{ACS DELETE UNIT}
23143 @tab Delete file (*)@*
23144 On OpenVMS systems, deletes one or more compiled units from
23145 the current program library.
23147 @item @command{ACS DIRECTORY}
23148 @tab Directory (*)@*
23149 On OpenVMS systems, lists units contained in the current
23152 @item @command{ACS ENTER FOREIGN}
23154 Allows the import of a foreign body as an Ada library
23155 spec and enters a reference to a pointer.
23157 @item @command{ACS ENTER UNIT}
23159 Enters a reference (pointer) from the current program library to
23160 a unit compiled into another program library.
23162 @item @command{ACS EXIT}
23163 @tab [No equivalent]@*
23164 Exits from the program library manager.
23166 @item @command{ACS EXPORT}
23168 Creates an object file that contains system-specific object code
23169 for one or more units. With GNAT, object files can simply be copied
23170 into the desired directory.
23172 @item @command{ACS EXTRACT SOURCE}
23174 Allows access to the copied source file for each Ada compilation unit
23176 @item @command{ACS HELP}
23177 @tab @command{HELP GNAT}@*
23178 Provides online help.
23180 @item @command{ACS LINK}
23181 @tab @command{GNAT LINK}@*
23182 Links an object file containing Ada units into an executable file.
23184 @item @command{ACS LOAD}
23186 Loads (partially compiles) Ada units into the program library.
23187 Allows loading a program from a collection of files into a library
23188 without knowing the relationship among units.
23190 @item @command{ACS MERGE}
23192 Merges into the current program library, one or more units from
23193 another library where they were modified.
23195 @item @command{ACS RECOMPILE}
23196 @tab @command{GNAT MAKE /ACTIONS=COMPILE}@*
23197 Recompiles from external or copied source files any obsolete
23198 unit in the closure. Also, completes any incomplete generic
23201 @item @command{ACS REENTER}
23202 @tab @command{GNAT MAKE}@*
23203 Reenters current references to units compiled after last entered
23204 with the @command{ACS ENTER UNIT} command.
23206 @item @command{ACS SET LIBRARY}
23207 @tab Set default (*)@*
23208 Defines a program library to be the compilation context as well
23209 as the target library for compiler output and commands in general.
23211 @item @command{ACS SET PRAGMA}
23212 @tab Edit @file{gnat.adc} (*)@*
23213 Redefines specified values of the library characteristics
23214 @code{LONG_ FLOAT}, @code{MEMORY_SIZE}, @code{SYSTEM_NAME},
23215 and @code{Float_Representation}.
23217 @item @command{ACS SET SOURCE}
23218 @tab Define @code{ADA_INCLUDE_PATH} path (*)@*
23219 Defines the source file search list for the @command{ACS COMPILE} command.
23221 @item @command{ACS SHOW LIBRARY}
23222 @tab Directory (*)@*
23223 Lists information about one or more program libraries.
23225 @item @command{ACS SHOW PROGRAM}
23226 @tab [No equivalent]@*
23227 Lists information about the execution closure of one or
23228 more units in the program library.
23230 @item @command{ACS SHOW SOURCE}
23231 @tab Show logical @code{ADA_INCLUDE_PATH}@*
23232 Shows the source file search used when compiling units.
23234 @item @command{ACS SHOW VERSION}
23235 @tab Compile with @option{VERBOSE} option
23236 Displays the version number of the compiler and program library
23239 @item @command{ACS SPAWN}
23240 @tab [No equivalent]@*
23241 Creates a subprocess of the current process (same as @command{DCL SPAWN}
23244 @item @command{ACS VERIFY}
23245 @tab [No equivalent]@*
23246 Performs a series of consistency checks on a program library to
23247 determine whether the library structure and library files are in
23254 @section Input-Output
23257 On OpenVMS Alpha systems, HP Ada uses OpenVMS Record
23258 Management Services (RMS) to perform operations on
23262 HP Ada and GNAT predefine an identical set of input-
23263 output packages. To make the use of the
23264 generic @code{TEXT_IO} operations more convenient, HP Ada
23265 provides predefined library packages that instantiate the
23266 integer and floating-point operations for the predefined
23267 integer and floating-point types as shown in the following table.
23269 @multitable @columnfractions .45 .55
23270 @item @emph{Package Name} @tab Instantiation
23272 @item @code{INTEGER_TEXT_IO}
23273 @tab @code{INTEGER_IO(INTEGER)}
23275 @item @code{SHORT_INTEGER_TEXT_IO}
23276 @tab @code{INTEGER_IO(SHORT_INTEGER)}
23278 @item @code{SHORT_SHORT_INTEGER_TEXT_IO}
23279 @tab @code{INTEGER_IO(SHORT_SHORT_INTEGER)}
23281 @item @code{FLOAT_TEXT_IO}
23282 @tab @code{FLOAT_IO(FLOAT)}
23284 @item @code{LONG_FLOAT_TEXT_IO}
23285 @tab @code{FLOAT_IO(LONG_FLOAT)}
23289 The HP Ada predefined packages and their operations
23290 are implemented using OpenVMS Alpha files and input-output
23291 facilities. HP Ada supports asynchronous input-output on OpenVMS Alpha.
23292 Familiarity with the following is recommended:
23294 @item RMS file organizations and access methods
23296 @item OpenVMS file specifications and directories
23298 @item OpenVMS File Definition Language (FDL)
23302 GNAT provides I/O facilities that are completely
23303 compatible with HP Ada. The distribution includes the
23304 standard HP Ada versions of all I/O packages, operating
23305 in a manner compatible with HP Ada. In particular, the
23306 following packages are by default the HP Ada (Ada 83)
23307 versions of these packages rather than the renamings
23308 suggested in Annex J of the Ada Reference Manual:
23310 @item @code{TEXT_IO}
23312 @item @code{SEQUENTIAL_IO}
23314 @item @code{DIRECT_IO}
23318 The use of the standard child package syntax (for
23319 example, @code{ADA.TEXT_IO}) retrieves the post-Ada 83 versions of these
23321 GNAT provides HP-compatible predefined instantiations
23322 of the @code{TEXT_IO} packages, and also
23323 provides the standard predefined instantiations required
23324 by the @cite{Ada Reference Manual}.
23326 For further information on how GNAT interfaces to the file
23327 system or how I/O is implemented in programs written in
23328 mixed languages, see @ref{Implementation of the Standard I/O,,,
23329 gnat_rm, GNAT Reference Manual}.
23330 This chapter covers the following:
23332 @item Standard I/O packages
23334 @item @code{FORM} strings
23336 @item @code{ADA.DIRECT_IO}
23338 @item @code{ADA.SEQUENTIAL_IO}
23340 @item @code{ADA.TEXT_IO}
23342 @item Stream pointer positioning
23344 @item Reading and writing non-regular files
23346 @item @code{GET_IMMEDIATE}
23348 @item Treating @code{TEXT_IO} files as streams
23355 @node Implementation Limits
23356 @section Implementation Limits
23359 The following table lists implementation limits for HP Ada
23361 @multitable @columnfractions .60 .20 .20
23363 @item @emph{Compilation Parameter}
23368 @item In a subprogram or entry declaration, maximum number of
23369 formal parameters that are of an unconstrained record type
23374 @item Maximum identifier length (number of characters)
23379 @item Maximum number of characters in a source line
23384 @item Maximum collection size (number of bytes)
23389 @item Maximum number of discriminants for a record type
23394 @item Maximum number of formal parameters in an entry or
23395 subprogram declaration
23400 @item Maximum number of dimensions in an array type
23405 @item Maximum number of library units and subunits in a compilation.
23410 @item Maximum number of library units and subunits in an execution.
23415 @item Maximum number of objects declared with the pragma @code{COMMON_OBJECT}
23416 or @code{PSECT_OBJECT}
23421 @item Maximum number of enumeration literals in an enumeration type
23427 @item Maximum number of lines in a source file
23432 @item Maximum number of bits in any object
23437 @item Maximum size of the static portion of a stack frame (approximate)
23442 @node Tools and Utilities
23443 @section Tools and Utilities
23446 The following table lists some of the OpenVMS development tools
23447 available for HP Ada, and the corresponding tools for
23448 use with @value{EDITION} on Alpha and I64 platforms.
23449 Aside from the debugger, all the OpenVMS tools identified are part
23450 of the DECset package.
23453 @c Specify table in TeX since Texinfo does a poor job
23457 \settabs\+Language-Sensitive Editor\quad
23458 &Product with HP Ada\quad
23461 &\it Product with HP Ada
23462 & \it Product with @value{EDITION}\cr
23464 \+Code Management System
23468 \+Language-Sensitive Editor
23470 & emacs or HP LSE (Alpha)\cr
23480 & OpenVMS Debug (I64)\cr
23482 \+Source Code Analyzer /
23499 \+Coverage Analyzer
23503 \+Module Management
23505 & Not applicable\cr
23515 @c This is the Texinfo version of the table. It renders poorly in pdf, hence
23516 @c the TeX version above for the printed version
23518 @c @multitable @columnfractions .3 .4 .4
23519 @multitable {Source Code Analyzer /}{Tool with HP Ada}{Tool with @value{EDITION}}
23521 @tab @i{Tool with HP Ada}
23522 @tab @i{Tool with @value{EDITION}}
23523 @item Code Management@*System
23526 @item Language-Sensitive@*Editor
23528 @tab emacs or HP LSE (Alpha)
23537 @tab OpenVMS Debug (I64)
23538 @item Source Code Analyzer /@*Cross Referencer
23542 @tab HP Digital Test@*Manager (DTM)
23544 @item Performance and@*Coverage Analyzer
23547 @item Module Management@*System
23549 @tab Not applicable
23556 @c **************************************
23557 @node Platform-Specific Information for the Run-Time Libraries
23558 @appendix Platform-Specific Information for the Run-Time Libraries
23559 @cindex Tasking and threads libraries
23560 @cindex Threads libraries and tasking
23561 @cindex Run-time libraries (platform-specific information)
23564 The GNAT run-time implementation may vary with respect to both the
23565 underlying threads library and the exception handling scheme.
23566 For threads support, one or more of the following are supplied:
23568 @item @b{native threads library}, a binding to the thread package from
23569 the underlying operating system
23571 @item @b{pthreads library} (Sparc Solaris only), a binding to the Solaris
23572 POSIX thread package
23576 For exception handling, either or both of two models are supplied:
23578 @item @b{Zero-Cost Exceptions} (``ZCX''),@footnote{
23579 Most programs should experience a substantial speed improvement by
23580 being compiled with a ZCX run-time.
23581 This is especially true for
23582 tasking applications or applications with many exception handlers.}
23583 @cindex Zero-Cost Exceptions
23584 @cindex ZCX (Zero-Cost Exceptions)
23585 which uses binder-generated tables that
23586 are interrogated at run time to locate a handler
23588 @item @b{setjmp / longjmp} (``SJLJ''),
23589 @cindex setjmp/longjmp Exception Model
23590 @cindex SJLJ (setjmp/longjmp Exception Model)
23591 which uses dynamically-set data to establish
23592 the set of handlers
23596 This appendix summarizes which combinations of threads and exception support
23597 are supplied on various GNAT platforms.
23598 It then shows how to select a particular library either
23599 permanently or temporarily,
23600 explains the properties of (and tradeoffs among) the various threads
23601 libraries, and provides some additional
23602 information about several specific platforms.
23605 * Summary of Run-Time Configurations::
23606 * Specifying a Run-Time Library::
23607 * Choosing the Scheduling Policy::
23608 * Solaris-Specific Considerations::
23609 * Linux-Specific Considerations::
23610 * AIX-Specific Considerations::
23611 * RTX-Specific Considerations::
23612 * HP-UX-Specific Considerations::
23615 @node Summary of Run-Time Configurations
23616 @section Summary of Run-Time Configurations
23618 @multitable @columnfractions .30 .70
23619 @item @b{alpha-openvms}
23620 @item @code{@ @ }@i{rts-native (default)}
23621 @item @code{@ @ @ @ }Tasking @tab native VMS threads
23622 @item @code{@ @ @ @ }Exceptions @tab ZCX
23624 @item @code{@ @ }@i{rts-sjlj}
23625 @item @code{@ @ @ @ }Tasking @tab native TRU64 threads
23626 @item @code{@ @ @ @ }Exceptions @tab SJLJ
23628 @item @b{ia64-hp_linux}
23629 @item @code{@ @ }@i{rts-native (default)}
23630 @item @code{@ @ @ @ }Tasking @tab pthread library
23631 @item @code{@ @ @ @ }Exceptions @tab ZCX
23633 @item @b{ia64-hpux}
23634 @item @code{@ @ }@i{rts-native (default)}
23635 @item @code{@ @ @ @ }Tasking @tab native HP-UX threads
23636 @item @code{@ @ @ @ }Exceptions @tab SJLJ
23638 @item @b{ia64-openvms}
23639 @item @code{@ @ }@i{rts-native (default)}
23640 @item @code{@ @ @ @ }Tasking @tab native VMS threads
23641 @item @code{@ @ @ @ }Exceptions @tab ZCX
23643 @item @b{ia64-sgi_linux}
23644 @item @code{@ @ }@i{rts-native (default)}
23645 @item @code{@ @ @ @ }Tasking @tab pthread library
23646 @item @code{@ @ @ @ }Exceptions @tab ZCX
23649 @item @code{@ @ }@i{rts-native (default)}
23650 @item @code{@ @ @ @ }Tasking @tab native HP-UX threads
23651 @item @code{@ @ @ @ }Exceptions @tab ZCX
23653 @item @code{@ @ }@i{rts-sjlj}
23654 @item @code{@ @ @ @ }Tasking @tab native HP-UX threads
23655 @item @code{@ @ @ @ }Exceptions @tab SJLJ
23658 @item @code{@ @ }@i{rts-native (default)}
23659 @item @code{@ @ @ @ }Tasking @tab native AIX threads
23660 @item @code{@ @ @ @ }Exceptions @tab ZCX
23662 @item @code{@ @ }@i{rts-sjlj}
23663 @item @code{@ @ @ @ }Tasking @tab native AIX threads
23664 @item @code{@ @ @ @ }Exceptions @tab SJLJ
23666 @item @b{ppc-darwin}
23667 @item @code{@ @ }@i{rts-native (default)}
23668 @item @code{@ @ @ @ }Tasking @tab native MacOS threads
23669 @item @code{@ @ @ @ }Exceptions @tab ZCX
23671 @item @b{sparc-solaris} @tab
23672 @item @code{@ @ }@i{rts-native (default)}
23673 @item @code{@ @ @ @ }Tasking @tab native Solaris threads library
23674 @item @code{@ @ @ @ }Exceptions @tab ZCX
23676 @item @code{@ @ }@i{rts-pthread}
23677 @item @code{@ @ @ @ }Tasking @tab pthread library
23678 @item @code{@ @ @ @ }Exceptions @tab ZCX
23680 @item @code{@ @ }@i{rts-sjlj}
23681 @item @code{@ @ @ @ }Tasking @tab native Solaris threads library
23682 @item @code{@ @ @ @ }Exceptions @tab SJLJ
23684 @item @b{sparc64-solaris} @tab
23685 @item @code{@ @ }@i{rts-native (default)}
23686 @item @code{@ @ @ @ }Tasking @tab native Solaris threads library
23687 @item @code{@ @ @ @ }Exceptions @tab ZCX
23689 @item @b{x86-linux}
23690 @item @code{@ @ }@i{rts-native (default)}
23691 @item @code{@ @ @ @ }Tasking @tab pthread library
23692 @item @code{@ @ @ @ }Exceptions @tab ZCX
23694 @item @code{@ @ }@i{rts-sjlj}
23695 @item @code{@ @ @ @ }Tasking @tab pthread library
23696 @item @code{@ @ @ @ }Exceptions @tab SJLJ
23699 @item @code{@ @ }@i{rts-native (default)}
23700 @item @code{@ @ @ @ }Tasking @tab native LynxOS threads
23701 @item @code{@ @ @ @ }Exceptions @tab SJLJ
23703 @item @b{x86-solaris}
23704 @item @code{@ @ }@i{rts-native (default)}
23705 @item @code{@ @ @ @ }Tasking @tab native Solaris threads
23706 @item @code{@ @ @ @ }Exceptions @tab ZCX
23708 @item @code{@ @ }@i{rts-sjlj}
23709 @item @code{@ @ @ @ }Tasking @tab native Solaris threads library
23710 @item @code{@ @ @ @ }Exceptions @tab SJLJ
23712 @item @b{x86-windows}
23713 @item @code{@ @ }@i{rts-native (default)}
23714 @item @code{@ @ @ @ }Tasking @tab native Win32 threads
23715 @item @code{@ @ @ @ }Exceptions @tab ZCX
23717 @item @code{@ @ }@i{rts-sjlj}
23718 @item @code{@ @ @ @ }Tasking @tab native Win32 threads
23719 @item @code{@ @ @ @ }Exceptions @tab SJLJ
23721 @item @b{x86-windows-rtx}
23722 @item @code{@ @ }@i{rts-rtx-rtss (default)}
23723 @item @code{@ @ @ @ }Tasking @tab RTX real-time subsystem RTSS threads (kernel mode)
23724 @item @code{@ @ @ @ }Exceptions @tab SJLJ
23726 @item @code{@ @ }@i{rts-rtx-w32}
23727 @item @code{@ @ @ @ }Tasking @tab RTX Win32 threads (user mode)
23728 @item @code{@ @ @ @ }Exceptions @tab ZCX
23730 @item @b{x86_64-linux}
23731 @item @code{@ @ }@i{rts-native (default)}
23732 @item @code{@ @ @ @ }Tasking @tab pthread library
23733 @item @code{@ @ @ @ }Exceptions @tab ZCX
23735 @item @code{@ @ }@i{rts-sjlj}
23736 @item @code{@ @ @ @ }Tasking @tab pthread library
23737 @item @code{@ @ @ @ }Exceptions @tab SJLJ
23741 @node Specifying a Run-Time Library
23742 @section Specifying a Run-Time Library
23745 The @file{adainclude} subdirectory containing the sources of the GNAT
23746 run-time library, and the @file{adalib} subdirectory containing the
23747 @file{ALI} files and the static and/or shared GNAT library, are located
23748 in the gcc target-dependent area:
23751 target=$prefix/lib/gcc/gcc-@i{dumpmachine}/gcc-@i{dumpversion}/
23755 As indicated above, on some platforms several run-time libraries are supplied.
23756 These libraries are installed in the target dependent area and
23757 contain a complete source and binary subdirectory. The detailed description
23758 below explains the differences between the different libraries in terms of
23759 their thread support.
23761 The default run-time library (when GNAT is installed) is @emph{rts-native}.
23762 This default run time is selected by the means of soft links.
23763 For example on x86-linux:
23769 +--- adainclude----------+
23771 +--- adalib-----------+ |
23773 +--- rts-native | |
23775 | +--- adainclude <---+
23777 | +--- adalib <----+
23788 If the @i{rts-sjlj} library is to be selected on a permanent basis,
23789 these soft links can be modified with the following commands:
23793 $ rm -f adainclude adalib
23794 $ ln -s rts-sjlj/adainclude adainclude
23795 $ ln -s rts-sjlj/adalib adalib
23799 Alternatively, you can specify @file{rts-sjlj/adainclude} in the file
23800 @file{$target/ada_source_path} and @file{rts-sjlj/adalib} in
23801 @file{$target/ada_object_path}.
23803 Selecting another run-time library temporarily can be
23804 achieved by using the @option{--RTS} switch, e.g., @option{--RTS=sjlj}
23805 @cindex @option{--RTS} option
23807 @node Choosing the Scheduling Policy
23808 @section Choosing the Scheduling Policy
23811 When using a POSIX threads implementation, you have a choice of several
23812 scheduling policies: @code{SCHED_FIFO},
23813 @cindex @code{SCHED_FIFO} scheduling policy
23815 @cindex @code{SCHED_RR} scheduling policy
23816 and @code{SCHED_OTHER}.
23817 @cindex @code{SCHED_OTHER} scheduling policy
23818 Typically, the default is @code{SCHED_OTHER}, while using @code{SCHED_FIFO}
23819 or @code{SCHED_RR} requires special (e.g., root) privileges.
23821 By default, GNAT uses the @code{SCHED_OTHER} policy. To specify
23823 @cindex @code{SCHED_FIFO} scheduling policy
23824 you can use one of the following:
23828 @code{pragma Time_Slice (0.0)}
23829 @cindex pragma Time_Slice
23831 the corresponding binder option @option{-T0}
23832 @cindex @option{-T0} option
23834 @code{pragma Task_Dispatching_Policy (FIFO_Within_Priorities)}
23835 @cindex pragma Task_Dispatching_Policy
23839 To specify @code{SCHED_RR},
23840 @cindex @code{SCHED_RR} scheduling policy
23841 you should use @code{pragma Time_Slice} with a
23842 value greater than @code{0.0}, or else use the corresponding @option{-T}
23845 @node Solaris-Specific Considerations
23846 @section Solaris-Specific Considerations
23847 @cindex Solaris Sparc threads libraries
23850 This section addresses some topics related to the various threads libraries
23854 * Solaris Threads Issues::
23857 @node Solaris Threads Issues
23858 @subsection Solaris Threads Issues
23861 GNAT under Solaris/Sparc 32 bits comes with an alternate tasking run-time
23862 library based on POSIX threads --- @emph{rts-pthread}.
23863 @cindex rts-pthread threads library
23864 This run-time library has the advantage of being mostly shared across all
23865 POSIX-compliant thread implementations, and it also provides under
23866 @w{Solaris 8} the @code{PTHREAD_PRIO_INHERIT}
23867 @cindex @code{PTHREAD_PRIO_INHERIT} policy (under rts-pthread)
23868 and @code{PTHREAD_PRIO_PROTECT}
23869 @cindex @code{PTHREAD_PRIO_PROTECT} policy (under rts-pthread)
23870 semantics that can be selected using the predefined pragma
23871 @code{Locking_Policy}
23872 @cindex pragma Locking_Policy (under rts-pthread)
23874 @code{Inheritance_Locking} and @code{Ceiling_Locking} as the policy.
23875 @cindex @code{Inheritance_Locking} (under rts-pthread)
23876 @cindex @code{Ceiling_Locking} (under rts-pthread)
23878 As explained above, the native run-time library is based on the Solaris thread
23879 library (@code{libthread}) and is the default library.
23881 When the Solaris threads library is used (this is the default), programs
23882 compiled with GNAT can automatically take advantage of
23883 and can thus execute on multiple processors.
23884 The user can alternatively specify a processor on which the program should run
23885 to emulate a single-processor system. The multiprocessor / uniprocessor choice
23887 setting the environment variable @env{GNAT_PROCESSOR}
23888 @cindex @env{GNAT_PROCESSOR} environment variable (on Sparc Solaris)
23889 to one of the following:
23893 Use the default configuration (run the program on all
23894 available processors) - this is the same as having @code{GNAT_PROCESSOR}
23898 Let the run-time implementation choose one processor and run the program on
23901 @item 0 .. Last_Proc
23902 Run the program on the specified processor.
23903 @code{Last_Proc} is equal to @code{_SC_NPROCESSORS_CONF - 1}
23904 (where @code{_SC_NPROCESSORS_CONF} is a system variable).
23907 @node Linux-Specific Considerations
23908 @section Linux-Specific Considerations
23909 @cindex Linux threads libraries
23912 On GNU/Linux without NPTL support (usually system with GNU C Library
23913 older than 2.3), the signal model is not POSIX compliant, which means
23914 that to send a signal to the process, you need to send the signal to all
23915 threads, e.g.@: by using @code{killpg()}.
23917 @node AIX-Specific Considerations
23918 @section AIX-Specific Considerations
23919 @cindex AIX resolver library
23922 On AIX, the resolver library initializes some internal structure on
23923 the first call to @code{get*by*} functions, which are used to implement
23924 @code{GNAT.Sockets.Get_Host_By_Name} and
23925 @code{GNAT.Sockets.Get_Host_By_Address}.
23926 If such initialization occurs within an Ada task, and the stack size for
23927 the task is the default size, a stack overflow may occur.
23929 To avoid this overflow, the user should either ensure that the first call
23930 to @code{GNAT.Sockets.Get_Host_By_Name} or
23931 @code{GNAT.Sockets.Get_Host_By_Addrss}
23932 occurs in the environment task, or use @code{pragma Storage_Size} to
23933 specify a sufficiently large size for the stack of the task that contains
23936 @node RTX-Specific Considerations
23937 @section RTX-Specific Considerations
23938 @cindex RTX libraries
23941 The Real-time Extension (RTX) to Windows is based on the Windows Win32
23942 API. Applications can be built to work in two different modes:
23946 Windows executables that run in Ring 3 to utilize memory protection
23947 (@emph{rts-rtx-w32}).
23950 Real-time subsystem (RTSS) executables that run in Ring 0, where
23951 performance can be optimized with RTSS applications taking precedent
23952 over all Windows applications (@emph{rts-rtx-rtss}). This mode requires
23953 the Microsoft linker to handle RTSS libraries.
23957 @node HP-UX-Specific Considerations
23958 @section HP-UX-Specific Considerations
23959 @cindex HP-UX Scheduling
23962 On HP-UX, appropriate privileges are required to change the scheduling
23963 parameters of a task. The calling process must have appropriate
23964 privileges or be a member of a group having @code{PRIV_RTSCHED} access to
23965 successfully change the scheduling parameters.
23967 By default, GNAT uses the @code{SCHED_HPUX} policy. To have access to the
23968 priority range 0-31 either the @code{FIFO_Within_Priorities} or the
23969 @code{Round_Robin_Within_Priorities} scheduling policies need to be set.
23971 To specify the @code{FIFO_Within_Priorities} scheduling policy you can use
23972 one of the following:
23976 @code{pragma Time_Slice (0.0)}
23977 @cindex pragma Time_Slice
23979 the corresponding binder option @option{-T0}
23980 @cindex @option{-T0} option
23982 @code{pragma Task_Dispatching_Policy (FIFO_Within_Priorities)}
23983 @cindex pragma Task_Dispatching_Policy
23987 To specify the @code{Round_Robin_Within_Priorities}, scheduling policy
23988 you should use @code{pragma Time_Slice} with a
23989 value greater than @code{0.0}, or use the corresponding @option{-T}
23990 binder option, or set the @code{pragma Task_Dispatching_Policy
23991 (Round_Robin_Within_Priorities)}.
23993 @c *******************************
23994 @node Example of Binder Output File
23995 @appendix Example of Binder Output File
23998 This Appendix displays the source code for @command{gnatbind}'s output
23999 file generated for a simple ``Hello World'' program.
24000 Comments have been added for clarification purposes.
24002 @smallexample @c adanocomment
24006 -- The package is called Ada_Main unless this name is actually used
24007 -- as a unit name in the partition, in which case some other unique
24011 package ada_main is
24013 Elab_Final_Code : Integer;
24014 pragma Import (C, Elab_Final_Code, "__gnat_inside_elab_final_code");
24016 -- The main program saves the parameters (argument count,
24017 -- argument values, environment pointer) in global variables
24018 -- for later access by other units including
24019 -- Ada.Command_Line.
24021 gnat_argc : Integer;
24022 gnat_argv : System.Address;
24023 gnat_envp : System.Address;
24025 -- The actual variables are stored in a library routine. This
24026 -- is useful for some shared library situations, where there
24027 -- are problems if variables are not in the library.
24029 pragma Import (C, gnat_argc);
24030 pragma Import (C, gnat_argv);
24031 pragma Import (C, gnat_envp);
24033 -- The exit status is similarly an external location
24035 gnat_exit_status : Integer;
24036 pragma Import (C, gnat_exit_status);
24038 GNAT_Version : constant String :=
24039 "GNAT Version: 6.0.0w (20061115)";
24040 pragma Export (C, GNAT_Version, "__gnat_version");
24042 -- This is the generated adafinal routine that performs
24043 -- finalization at the end of execution. In the case where
24044 -- Ada is the main program, this main program makes a call
24045 -- to adafinal at program termination.
24047 procedure adafinal;
24048 pragma Export (C, adafinal, "adafinal");
24050 -- This is the generated adainit routine that performs
24051 -- initialization at the start of execution. In the case
24052 -- where Ada is the main program, this main program makes
24053 -- a call to adainit at program startup.
24056 pragma Export (C, adainit, "adainit");
24058 -- This routine is called at the start of execution. It is
24059 -- a dummy routine that is used by the debugger to breakpoint
24060 -- at the start of execution.
24062 procedure Break_Start;
24063 pragma Import (C, Break_Start, "__gnat_break_start");
24065 -- This is the actual generated main program (it would be
24066 -- suppressed if the no main program switch were used). As
24067 -- required by standard system conventions, this program has
24068 -- the external name main.
24072 argv : System.Address;
24073 envp : System.Address)
24075 pragma Export (C, main, "main");
24077 -- The following set of constants give the version
24078 -- identification values for every unit in the bound
24079 -- partition. This identification is computed from all
24080 -- dependent semantic units, and corresponds to the
24081 -- string that would be returned by use of the
24082 -- Body_Version or Version attributes.
24084 type Version_32 is mod 2 ** 32;
24085 u00001 : constant Version_32 := 16#7880BEB3#;
24086 u00002 : constant Version_32 := 16#0D24CBD0#;
24087 u00003 : constant Version_32 := 16#3283DBEB#;
24088 u00004 : constant Version_32 := 16#2359F9ED#;
24089 u00005 : constant Version_32 := 16#664FB847#;
24090 u00006 : constant Version_32 := 16#68E803DF#;
24091 u00007 : constant Version_32 := 16#5572E604#;
24092 u00008 : constant Version_32 := 16#46B173D8#;
24093 u00009 : constant Version_32 := 16#156A40CF#;
24094 u00010 : constant Version_32 := 16#033DABE0#;
24095 u00011 : constant Version_32 := 16#6AB38FEA#;
24096 u00012 : constant Version_32 := 16#22B6217D#;
24097 u00013 : constant Version_32 := 16#68A22947#;
24098 u00014 : constant Version_32 := 16#18CC4A56#;
24099 u00015 : constant Version_32 := 16#08258E1B#;
24100 u00016 : constant Version_32 := 16#367D5222#;
24101 u00017 : constant Version_32 := 16#20C9ECA4#;
24102 u00018 : constant Version_32 := 16#50D32CB6#;
24103 u00019 : constant Version_32 := 16#39A8BB77#;
24104 u00020 : constant Version_32 := 16#5CF8FA2B#;
24105 u00021 : constant Version_32 := 16#2F1EB794#;
24106 u00022 : constant Version_32 := 16#31AB6444#;
24107 u00023 : constant Version_32 := 16#1574B6E9#;
24108 u00024 : constant Version_32 := 16#5109C189#;
24109 u00025 : constant Version_32 := 16#56D770CD#;
24110 u00026 : constant Version_32 := 16#02F9DE3D#;
24111 u00027 : constant Version_32 := 16#08AB6B2C#;
24112 u00028 : constant Version_32 := 16#3FA37670#;
24113 u00029 : constant Version_32 := 16#476457A0#;
24114 u00030 : constant Version_32 := 16#731E1B6E#;
24115 u00031 : constant Version_32 := 16#23C2E789#;
24116 u00032 : constant Version_32 := 16#0F1BD6A1#;
24117 u00033 : constant Version_32 := 16#7C25DE96#;
24118 u00034 : constant Version_32 := 16#39ADFFA2#;
24119 u00035 : constant Version_32 := 16#571DE3E7#;
24120 u00036 : constant Version_32 := 16#5EB646AB#;
24121 u00037 : constant Version_32 := 16#4249379B#;
24122 u00038 : constant Version_32 := 16#0357E00A#;
24123 u00039 : constant Version_32 := 16#3784FB72#;
24124 u00040 : constant Version_32 := 16#2E723019#;
24125 u00041 : constant Version_32 := 16#623358EA#;
24126 u00042 : constant Version_32 := 16#107F9465#;
24127 u00043 : constant Version_32 := 16#6843F68A#;
24128 u00044 : constant Version_32 := 16#63305874#;
24129 u00045 : constant Version_32 := 16#31E56CE1#;
24130 u00046 : constant Version_32 := 16#02917970#;
24131 u00047 : constant Version_32 := 16#6CCBA70E#;
24132 u00048 : constant Version_32 := 16#41CD4204#;
24133 u00049 : constant Version_32 := 16#572E3F58#;
24134 u00050 : constant Version_32 := 16#20729FF5#;
24135 u00051 : constant Version_32 := 16#1D4F93E8#;
24136 u00052 : constant Version_32 := 16#30B2EC3D#;
24137 u00053 : constant Version_32 := 16#34054F96#;
24138 u00054 : constant Version_32 := 16#5A199860#;
24139 u00055 : constant Version_32 := 16#0E7F912B#;
24140 u00056 : constant Version_32 := 16#5760634A#;
24141 u00057 : constant Version_32 := 16#5D851835#;
24143 -- The following Export pragmas export the version numbers
24144 -- with symbolic names ending in B (for body) or S
24145 -- (for spec) so that they can be located in a link. The
24146 -- information provided here is sufficient to track down
24147 -- the exact versions of units used in a given build.
24149 pragma Export (C, u00001, "helloB");
24150 pragma Export (C, u00002, "system__standard_libraryB");
24151 pragma Export (C, u00003, "system__standard_libraryS");
24152 pragma Export (C, u00004, "adaS");
24153 pragma Export (C, u00005, "ada__text_ioB");
24154 pragma Export (C, u00006, "ada__text_ioS");
24155 pragma Export (C, u00007, "ada__exceptionsB");
24156 pragma Export (C, u00008, "ada__exceptionsS");
24157 pragma Export (C, u00009, "gnatS");
24158 pragma Export (C, u00010, "gnat__heap_sort_aB");
24159 pragma Export (C, u00011, "gnat__heap_sort_aS");
24160 pragma Export (C, u00012, "systemS");
24161 pragma Export (C, u00013, "system__exception_tableB");
24162 pragma Export (C, u00014, "system__exception_tableS");
24163 pragma Export (C, u00015, "gnat__htableB");
24164 pragma Export (C, u00016, "gnat__htableS");
24165 pragma Export (C, u00017, "system__exceptionsS");
24166 pragma Export (C, u00018, "system__machine_state_operationsB");
24167 pragma Export (C, u00019, "system__machine_state_operationsS");
24168 pragma Export (C, u00020, "system__machine_codeS");
24169 pragma Export (C, u00021, "system__storage_elementsB");
24170 pragma Export (C, u00022, "system__storage_elementsS");
24171 pragma Export (C, u00023, "system__secondary_stackB");
24172 pragma Export (C, u00024, "system__secondary_stackS");
24173 pragma Export (C, u00025, "system__parametersB");
24174 pragma Export (C, u00026, "system__parametersS");
24175 pragma Export (C, u00027, "system__soft_linksB");
24176 pragma Export (C, u00028, "system__soft_linksS");
24177 pragma Export (C, u00029, "system__stack_checkingB");
24178 pragma Export (C, u00030, "system__stack_checkingS");
24179 pragma Export (C, u00031, "system__tracebackB");
24180 pragma Export (C, u00032, "system__tracebackS");
24181 pragma Export (C, u00033, "ada__streamsS");
24182 pragma Export (C, u00034, "ada__tagsB");
24183 pragma Export (C, u00035, "ada__tagsS");
24184 pragma Export (C, u00036, "system__string_opsB");
24185 pragma Export (C, u00037, "system__string_opsS");
24186 pragma Export (C, u00038, "interfacesS");
24187 pragma Export (C, u00039, "interfaces__c_streamsB");
24188 pragma Export (C, u00040, "interfaces__c_streamsS");
24189 pragma Export (C, u00041, "system__file_ioB");
24190 pragma Export (C, u00042, "system__file_ioS");
24191 pragma Export (C, u00043, "ada__finalizationB");
24192 pragma Export (C, u00044, "ada__finalizationS");
24193 pragma Export (C, u00045, "system__finalization_rootB");
24194 pragma Export (C, u00046, "system__finalization_rootS");
24195 pragma Export (C, u00047, "system__finalization_implementationB");
24196 pragma Export (C, u00048, "system__finalization_implementationS");
24197 pragma Export (C, u00049, "system__string_ops_concat_3B");
24198 pragma Export (C, u00050, "system__string_ops_concat_3S");
24199 pragma Export (C, u00051, "system__stream_attributesB");
24200 pragma Export (C, u00052, "system__stream_attributesS");
24201 pragma Export (C, u00053, "ada__io_exceptionsS");
24202 pragma Export (C, u00054, "system__unsigned_typesS");
24203 pragma Export (C, u00055, "system__file_control_blockS");
24204 pragma Export (C, u00056, "ada__finalization__list_controllerB");
24205 pragma Export (C, u00057, "ada__finalization__list_controllerS");
24207 -- BEGIN ELABORATION ORDER
24210 -- gnat.heap_sort_a (spec)
24211 -- gnat.heap_sort_a (body)
24212 -- gnat.htable (spec)
24213 -- gnat.htable (body)
24214 -- interfaces (spec)
24216 -- system.machine_code (spec)
24217 -- system.parameters (spec)
24218 -- system.parameters (body)
24219 -- interfaces.c_streams (spec)
24220 -- interfaces.c_streams (body)
24221 -- system.standard_library (spec)
24222 -- ada.exceptions (spec)
24223 -- system.exception_table (spec)
24224 -- system.exception_table (body)
24225 -- ada.io_exceptions (spec)
24226 -- system.exceptions (spec)
24227 -- system.storage_elements (spec)
24228 -- system.storage_elements (body)
24229 -- system.machine_state_operations (spec)
24230 -- system.machine_state_operations (body)
24231 -- system.secondary_stack (spec)
24232 -- system.stack_checking (spec)
24233 -- system.soft_links (spec)
24234 -- system.soft_links (body)
24235 -- system.stack_checking (body)
24236 -- system.secondary_stack (body)
24237 -- system.standard_library (body)
24238 -- system.string_ops (spec)
24239 -- system.string_ops (body)
24242 -- ada.streams (spec)
24243 -- system.finalization_root (spec)
24244 -- system.finalization_root (body)
24245 -- system.string_ops_concat_3 (spec)
24246 -- system.string_ops_concat_3 (body)
24247 -- system.traceback (spec)
24248 -- system.traceback (body)
24249 -- ada.exceptions (body)
24250 -- system.unsigned_types (spec)
24251 -- system.stream_attributes (spec)
24252 -- system.stream_attributes (body)
24253 -- system.finalization_implementation (spec)
24254 -- system.finalization_implementation (body)
24255 -- ada.finalization (spec)
24256 -- ada.finalization (body)
24257 -- ada.finalization.list_controller (spec)
24258 -- ada.finalization.list_controller (body)
24259 -- system.file_control_block (spec)
24260 -- system.file_io (spec)
24261 -- system.file_io (body)
24262 -- ada.text_io (spec)
24263 -- ada.text_io (body)
24265 -- END ELABORATION ORDER
24269 -- The following source file name pragmas allow the generated file
24270 -- names to be unique for different main programs. They are needed
24271 -- since the package name will always be Ada_Main.
24273 pragma Source_File_Name (ada_main, Spec_File_Name => "b~hello.ads");
24274 pragma Source_File_Name (ada_main, Body_File_Name => "b~hello.adb");
24276 -- Generated package body for Ada_Main starts here
24278 package body ada_main is
24280 -- The actual finalization is performed by calling the
24281 -- library routine in System.Standard_Library.Adafinal
24283 procedure Do_Finalize;
24284 pragma Import (C, Do_Finalize, "system__standard_library__adafinal");
24291 procedure adainit is
24293 -- These booleans are set to True once the associated unit has
24294 -- been elaborated. It is also used to avoid elaborating the
24295 -- same unit twice.
24298 pragma Import (Ada, E040, "interfaces__c_streams_E");
24301 pragma Import (Ada, E008, "ada__exceptions_E");
24304 pragma Import (Ada, E014, "system__exception_table_E");
24307 pragma Import (Ada, E053, "ada__io_exceptions_E");
24310 pragma Import (Ada, E017, "system__exceptions_E");
24313 pragma Import (Ada, E024, "system__secondary_stack_E");
24316 pragma Import (Ada, E030, "system__stack_checking_E");
24319 pragma Import (Ada, E028, "system__soft_links_E");
24322 pragma Import (Ada, E035, "ada__tags_E");
24325 pragma Import (Ada, E033, "ada__streams_E");
24328 pragma Import (Ada, E046, "system__finalization_root_E");
24331 pragma Import (Ada, E048, "system__finalization_implementation_E");
24334 pragma Import (Ada, E044, "ada__finalization_E");
24337 pragma Import (Ada, E057, "ada__finalization__list_controller_E");
24340 pragma Import (Ada, E055, "system__file_control_block_E");
24343 pragma Import (Ada, E042, "system__file_io_E");
24346 pragma Import (Ada, E006, "ada__text_io_E");
24348 -- Set_Globals is a library routine that stores away the
24349 -- value of the indicated set of global values in global
24350 -- variables within the library.
24352 procedure Set_Globals
24353 (Main_Priority : Integer;
24354 Time_Slice_Value : Integer;
24355 WC_Encoding : Character;
24356 Locking_Policy : Character;
24357 Queuing_Policy : Character;
24358 Task_Dispatching_Policy : Character;
24359 Adafinal : System.Address;
24360 Unreserve_All_Interrupts : Integer;
24361 Exception_Tracebacks : Integer);
24362 @findex __gnat_set_globals
24363 pragma Import (C, Set_Globals, "__gnat_set_globals");
24365 -- SDP_Table_Build is a library routine used to build the
24366 -- exception tables. See unit Ada.Exceptions in files
24367 -- a-except.ads/adb for full details of how zero cost
24368 -- exception handling works. This procedure, the call to
24369 -- it, and the two following tables are all omitted if the
24370 -- build is in longjmp/setjmp exception mode.
24372 @findex SDP_Table_Build
24373 @findex Zero Cost Exceptions
24374 procedure SDP_Table_Build
24375 (SDP_Addresses : System.Address;
24376 SDP_Count : Natural;
24377 Elab_Addresses : System.Address;
24378 Elab_Addr_Count : Natural);
24379 pragma Import (C, SDP_Table_Build, "__gnat_SDP_Table_Build");
24381 -- Table of Unit_Exception_Table addresses. Used for zero
24382 -- cost exception handling to build the top level table.
24384 ST : aliased constant array (1 .. 23) of System.Address := (
24386 Ada.Text_Io'UET_Address,
24387 Ada.Exceptions'UET_Address,
24388 Gnat.Heap_Sort_A'UET_Address,
24389 System.Exception_Table'UET_Address,
24390 System.Machine_State_Operations'UET_Address,
24391 System.Secondary_Stack'UET_Address,
24392 System.Parameters'UET_Address,
24393 System.Soft_Links'UET_Address,
24394 System.Stack_Checking'UET_Address,
24395 System.Traceback'UET_Address,
24396 Ada.Streams'UET_Address,
24397 Ada.Tags'UET_Address,
24398 System.String_Ops'UET_Address,
24399 Interfaces.C_Streams'UET_Address,
24400 System.File_Io'UET_Address,
24401 Ada.Finalization'UET_Address,
24402 System.Finalization_Root'UET_Address,
24403 System.Finalization_Implementation'UET_Address,
24404 System.String_Ops_Concat_3'UET_Address,
24405 System.Stream_Attributes'UET_Address,
24406 System.File_Control_Block'UET_Address,
24407 Ada.Finalization.List_Controller'UET_Address);
24409 -- Table of addresses of elaboration routines. Used for
24410 -- zero cost exception handling to make sure these
24411 -- addresses are included in the top level procedure
24414 EA : aliased constant array (1 .. 23) of System.Address := (
24415 adainit'Code_Address,
24416 Do_Finalize'Code_Address,
24417 Ada.Exceptions'Elab_Spec'Address,
24418 System.Exceptions'Elab_Spec'Address,
24419 Interfaces.C_Streams'Elab_Spec'Address,
24420 System.Exception_Table'Elab_Body'Address,
24421 Ada.Io_Exceptions'Elab_Spec'Address,
24422 System.Stack_Checking'Elab_Spec'Address,
24423 System.Soft_Links'Elab_Body'Address,
24424 System.Secondary_Stack'Elab_Body'Address,
24425 Ada.Tags'Elab_Spec'Address,
24426 Ada.Tags'Elab_Body'Address,
24427 Ada.Streams'Elab_Spec'Address,
24428 System.Finalization_Root'Elab_Spec'Address,
24429 Ada.Exceptions'Elab_Body'Address,
24430 System.Finalization_Implementation'Elab_Spec'Address,
24431 System.Finalization_Implementation'Elab_Body'Address,
24432 Ada.Finalization'Elab_Spec'Address,
24433 Ada.Finalization.List_Controller'Elab_Spec'Address,
24434 System.File_Control_Block'Elab_Spec'Address,
24435 System.File_Io'Elab_Body'Address,
24436 Ada.Text_Io'Elab_Spec'Address,
24437 Ada.Text_Io'Elab_Body'Address);
24439 -- Start of processing for adainit
24443 -- Call SDP_Table_Build to build the top level procedure
24444 -- table for zero cost exception handling (omitted in
24445 -- longjmp/setjmp mode).
24447 SDP_Table_Build (ST'Address, 23, EA'Address, 23);
24449 -- Call Set_Globals to record various information for
24450 -- this partition. The values are derived by the binder
24451 -- from information stored in the ali files by the compiler.
24453 @findex __gnat_set_globals
24455 (Main_Priority => -1,
24456 -- Priority of main program, -1 if no pragma Priority used
24458 Time_Slice_Value => -1,
24459 -- Time slice from Time_Slice pragma, -1 if none used
24461 WC_Encoding => 'b',
24462 -- Wide_Character encoding used, default is brackets
24464 Locking_Policy => ' ',
24465 -- Locking_Policy used, default of space means not
24466 -- specified, otherwise it is the first character of
24467 -- the policy name.
24469 Queuing_Policy => ' ',
24470 -- Queuing_Policy used, default of space means not
24471 -- specified, otherwise it is the first character of
24472 -- the policy name.
24474 Task_Dispatching_Policy => ' ',
24475 -- Task_Dispatching_Policy used, default of space means
24476 -- not specified, otherwise first character of the
24479 Adafinal => System.Null_Address,
24480 -- Address of Adafinal routine, not used anymore
24482 Unreserve_All_Interrupts => 0,
24483 -- Set true if pragma Unreserve_All_Interrupts was used
24485 Exception_Tracebacks => 0);
24486 -- Indicates if exception tracebacks are enabled
24488 Elab_Final_Code := 1;
24490 -- Now we have the elaboration calls for all units in the partition.
24491 -- The Elab_Spec and Elab_Body attributes generate references to the
24492 -- implicit elaboration procedures generated by the compiler for
24493 -- each unit that requires elaboration.
24496 Interfaces.C_Streams'Elab_Spec;
24500 Ada.Exceptions'Elab_Spec;
24503 System.Exception_Table'Elab_Body;
24507 Ada.Io_Exceptions'Elab_Spec;
24511 System.Exceptions'Elab_Spec;
24515 System.Stack_Checking'Elab_Spec;
24518 System.Soft_Links'Elab_Body;
24523 System.Secondary_Stack'Elab_Body;
24527 Ada.Tags'Elab_Spec;
24530 Ada.Tags'Elab_Body;
24534 Ada.Streams'Elab_Spec;
24538 System.Finalization_Root'Elab_Spec;
24542 Ada.Exceptions'Elab_Body;
24546 System.Finalization_Implementation'Elab_Spec;
24549 System.Finalization_Implementation'Elab_Body;
24553 Ada.Finalization'Elab_Spec;
24557 Ada.Finalization.List_Controller'Elab_Spec;
24561 System.File_Control_Block'Elab_Spec;
24565 System.File_Io'Elab_Body;
24569 Ada.Text_Io'Elab_Spec;
24572 Ada.Text_Io'Elab_Body;
24576 Elab_Final_Code := 0;
24584 procedure adafinal is
24593 -- main is actually a function, as in the ANSI C standard,
24594 -- defined to return the exit status. The three parameters
24595 -- are the argument count, argument values and environment
24598 @findex Main Program
24601 argv : System.Address;
24602 envp : System.Address)
24605 -- The initialize routine performs low level system
24606 -- initialization using a standard library routine which
24607 -- sets up signal handling and performs any other
24608 -- required setup. The routine can be found in file
24611 @findex __gnat_initialize
24612 procedure initialize;
24613 pragma Import (C, initialize, "__gnat_initialize");
24615 -- The finalize routine performs low level system
24616 -- finalization using a standard library routine. The
24617 -- routine is found in file a-final.c and in the standard
24618 -- distribution is a dummy routine that does nothing, so
24619 -- really this is a hook for special user finalization.
24621 @findex __gnat_finalize
24622 procedure finalize;
24623 pragma Import (C, finalize, "__gnat_finalize");
24625 -- We get to the main program of the partition by using
24626 -- pragma Import because if we try to with the unit and
24627 -- call it Ada style, then not only do we waste time
24628 -- recompiling it, but also, we don't really know the right
24629 -- switches (e.g.@: identifier character set) to be used
24632 procedure Ada_Main_Program;
24633 pragma Import (Ada, Ada_Main_Program, "_ada_hello");
24635 -- Start of processing for main
24638 -- Save global variables
24644 -- Call low level system initialization
24648 -- Call our generated Ada initialization routine
24652 -- This is the point at which we want the debugger to get
24657 -- Now we call the main program of the partition
24661 -- Perform Ada finalization
24665 -- Perform low level system finalization
24669 -- Return the proper exit status
24670 return (gnat_exit_status);
24673 -- This section is entirely comments, so it has no effect on the
24674 -- compilation of the Ada_Main package. It provides the list of
24675 -- object files and linker options, as well as some standard
24676 -- libraries needed for the link. The gnatlink utility parses
24677 -- this b~hello.adb file to read these comment lines to generate
24678 -- the appropriate command line arguments for the call to the
24679 -- system linker. The BEGIN/END lines are used for sentinels for
24680 -- this parsing operation.
24682 -- The exact file names will of course depend on the environment,
24683 -- host/target and location of files on the host system.
24685 @findex Object file list
24686 -- BEGIN Object file/option list
24689 -- -L/usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/
24690 -- /usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/libgnat.a
24691 -- END Object file/option list
24697 The Ada code in the above example is exactly what is generated by the
24698 binder. We have added comments to more clearly indicate the function
24699 of each part of the generated @code{Ada_Main} package.
24701 The code is standard Ada in all respects, and can be processed by any
24702 tools that handle Ada. In particular, it is possible to use the debugger
24703 in Ada mode to debug the generated @code{Ada_Main} package. For example,
24704 suppose that for reasons that you do not understand, your program is crashing
24705 during elaboration of the body of @code{Ada.Text_IO}. To locate this bug,
24706 you can place a breakpoint on the call:
24708 @smallexample @c ada
24709 Ada.Text_Io'Elab_Body;
24713 and trace the elaboration routine for this package to find out where
24714 the problem might be (more usually of course you would be debugging
24715 elaboration code in your own application).
24717 @node Elaboration Order Handling in GNAT
24718 @appendix Elaboration Order Handling in GNAT
24719 @cindex Order of elaboration
24720 @cindex Elaboration control
24723 * Elaboration Code::
24724 * Checking the Elaboration Order::
24725 * Controlling the Elaboration Order::
24726 * Controlling Elaboration in GNAT - Internal Calls::
24727 * Controlling Elaboration in GNAT - External Calls::
24728 * Default Behavior in GNAT - Ensuring Safety::
24729 * Treatment of Pragma Elaborate::
24730 * Elaboration Issues for Library Tasks::
24731 * Mixing Elaboration Models::
24732 * What to Do If the Default Elaboration Behavior Fails::
24733 * Elaboration for Dispatching Calls::
24734 * Summary of Procedures for Elaboration Control::
24735 * Other Elaboration Order Considerations::
24739 This chapter describes the handling of elaboration code in Ada and
24740 in GNAT, and discusses how the order of elaboration of program units can
24741 be controlled in GNAT, either automatically or with explicit programming
24744 @node Elaboration Code
24745 @section Elaboration Code
24748 Ada provides rather general mechanisms for executing code at elaboration
24749 time, that is to say before the main program starts executing. Such code arises
24753 @item Initializers for variables.
24754 Variables declared at the library level, in package specs or bodies, can
24755 require initialization that is performed at elaboration time, as in:
24756 @smallexample @c ada
24758 Sqrt_Half : Float := Sqrt (0.5);
24762 @item Package initialization code
24763 Code in a @code{BEGIN-END} section at the outer level of a package body is
24764 executed as part of the package body elaboration code.
24766 @item Library level task allocators
24767 Tasks that are declared using task allocators at the library level
24768 start executing immediately and hence can execute at elaboration time.
24772 Subprogram calls are possible in any of these contexts, which means that
24773 any arbitrary part of the program may be executed as part of the elaboration
24774 code. It is even possible to write a program which does all its work at
24775 elaboration time, with a null main program, although stylistically this
24776 would usually be considered an inappropriate way to structure
24779 An important concern arises in the context of elaboration code:
24780 we have to be sure that it is executed in an appropriate order. What we
24781 have is a series of elaboration code sections, potentially one section
24782 for each unit in the program. It is important that these execute
24783 in the correct order. Correctness here means that, taking the above
24784 example of the declaration of @code{Sqrt_Half},
24785 if some other piece of
24786 elaboration code references @code{Sqrt_Half},
24787 then it must run after the
24788 section of elaboration code that contains the declaration of
24791 There would never be any order of elaboration problem if we made a rule
24792 that whenever you @code{with} a unit, you must elaborate both the spec and body
24793 of that unit before elaborating the unit doing the @code{with}'ing:
24795 @smallexample @c ada
24799 package Unit_2 is @dots{}
24805 would require that both the body and spec of @code{Unit_1} be elaborated
24806 before the spec of @code{Unit_2}. However, a rule like that would be far too
24807 restrictive. In particular, it would make it impossible to have routines
24808 in separate packages that were mutually recursive.
24810 You might think that a clever enough compiler could look at the actual
24811 elaboration code and determine an appropriate correct order of elaboration,
24812 but in the general case, this is not possible. Consider the following
24815 In the body of @code{Unit_1}, we have a procedure @code{Func_1}
24817 the variable @code{Sqrt_1}, which is declared in the elaboration code
24818 of the body of @code{Unit_1}:
24820 @smallexample @c ada
24822 Sqrt_1 : Float := Sqrt (0.1);
24827 The elaboration code of the body of @code{Unit_1} also contains:
24829 @smallexample @c ada
24832 if expression_1 = 1 then
24833 Q := Unit_2.Func_2;
24840 @code{Unit_2} is exactly parallel,
24841 it has a procedure @code{Func_2} that references
24842 the variable @code{Sqrt_2}, which is declared in the elaboration code of
24843 the body @code{Unit_2}:
24845 @smallexample @c ada
24847 Sqrt_2 : Float := Sqrt (0.1);
24852 The elaboration code of the body of @code{Unit_2} also contains:
24854 @smallexample @c ada
24857 if expression_2 = 2 then
24858 Q := Unit_1.Func_1;
24865 Now the question is, which of the following orders of elaboration is
24890 If you carefully analyze the flow here, you will see that you cannot tell
24891 at compile time the answer to this question.
24892 If @code{expression_1} is not equal to 1,
24893 and @code{expression_2} is not equal to 2,
24894 then either order is acceptable, because neither of the function calls is
24895 executed. If both tests evaluate to true, then neither order is acceptable
24896 and in fact there is no correct order.
24898 If one of the two expressions is true, and the other is false, then one
24899 of the above orders is correct, and the other is incorrect. For example,
24900 if @code{expression_1} /= 1 and @code{expression_2} = 2,
24901 then the call to @code{Func_1}
24902 will occur, but not the call to @code{Func_2.}
24903 This means that it is essential
24904 to elaborate the body of @code{Unit_1} before
24905 the body of @code{Unit_2}, so the first
24906 order of elaboration is correct and the second is wrong.
24908 By making @code{expression_1} and @code{expression_2}
24909 depend on input data, or perhaps
24910 the time of day, we can make it impossible for the compiler or binder
24911 to figure out which of these expressions will be true, and hence it
24912 is impossible to guarantee a safe order of elaboration at run time.
24914 @node Checking the Elaboration Order
24915 @section Checking the Elaboration Order
24918 In some languages that involve the same kind of elaboration problems,
24919 e.g.@: Java and C++, the programmer is expected to worry about these
24920 ordering problems himself, and it is common to
24921 write a program in which an incorrect elaboration order gives
24922 surprising results, because it references variables before they
24924 Ada is designed to be a safe language, and a programmer-beware approach is
24925 clearly not sufficient. Consequently, the language provides three lines
24929 @item Standard rules
24930 Some standard rules restrict the possible choice of elaboration
24931 order. In particular, if you @code{with} a unit, then its spec is always
24932 elaborated before the unit doing the @code{with}. Similarly, a parent
24933 spec is always elaborated before the child spec, and finally
24934 a spec is always elaborated before its corresponding body.
24936 @item Dynamic elaboration checks
24937 @cindex Elaboration checks
24938 @cindex Checks, elaboration
24939 Dynamic checks are made at run time, so that if some entity is accessed
24940 before it is elaborated (typically by means of a subprogram call)
24941 then the exception (@code{Program_Error}) is raised.
24943 @item Elaboration control
24944 Facilities are provided for the programmer to specify the desired order
24948 Let's look at these facilities in more detail. First, the rules for
24949 dynamic checking. One possible rule would be simply to say that the
24950 exception is raised if you access a variable which has not yet been
24951 elaborated. The trouble with this approach is that it could require
24952 expensive checks on every variable reference. Instead Ada has two
24953 rules which are a little more restrictive, but easier to check, and
24957 @item Restrictions on calls
24958 A subprogram can only be called at elaboration time if its body
24959 has been elaborated. The rules for elaboration given above guarantee
24960 that the spec of the subprogram has been elaborated before the
24961 call, but not the body. If this rule is violated, then the
24962 exception @code{Program_Error} is raised.
24964 @item Restrictions on instantiations
24965 A generic unit can only be instantiated if the body of the generic
24966 unit has been elaborated. Again, the rules for elaboration given above
24967 guarantee that the spec of the generic unit has been elaborated
24968 before the instantiation, but not the body. If this rule is
24969 violated, then the exception @code{Program_Error} is raised.
24973 The idea is that if the body has been elaborated, then any variables
24974 it references must have been elaborated; by checking for the body being
24975 elaborated we guarantee that none of its references causes any
24976 trouble. As we noted above, this is a little too restrictive, because a
24977 subprogram that has no non-local references in its body may in fact be safe
24978 to call. However, it really would be unsafe to rely on this, because
24979 it would mean that the caller was aware of details of the implementation
24980 in the body. This goes against the basic tenets of Ada.
24982 A plausible implementation can be described as follows.
24983 A Boolean variable is associated with each subprogram
24984 and each generic unit. This variable is initialized to False, and is set to
24985 True at the point body is elaborated. Every call or instantiation checks the
24986 variable, and raises @code{Program_Error} if the variable is False.
24988 Note that one might think that it would be good enough to have one Boolean
24989 variable for each package, but that would not deal with cases of trying
24990 to call a body in the same package as the call
24991 that has not been elaborated yet.
24992 Of course a compiler may be able to do enough analysis to optimize away
24993 some of the Boolean variables as unnecessary, and @code{GNAT} indeed
24994 does such optimizations, but still the easiest conceptual model is to
24995 think of there being one variable per subprogram.
24997 @node Controlling the Elaboration Order
24998 @section Controlling the Elaboration Order
25001 In the previous section we discussed the rules in Ada which ensure
25002 that @code{Program_Error} is raised if an incorrect elaboration order is
25003 chosen. This prevents erroneous executions, but we need mechanisms to
25004 specify a correct execution and avoid the exception altogether.
25005 To achieve this, Ada provides a number of features for controlling
25006 the order of elaboration. We discuss these features in this section.
25008 First, there are several ways of indicating to the compiler that a given
25009 unit has no elaboration problems:
25012 @item packages that do not require a body
25013 A library package that does not require a body does not permit
25014 a body (this rule was introduced in Ada 95).
25015 Thus if we have a such a package, as in:
25017 @smallexample @c ada
25020 package Definitions is
25022 type m is new integer;
25024 type a is array (1 .. 10) of m;
25025 type b is array (1 .. 20) of m;
25033 A package that @code{with}'s @code{Definitions} may safely instantiate
25034 @code{Definitions.Subp} because the compiler can determine that there
25035 definitely is no package body to worry about in this case
25038 @cindex pragma Pure
25040 Places sufficient restrictions on a unit to guarantee that
25041 no call to any subprogram in the unit can result in an
25042 elaboration problem. This means that the compiler does not need
25043 to worry about the point of elaboration of such units, and in
25044 particular, does not need to check any calls to any subprograms
25047 @item pragma Preelaborate
25048 @findex Preelaborate
25049 @cindex pragma Preelaborate
25050 This pragma places slightly less stringent restrictions on a unit than
25052 but these restrictions are still sufficient to ensure that there
25053 are no elaboration problems with any calls to the unit.
25055 @item pragma Elaborate_Body
25056 @findex Elaborate_Body
25057 @cindex pragma Elaborate_Body
25058 This pragma requires that the body of a unit be elaborated immediately
25059 after its spec. Suppose a unit @code{A} has such a pragma,
25060 and unit @code{B} does
25061 a @code{with} of unit @code{A}. Recall that the standard rules require
25062 the spec of unit @code{A}
25063 to be elaborated before the @code{with}'ing unit; given the pragma in
25064 @code{A}, we also know that the body of @code{A}
25065 will be elaborated before @code{B}, so
25066 that calls to @code{A} are safe and do not need a check.
25071 unlike pragma @code{Pure} and pragma @code{Preelaborate},
25073 @code{Elaborate_Body} does not guarantee that the program is
25074 free of elaboration problems, because it may not be possible
25075 to satisfy the requested elaboration order.
25076 Let's go back to the example with @code{Unit_1} and @code{Unit_2}.
25078 marks @code{Unit_1} as @code{Elaborate_Body},
25079 and not @code{Unit_2,} then the order of
25080 elaboration will be:
25092 Now that means that the call to @code{Func_1} in @code{Unit_2}
25093 need not be checked,
25094 it must be safe. But the call to @code{Func_2} in
25095 @code{Unit_1} may still fail if
25096 @code{Expression_1} is equal to 1,
25097 and the programmer must still take
25098 responsibility for this not being the case.
25100 If all units carry a pragma @code{Elaborate_Body}, then all problems are
25101 eliminated, except for calls entirely within a body, which are
25102 in any case fully under programmer control. However, using the pragma
25103 everywhere is not always possible.
25104 In particular, for our @code{Unit_1}/@code{Unit_2} example, if
25105 we marked both of them as having pragma @code{Elaborate_Body}, then
25106 clearly there would be no possible elaboration order.
25108 The above pragmas allow a server to guarantee safe use by clients, and
25109 clearly this is the preferable approach. Consequently a good rule
25110 is to mark units as @code{Pure} or @code{Preelaborate} if possible,
25111 and if this is not possible,
25112 mark them as @code{Elaborate_Body} if possible.
25113 As we have seen, there are situations where neither of these
25114 three pragmas can be used.
25115 So we also provide methods for clients to control the
25116 order of elaboration of the servers on which they depend:
25119 @item pragma Elaborate (unit)
25121 @cindex pragma Elaborate
25122 This pragma is placed in the context clause, after a @code{with} clause,
25123 and it requires that the body of the named unit be elaborated before
25124 the unit in which the pragma occurs. The idea is to use this pragma
25125 if the current unit calls at elaboration time, directly or indirectly,
25126 some subprogram in the named unit.
25128 @item pragma Elaborate_All (unit)
25129 @findex Elaborate_All
25130 @cindex pragma Elaborate_All
25131 This is a stronger version of the Elaborate pragma. Consider the
25135 Unit A @code{with}'s unit B and calls B.Func in elab code
25136 Unit B @code{with}'s unit C, and B.Func calls C.Func
25140 Now if we put a pragma @code{Elaborate (B)}
25141 in unit @code{A}, this ensures that the
25142 body of @code{B} is elaborated before the call, but not the
25143 body of @code{C}, so
25144 the call to @code{C.Func} could still cause @code{Program_Error} to
25147 The effect of a pragma @code{Elaborate_All} is stronger, it requires
25148 not only that the body of the named unit be elaborated before the
25149 unit doing the @code{with}, but also the bodies of all units that the
25150 named unit uses, following @code{with} links transitively. For example,
25151 if we put a pragma @code{Elaborate_All (B)} in unit @code{A},
25153 not only that the body of @code{B} be elaborated before @code{A},
25155 body of @code{C}, because @code{B} @code{with}'s @code{C}.
25159 We are now in a position to give a usage rule in Ada for avoiding
25160 elaboration problems, at least if dynamic dispatching and access to
25161 subprogram values are not used. We will handle these cases separately
25164 The rule is simple. If a unit has elaboration code that can directly or
25165 indirectly make a call to a subprogram in a @code{with}'ed unit, or instantiate
25166 a generic package in a @code{with}'ed unit,
25167 then if the @code{with}'ed unit does not have
25168 pragma @code{Pure} or @code{Preelaborate}, then the client should have
25169 a pragma @code{Elaborate_All}
25170 for the @code{with}'ed unit. By following this rule a client is
25171 assured that calls can be made without risk of an exception.
25173 For generic subprogram instantiations, the rule can be relaxed to
25174 require only a pragma @code{Elaborate} since elaborating the body
25175 of a subprogram cannot cause any transitive elaboration (we are
25176 not calling the subprogram in this case, just elaborating its
25179 If this rule is not followed, then a program may be in one of four
25183 @item No order exists
25184 No order of elaboration exists which follows the rules, taking into
25185 account any @code{Elaborate}, @code{Elaborate_All},
25186 or @code{Elaborate_Body} pragmas. In
25187 this case, an Ada compiler must diagnose the situation at bind
25188 time, and refuse to build an executable program.
25190 @item One or more orders exist, all incorrect
25191 One or more acceptable elaboration orders exist, and all of them
25192 generate an elaboration order problem. In this case, the binder
25193 can build an executable program, but @code{Program_Error} will be raised
25194 when the program is run.
25196 @item Several orders exist, some right, some incorrect
25197 One or more acceptable elaboration orders exists, and some of them
25198 work, and some do not. The programmer has not controlled
25199 the order of elaboration, so the binder may or may not pick one of
25200 the correct orders, and the program may or may not raise an
25201 exception when it is run. This is the worst case, because it means
25202 that the program may fail when moved to another compiler, or even
25203 another version of the same compiler.
25205 @item One or more orders exists, all correct
25206 One ore more acceptable elaboration orders exist, and all of them
25207 work. In this case the program runs successfully. This state of
25208 affairs can be guaranteed by following the rule we gave above, but
25209 may be true even if the rule is not followed.
25213 Note that one additional advantage of following our rules on the use
25214 of @code{Elaborate} and @code{Elaborate_All}
25215 is that the program continues to stay in the ideal (all orders OK) state
25216 even if maintenance
25217 changes some bodies of some units. Conversely, if a program that does
25218 not follow this rule happens to be safe at some point, this state of affairs
25219 may deteriorate silently as a result of maintenance changes.
25221 You may have noticed that the above discussion did not mention
25222 the use of @code{Elaborate_Body}. This was a deliberate omission. If you
25223 @code{with} an @code{Elaborate_Body} unit, it still may be the case that
25224 code in the body makes calls to some other unit, so it is still necessary
25225 to use @code{Elaborate_All} on such units.
25227 @node Controlling Elaboration in GNAT - Internal Calls
25228 @section Controlling Elaboration in GNAT - Internal Calls
25231 In the case of internal calls, i.e., calls within a single package, the
25232 programmer has full control over the order of elaboration, and it is up
25233 to the programmer to elaborate declarations in an appropriate order. For
25236 @smallexample @c ada
25239 function One return Float;
25243 function One return Float is
25252 will obviously raise @code{Program_Error} at run time, because function
25253 One will be called before its body is elaborated. In this case GNAT will
25254 generate a warning that the call will raise @code{Program_Error}:
25260 2. function One return Float;
25262 4. Q : Float := One;
25264 >>> warning: cannot call "One" before body is elaborated
25265 >>> warning: Program_Error will be raised at run time
25268 6. function One return Float is
25281 Note that in this particular case, it is likely that the call is safe, because
25282 the function @code{One} does not access any global variables.
25283 Nevertheless in Ada, we do not want the validity of the check to depend on
25284 the contents of the body (think about the separate compilation case), so this
25285 is still wrong, as we discussed in the previous sections.
25287 The error is easily corrected by rearranging the declarations so that the
25288 body of @code{One} appears before the declaration containing the call
25289 (note that in Ada 95 and Ada 2005,
25290 declarations can appear in any order, so there is no restriction that
25291 would prevent this reordering, and if we write:
25293 @smallexample @c ada
25296 function One return Float;
25298 function One return Float is
25309 then all is well, no warning is generated, and no
25310 @code{Program_Error} exception
25312 Things are more complicated when a chain of subprograms is executed:
25314 @smallexample @c ada
25317 function A return Integer;
25318 function B return Integer;
25319 function C return Integer;
25321 function B return Integer is begin return A; end;
25322 function C return Integer is begin return B; end;
25326 function A return Integer is begin return 1; end;
25332 Now the call to @code{C}
25333 at elaboration time in the declaration of @code{X} is correct, because
25334 the body of @code{C} is already elaborated,
25335 and the call to @code{B} within the body of
25336 @code{C} is correct, but the call
25337 to @code{A} within the body of @code{B} is incorrect, because the body
25338 of @code{A} has not been elaborated, so @code{Program_Error}
25339 will be raised on the call to @code{A}.
25340 In this case GNAT will generate a
25341 warning that @code{Program_Error} may be
25342 raised at the point of the call. Let's look at the warning:
25348 2. function A return Integer;
25349 3. function B return Integer;
25350 4. function C return Integer;
25352 6. function B return Integer is begin return A; end;
25354 >>> warning: call to "A" before body is elaborated may
25355 raise Program_Error
25356 >>> warning: "B" called at line 7
25357 >>> warning: "C" called at line 9
25359 7. function C return Integer is begin return B; end;
25361 9. X : Integer := C;
25363 11. function A return Integer is begin return 1; end;
25373 Note that the message here says ``may raise'', instead of the direct case,
25374 where the message says ``will be raised''. That's because whether
25376 actually called depends in general on run-time flow of control.
25377 For example, if the body of @code{B} said
25379 @smallexample @c ada
25382 function B return Integer is
25384 if some-condition-depending-on-input-data then
25395 then we could not know until run time whether the incorrect call to A would
25396 actually occur, so @code{Program_Error} might
25397 or might not be raised. It is possible for a compiler to
25398 do a better job of analyzing bodies, to
25399 determine whether or not @code{Program_Error}
25400 might be raised, but it certainly
25401 couldn't do a perfect job (that would require solving the halting problem
25402 and is provably impossible), and because this is a warning anyway, it does
25403 not seem worth the effort to do the analysis. Cases in which it
25404 would be relevant are rare.
25406 In practice, warnings of either of the forms given
25407 above will usually correspond to
25408 real errors, and should be examined carefully and eliminated.
25409 In the rare case where a warning is bogus, it can be suppressed by any of
25410 the following methods:
25414 Compile with the @option{-gnatws} switch set
25417 Suppress @code{Elaboration_Check} for the called subprogram
25420 Use pragma @code{Warnings_Off} to turn warnings off for the call
25424 For the internal elaboration check case,
25425 GNAT by default generates the
25426 necessary run-time checks to ensure
25427 that @code{Program_Error} is raised if any
25428 call fails an elaboration check. Of course this can only happen if a
25429 warning has been issued as described above. The use of pragma
25430 @code{Suppress (Elaboration_Check)} may (but is not guaranteed to) suppress
25431 some of these checks, meaning that it may be possible (but is not
25432 guaranteed) for a program to be able to call a subprogram whose body
25433 is not yet elaborated, without raising a @code{Program_Error} exception.
25435 @node Controlling Elaboration in GNAT - External Calls
25436 @section Controlling Elaboration in GNAT - External Calls
25439 The previous section discussed the case in which the execution of a
25440 particular thread of elaboration code occurred entirely within a
25441 single unit. This is the easy case to handle, because a programmer
25442 has direct and total control over the order of elaboration, and
25443 furthermore, checks need only be generated in cases which are rare
25444 and which the compiler can easily detect.
25445 The situation is more complex when separate compilation is taken into account.
25446 Consider the following:
25448 @smallexample @c ada
25452 function Sqrt (Arg : Float) return Float;
25455 package body Math is
25456 function Sqrt (Arg : Float) return Float is
25465 X : Float := Math.Sqrt (0.5);
25478 where @code{Main} is the main program. When this program is executed, the
25479 elaboration code must first be executed, and one of the jobs of the
25480 binder is to determine the order in which the units of a program are
25481 to be elaborated. In this case we have four units: the spec and body
25483 the spec of @code{Stuff} and the body of @code{Main}).
25484 In what order should the four separate sections of elaboration code
25487 There are some restrictions in the order of elaboration that the binder
25488 can choose. In particular, if unit U has a @code{with}
25489 for a package @code{X}, then you
25490 are assured that the spec of @code{X}
25491 is elaborated before U , but you are
25492 not assured that the body of @code{X}
25493 is elaborated before U.
25494 This means that in the above case, the binder is allowed to choose the
25505 but that's not good, because now the call to @code{Math.Sqrt}
25506 that happens during
25507 the elaboration of the @code{Stuff}
25508 spec happens before the body of @code{Math.Sqrt} is
25509 elaborated, and hence causes @code{Program_Error} exception to be raised.
25510 At first glance, one might say that the binder is misbehaving, because
25511 obviously you want to elaborate the body of something you @code{with}
25513 that is not a general rule that can be followed in all cases. Consider
25515 @smallexample @c ada
25518 package X is @dots{}
25520 package Y is @dots{}
25523 package body Y is @dots{}
25526 package body X is @dots{}
25532 This is a common arrangement, and, apart from the order of elaboration
25533 problems that might arise in connection with elaboration code, this works fine.
25534 A rule that says that you must first elaborate the body of anything you
25535 @code{with} cannot work in this case:
25536 the body of @code{X} @code{with}'s @code{Y},
25537 which means you would have to
25538 elaborate the body of @code{Y} first, but that @code{with}'s @code{X},
25540 you have to elaborate the body of @code{X} first, but @dots{} and we have a
25541 loop that cannot be broken.
25543 It is true that the binder can in many cases guess an order of elaboration
25544 that is unlikely to cause a @code{Program_Error}
25545 exception to be raised, and it tries to do so (in the
25546 above example of @code{Math/Stuff/Spec}, the GNAT binder will
25548 elaborate the body of @code{Math} right after its spec, so all will be well).
25550 However, a program that blindly relies on the binder to be helpful can
25551 get into trouble, as we discussed in the previous sections, so
25553 provides a number of facilities for assisting the programmer in
25554 developing programs that are robust with respect to elaboration order.
25556 @node Default Behavior in GNAT - Ensuring Safety
25557 @section Default Behavior in GNAT - Ensuring Safety
25560 The default behavior in GNAT ensures elaboration safety. In its
25561 default mode GNAT implements the
25562 rule we previously described as the right approach. Let's restate it:
25566 @emph{If a unit has elaboration code that can directly or indirectly make a
25567 call to a subprogram in a @code{with}'ed unit, or instantiate a generic
25568 package in a @code{with}'ed unit, then if the @code{with}'ed unit
25569 does not have pragma @code{Pure} or
25570 @code{Preelaborate}, then the client should have an
25571 @code{Elaborate_All} pragma for the @code{with}'ed unit.}
25573 @emph{In the case of instantiating a generic subprogram, it is always
25574 sufficient to have only an @code{Elaborate} pragma for the
25575 @code{with}'ed unit.}
25579 By following this rule a client is assured that calls and instantiations
25580 can be made without risk of an exception.
25582 In this mode GNAT traces all calls that are potentially made from
25583 elaboration code, and puts in any missing implicit @code{Elaborate}
25584 and @code{Elaborate_All} pragmas.
25585 The advantage of this approach is that no elaboration problems
25586 are possible if the binder can find an elaboration order that is
25587 consistent with these implicit @code{Elaborate} and
25588 @code{Elaborate_All} pragmas. The
25589 disadvantage of this approach is that no such order may exist.
25591 If the binder does not generate any diagnostics, then it means that it has
25592 found an elaboration order that is guaranteed to be safe. However, the binder
25593 may still be relying on implicitly generated @code{Elaborate} and
25594 @code{Elaborate_All} pragmas so portability to other compilers than GNAT is not
25597 If it is important to guarantee portability, then the compilations should
25600 (warn on elaboration problems) switch. This will cause warning messages
25601 to be generated indicating the missing @code{Elaborate} and
25602 @code{Elaborate_All} pragmas.
25603 Consider the following source program:
25605 @smallexample @c ada
25610 m : integer := k.r;
25617 where it is clear that there
25618 should be a pragma @code{Elaborate_All}
25619 for unit @code{k}. An implicit pragma will be generated, and it is
25620 likely that the binder will be able to honor it. However, if you want
25621 to port this program to some other Ada compiler than GNAT.
25622 it is safer to include the pragma explicitly in the source. If this
25623 unit is compiled with the
25625 switch, then the compiler outputs a warning:
25632 3. m : integer := k.r;
25634 >>> warning: call to "r" may raise Program_Error
25635 >>> warning: missing pragma Elaborate_All for "k"
25643 and these warnings can be used as a guide for supplying manually
25644 the missing pragmas. It is usually a bad idea to use this warning
25645 option during development. That's because it will warn you when
25646 you need to put in a pragma, but cannot warn you when it is time
25647 to take it out. So the use of pragma @code{Elaborate_All} may lead to
25648 unnecessary dependencies and even false circularities.
25650 This default mode is more restrictive than the Ada Reference
25651 Manual, and it is possible to construct programs which will compile
25652 using the dynamic model described there, but will run into a
25653 circularity using the safer static model we have described.
25655 Of course any Ada compiler must be able to operate in a mode
25656 consistent with the requirements of the Ada Reference Manual,
25657 and in particular must have the capability of implementing the
25658 standard dynamic model of elaboration with run-time checks.
25660 In GNAT, this standard mode can be achieved either by the use of
25661 the @option{-gnatE} switch on the compiler (@command{gcc} or
25662 @command{gnatmake}) command, or by the use of the configuration pragma:
25664 @smallexample @c ada
25665 pragma Elaboration_Checks (DYNAMIC);
25669 Either approach will cause the unit affected to be compiled using the
25670 standard dynamic run-time elaboration checks described in the Ada
25671 Reference Manual. The static model is generally preferable, since it
25672 is clearly safer to rely on compile and link time checks rather than
25673 run-time checks. However, in the case of legacy code, it may be
25674 difficult to meet the requirements of the static model. This
25675 issue is further discussed in
25676 @ref{What to Do If the Default Elaboration Behavior Fails}.
25678 Note that the static model provides a strict subset of the allowed
25679 behavior and programs of the Ada Reference Manual, so if you do
25680 adhere to the static model and no circularities exist,
25681 then you are assured that your program will
25682 work using the dynamic model, providing that you remove any
25683 pragma Elaborate statements from the source.
25685 @node Treatment of Pragma Elaborate
25686 @section Treatment of Pragma Elaborate
25687 @cindex Pragma Elaborate
25690 The use of @code{pragma Elaborate}
25691 should generally be avoided in Ada 95 and Ada 2005 programs,
25692 since there is no guarantee that transitive calls
25693 will be properly handled. Indeed at one point, this pragma was placed
25694 in Annex J (Obsolescent Features), on the grounds that it is never useful.
25696 Now that's a bit restrictive. In practice, the case in which
25697 @code{pragma Elaborate} is useful is when the caller knows that there
25698 are no transitive calls, or that the called unit contains all necessary
25699 transitive @code{pragma Elaborate} statements, and legacy code often
25700 contains such uses.
25702 Strictly speaking the static mode in GNAT should ignore such pragmas,
25703 since there is no assurance at compile time that the necessary safety
25704 conditions are met. In practice, this would cause GNAT to be incompatible
25705 with correctly written Ada 83 code that had all necessary
25706 @code{pragma Elaborate} statements in place. Consequently, we made the
25707 decision that GNAT in its default mode will believe that if it encounters
25708 a @code{pragma Elaborate} then the programmer knows what they are doing,
25709 and it will trust that no elaboration errors can occur.
25711 The result of this decision is two-fold. First to be safe using the
25712 static mode, you should remove all @code{pragma Elaborate} statements.
25713 Second, when fixing circularities in existing code, you can selectively
25714 use @code{pragma Elaborate} statements to convince the static mode of
25715 GNAT that it need not generate an implicit @code{pragma Elaborate_All}
25718 When using the static mode with @option{-gnatwl}, any use of
25719 @code{pragma Elaborate} will generate a warning about possible
25722 @node Elaboration Issues for Library Tasks
25723 @section Elaboration Issues for Library Tasks
25724 @cindex Library tasks, elaboration issues
25725 @cindex Elaboration of library tasks
25728 In this section we examine special elaboration issues that arise for
25729 programs that declare library level tasks.
25731 Generally the model of execution of an Ada program is that all units are
25732 elaborated, and then execution of the program starts. However, the
25733 declaration of library tasks definitely does not fit this model. The
25734 reason for this is that library tasks start as soon as they are declared
25735 (more precisely, as soon as the statement part of the enclosing package
25736 body is reached), that is to say before elaboration
25737 of the program is complete. This means that if such a task calls a
25738 subprogram, or an entry in another task, the callee may or may not be
25739 elaborated yet, and in the standard
25740 Reference Manual model of dynamic elaboration checks, you can even
25741 get timing dependent Program_Error exceptions, since there can be
25742 a race between the elaboration code and the task code.
25744 The static model of elaboration in GNAT seeks to avoid all such
25745 dynamic behavior, by being conservative, and the conservative
25746 approach in this particular case is to assume that all the code
25747 in a task body is potentially executed at elaboration time if
25748 a task is declared at the library level.
25750 This can definitely result in unexpected circularities. Consider
25751 the following example
25753 @smallexample @c ada
25759 type My_Int is new Integer;
25761 function Ident (M : My_Int) return My_Int;
25765 package body Decls is
25766 task body Lib_Task is
25772 function Ident (M : My_Int) return My_Int is
25780 procedure Put_Val (Arg : Decls.My_Int);
25784 package body Utils is
25785 procedure Put_Val (Arg : Decls.My_Int) is
25787 Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
25794 Decls.Lib_Task.Start;
25799 If the above example is compiled in the default static elaboration
25800 mode, then a circularity occurs. The circularity comes from the call
25801 @code{Utils.Put_Val} in the task body of @code{Decls.Lib_Task}. Since
25802 this call occurs in elaboration code, we need an implicit pragma
25803 @code{Elaborate_All} for @code{Utils}. This means that not only must
25804 the spec and body of @code{Utils} be elaborated before the body
25805 of @code{Decls}, but also the spec and body of any unit that is
25806 @code{with'ed} by the body of @code{Utils} must also be elaborated before
25807 the body of @code{Decls}. This is the transitive implication of
25808 pragma @code{Elaborate_All} and it makes sense, because in general
25809 the body of @code{Put_Val} might have a call to something in a
25810 @code{with'ed} unit.
25812 In this case, the body of Utils (actually its spec) @code{with's}
25813 @code{Decls}. Unfortunately this means that the body of @code{Decls}
25814 must be elaborated before itself, in case there is a call from the
25815 body of @code{Utils}.
25817 Here is the exact chain of events we are worrying about:
25821 In the body of @code{Decls} a call is made from within the body of a library
25822 task to a subprogram in the package @code{Utils}. Since this call may
25823 occur at elaboration time (given that the task is activated at elaboration
25824 time), we have to assume the worst, i.e., that the
25825 call does happen at elaboration time.
25828 This means that the body and spec of @code{Util} must be elaborated before
25829 the body of @code{Decls} so that this call does not cause an access before
25833 Within the body of @code{Util}, specifically within the body of
25834 @code{Util.Put_Val} there may be calls to any unit @code{with}'ed
25838 One such @code{with}'ed package is package @code{Decls}, so there
25839 might be a call to a subprogram in @code{Decls} in @code{Put_Val}.
25840 In fact there is such a call in this example, but we would have to
25841 assume that there was such a call even if it were not there, since
25842 we are not supposed to write the body of @code{Decls} knowing what
25843 is in the body of @code{Utils}; certainly in the case of the
25844 static elaboration model, the compiler does not know what is in
25845 other bodies and must assume the worst.
25848 This means that the spec and body of @code{Decls} must also be
25849 elaborated before we elaborate the unit containing the call, but
25850 that unit is @code{Decls}! This means that the body of @code{Decls}
25851 must be elaborated before itself, and that's a circularity.
25855 Indeed, if you add an explicit pragma @code{Elaborate_All} for @code{Utils} in
25856 the body of @code{Decls} you will get a true Ada Reference Manual
25857 circularity that makes the program illegal.
25859 In practice, we have found that problems with the static model of
25860 elaboration in existing code often arise from library tasks, so
25861 we must address this particular situation.
25863 Note that if we compile and run the program above, using the dynamic model of
25864 elaboration (that is to say use the @option{-gnatE} switch),
25865 then it compiles, binds,
25866 links, and runs, printing the expected result of 2. Therefore in some sense
25867 the circularity here is only apparent, and we need to capture
25868 the properties of this program that distinguish it from other library-level
25869 tasks that have real elaboration problems.
25871 We have four possible answers to this question:
25876 Use the dynamic model of elaboration.
25878 If we use the @option{-gnatE} switch, then as noted above, the program works.
25879 Why is this? If we examine the task body, it is apparent that the task cannot
25881 @code{accept} statement until after elaboration has been completed, because
25882 the corresponding entry call comes from the main program, not earlier.
25883 This is why the dynamic model works here. But that's really giving
25884 up on a precise analysis, and we prefer to take this approach only if we cannot
25886 problem in any other manner. So let us examine two ways to reorganize
25887 the program to avoid the potential elaboration problem.
25890 Split library tasks into separate packages.
25892 Write separate packages, so that library tasks are isolated from
25893 other declarations as much as possible. Let us look at a variation on
25896 @smallexample @c ada
25904 package body Decls1 is
25905 task body Lib_Task is
25913 type My_Int is new Integer;
25914 function Ident (M : My_Int) return My_Int;
25918 package body Decls2 is
25919 function Ident (M : My_Int) return My_Int is
25927 procedure Put_Val (Arg : Decls2.My_Int);
25931 package body Utils is
25932 procedure Put_Val (Arg : Decls2.My_Int) is
25934 Text_IO.Put_Line (Decls2.My_Int'Image (Decls2.Ident (Arg)));
25941 Decls1.Lib_Task.Start;
25946 All we have done is to split @code{Decls} into two packages, one
25947 containing the library task, and one containing everything else. Now
25948 there is no cycle, and the program compiles, binds, links and executes
25949 using the default static model of elaboration.
25952 Declare separate task types.
25954 A significant part of the problem arises because of the use of the
25955 single task declaration form. This means that the elaboration of
25956 the task type, and the elaboration of the task itself (i.e.@: the
25957 creation of the task) happen at the same time. A good rule
25958 of style in Ada is to always create explicit task types. By
25959 following the additional step of placing task objects in separate
25960 packages from the task type declaration, many elaboration problems
25961 are avoided. Here is another modified example of the example program:
25963 @smallexample @c ada
25965 task type Lib_Task_Type is
25969 type My_Int is new Integer;
25971 function Ident (M : My_Int) return My_Int;
25975 package body Decls is
25976 task body Lib_Task_Type is
25982 function Ident (M : My_Int) return My_Int is
25990 procedure Put_Val (Arg : Decls.My_Int);
25994 package body Utils is
25995 procedure Put_Val (Arg : Decls.My_Int) is
25997 Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
26003 Lib_Task : Decls.Lib_Task_Type;
26009 Declst.Lib_Task.Start;
26014 What we have done here is to replace the @code{task} declaration in
26015 package @code{Decls} with a @code{task type} declaration. Then we
26016 introduce a separate package @code{Declst} to contain the actual
26017 task object. This separates the elaboration issues for
26018 the @code{task type}
26019 declaration, which causes no trouble, from the elaboration issues
26020 of the task object, which is also unproblematic, since it is now independent
26021 of the elaboration of @code{Utils}.
26022 This separation of concerns also corresponds to
26023 a generally sound engineering principle of separating declarations
26024 from instances. This version of the program also compiles, binds, links,
26025 and executes, generating the expected output.
26028 Use No_Entry_Calls_In_Elaboration_Code restriction.
26029 @cindex No_Entry_Calls_In_Elaboration_Code
26031 The previous two approaches described how a program can be restructured
26032 to avoid the special problems caused by library task bodies. in practice,
26033 however, such restructuring may be difficult to apply to existing legacy code,
26034 so we must consider solutions that do not require massive rewriting.
26036 Let us consider more carefully why our original sample program works
26037 under the dynamic model of elaboration. The reason is that the code
26038 in the task body blocks immediately on the @code{accept}
26039 statement. Now of course there is nothing to prohibit elaboration
26040 code from making entry calls (for example from another library level task),
26041 so we cannot tell in isolation that
26042 the task will not execute the accept statement during elaboration.
26044 However, in practice it is very unusual to see elaboration code
26045 make any entry calls, and the pattern of tasks starting
26046 at elaboration time and then immediately blocking on @code{accept} or
26047 @code{select} statements is very common. What this means is that
26048 the compiler is being too pessimistic when it analyzes the
26049 whole package body as though it might be executed at elaboration
26052 If we know that the elaboration code contains no entry calls, (a very safe
26053 assumption most of the time, that could almost be made the default
26054 behavior), then we can compile all units of the program under control
26055 of the following configuration pragma:
26058 pragma Restrictions (No_Entry_Calls_In_Elaboration_Code);
26062 This pragma can be placed in the @file{gnat.adc} file in the usual
26063 manner. If we take our original unmodified program and compile it
26064 in the presence of a @file{gnat.adc} containing the above pragma,
26065 then once again, we can compile, bind, link, and execute, obtaining
26066 the expected result. In the presence of this pragma, the compiler does
26067 not trace calls in a task body, that appear after the first @code{accept}
26068 or @code{select} statement, and therefore does not report a potential
26069 circularity in the original program.
26071 The compiler will check to the extent it can that the above
26072 restriction is not violated, but it is not always possible to do a
26073 complete check at compile time, so it is important to use this
26074 pragma only if the stated restriction is in fact met, that is to say
26075 no task receives an entry call before elaboration of all units is completed.
26079 @node Mixing Elaboration Models
26080 @section Mixing Elaboration Models
26082 So far, we have assumed that the entire program is either compiled
26083 using the dynamic model or static model, ensuring consistency. It
26084 is possible to mix the two models, but rules have to be followed
26085 if this mixing is done to ensure that elaboration checks are not
26088 The basic rule is that @emph{a unit compiled with the static model cannot
26089 be @code{with'ed} by a unit compiled with the dynamic model}. The
26090 reason for this is that in the static model, a unit assumes that
26091 its clients guarantee to use (the equivalent of) pragma
26092 @code{Elaborate_All} so that no elaboration checks are required
26093 in inner subprograms, and this assumption is violated if the
26094 client is compiled with dynamic checks.
26096 The precise rule is as follows. A unit that is compiled with dynamic
26097 checks can only @code{with} a unit that meets at least one of the
26098 following criteria:
26103 The @code{with'ed} unit is itself compiled with dynamic elaboration
26104 checks (that is with the @option{-gnatE} switch.
26107 The @code{with'ed} unit is an internal GNAT implementation unit from
26108 the System, Interfaces, Ada, or GNAT hierarchies.
26111 The @code{with'ed} unit has pragma Preelaborate or pragma Pure.
26114 The @code{with'ing} unit (that is the client) has an explicit pragma
26115 @code{Elaborate_All} for the @code{with'ed} unit.
26120 If this rule is violated, that is if a unit with dynamic elaboration
26121 checks @code{with's} a unit that does not meet one of the above four
26122 criteria, then the binder (@code{gnatbind}) will issue a warning
26123 similar to that in the following example:
26126 warning: "x.ads" has dynamic elaboration checks and with's
26127 warning: "y.ads" which has static elaboration checks
26131 These warnings indicate that the rule has been violated, and that as a result
26132 elaboration checks may be missed in the resulting executable file.
26133 This warning may be suppressed using the @option{-ws} binder switch
26134 in the usual manner.
26136 One useful application of this mixing rule is in the case of a subsystem
26137 which does not itself @code{with} units from the remainder of the
26138 application. In this case, the entire subsystem can be compiled with
26139 dynamic checks to resolve a circularity in the subsystem, while
26140 allowing the main application that uses this subsystem to be compiled
26141 using the more reliable default static model.
26143 @node What to Do If the Default Elaboration Behavior Fails
26144 @section What to Do If the Default Elaboration Behavior Fails
26147 If the binder cannot find an acceptable order, it outputs detailed
26148 diagnostics. For example:
26154 error: elaboration circularity detected
26155 info: "proc (body)" must be elaborated before "pack (body)"
26156 info: reason: Elaborate_All probably needed in unit "pack (body)"
26157 info: recompile "pack (body)" with -gnatwl
26158 info: for full details
26159 info: "proc (body)"
26160 info: is needed by its spec:
26161 info: "proc (spec)"
26162 info: which is withed by:
26163 info: "pack (body)"
26164 info: "pack (body)" must be elaborated before "proc (body)"
26165 info: reason: pragma Elaborate in unit "proc (body)"
26171 In this case we have a cycle that the binder cannot break. On the one
26172 hand, there is an explicit pragma Elaborate in @code{proc} for
26173 @code{pack}. This means that the body of @code{pack} must be elaborated
26174 before the body of @code{proc}. On the other hand, there is elaboration
26175 code in @code{pack} that calls a subprogram in @code{proc}. This means
26176 that for maximum safety, there should really be a pragma
26177 Elaborate_All in @code{pack} for @code{proc} which would require that
26178 the body of @code{proc} be elaborated before the body of
26179 @code{pack}. Clearly both requirements cannot be satisfied.
26180 Faced with a circularity of this kind, you have three different options.
26183 @item Fix the program
26184 The most desirable option from the point of view of long-term maintenance
26185 is to rearrange the program so that the elaboration problems are avoided.
26186 One useful technique is to place the elaboration code into separate
26187 child packages. Another is to move some of the initialization code to
26188 explicitly called subprograms, where the program controls the order
26189 of initialization explicitly. Although this is the most desirable option,
26190 it may be impractical and involve too much modification, especially in
26191 the case of complex legacy code.
26193 @item Perform dynamic checks
26194 If the compilations are done using the
26196 (dynamic elaboration check) switch, then GNAT behaves in a quite different
26197 manner. Dynamic checks are generated for all calls that could possibly result
26198 in raising an exception. With this switch, the compiler does not generate
26199 implicit @code{Elaborate} or @code{Elaborate_All} pragmas. The behavior then is
26200 exactly as specified in the @cite{Ada Reference Manual}.
26201 The binder will generate
26202 an executable program that may or may not raise @code{Program_Error}, and then
26203 it is the programmer's job to ensure that it does not raise an exception. Note
26204 that it is important to compile all units with the switch, it cannot be used
26207 @item Suppress checks
26208 The drawback of dynamic checks is that they generate a
26209 significant overhead at run time, both in space and time. If you
26210 are absolutely sure that your program cannot raise any elaboration
26211 exceptions, and you still want to use the dynamic elaboration model,
26212 then you can use the configuration pragma
26213 @code{Suppress (Elaboration_Check)} to suppress all such checks. For
26214 example this pragma could be placed in the @file{gnat.adc} file.
26216 @item Suppress checks selectively
26217 When you know that certain calls or instantiations in elaboration code cannot
26218 possibly lead to an elaboration error, and the binder nevertheless complains
26219 about implicit @code{Elaborate} and @code{Elaborate_All} pragmas that lead to
26220 elaboration circularities, it is possible to remove those warnings locally and
26221 obtain a program that will bind. Clearly this can be unsafe, and it is the
26222 responsibility of the programmer to make sure that the resulting program has no
26223 elaboration anomalies. The pragma @code{Suppress (Elaboration_Check)} can be
26224 used with different granularity to suppress warnings and break elaboration
26229 Place the pragma that names the called subprogram in the declarative part
26230 that contains the call.
26233 Place the pragma in the declarative part, without naming an entity. This
26234 disables warnings on all calls in the corresponding declarative region.
26237 Place the pragma in the package spec that declares the called subprogram,
26238 and name the subprogram. This disables warnings on all elaboration calls to
26242 Place the pragma in the package spec that declares the called subprogram,
26243 without naming any entity. This disables warnings on all elaboration calls to
26244 all subprograms declared in this spec.
26246 @item Use Pragma Elaborate
26247 As previously described in section @xref{Treatment of Pragma Elaborate},
26248 GNAT in static mode assumes that a @code{pragma} Elaborate indicates correctly
26249 that no elaboration checks are required on calls to the designated unit.
26250 There may be cases in which the caller knows that no transitive calls
26251 can occur, so that a @code{pragma Elaborate} will be sufficient in a
26252 case where @code{pragma Elaborate_All} would cause a circularity.
26256 These five cases are listed in order of decreasing safety, and therefore
26257 require increasing programmer care in their application. Consider the
26260 @smallexample @c adanocomment
26262 function F1 return Integer;
26267 function F2 return Integer;
26268 function Pure (x : integer) return integer;
26269 -- pragma Suppress (Elaboration_Check, On => Pure); -- (3)
26270 -- pragma Suppress (Elaboration_Check); -- (4)
26274 package body Pack1 is
26275 function F1 return Integer is
26279 Val : integer := Pack2.Pure (11); -- Elab. call (1)
26282 -- pragma Suppress(Elaboration_Check, Pack2.F2); -- (1)
26283 -- pragma Suppress(Elaboration_Check); -- (2)
26285 X1 := Pack2.F2 + 1; -- Elab. call (2)
26290 package body Pack2 is
26291 function F2 return Integer is
26295 function Pure (x : integer) return integer is
26297 return x ** 3 - 3 * x;
26301 with Pack1, Ada.Text_IO;
26304 Ada.Text_IO.Put_Line(Pack1.X1'Img); -- 101
26307 In the absence of any pragmas, an attempt to bind this program produces
26308 the following diagnostics:
26314 error: elaboration circularity detected
26315 info: "pack1 (body)" must be elaborated before "pack1 (body)"
26316 info: reason: Elaborate_All probably needed in unit "pack1 (body)"
26317 info: recompile "pack1 (body)" with -gnatwl for full details
26318 info: "pack1 (body)"
26319 info: must be elaborated along with its spec:
26320 info: "pack1 (spec)"
26321 info: which is withed by:
26322 info: "pack2 (body)"
26323 info: which must be elaborated along with its spec:
26324 info: "pack2 (spec)"
26325 info: which is withed by:
26326 info: "pack1 (body)"
26329 The sources of the circularity are the two calls to @code{Pack2.Pure} and
26330 @code{Pack2.F2} in the body of @code{Pack1}. We can see that the call to
26331 F2 is safe, even though F2 calls F1, because the call appears after the
26332 elaboration of the body of F1. Therefore the pragma (1) is safe, and will
26333 remove the warning on the call. It is also possible to use pragma (2)
26334 because there are no other potentially unsafe calls in the block.
26337 The call to @code{Pure} is safe because this function does not depend on the
26338 state of @code{Pack2}. Therefore any call to this function is safe, and it
26339 is correct to place pragma (3) in the corresponding package spec.
26342 Finally, we could place pragma (4) in the spec of @code{Pack2} to disable
26343 warnings on all calls to functions declared therein. Note that this is not
26344 necessarily safe, and requires more detailed examination of the subprogram
26345 bodies involved. In particular, a call to @code{F2} requires that @code{F1}
26346 be already elaborated.
26350 It is hard to generalize on which of these four approaches should be
26351 taken. Obviously if it is possible to fix the program so that the default
26352 treatment works, this is preferable, but this may not always be practical.
26353 It is certainly simple enough to use
26355 but the danger in this case is that, even if the GNAT binder
26356 finds a correct elaboration order, it may not always do so,
26357 and certainly a binder from another Ada compiler might not. A
26358 combination of testing and analysis (for which the warnings generated
26361 switch can be useful) must be used to ensure that the program is free
26362 of errors. One switch that is useful in this testing is the
26363 @option{^-p (pessimistic elaboration order)^/PESSIMISTIC_ELABORATION_ORDER^}
26366 Normally the binder tries to find an order that has the best chance
26367 of avoiding elaboration problems. However, if this switch is used, the binder
26368 plays a devil's advocate role, and tries to choose the order that
26369 has the best chance of failing. If your program works even with this
26370 switch, then it has a better chance of being error free, but this is still
26373 For an example of this approach in action, consider the C-tests (executable
26374 tests) from the ACVC suite. If these are compiled and run with the default
26375 treatment, then all but one of them succeed without generating any error
26376 diagnostics from the binder. However, there is one test that fails, and
26377 this is not surprising, because the whole point of this test is to ensure
26378 that the compiler can handle cases where it is impossible to determine
26379 a correct order statically, and it checks that an exception is indeed
26380 raised at run time.
26382 This one test must be compiled and run using the
26384 switch, and then it passes. Alternatively, the entire suite can
26385 be run using this switch. It is never wrong to run with the dynamic
26386 elaboration switch if your code is correct, and we assume that the
26387 C-tests are indeed correct (it is less efficient, but efficiency is
26388 not a factor in running the ACVC tests.)
26390 @node Elaboration for Dispatching Calls
26391 @section Elaboration for Dispatching Calls
26392 @cindex Dispatching calls
26395 In rare cases, the static elaboration model fails to prevent
26396 dispatching calls to not-yet-elaborated subprograms. In such cases, we
26397 fall back to run-time checks; premature calls to any primitive
26398 operation of a tagged type before the body of the operation has been
26399 elaborated will raise @code{Program_Error}.
26401 Access-to-subprogram types, however, are handled conservatively, and
26402 do not require run-time checks. This was not true in earlier versions
26403 of the compiler; you can use the @option{-gnatd.U} debug switch to
26404 revert to the old behavior if the new conservative behavior causes
26405 elaboration cycles.
26407 @node Summary of Procedures for Elaboration Control
26408 @section Summary of Procedures for Elaboration Control
26409 @cindex Elaboration control
26412 First, compile your program with the default options, using none of
26413 the special elaboration control switches. If the binder successfully
26414 binds your program, then you can be confident that, apart from issues
26415 raised by the use of access-to-subprogram types and dynamic dispatching,
26416 the program is free of elaboration errors. If it is important that the
26417 program be portable, then use the
26419 switch to generate warnings about missing @code{Elaborate} or
26420 @code{Elaborate_All} pragmas, and supply the missing pragmas.
26422 If the program fails to bind using the default static elaboration
26423 handling, then you can fix the program to eliminate the binder
26424 message, or recompile the entire program with the
26425 @option{-gnatE} switch to generate dynamic elaboration checks,
26426 and, if you are sure there really are no elaboration problems,
26427 use a global pragma @code{Suppress (Elaboration_Check)}.
26429 @node Other Elaboration Order Considerations
26430 @section Other Elaboration Order Considerations
26432 This section has been entirely concerned with the issue of finding a valid
26433 elaboration order, as defined by the Ada Reference Manual. In a case
26434 where several elaboration orders are valid, the task is to find one
26435 of the possible valid elaboration orders (and the static model in GNAT
26436 will ensure that this is achieved).
26438 The purpose of the elaboration rules in the Ada Reference Manual is to
26439 make sure that no entity is accessed before it has been elaborated. For
26440 a subprogram, this means that the spec and body must have been elaborated
26441 before the subprogram is called. For an object, this means that the object
26442 must have been elaborated before its value is read or written. A violation
26443 of either of these two requirements is an access before elaboration order,
26444 and this section has been all about avoiding such errors.
26446 In the case where more than one order of elaboration is possible, in the
26447 sense that access before elaboration errors are avoided, then any one of
26448 the orders is ``correct'' in the sense that it meets the requirements of
26449 the Ada Reference Manual, and no such error occurs.
26451 However, it may be the case for a given program, that there are
26452 constraints on the order of elaboration that come not from consideration
26453 of avoiding elaboration errors, but rather from extra-lingual logic
26454 requirements. Consider this example:
26456 @smallexample @c ada
26457 with Init_Constants;
26458 package Constants is
26463 package Init_Constants is
26464 procedure P; -- require a body
26465 end Init_Constants;
26468 package body Init_Constants is
26469 procedure P is begin null; end;
26473 end Init_Constants;
26477 Z : Integer := Constants.X + Constants.Y;
26481 with Text_IO; use Text_IO;
26484 Put_Line (Calc.Z'Img);
26489 In this example, there is more than one valid order of elaboration. For
26490 example both the following are correct orders:
26493 Init_Constants spec
26496 Init_Constants body
26501 Init_Constants spec
26502 Init_Constants body
26509 There is no language rule to prefer one or the other, both are correct
26510 from an order of elaboration point of view. But the programmatic effects
26511 of the two orders are very different. In the first, the elaboration routine
26512 of @code{Calc} initializes @code{Z} to zero, and then the main program
26513 runs with this value of zero. But in the second order, the elaboration
26514 routine of @code{Calc} runs after the body of Init_Constants has set
26515 @code{X} and @code{Y} and thus @code{Z} is set to 7 before @code{Main}
26518 One could perhaps by applying pretty clever non-artificial intelligence
26519 to the situation guess that it is more likely that the second order of
26520 elaboration is the one desired, but there is no formal linguistic reason
26521 to prefer one over the other. In fact in this particular case, GNAT will
26522 prefer the second order, because of the rule that bodies are elaborated
26523 as soon as possible, but it's just luck that this is what was wanted
26524 (if indeed the second order was preferred).
26526 If the program cares about the order of elaboration routines in a case like
26527 this, it is important to specify the order required. In this particular
26528 case, that could have been achieved by adding to the spec of Calc:
26530 @smallexample @c ada
26531 pragma Elaborate_All (Constants);
26535 which requires that the body (if any) and spec of @code{Constants},
26536 as well as the body and spec of any unit @code{with}'ed by
26537 @code{Constants} be elaborated before @code{Calc} is elaborated.
26539 Clearly no automatic method can always guess which alternative you require,
26540 and if you are working with legacy code that had constraints of this kind
26541 which were not properly specified by adding @code{Elaborate} or
26542 @code{Elaborate_All} pragmas, then indeed it is possible that two different
26543 compilers can choose different orders.
26545 However, GNAT does attempt to diagnose the common situation where there
26546 are uninitialized variables in the visible part of a package spec, and the
26547 corresponding package body has an elaboration block that directly or
26548 indirectly initialized one or more of these variables. This is the situation
26549 in which a pragma Elaborate_Body is usually desirable, and GNAT will generate
26550 a warning that suggests this addition if it detects this situation.
26552 The @code{gnatbind}
26553 @option{^-p^/PESSIMISTIC_ELABORATION^} switch may be useful in smoking
26554 out problems. This switch causes bodies to be elaborated as late as possible
26555 instead of as early as possible. In the example above, it would have forced
26556 the choice of the first elaboration order. If you get different results
26557 when using this switch, and particularly if one set of results is right,
26558 and one is wrong as far as you are concerned, it shows that you have some
26559 missing @code{Elaborate} pragmas. For the example above, we have the
26563 gnatmake -f -q main
26566 gnatmake -f -q main -bargs -p
26572 It is of course quite unlikely that both these results are correct, so
26573 it is up to you in a case like this to investigate the source of the
26574 difference, by looking at the two elaboration orders that are chosen,
26575 and figuring out which is correct, and then adding the necessary
26576 @code{Elaborate} or @code{Elaborate_All} pragmas to ensure the desired order.
26579 @c **********************************
26580 @node Overflow Check Handling in GNAT
26581 @appendix Overflow Check Handling in GNAT
26582 @cindex Overflow checks
26583 @cindex Checks (overflow)
26584 @c **********************************
26588 * Overflow Checking Modes in GNAT::
26589 * Specifying the Desired Mode::
26590 * Default Settings::
26591 * Implementation Notes::
26596 @section Background
26599 Overflow checks are checks that the compiler may make to ensure
26600 that intermediate results are not out of range. For example:
26602 @smallexample @c ada
26609 if @code{A} has the value @code{Integer'Last}, then the addition may cause
26610 overflow since the result is out of range of the type @code{Integer}.
26611 In this case @code{Constraint_Error} will be raised if checks are
26614 A trickier situation arises in examples like the following:
26616 @smallexample @c ada
26623 where @code{A} is @code{Integer'Last} and @code{C} is @code{-1}.
26624 Now the final result of the expression on the right hand side is
26625 @code{Integer'Last} which is in range, but the question arises whether the
26626 intermediate addition of @code{(A + 1)} raises an overflow error.
26628 The (perhaps surprising) answer is that the Ada language
26629 definition does not answer this question. Instead it leaves
26630 it up to the implementation to do one of two things if overflow
26631 checks are enabled.
26635 raise an exception (@code{Constraint_Error}), or
26638 yield the correct mathematical result which is then used in
26639 subsequent operations.
26643 If the compiler chooses the first approach, then the assignment of this
26644 example will indeed raise @code{Constraint_Error} if overflow checking is
26645 enabled, or result in erroneous execution if overflow checks are suppressed.
26647 But if the compiler
26648 chooses the second approach, then it can perform both additions yielding
26649 the correct mathematical result, which is in range, so no exception
26650 will be raised, and the right result is obtained, regardless of whether
26651 overflow checks are suppressed.
26653 Note that in the first example an
26654 exception will be raised in either case, since if the compiler
26655 gives the correct mathematical result for the addition, it will
26656 be out of range of the target type of the assignment, and thus
26657 fails the range check.
26659 This lack of specified behavior in the handling of overflow for
26660 intermediate results is a source of non-portability, and can thus
26661 be problematic when programs are ported. Most typically this arises
26662 in a situation where the original compiler did not raise an exception,
26663 and then the application is moved to a compiler where the check is
26664 performed on the intermediate result and an unexpected exception is
26667 Furthermore, when using Ada 2012's preconditions and other
26668 assertion forms, another issue arises. Consider:
26670 @smallexample @c ada
26671 procedure P (A, B : Integer) with
26672 Pre => A + B <= Integer'Last;
26676 One often wants to regard arithmetic in a context like this from
26677 a mathematical point of view. So for example, if the two actual parameters
26678 for a call to @code{P} are both @code{Integer'Last}, then
26679 the precondition should be regarded as False. If we are executing
26680 in a mode with run-time checks enabled for preconditions, then we would
26681 like this precondition to fail, rather than raising an exception
26682 because of the intermediate overflow.
26684 However, the language definition leaves the specification of
26685 whether the above condition fails (raising @code{Assert_Error}) or
26686 causes an intermediate overflow (raising @code{Constraint_Error})
26687 up to the implementation.
26689 The situation is worse in a case such as the following:
26691 @smallexample @c ada
26692 procedure Q (A, B, C : Integer) with
26693 Pre => A + B + C <= Integer'Last;
26699 @smallexample @c ada
26700 Q (A => Integer'Last, B => 1, C => -1);
26704 From a mathematical point of view the precondition
26705 is True, but at run time we may (but are not guaranteed to) get an
26706 exception raised because of the intermediate overflow (and we really
26707 would prefer this precondition to be considered True at run time).
26709 @node Overflow Checking Modes in GNAT
26710 @section Overflow Checking Modes in GNAT
26713 To deal with the portability issue, and with the problem of
26714 mathematical versus run-time interpretation of the expressions in
26715 assertions, GNAT provides comprehensive control over the handling
26716 of intermediate overflow. GNAT can operate in three modes, and
26717 furthemore, permits separate selection of operating modes for
26718 the expressions within assertions (here the term ``assertions''
26719 is used in the technical sense, which includes preconditions and so forth)
26720 and for expressions appearing outside assertions.
26722 The three modes are:
26725 @item @i{Use base type for intermediate operations} (@code{STRICT})
26727 In this mode, all intermediate results for predefined arithmetic
26728 operators are computed using the base type, and the result must
26729 be in range of the base type. If this is not the
26730 case then either an exception is raised (if overflow checks are
26731 enabled) or the execution is erroneous (if overflow checks are suppressed).
26732 This is the normal default mode.
26734 @item @i{Most intermediate overflows avoided} (@code{MINIMIZED})
26736 In this mode, the compiler attempts to avoid intermediate overflows by
26737 using a larger integer type, typically @code{Long_Long_Integer},
26738 as the type in which arithmetic is
26739 performed for predefined arithmetic operators. This may be slightly more
26741 run time (compared to suppressing intermediate overflow checks), though
26742 the cost is negligible on modern 64-bit machines. For the examples given
26743 earlier, no intermediate overflows would have resulted in exceptions,
26744 since the intermediate results are all in the range of
26745 @code{Long_Long_Integer} (typically 64-bits on nearly all implementations
26746 of GNAT). In addition, if checks are enabled, this reduces the number of
26747 checks that must be made, so this choice may actually result in an
26748 improvement in space and time behavior.
26750 However, there are cases where @code{Long_Long_Integer} is not large
26751 enough, consider the following example:
26753 @smallexample @c ada
26754 procedure R (A, B, C, D : Integer) with
26755 Pre => (A**2 * B**2) / (C**2 * D**2) <= 10;
26758 where @code{A} = @code{B} = @code{C} = @code{D} = @code{Integer'Last}.
26759 Now the intermediate results are
26760 out of the range of @code{Long_Long_Integer} even though the final result
26761 is in range and the precondition is True (from a mathematical point
26762 of view). In such a case, operating in this mode, an overflow occurs
26763 for the intermediate computation (which is why this mode
26764 says @i{most} intermediate overflows are avoided). In this case,
26765 an exception is raised if overflow checks are enabled, and the
26766 execution is erroneous if overflow checks are suppressed.
26768 @item @i{All intermediate overflows avoided} (@code{ELIMINATED})
26770 In this mode, the compiler avoids all intermediate overflows
26771 by using arbitrary precision arithmetic as required. In this
26772 mode, the above example with @code{A**2 * B**2} would
26773 not cause intermediate overflow, because the intermediate result
26774 would be evaluated using sufficient precision, and the result
26775 of evaluating the precondition would be True.
26777 This mode has the advantage of avoiding any intermediate
26778 overflows, but at the expense of significant run-time overhead,
26779 including the use of a library (included automatically in this
26780 mode) for multiple-precision arithmetic.
26782 This mode provides cleaner semantics for assertions, since now
26783 the run-time behavior emulates true arithmetic behavior for the
26784 predefined arithmetic operators, meaning that there is never a
26785 conflict between the mathematical view of the assertion, and its
26788 Note that in this mode, the behavior is unaffected by whether or
26789 not overflow checks are suppressed, since overflow does not occur.
26790 It is possible for gigantic intermediate expressions to raise
26791 @code{Storage_Error} as a result of attempting to compute the
26792 results of such expressions (e.g. @code{Integer'Last ** Integer'Last})
26793 but overflow is impossible.
26799 Note that these modes apply only to the evaluation of predefined
26800 arithmetic, membership, and comparison operators for signed integer
26803 For fixed-point arithmetic, checks can be suppressed. But if checks
26805 then fixed-point values are always checked for overflow against the
26806 base type for intermediate expressions (that is such checks always
26807 operate in the equivalent of @code{STRICT} mode).
26809 For floating-point, on nearly all architectures, @code{Machine_Overflows}
26810 is False, and IEEE infinities are generated, so overflow exceptions
26811 are never raised. If you want to avoid infinities, and check that
26812 final results of expressions are in range, then you can declare a
26813 constrained floating-point type, and range checks will be carried
26814 out in the normal manner (with infinite values always failing all
26818 @c -------------------------
26819 @node Specifying the Desired Mode
26820 @section Specifying the Desired Mode
26823 The desired mode of for handling intermediate overflow can be specified using
26824 either the @code{Overflow_Mode} pragma or an equivalent compiler switch.
26825 The pragma has the form
26826 @cindex pragma @code{Overflow_Mode}
26828 @smallexample @c ada
26829 pragma Overflow_Mode ([General =>] MODE [, [Assertions =>] MODE]);
26833 where @code{MODE} is one of
26836 @item @code{STRICT}: intermediate overflows checked (using base type)
26837 @item @code{MINIMIZED}: minimize intermediate overflows
26838 @item @code{ELIMINATED}: eliminate intermediate overflows
26842 The case is ignored, so @code{MINIMIZED}, @code{Minimized} and
26843 @code{minimized} all have the same effect.
26845 If only the @code{General} parameter is present, then the given @code{MODE}
26847 to expressions both within and outside assertions. If both arguments
26848 are present, then @code{General} applies to expressions outside assertions,
26849 and @code{Assertions} applies to expressions within assertions. For example:
26851 @smallexample @c ada
26852 pragma Overflow_Mode
26853 (General => Minimized, Assertions => Eliminated);
26857 specifies that general expressions outside assertions be evaluated
26858 in ``minimize intermediate overflows'' mode, and expressions within
26859 assertions be evaluated in ``eliminate intermediate overflows'' mode.
26860 This is often a reasonable choice, avoiding excessive overhead
26861 outside assertions, but assuring a high degree of portability
26862 when importing code from another compiler, while incurring
26863 the extra overhead for assertion expressions to ensure that
26864 the behavior at run time matches the expected mathematical
26867 The @code{Overflow_Mode} pragma has the same scoping and placement
26868 rules as pragma @code{Suppress}, so it can occur either as a
26869 configuration pragma, specifying a default for the whole
26870 program, or in a declarative scope, where it applies to the
26871 remaining declarations and statements in that scope.
26873 Note that pragma @code{Overflow_Mode} does not affect whether
26874 overflow checks are enabled or suppressed. It only controls the
26875 method used to compute intermediate values. To control whether
26876 overflow checking is enabled or suppressed, use pragma @code{Suppress}
26877 or @code{Unsuppress} in the usual manner
26879 Additionally, a compiler switch @option{-gnato?} or @option{-gnato??}
26880 can be used to control the checking mode default (which can be subsequently
26881 overridden using pragmas).
26882 @cindex @option{-gnato?} (gcc)
26883 @cindex @option{-gnato??} (gcc)
26885 Here `@code{?}' is one of the digits `@code{1}' through `@code{3}':
26889 use base type for intermediate operations (@code{STRICT})
26891 minimize intermediate overflows (@code{MINIMIZED})
26893 eliminate intermediate overflows (@code{ELIMINATED})
26897 As with the pragma, if only one digit appears then it applies to all
26898 cases; if two digits are given, then the first applies outside
26899 assertions, and the second within assertions. Thus the equivalent
26900 of the example pragma above would be
26901 @option{^-gnato23^/OVERFLOW_CHECKS=23^}.
26903 If no digits follow the @option{-gnato}, then it is equivalent to
26904 @option{^-gnato11^/OVERFLOW_CHECKS=11^},
26905 causing all intermediate operations to be computed using the base
26906 type (@code{STRICT} mode).
26908 In addition to setting the mode used for computation of intermediate
26909 results, the @code{-gnato} switch also enables overflow checking (which
26910 is suppressed by default). It thus combines the effect of using
26911 a pragma @code{Overflow_Mode} and pragma @code{Unsuppress}.
26914 @c -------------------------
26915 @node Default Settings
26916 @section Default Settings
26918 The default mode for overflow checks is
26925 which causes all computations both inside and outside assertions to use
26926 the base type. In addition overflow checks are suppressed.
26928 This retains compatibility with previous versions of
26929 GNAT which suppressed overflow checks by default and always
26930 used the base type for computation of intermediate results.
26932 The switch @option{-gnato} (with no digits following) is equivalent to
26933 @cindex @option{-gnato} (gcc)
26940 which causes overflow checking of all intermediate overflows
26941 both inside and outside assertions against the base type.
26942 This provides compatibility
26943 with this switch as implemented in previous versions of GNAT.
26945 The pragma @code{Suppress (Overflow_Check)} disables overflow
26946 checking, but it has no effect on the method used for computing
26947 intermediate results.
26949 The pragma @code{Unsuppress (Overflow_Check)} enables overflow
26950 checking, but it has no effect on the method used for computing
26951 intermediate results.
26953 @c -------------------------
26954 @node Implementation Notes
26955 @section Implementation Notes
26957 In practice on typical 64-bit machines, the @code{MINIMIZED} mode is
26958 reasonably efficient, and can be generally used. It also helps
26959 to ensure compatibility with code imported from some other
26962 Setting all intermediate overflows checking (@code{CHECKED} mode)
26963 makes sense if you want to
26964 make sure that your code is compatible with any other possible
26965 Ada implementation. This may be useful in ensuring portability
26966 for code that is to be exported to some other compiler than GNAT.
26969 The Ada standard allows the reassociation of expressions at
26970 the same precedence level if no parentheses are present. For
26971 example, @w{@code{A+B+C}} parses as though it were @w{@code{(A+B)+C}}, but
26972 the compiler can reintepret this as @w{@code{A+(B+C)}}, possibly
26973 introducing or eliminating an overflow exception. The GNAT
26974 compiler never takes advantage of this freedom, and the
26975 expression @w{@code{A+B+C}} will be evaluated as @w{@code{(A+B)+C}}.
26976 If you need the other order, you can write the parentheses
26977 explicitly @w{@code{A+(B+C)}} and GNAT will respect this order.
26979 The use of @code{ELIMINATED} mode will cause the compiler to
26980 automatically include an appropriate arbitrary precision
26981 integer arithmetic package. The compiler will make calls
26982 to this package, though only in cases where it cannot be
26983 sure that @code{Long_Long_Integer} is sufficient to guard against
26984 intermediate overflows. This package does not use dynamic
26985 alllocation, but it does use the secondary stack, so an
26986 appropriate secondary stack package must be present (this
26987 is always true for standard full Ada, but may require
26988 specific steps for restricted run times such as ZFP).
26990 Although @code{ELIMINATED} mode causes expressions to use arbitrary
26991 precision arithmetic, avoiding overflow, the final result
26992 must be in an appropriate range. This is true even if the
26993 final result is of type @code{[Long_[Long_]]Integer'Base}, which
26994 still has the same bounds as its associated constrained
26997 Currently, the @code{ELIMINATED} mode is only available on target
26998 platforms for which @code{Long_Long_Integer} is 64-bits (nearly all GNAT
27001 @c *******************************
27002 @node Conditional Compilation
27003 @appendix Conditional Compilation
27004 @c *******************************
27005 @cindex Conditional compilation
27008 It is often necessary to arrange for a single source program
27009 to serve multiple purposes, where it is compiled in different
27010 ways to achieve these different goals. Some examples of the
27011 need for this feature are
27014 @item Adapting a program to a different hardware environment
27015 @item Adapting a program to a different target architecture
27016 @item Turning debugging features on and off
27017 @item Arranging for a program to compile with different compilers
27021 In C, or C++, the typical approach would be to use the preprocessor
27022 that is defined as part of the language. The Ada language does not
27023 contain such a feature. This is not an oversight, but rather a very
27024 deliberate design decision, based on the experience that overuse of
27025 the preprocessing features in C and C++ can result in programs that
27026 are extremely difficult to maintain. For example, if we have ten
27027 switches that can be on or off, this means that there are a thousand
27028 separate programs, any one of which might not even be syntactically
27029 correct, and even if syntactically correct, the resulting program
27030 might not work correctly. Testing all combinations can quickly become
27033 Nevertheless, the need to tailor programs certainly exists, and in
27034 this Appendix we will discuss how this can
27035 be achieved using Ada in general, and GNAT in particular.
27038 * Use of Boolean Constants::
27039 * Debugging - A Special Case::
27040 * Conditionalizing Declarations::
27041 * Use of Alternative Implementations::
27045 @node Use of Boolean Constants
27046 @section Use of Boolean Constants
27049 In the case where the difference is simply which code
27050 sequence is executed, the cleanest solution is to use Boolean
27051 constants to control which code is executed.
27053 @smallexample @c ada
27055 FP_Initialize_Required : constant Boolean := True;
27057 if FP_Initialize_Required then
27064 Not only will the code inside the @code{if} statement not be executed if
27065 the constant Boolean is @code{False}, but it will also be completely
27066 deleted from the program.
27067 However, the code is only deleted after the @code{if} statement
27068 has been checked for syntactic and semantic correctness.
27069 (In contrast, with preprocessors the code is deleted before the
27070 compiler ever gets to see it, so it is not checked until the switch
27072 @cindex Preprocessors (contrasted with conditional compilation)
27074 Typically the Boolean constants will be in a separate package,
27077 @smallexample @c ada
27080 FP_Initialize_Required : constant Boolean := True;
27081 Reset_Available : constant Boolean := False;
27088 The @code{Config} package exists in multiple forms for the various targets,
27089 with an appropriate script selecting the version of @code{Config} needed.
27090 Then any other unit requiring conditional compilation can do a @code{with}
27091 of @code{Config} to make the constants visible.
27094 @node Debugging - A Special Case
27095 @section Debugging - A Special Case
27098 A common use of conditional code is to execute statements (for example
27099 dynamic checks, or output of intermediate results) under control of a
27100 debug switch, so that the debugging behavior can be turned on and off.
27101 This can be done using a Boolean constant to control whether the code
27104 @smallexample @c ada
27107 Put_Line ("got to the first stage!");
27115 @smallexample @c ada
27117 if Debugging and then Temperature > 999.0 then
27118 raise Temperature_Crazy;
27124 Since this is a common case, there are special features to deal with
27125 this in a convenient manner. For the case of tests, Ada 2005 has added
27126 a pragma @code{Assert} that can be used for such tests. This pragma is modeled
27127 @cindex pragma @code{Assert}
27128 on the @code{Assert} pragma that has always been available in GNAT, so this
27129 feature may be used with GNAT even if you are not using Ada 2005 features.
27130 The use of pragma @code{Assert} is described in
27131 @ref{Pragma Assert,,, gnat_rm, GNAT Reference Manual}, but as an
27132 example, the last test could be written:
27134 @smallexample @c ada
27135 pragma Assert (Temperature <= 999.0, "Temperature Crazy");
27141 @smallexample @c ada
27142 pragma Assert (Temperature <= 999.0);
27146 In both cases, if assertions are active and the temperature is excessive,
27147 the exception @code{Assert_Failure} will be raised, with the given string in
27148 the first case or a string indicating the location of the pragma in the second
27149 case used as the exception message.
27151 You can turn assertions on and off by using the @code{Assertion_Policy}
27153 @cindex pragma @code{Assertion_Policy}
27154 This is an Ada 2005 pragma which is implemented in all modes by
27155 GNAT, but only in the latest versions of GNAT which include Ada 2005
27156 capability. Alternatively, you can use the @option{-gnata} switch
27157 @cindex @option{-gnata} switch
27158 to enable assertions from the command line (this is recognized by all versions
27161 For the example above with the @code{Put_Line}, the GNAT-specific pragma
27162 @code{Debug} can be used:
27163 @cindex pragma @code{Debug}
27165 @smallexample @c ada
27166 pragma Debug (Put_Line ("got to the first stage!"));
27170 If debug pragmas are enabled, the argument, which must be of the form of
27171 a procedure call, is executed (in this case, @code{Put_Line} will be called).
27172 Only one call can be present, but of course a special debugging procedure
27173 containing any code you like can be included in the program and then
27174 called in a pragma @code{Debug} argument as needed.
27176 One advantage of pragma @code{Debug} over the @code{if Debugging then}
27177 construct is that pragma @code{Debug} can appear in declarative contexts,
27178 such as at the very beginning of a procedure, before local declarations have
27181 Debug pragmas are enabled using either the @option{-gnata} switch that also
27182 controls assertions, or with a separate Debug_Policy pragma.
27183 @cindex pragma @code{Debug_Policy}
27184 The latter pragma is new in the Ada 2005 versions of GNAT (but it can be used
27185 in Ada 95 and Ada 83 programs as well), and is analogous to
27186 pragma @code{Assertion_Policy} to control assertions.
27188 @code{Assertion_Policy} and @code{Debug_Policy} are configuration pragmas,
27189 and thus they can appear in @file{gnat.adc} if you are not using a
27190 project file, or in the file designated to contain configuration pragmas
27192 They then apply to all subsequent compilations. In practice the use of
27193 the @option{-gnata} switch is often the most convenient method of controlling
27194 the status of these pragmas.
27196 Note that a pragma is not a statement, so in contexts where a statement
27197 sequence is required, you can't just write a pragma on its own. You have
27198 to add a @code{null} statement.
27200 @smallexample @c ada
27203 @dots{} -- some statements
27205 pragma Assert (Num_Cases < 10);
27212 @node Conditionalizing Declarations
27213 @section Conditionalizing Declarations
27216 In some cases, it may be necessary to conditionalize declarations to meet
27217 different requirements. For example we might want a bit string whose length
27218 is set to meet some hardware message requirement.
27220 In some cases, it may be possible to do this using declare blocks controlled
27221 by conditional constants:
27223 @smallexample @c ada
27225 if Small_Machine then
27227 X : Bit_String (1 .. 10);
27233 X : Large_Bit_String (1 .. 1000);
27242 Note that in this approach, both declarations are analyzed by the
27243 compiler so this can only be used where both declarations are legal,
27244 even though one of them will not be used.
27246 Another approach is to define integer constants, e.g.@: @code{Bits_Per_Word},
27247 or Boolean constants, e.g.@: @code{Little_Endian}, and then write declarations
27248 that are parameterized by these constants. For example
27250 @smallexample @c ada
27253 Field1 at 0 range Boolean'Pos (Little_Endian) * 10 .. Bits_Per_Word;
27259 If @code{Bits_Per_Word} is set to 32, this generates either
27261 @smallexample @c ada
27264 Field1 at 0 range 0 .. 32;
27270 for the big endian case, or
27272 @smallexample @c ada
27275 Field1 at 0 range 10 .. 32;
27281 for the little endian case. Since a powerful subset of Ada expression
27282 notation is usable for creating static constants, clever use of this
27283 feature can often solve quite difficult problems in conditionalizing
27284 compilation (note incidentally that in Ada 95, the little endian
27285 constant was introduced as @code{System.Default_Bit_Order}, so you do not
27286 need to define this one yourself).
27289 @node Use of Alternative Implementations
27290 @section Use of Alternative Implementations
27293 In some cases, none of the approaches described above are adequate. This
27294 can occur for example if the set of declarations required is radically
27295 different for two different configurations.
27297 In this situation, the official Ada way of dealing with conditionalizing
27298 such code is to write separate units for the different cases. As long as
27299 this does not result in excessive duplication of code, this can be done
27300 without creating maintenance problems. The approach is to share common
27301 code as far as possible, and then isolate the code and declarations
27302 that are different. Subunits are often a convenient method for breaking
27303 out a piece of a unit that is to be conditionalized, with separate files
27304 for different versions of the subunit for different targets, where the
27305 build script selects the right one to give to the compiler.
27306 @cindex Subunits (and conditional compilation)
27308 As an example, consider a situation where a new feature in Ada 2005
27309 allows something to be done in a really nice way. But your code must be able
27310 to compile with an Ada 95 compiler. Conceptually you want to say:
27312 @smallexample @c ada
27315 @dots{} neat Ada 2005 code
27317 @dots{} not quite as neat Ada 95 code
27323 where @code{Ada_2005} is a Boolean constant.
27325 But this won't work when @code{Ada_2005} is set to @code{False},
27326 since the @code{then} clause will be illegal for an Ada 95 compiler.
27327 (Recall that although such unreachable code would eventually be deleted
27328 by the compiler, it still needs to be legal. If it uses features
27329 introduced in Ada 2005, it will be illegal in Ada 95.)
27331 So instead we write
27333 @smallexample @c ada
27334 procedure Insert is separate;
27338 Then we have two files for the subunit @code{Insert}, with the two sets of
27340 If the package containing this is called @code{File_Queries}, then we might
27344 @item @file{file_queries-insert-2005.adb}
27345 @item @file{file_queries-insert-95.adb}
27349 and the build script renames the appropriate file to
27352 file_queries-insert.adb
27356 and then carries out the compilation.
27358 This can also be done with project files' naming schemes. For example:
27360 @smallexample @c project
27361 For Body ("File_Queries.Insert") use "file_queries-insert-2005.ada";
27365 Note also that with project files it is desirable to use a different extension
27366 than @file{ads} / @file{adb} for alternative versions. Otherwise a naming
27367 conflict may arise through another commonly used feature: to declare as part
27368 of the project a set of directories containing all the sources obeying the
27369 default naming scheme.
27371 The use of alternative units is certainly feasible in all situations,
27372 and for example the Ada part of the GNAT run-time is conditionalized
27373 based on the target architecture using this approach. As a specific example,
27374 consider the implementation of the AST feature in VMS. There is one
27382 which is the same for all architectures, and three bodies:
27386 used for all non-VMS operating systems
27387 @item s-asthan-vms-alpha.adb
27388 used for VMS on the Alpha
27389 @item s-asthan-vms-ia64.adb
27390 used for VMS on the ia64
27394 The dummy version @file{s-asthan.adb} simply raises exceptions noting that
27395 this operating system feature is not available, and the two remaining
27396 versions interface with the corresponding versions of VMS to provide
27397 VMS-compatible AST handling. The GNAT build script knows the architecture
27398 and operating system, and automatically selects the right version,
27399 renaming it if necessary to @file{s-asthan.adb} before the run-time build.
27401 Another style for arranging alternative implementations is through Ada's
27402 access-to-subprogram facility.
27403 In case some functionality is to be conditionally included,
27404 you can declare an access-to-procedure variable @code{Ref} that is initialized
27405 to designate a ``do nothing'' procedure, and then invoke @code{Ref.all}
27407 In some library package, set @code{Ref} to @code{Proc'Access} for some
27408 procedure @code{Proc} that performs the relevant processing.
27409 The initialization only occurs if the library package is included in the
27411 The same idea can also be implemented using tagged types and dispatching
27415 @node Preprocessing
27416 @section Preprocessing
27417 @cindex Preprocessing
27420 Although it is quite possible to conditionalize code without the use of
27421 C-style preprocessing, as described earlier in this section, it is
27422 nevertheless convenient in some cases to use the C approach. Moreover,
27423 older Ada compilers have often provided some preprocessing capability,
27424 so legacy code may depend on this approach, even though it is not
27427 To accommodate such use, GNAT provides a preprocessor (modeled to a large
27428 extent on the various preprocessors that have been used
27429 with legacy code on other compilers, to enable easier transition).
27431 The preprocessor may be used in two separate modes. It can be used quite
27432 separately from the compiler, to generate a separate output source file
27433 that is then fed to the compiler as a separate step. This is the
27434 @code{gnatprep} utility, whose use is fully described in
27435 @ref{Preprocessing with gnatprep}.
27436 @cindex @code{gnatprep}
27438 The preprocessing language allows such constructs as
27442 #if DEBUG or PRIORITY > 4 then
27443 bunch of declarations
27445 completely different bunch of declarations
27451 The values of the symbols @code{DEBUG} and @code{PRIORITY} can be
27452 defined either on the command line or in a separate file.
27454 The other way of running the preprocessor is even closer to the C style and
27455 often more convenient. In this approach the preprocessing is integrated into
27456 the compilation process. The compiler is fed the preprocessor input which
27457 includes @code{#if} lines etc, and then the compiler carries out the
27458 preprocessing internally and processes the resulting output.
27459 For more details on this approach, see @ref{Integrated Preprocessing}.
27462 @c *******************************
27463 @node Inline Assembler
27464 @appendix Inline Assembler
27465 @c *******************************
27468 If you need to write low-level software that interacts directly
27469 with the hardware, Ada provides two ways to incorporate assembly
27470 language code into your program. First, you can import and invoke
27471 external routines written in assembly language, an Ada feature fully
27472 supported by GNAT@. However, for small sections of code it may be simpler
27473 or more efficient to include assembly language statements directly
27474 in your Ada source program, using the facilities of the implementation-defined
27475 package @code{System.Machine_Code}, which incorporates the gcc
27476 Inline Assembler. The Inline Assembler approach offers a number of advantages,
27477 including the following:
27480 @item No need to use non-Ada tools
27481 @item Consistent interface over different targets
27482 @item Automatic usage of the proper calling conventions
27483 @item Access to Ada constants and variables
27484 @item Definition of intrinsic routines
27485 @item Possibility of inlining a subprogram comprising assembler code
27486 @item Code optimizer can take Inline Assembler code into account
27489 This chapter presents a series of examples to show you how to use
27490 the Inline Assembler. Although it focuses on the Intel x86,
27491 the general approach applies also to other processors.
27492 It is assumed that you are familiar with Ada
27493 and with assembly language programming.
27496 * Basic Assembler Syntax::
27497 * A Simple Example of Inline Assembler::
27498 * Output Variables in Inline Assembler::
27499 * Input Variables in Inline Assembler::
27500 * Inlining Inline Assembler Code::
27501 * Other Asm Functionality::
27504 @c ---------------------------------------------------------------------------
27505 @node Basic Assembler Syntax
27506 @section Basic Assembler Syntax
27509 The assembler used by GNAT and gcc is based not on the Intel assembly
27510 language, but rather on a language that descends from the AT&T Unix
27511 assembler @emph{as} (and which is often referred to as ``AT&T syntax'').
27512 The following table summarizes the main features of @emph{as} syntax
27513 and points out the differences from the Intel conventions.
27514 See the gcc @emph{as} and @emph{gas} (an @emph{as} macro
27515 pre-processor) documentation for further information.
27518 @item Register names
27519 gcc / @emph{as}: Prefix with ``%''; for example @code{%eax}
27521 Intel: No extra punctuation; for example @code{eax}
27523 @item Immediate operand
27524 gcc / @emph{as}: Prefix with ``$''; for example @code{$4}
27526 Intel: No extra punctuation; for example @code{4}
27529 gcc / @emph{as}: Prefix with ``$''; for example @code{$loc}
27531 Intel: No extra punctuation; for example @code{loc}
27533 @item Memory contents
27534 gcc / @emph{as}: No extra punctuation; for example @code{loc}
27536 Intel: Square brackets; for example @code{[loc]}
27538 @item Register contents
27539 gcc / @emph{as}: Parentheses; for example @code{(%eax)}
27541 Intel: Square brackets; for example @code{[eax]}
27543 @item Hexadecimal numbers
27544 gcc / @emph{as}: Leading ``0x'' (C language syntax); for example @code{0xA0}
27546 Intel: Trailing ``h''; for example @code{A0h}
27549 gcc / @emph{as}: Explicit in op code; for example @code{movw} to move
27552 Intel: Implicit, deduced by assembler; for example @code{mov}
27554 @item Instruction repetition
27555 gcc / @emph{as}: Split into two lines; for example
27561 Intel: Keep on one line; for example @code{rep stosl}
27563 @item Order of operands
27564 gcc / @emph{as}: Source first; for example @code{movw $4, %eax}
27566 Intel: Destination first; for example @code{mov eax, 4}
27569 @c ---------------------------------------------------------------------------
27570 @node A Simple Example of Inline Assembler
27571 @section A Simple Example of Inline Assembler
27574 The following example will generate a single assembly language statement,
27575 @code{nop}, which does nothing. Despite its lack of run-time effect,
27576 the example will be useful in illustrating the basics of
27577 the Inline Assembler facility.
27579 @smallexample @c ada
27581 with System.Machine_Code; use System.Machine_Code;
27582 procedure Nothing is
27589 @code{Asm} is a procedure declared in package @code{System.Machine_Code};
27590 here it takes one parameter, a @emph{template string} that must be a static
27591 expression and that will form the generated instruction.
27592 @code{Asm} may be regarded as a compile-time procedure that parses
27593 the template string and additional parameters (none here),
27594 from which it generates a sequence of assembly language instructions.
27596 The examples in this chapter will illustrate several of the forms
27597 for invoking @code{Asm}; a complete specification of the syntax
27598 is found in @ref{Machine Code Insertions,,, gnat_rm, GNAT Reference
27601 Under the standard GNAT conventions, the @code{Nothing} procedure
27602 should be in a file named @file{nothing.adb}.
27603 You can build the executable in the usual way:
27607 However, the interesting aspect of this example is not its run-time behavior
27608 but rather the generated assembly code.
27609 To see this output, invoke the compiler as follows:
27611 gcc -c -S -fomit-frame-pointer -gnatp @file{nothing.adb}
27613 where the options are:
27617 compile only (no bind or link)
27619 generate assembler listing
27620 @item -fomit-frame-pointer
27621 do not set up separate stack frames
27623 do not add runtime checks
27626 This gives a human-readable assembler version of the code. The resulting
27627 file will have the same name as the Ada source file, but with a @code{.s}
27628 extension. In our example, the file @file{nothing.s} has the following
27633 .file "nothing.adb"
27635 ___gnu_compiled_ada:
27638 .globl __ada_nothing
27650 The assembly code you included is clearly indicated by
27651 the compiler, between the @code{#APP} and @code{#NO_APP}
27652 delimiters. The character before the 'APP' and 'NOAPP'
27653 can differ on different targets. For example, GNU/Linux uses '#APP' while
27654 on NT you will see '/APP'.
27656 If you make a mistake in your assembler code (such as using the
27657 wrong size modifier, or using a wrong operand for the instruction) GNAT
27658 will report this error in a temporary file, which will be deleted when
27659 the compilation is finished. Generating an assembler file will help
27660 in such cases, since you can assemble this file separately using the
27661 @emph{as} assembler that comes with gcc.
27663 Assembling the file using the command
27666 as @file{nothing.s}
27669 will give you error messages whose lines correspond to the assembler
27670 input file, so you can easily find and correct any mistakes you made.
27671 If there are no errors, @emph{as} will generate an object file
27672 @file{nothing.out}.
27674 @c ---------------------------------------------------------------------------
27675 @node Output Variables in Inline Assembler
27676 @section Output Variables in Inline Assembler
27679 The examples in this section, showing how to access the processor flags,
27680 illustrate how to specify the destination operands for assembly language
27683 @smallexample @c ada
27685 with Interfaces; use Interfaces;
27686 with Ada.Text_IO; use Ada.Text_IO;
27687 with System.Machine_Code; use System.Machine_Code;
27688 procedure Get_Flags is
27689 Flags : Unsigned_32;
27692 Asm ("pushfl" & LF & HT & -- push flags on stack
27693 "popl %%eax" & LF & HT & -- load eax with flags
27694 "movl %%eax, %0", -- store flags in variable
27695 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
27696 Put_Line ("Flags register:" & Flags'Img);
27701 In order to have a nicely aligned assembly listing, we have separated
27702 multiple assembler statements in the Asm template string with linefeed
27703 (ASCII.LF) and horizontal tab (ASCII.HT) characters.
27704 The resulting section of the assembly output file is:
27711 movl %eax, -40(%ebp)
27716 It would have been legal to write the Asm invocation as:
27719 Asm ("pushfl popl %%eax movl %%eax, %0")
27722 but in the generated assembler file, this would come out as:
27726 pushfl popl %eax movl %eax, -40(%ebp)
27730 which is not so convenient for the human reader.
27732 We use Ada comments
27733 at the end of each line to explain what the assembler instructions
27734 actually do. This is a useful convention.
27736 When writing Inline Assembler instructions, you need to precede each register
27737 and variable name with a percent sign. Since the assembler already requires
27738 a percent sign at the beginning of a register name, you need two consecutive
27739 percent signs for such names in the Asm template string, thus @code{%%eax}.
27740 In the generated assembly code, one of the percent signs will be stripped off.
27742 Names such as @code{%0}, @code{%1}, @code{%2}, etc., denote input or output
27743 variables: operands you later define using @code{Input} or @code{Output}
27744 parameters to @code{Asm}.
27745 An output variable is illustrated in
27746 the third statement in the Asm template string:
27750 The intent is to store the contents of the eax register in a variable that can
27751 be accessed in Ada. Simply writing @code{movl %%eax, Flags} would not
27752 necessarily work, since the compiler might optimize by using a register
27753 to hold Flags, and the expansion of the @code{movl} instruction would not be
27754 aware of this optimization. The solution is not to store the result directly
27755 but rather to advise the compiler to choose the correct operand form;
27756 that is the purpose of the @code{%0} output variable.
27758 Information about the output variable is supplied in the @code{Outputs}
27759 parameter to @code{Asm}:
27761 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
27764 The output is defined by the @code{Asm_Output} attribute of the target type;
27765 the general format is
27767 Type'Asm_Output (constraint_string, variable_name)
27770 The constraint string directs the compiler how
27771 to store/access the associated variable. In the example
27773 Unsigned_32'Asm_Output ("=m", Flags);
27775 the @code{"m"} (memory) constraint tells the compiler that the variable
27776 @code{Flags} should be stored in a memory variable, thus preventing
27777 the optimizer from keeping it in a register. In contrast,
27779 Unsigned_32'Asm_Output ("=r", Flags);
27781 uses the @code{"r"} (register) constraint, telling the compiler to
27782 store the variable in a register.
27784 If the constraint is preceded by the equal character (@strong{=}), it tells
27785 the compiler that the variable will be used to store data into it.
27787 In the @code{Get_Flags} example, we used the @code{"g"} (global) constraint,
27788 allowing the optimizer to choose whatever it deems best.
27790 There are a fairly large number of constraints, but the ones that are
27791 most useful (for the Intel x86 processor) are the following:
27797 global (i.e.@: can be stored anywhere)
27815 use one of eax, ebx, ecx or edx
27817 use one of eax, ebx, ecx, edx, esi or edi
27820 The full set of constraints is described in the gcc and @emph{as}
27821 documentation; note that it is possible to combine certain constraints
27822 in one constraint string.
27824 You specify the association of an output variable with an assembler operand
27825 through the @code{%}@emph{n} notation, where @emph{n} is a non-negative
27827 @smallexample @c ada
27829 Asm ("pushfl" & LF & HT & -- push flags on stack
27830 "popl %%eax" & LF & HT & -- load eax with flags
27831 "movl %%eax, %0", -- store flags in variable
27832 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
27836 @code{%0} will be replaced in the expanded code by the appropriate operand,
27838 the compiler decided for the @code{Flags} variable.
27840 In general, you may have any number of output variables:
27843 Count the operands starting at 0; thus @code{%0}, @code{%1}, etc.
27845 Specify the @code{Outputs} parameter as a parenthesized comma-separated list
27846 of @code{Asm_Output} attributes
27850 @smallexample @c ada
27852 Asm ("movl %%eax, %0" & LF & HT &
27853 "movl %%ebx, %1" & LF & HT &
27855 Outputs => (Unsigned_32'Asm_Output ("=g", Var_A), -- %0 = Var_A
27856 Unsigned_32'Asm_Output ("=g", Var_B), -- %1 = Var_B
27857 Unsigned_32'Asm_Output ("=g", Var_C))); -- %2 = Var_C
27861 where @code{Var_A}, @code{Var_B}, and @code{Var_C} are variables
27862 in the Ada program.
27864 As a variation on the @code{Get_Flags} example, we can use the constraints
27865 string to direct the compiler to store the eax register into the @code{Flags}
27866 variable, instead of including the store instruction explicitly in the
27867 @code{Asm} template string:
27869 @smallexample @c ada
27871 with Interfaces; use Interfaces;
27872 with Ada.Text_IO; use Ada.Text_IO;
27873 with System.Machine_Code; use System.Machine_Code;
27874 procedure Get_Flags_2 is
27875 Flags : Unsigned_32;
27878 Asm ("pushfl" & LF & HT & -- push flags on stack
27879 "popl %%eax", -- save flags in eax
27880 Outputs => Unsigned_32'Asm_Output ("=a", Flags));
27881 Put_Line ("Flags register:" & Flags'Img);
27887 The @code{"a"} constraint tells the compiler that the @code{Flags}
27888 variable will come from the eax register. Here is the resulting code:
27896 movl %eax,-40(%ebp)
27901 The compiler generated the store of eax into Flags after
27902 expanding the assembler code.
27904 Actually, there was no need to pop the flags into the eax register;
27905 more simply, we could just pop the flags directly into the program variable:
27907 @smallexample @c ada
27909 with Interfaces; use Interfaces;
27910 with Ada.Text_IO; use Ada.Text_IO;
27911 with System.Machine_Code; use System.Machine_Code;
27912 procedure Get_Flags_3 is
27913 Flags : Unsigned_32;
27916 Asm ("pushfl" & LF & HT & -- push flags on stack
27917 "pop %0", -- save flags in Flags
27918 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
27919 Put_Line ("Flags register:" & Flags'Img);
27924 @c ---------------------------------------------------------------------------
27925 @node Input Variables in Inline Assembler
27926 @section Input Variables in Inline Assembler
27929 The example in this section illustrates how to specify the source operands
27930 for assembly language statements.
27931 The program simply increments its input value by 1:
27933 @smallexample @c ada
27935 with Interfaces; use Interfaces;
27936 with Ada.Text_IO; use Ada.Text_IO;
27937 with System.Machine_Code; use System.Machine_Code;
27938 procedure Increment is
27940 function Incr (Value : Unsigned_32) return Unsigned_32 is
27941 Result : Unsigned_32;
27944 Outputs => Unsigned_32'Asm_Output ("=a", Result),
27945 Inputs => Unsigned_32'Asm_Input ("a", Value));
27949 Value : Unsigned_32;
27953 Put_Line ("Value before is" & Value'Img);
27954 Value := Incr (Value);
27955 Put_Line ("Value after is" & Value'Img);
27960 The @code{Outputs} parameter to @code{Asm} specifies
27961 that the result will be in the eax register and that it is to be stored
27962 in the @code{Result} variable.
27964 The @code{Inputs} parameter looks much like the @code{Outputs} parameter,
27965 but with an @code{Asm_Input} attribute.
27966 The @code{"="} constraint, indicating an output value, is not present.
27968 You can have multiple input variables, in the same way that you can have more
27969 than one output variable.
27971 The parameter count (%0, %1) etc, still starts at the first output statement,
27972 and continues with the input statements.
27974 Just as the @code{Outputs} parameter causes the register to be stored into the
27975 target variable after execution of the assembler statements, so does the
27976 @code{Inputs} parameter cause its variable to be loaded into the register
27977 before execution of the assembler statements.
27979 Thus the effect of the @code{Asm} invocation is:
27981 @item load the 32-bit value of @code{Value} into eax
27982 @item execute the @code{incl %eax} instruction
27983 @item store the contents of eax into the @code{Result} variable
27986 The resulting assembler file (with @option{-O2} optimization) contains:
27989 _increment__incr.1:
28002 @c ---------------------------------------------------------------------------
28003 @node Inlining Inline Assembler Code
28004 @section Inlining Inline Assembler Code
28007 For a short subprogram such as the @code{Incr} function in the previous
28008 section, the overhead of the call and return (creating / deleting the stack
28009 frame) can be significant, compared to the amount of code in the subprogram
28010 body. A solution is to apply Ada's @code{Inline} pragma to the subprogram,
28011 which directs the compiler to expand invocations of the subprogram at the
28012 point(s) of call, instead of setting up a stack frame for out-of-line calls.
28013 Here is the resulting program:
28015 @smallexample @c ada
28017 with Interfaces; use Interfaces;
28018 with Ada.Text_IO; use Ada.Text_IO;
28019 with System.Machine_Code; use System.Machine_Code;
28020 procedure Increment_2 is
28022 function Incr (Value : Unsigned_32) return Unsigned_32 is
28023 Result : Unsigned_32;
28026 Outputs => Unsigned_32'Asm_Output ("=a", Result),
28027 Inputs => Unsigned_32'Asm_Input ("a", Value));
28030 pragma Inline (Increment);
28032 Value : Unsigned_32;
28036 Put_Line ("Value before is" & Value'Img);
28037 Value := Increment (Value);
28038 Put_Line ("Value after is" & Value'Img);
28043 Compile the program with both optimization (@option{-O2}) and inlining
28044 (@option{-gnatn}) enabled.
28046 The @code{Incr} function is still compiled as usual, but at the
28047 point in @code{Increment} where our function used to be called:
28052 call _increment__incr.1
28057 the code for the function body directly appears:
28070 thus saving the overhead of stack frame setup and an out-of-line call.
28072 @c ---------------------------------------------------------------------------
28073 @node Other Asm Functionality
28074 @section Other @code{Asm} Functionality
28077 This section describes two important parameters to the @code{Asm}
28078 procedure: @code{Clobber}, which identifies register usage;
28079 and @code{Volatile}, which inhibits unwanted optimizations.
28082 * The Clobber Parameter::
28083 * The Volatile Parameter::
28086 @c ---------------------------------------------------------------------------
28087 @node The Clobber Parameter
28088 @subsection The @code{Clobber} Parameter
28091 One of the dangers of intermixing assembly language and a compiled language
28092 such as Ada is that the compiler needs to be aware of which registers are
28093 being used by the assembly code. In some cases, such as the earlier examples,
28094 the constraint string is sufficient to indicate register usage (e.g.,
28096 the eax register). But more generally, the compiler needs an explicit
28097 identification of the registers that are used by the Inline Assembly
28100 Using a register that the compiler doesn't know about
28101 could be a side effect of an instruction (like @code{mull}
28102 storing its result in both eax and edx).
28103 It can also arise from explicit register usage in your
28104 assembly code; for example:
28107 Asm ("movl %0, %%ebx" & LF & HT &
28109 Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
28110 Inputs => Unsigned_32'Asm_Input ("g", Var_In));
28114 where the compiler (since it does not analyze the @code{Asm} template string)
28115 does not know you are using the ebx register.
28117 In such cases you need to supply the @code{Clobber} parameter to @code{Asm},
28118 to identify the registers that will be used by your assembly code:
28122 Asm ("movl %0, %%ebx" & LF & HT &
28124 Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
28125 Inputs => Unsigned_32'Asm_Input ("g", Var_In),
28130 The Clobber parameter is a static string expression specifying the
28131 register(s) you are using. Note that register names are @emph{not} prefixed
28132 by a percent sign. Also, if more than one register is used then their names
28133 are separated by commas; e.g., @code{"eax, ebx"}
28135 The @code{Clobber} parameter has several additional uses:
28137 @item Use ``register'' name @code{cc} to indicate that flags might have changed
28138 @item Use ``register'' name @code{memory} if you changed a memory location
28141 @c ---------------------------------------------------------------------------
28142 @node The Volatile Parameter
28143 @subsection The @code{Volatile} Parameter
28144 @cindex Volatile parameter
28147 Compiler optimizations in the presence of Inline Assembler may sometimes have
28148 unwanted effects. For example, when an @code{Asm} invocation with an input
28149 variable is inside a loop, the compiler might move the loading of the input
28150 variable outside the loop, regarding it as a one-time initialization.
28152 If this effect is not desired, you can disable such optimizations by setting
28153 the @code{Volatile} parameter to @code{True}; for example:
28155 @smallexample @c ada
28157 Asm ("movl %0, %%ebx" & LF & HT &
28159 Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
28160 Inputs => Unsigned_32'Asm_Input ("g", Var_In),
28166 By default, @code{Volatile} is set to @code{False} unless there is no
28167 @code{Outputs} parameter.
28169 Although setting @code{Volatile} to @code{True} prevents unwanted
28170 optimizations, it will also disable other optimizations that might be
28171 important for efficiency. In general, you should set @code{Volatile}
28172 to @code{True} only if the compiler's optimizations have created
28174 @c END OF INLINE ASSEMBLER CHAPTER
28175 @c ===============================
28177 @c ***********************************
28178 @c * Compatibility and Porting Guide *
28179 @c ***********************************
28180 @node Compatibility and Porting Guide
28181 @appendix Compatibility and Porting Guide
28184 This chapter describes the compatibility issues that may arise between
28185 GNAT and other Ada compilation systems (including those for Ada 83),
28186 and shows how GNAT can expedite porting
28187 applications developed in other Ada environments.
28190 * Compatibility with Ada 83::
28191 * Compatibility between Ada 95 and Ada 2005::
28192 * Implementation-dependent characteristics::
28193 * Compatibility with Other Ada Systems::
28194 * Representation Clauses::
28196 @c Brief section is only in non-VMS version
28197 @c Full chapter is in VMS version
28198 * Compatibility with HP Ada 83::
28201 * Transitioning to 64-Bit GNAT for OpenVMS::
28205 @node Compatibility with Ada 83
28206 @section Compatibility with Ada 83
28207 @cindex Compatibility (between Ada 83 and Ada 95 / Ada 2005)
28210 Ada 95 and Ada 2005 are highly upwards compatible with Ada 83. In
28211 particular, the design intention was that the difficulties associated
28212 with moving from Ada 83 to Ada 95 or Ada 2005 should be no greater than those
28213 that occur when moving from one Ada 83 system to another.
28215 However, there are a number of points at which there are minor
28216 incompatibilities. The @cite{Ada 95 Annotated Reference Manual} contains
28217 full details of these issues,
28218 and should be consulted for a complete treatment.
28220 following subsections treat the most likely issues to be encountered.
28223 * Legal Ada 83 programs that are illegal in Ada 95::
28224 * More deterministic semantics::
28225 * Changed semantics::
28226 * Other language compatibility issues::
28229 @node Legal Ada 83 programs that are illegal in Ada 95
28230 @subsection Legal Ada 83 programs that are illegal in Ada 95
28232 Some legal Ada 83 programs are illegal (i.e., they will fail to compile) in
28233 Ada 95 and thus also in Ada 2005:
28236 @item Character literals
28237 Some uses of character literals are ambiguous. Since Ada 95 has introduced
28238 @code{Wide_Character} as a new predefined character type, some uses of
28239 character literals that were legal in Ada 83 are illegal in Ada 95.
28241 @smallexample @c ada
28242 for Char in 'A' .. 'Z' loop @dots{} end loop;
28246 The problem is that @code{'A'} and @code{'Z'} could be from either
28247 @code{Character} or @code{Wide_Character}. The simplest correction
28248 is to make the type explicit; e.g.:
28249 @smallexample @c ada
28250 for Char in Character range 'A' .. 'Z' loop @dots{} end loop;
28253 @item New reserved words
28254 The identifiers @code{abstract}, @code{aliased}, @code{protected},
28255 @code{requeue}, @code{tagged}, and @code{until} are reserved in Ada 95.
28256 Existing Ada 83 code using any of these identifiers must be edited to
28257 use some alternative name.
28259 @item Freezing rules
28260 The rules in Ada 95 are slightly different with regard to the point at
28261 which entities are frozen, and representation pragmas and clauses are
28262 not permitted past the freeze point. This shows up most typically in
28263 the form of an error message complaining that a representation item
28264 appears too late, and the appropriate corrective action is to move
28265 the item nearer to the declaration of the entity to which it refers.
28267 A particular case is that representation pragmas
28270 extended HP Ada 83 compatibility pragmas such as @code{Export_Procedure})
28272 cannot be applied to a subprogram body. If necessary, a separate subprogram
28273 declaration must be introduced to which the pragma can be applied.
28275 @item Optional bodies for library packages
28276 In Ada 83, a package that did not require a package body was nevertheless
28277 allowed to have one. This lead to certain surprises in compiling large
28278 systems (situations in which the body could be unexpectedly ignored by the
28279 binder). In Ada 95, if a package does not require a body then it is not
28280 permitted to have a body. To fix this problem, simply remove a redundant
28281 body if it is empty, or, if it is non-empty, introduce a dummy declaration
28282 into the spec that makes the body required. One approach is to add a private
28283 part to the package declaration (if necessary), and define a parameterless
28284 procedure called @code{Requires_Body}, which must then be given a dummy
28285 procedure body in the package body, which then becomes required.
28286 Another approach (assuming that this does not introduce elaboration
28287 circularities) is to add an @code{Elaborate_Body} pragma to the package spec,
28288 since one effect of this pragma is to require the presence of a package body.
28290 @item @code{Numeric_Error} is now the same as @code{Constraint_Error}
28291 In Ada 95, the exception @code{Numeric_Error} is a renaming of
28292 @code{Constraint_Error}.
28293 This means that it is illegal to have separate exception handlers for
28294 the two exceptions. The fix is simply to remove the handler for the
28295 @code{Numeric_Error} case (since even in Ada 83, a compiler was free to raise
28296 @code{Constraint_Error} in place of @code{Numeric_Error} in all cases).
28298 @item Indefinite subtypes in generics
28299 In Ada 83, it was permissible to pass an indefinite type (e.g.@: @code{String})
28300 as the actual for a generic formal private type, but then the instantiation
28301 would be illegal if there were any instances of declarations of variables
28302 of this type in the generic body. In Ada 95, to avoid this clear violation
28303 of the methodological principle known as the ``contract model'',
28304 the generic declaration explicitly indicates whether
28305 or not such instantiations are permitted. If a generic formal parameter
28306 has explicit unknown discriminants, indicated by using @code{(<>)} after the
28307 subtype name, then it can be instantiated with indefinite types, but no
28308 stand-alone variables can be declared of this type. Any attempt to declare
28309 such a variable will result in an illegality at the time the generic is
28310 declared. If the @code{(<>)} notation is not used, then it is illegal
28311 to instantiate the generic with an indefinite type.
28312 This is the potential incompatibility issue when porting Ada 83 code to Ada 95.
28313 It will show up as a compile time error, and
28314 the fix is usually simply to add the @code{(<>)} to the generic declaration.
28317 @node More deterministic semantics
28318 @subsection More deterministic semantics
28322 Conversions from real types to integer types round away from 0. In Ada 83
28323 the conversion Integer(2.5) could deliver either 2 or 3 as its value. This
28324 implementation freedom was intended to support unbiased rounding in
28325 statistical applications, but in practice it interfered with portability.
28326 In Ada 95 the conversion semantics are unambiguous, and rounding away from 0
28327 is required. Numeric code may be affected by this change in semantics.
28328 Note, though, that this issue is no worse than already existed in Ada 83
28329 when porting code from one vendor to another.
28332 The Real-Time Annex introduces a set of policies that define the behavior of
28333 features that were implementation dependent in Ada 83, such as the order in
28334 which open select branches are executed.
28337 @node Changed semantics
28338 @subsection Changed semantics
28341 The worst kind of incompatibility is one where a program that is legal in
28342 Ada 83 is also legal in Ada 95 but can have an effect in Ada 95 that was not
28343 possible in Ada 83. Fortunately this is extremely rare, but the one
28344 situation that you should be alert to is the change in the predefined type
28345 @code{Character} from 7-bit ASCII to 8-bit Latin-1.
28348 @item Range of type @code{Character}
28349 The range of @code{Standard.Character} is now the full 256 characters
28350 of Latin-1, whereas in most Ada 83 implementations it was restricted
28351 to 128 characters. Although some of the effects of
28352 this change will be manifest in compile-time rejection of legal
28353 Ada 83 programs it is possible for a working Ada 83 program to have
28354 a different effect in Ada 95, one that was not permitted in Ada 83.
28355 As an example, the expression
28356 @code{Character'Pos(Character'Last)} returned @code{127} in Ada 83 and now
28357 delivers @code{255} as its value.
28358 In general, you should look at the logic of any
28359 character-processing Ada 83 program and see whether it needs to be adapted
28360 to work correctly with Latin-1. Note that the predefined Ada 95 API has a
28361 character handling package that may be relevant if code needs to be adapted
28362 to account for the additional Latin-1 elements.
28363 The desirable fix is to
28364 modify the program to accommodate the full character set, but in some cases
28365 it may be convenient to define a subtype or derived type of Character that
28366 covers only the restricted range.
28370 @node Other language compatibility issues
28371 @subsection Other language compatibility issues
28374 @item @option{-gnat83} switch
28375 All implementations of GNAT provide a switch that causes GNAT to operate
28376 in Ada 83 mode. In this mode, some but not all compatibility problems
28377 of the type described above are handled automatically. For example, the
28378 new reserved words introduced in Ada 95 and Ada 2005 are treated simply
28379 as identifiers as in Ada 83.
28381 in practice, it is usually advisable to make the necessary modifications
28382 to the program to remove the need for using this switch.
28383 See @ref{Compiling Different Versions of Ada}.
28385 @item Support for removed Ada 83 pragmas and attributes
28386 A number of pragmas and attributes from Ada 83 were removed from Ada 95,
28387 generally because they were replaced by other mechanisms. Ada 95 and Ada 2005
28388 compilers are allowed, but not required, to implement these missing
28389 elements. In contrast with some other compilers, GNAT implements all
28390 such pragmas and attributes, eliminating this compatibility concern. These
28391 include @code{pragma Interface} and the floating point type attributes
28392 (@code{Emax}, @code{Mantissa}, etc.), among other items.
28396 @node Compatibility between Ada 95 and Ada 2005
28397 @section Compatibility between Ada 95 and Ada 2005
28398 @cindex Compatibility between Ada 95 and Ada 2005
28401 Although Ada 2005 was designed to be upwards compatible with Ada 95, there are
28402 a number of incompatibilities. Several are enumerated below;
28403 for a complete description please see the
28404 Annotated Ada 2005 Reference Manual, or section 9.1.1 in
28405 @cite{Rationale for Ada 2005}.
28408 @item New reserved words.
28409 The words @code{interface}, @code{overriding} and @code{synchronized} are
28410 reserved in Ada 2005.
28411 A pre-Ada 2005 program that uses any of these as an identifier will be
28414 @item New declarations in predefined packages.
28415 A number of packages in the predefined environment contain new declarations:
28416 @code{Ada.Exceptions}, @code{Ada.Real_Time}, @code{Ada.Strings},
28417 @code{Ada.Strings.Fixed}, @code{Ada.Strings.Bounded},
28418 @code{Ada.Strings.Unbounded}, @code{Ada.Strings.Wide_Fixed},
28419 @code{Ada.Strings.Wide_Bounded}, @code{Ada.Strings.Wide_Unbounded},
28420 @code{Ada.Tags}, @code{Ada.Text_IO}, and @code{Interfaces.C}.
28421 If an Ada 95 program does a @code{with} and @code{use} of any of these
28422 packages, the new declarations may cause name clashes.
28424 @item Access parameters.
28425 A nondispatching subprogram with an access parameter cannot be renamed
28426 as a dispatching operation. This was permitted in Ada 95.
28428 @item Access types, discriminants, and constraints.
28429 Rule changes in this area have led to some incompatibilities; for example,
28430 constrained subtypes of some access types are not permitted in Ada 2005.
28432 @item Aggregates for limited types.
28433 The allowance of aggregates for limited types in Ada 2005 raises the
28434 possibility of ambiguities in legal Ada 95 programs, since additional types
28435 now need to be considered in expression resolution.
28437 @item Fixed-point multiplication and division.
28438 Certain expressions involving ``*'' or ``/'' for a fixed-point type, which
28439 were legal in Ada 95 and invoked the predefined versions of these operations,
28441 The ambiguity may be resolved either by applying a type conversion to the
28442 expression, or by explicitly invoking the operation from package
28445 @item Return-by-reference types.
28446 The Ada 95 return-by-reference mechanism has been removed. Instead, the user
28447 can declare a function returning a value from an anonymous access type.
28451 @node Implementation-dependent characteristics
28452 @section Implementation-dependent characteristics
28454 Although the Ada language defines the semantics of each construct as
28455 precisely as practical, in some situations (for example for reasons of
28456 efficiency, or where the effect is heavily dependent on the host or target
28457 platform) the implementation is allowed some freedom. In porting Ada 83
28458 code to GNAT, you need to be aware of whether / how the existing code
28459 exercised such implementation dependencies. Such characteristics fall into
28460 several categories, and GNAT offers specific support in assisting the
28461 transition from certain Ada 83 compilers.
28464 * Implementation-defined pragmas::
28465 * Implementation-defined attributes::
28467 * Elaboration order::
28468 * Target-specific aspects::
28471 @node Implementation-defined pragmas
28472 @subsection Implementation-defined pragmas
28475 Ada compilers are allowed to supplement the language-defined pragmas, and
28476 these are a potential source of non-portability. All GNAT-defined pragmas
28477 are described in @ref{Implementation Defined Pragmas,,, gnat_rm, GNAT
28478 Reference Manual}, and these include several that are specifically
28479 intended to correspond to other vendors' Ada 83 pragmas.
28480 For migrating from VADS, the pragma @code{Use_VADS_Size} may be useful.
28481 For compatibility with HP Ada 83, GNAT supplies the pragmas
28482 @code{Extend_System}, @code{Ident}, @code{Inline_Generic},
28483 @code{Interface_Name}, @code{Passive}, @code{Suppress_All},
28484 and @code{Volatile}.
28485 Other relevant pragmas include @code{External} and @code{Link_With}.
28486 Some vendor-specific
28487 Ada 83 pragmas (@code{Share_Generic}, @code{Subtitle}, and @code{Title}) are
28489 avoiding compiler rejection of units that contain such pragmas; they are not
28490 relevant in a GNAT context and hence are not otherwise implemented.
28492 @node Implementation-defined attributes
28493 @subsection Implementation-defined attributes
28495 Analogous to pragmas, the set of attributes may be extended by an
28496 implementation. All GNAT-defined attributes are described in
28497 @ref{Implementation Defined Attributes,,, gnat_rm, GNAT Reference
28498 Manual}, and these include several that are specifically intended
28499 to correspond to other vendors' Ada 83 attributes. For migrating from VADS,
28500 the attribute @code{VADS_Size} may be useful. For compatibility with HP
28501 Ada 83, GNAT supplies the attributes @code{Bit}, @code{Machine_Size} and
28505 @subsection Libraries
28507 Vendors may supply libraries to supplement the standard Ada API. If Ada 83
28508 code uses vendor-specific libraries then there are several ways to manage
28509 this in Ada 95 or Ada 2005:
28512 If the source code for the libraries (specs and bodies) are
28513 available, then the libraries can be migrated in the same way as the
28516 If the source code for the specs but not the bodies are
28517 available, then you can reimplement the bodies.
28519 Some features introduced by Ada 95 obviate the need for library support. For
28520 example most Ada 83 vendors supplied a package for unsigned integers. The
28521 Ada 95 modular type feature is the preferred way to handle this need, so
28522 instead of migrating or reimplementing the unsigned integer package it may
28523 be preferable to retrofit the application using modular types.
28526 @node Elaboration order
28527 @subsection Elaboration order
28529 The implementation can choose any elaboration order consistent with the unit
28530 dependency relationship. This freedom means that some orders can result in
28531 Program_Error being raised due to an ``Access Before Elaboration'': an attempt
28532 to invoke a subprogram its body has been elaborated, or to instantiate a
28533 generic before the generic body has been elaborated. By default GNAT
28534 attempts to choose a safe order (one that will not encounter access before
28535 elaboration problems) by implicitly inserting @code{Elaborate} or
28536 @code{Elaborate_All} pragmas where
28537 needed. However, this can lead to the creation of elaboration circularities
28538 and a resulting rejection of the program by gnatbind. This issue is
28539 thoroughly described in @ref{Elaboration Order Handling in GNAT}.
28540 In brief, there are several
28541 ways to deal with this situation:
28545 Modify the program to eliminate the circularities, e.g.@: by moving
28546 elaboration-time code into explicitly-invoked procedures
28548 Constrain the elaboration order by including explicit @code{Elaborate_Body} or
28549 @code{Elaborate} pragmas, and then inhibit the generation of implicit
28550 @code{Elaborate_All}
28551 pragmas either globally (as an effect of the @option{-gnatE} switch) or locally
28552 (by selectively suppressing elaboration checks via pragma
28553 @code{Suppress(Elaboration_Check)} when it is safe to do so).
28556 @node Target-specific aspects
28557 @subsection Target-specific aspects
28559 Low-level applications need to deal with machine addresses, data
28560 representations, interfacing with assembler code, and similar issues. If
28561 such an Ada 83 application is being ported to different target hardware (for
28562 example where the byte endianness has changed) then you will need to
28563 carefully examine the program logic; the porting effort will heavily depend
28564 on the robustness of the original design. Moreover, Ada 95 (and thus
28565 Ada 2005) are sometimes
28566 incompatible with typical Ada 83 compiler practices regarding implicit
28567 packing, the meaning of the Size attribute, and the size of access values.
28568 GNAT's approach to these issues is described in @ref{Representation Clauses}.
28570 @node Compatibility with Other Ada Systems
28571 @section Compatibility with Other Ada Systems
28574 If programs avoid the use of implementation dependent and
28575 implementation defined features, as documented in the @cite{Ada
28576 Reference Manual}, there should be a high degree of portability between
28577 GNAT and other Ada systems. The following are specific items which
28578 have proved troublesome in moving Ada 95 programs from GNAT to other Ada 95
28579 compilers, but do not affect porting code to GNAT@.
28580 (As of @value{NOW}, GNAT is the only compiler available for Ada 2005;
28581 the following issues may or may not arise for Ada 2005 programs
28582 when other compilers appear.)
28585 @item Ada 83 Pragmas and Attributes
28586 Ada 95 compilers are allowed, but not required, to implement the missing
28587 Ada 83 pragmas and attributes that are no longer defined in Ada 95.
28588 GNAT implements all such pragmas and attributes, eliminating this as
28589 a compatibility concern, but some other Ada 95 compilers reject these
28590 pragmas and attributes.
28592 @item Specialized Needs Annexes
28593 GNAT implements the full set of special needs annexes. At the
28594 current time, it is the only Ada 95 compiler to do so. This means that
28595 programs making use of these features may not be portable to other Ada
28596 95 compilation systems.
28598 @item Representation Clauses
28599 Some other Ada 95 compilers implement only the minimal set of
28600 representation clauses required by the Ada 95 reference manual. GNAT goes
28601 far beyond this minimal set, as described in the next section.
28604 @node Representation Clauses
28605 @section Representation Clauses
28608 The Ada 83 reference manual was quite vague in describing both the minimal
28609 required implementation of representation clauses, and also their precise
28610 effects. Ada 95 (and thus also Ada 2005) are much more explicit, but the
28611 minimal set of capabilities required is still quite limited.
28613 GNAT implements the full required set of capabilities in
28614 Ada 95 and Ada 2005, but also goes much further, and in particular
28615 an effort has been made to be compatible with existing Ada 83 usage to the
28616 greatest extent possible.
28618 A few cases exist in which Ada 83 compiler behavior is incompatible with
28619 the requirements in Ada 95 (and thus also Ada 2005). These are instances of
28620 intentional or accidental dependence on specific implementation dependent
28621 characteristics of these Ada 83 compilers. The following is a list of
28622 the cases most likely to arise in existing Ada 83 code.
28625 @item Implicit Packing
28626 Some Ada 83 compilers allowed a Size specification to cause implicit
28627 packing of an array or record. This could cause expensive implicit
28628 conversions for change of representation in the presence of derived
28629 types, and the Ada design intends to avoid this possibility.
28630 Subsequent AI's were issued to make it clear that such implicit
28631 change of representation in response to a Size clause is inadvisable,
28632 and this recommendation is represented explicitly in the Ada 95 (and Ada 2005)
28633 Reference Manuals as implementation advice that is followed by GNAT@.
28634 The problem will show up as an error
28635 message rejecting the size clause. The fix is simply to provide
28636 the explicit pragma @code{Pack}, or for more fine tuned control, provide
28637 a Component_Size clause.
28639 @item Meaning of Size Attribute
28640 The Size attribute in Ada 95 (and Ada 2005) for discrete types is defined as
28641 the minimal number of bits required to hold values of the type. For example,
28642 on a 32-bit machine, the size of @code{Natural} will typically be 31 and not
28643 32 (since no sign bit is required). Some Ada 83 compilers gave 31, and
28644 some 32 in this situation. This problem will usually show up as a compile
28645 time error, but not always. It is a good idea to check all uses of the
28646 'Size attribute when porting Ada 83 code. The GNAT specific attribute
28647 Object_Size can provide a useful way of duplicating the behavior of
28648 some Ada 83 compiler systems.
28650 @item Size of Access Types
28651 A common assumption in Ada 83 code is that an access type is in fact a pointer,
28652 and that therefore it will be the same size as a System.Address value. This
28653 assumption is true for GNAT in most cases with one exception. For the case of
28654 a pointer to an unconstrained array type (where the bounds may vary from one
28655 value of the access type to another), the default is to use a ``fat pointer'',
28656 which is represented as two separate pointers, one to the bounds, and one to
28657 the array. This representation has a number of advantages, including improved
28658 efficiency. However, it may cause some difficulties in porting existing Ada 83
28659 code which makes the assumption that, for example, pointers fit in 32 bits on
28660 a machine with 32-bit addressing.
28662 To get around this problem, GNAT also permits the use of ``thin pointers'' for
28663 access types in this case (where the designated type is an unconstrained array
28664 type). These thin pointers are indeed the same size as a System.Address value.
28665 To specify a thin pointer, use a size clause for the type, for example:
28667 @smallexample @c ada
28668 type X is access all String;
28669 for X'Size use Standard'Address_Size;
28673 which will cause the type X to be represented using a single pointer.
28674 When using this representation, the bounds are right behind the array.
28675 This representation is slightly less efficient, and does not allow quite
28676 such flexibility in the use of foreign pointers or in using the
28677 Unrestricted_Access attribute to create pointers to non-aliased objects.
28678 But for any standard portable use of the access type it will work in
28679 a functionally correct manner and allow porting of existing code.
28680 Note that another way of forcing a thin pointer representation
28681 is to use a component size clause for the element size in an array,
28682 or a record representation clause for an access field in a record.
28686 @c This brief section is only in the non-VMS version
28687 @c The complete chapter on HP Ada is in the VMS version
28688 @node Compatibility with HP Ada 83
28689 @section Compatibility with HP Ada 83
28692 The VMS version of GNAT fully implements all the pragmas and attributes
28693 provided by HP Ada 83, as well as providing the standard HP Ada 83
28694 libraries, including Starlet. In addition, data layouts and parameter
28695 passing conventions are highly compatible. This means that porting
28696 existing HP Ada 83 code to GNAT in VMS systems should be easier than
28697 most other porting efforts. The following are some of the most
28698 significant differences between GNAT and HP Ada 83.
28701 @item Default floating-point representation
28702 In GNAT, the default floating-point format is IEEE, whereas in HP Ada 83,
28703 it is VMS format. GNAT does implement the necessary pragmas
28704 (Long_Float, Float_Representation) for changing this default.
28707 The package System in GNAT exactly corresponds to the definition in the
28708 Ada 95 reference manual, which means that it excludes many of the
28709 HP Ada 83 extensions. However, a separate package Aux_DEC is provided
28710 that contains the additional definitions, and a special pragma,
28711 Extend_System allows this package to be treated transparently as an
28712 extension of package System.
28715 The definitions provided by Aux_DEC are exactly compatible with those
28716 in the HP Ada 83 version of System, with one exception.
28717 HP Ada provides the following declarations:
28719 @smallexample @c ada
28720 TO_ADDRESS (INTEGER)
28721 TO_ADDRESS (UNSIGNED_LONGWORD)
28722 TO_ADDRESS (@i{universal_integer})
28726 The version of TO_ADDRESS taking a @i{universal integer} argument is in fact
28727 an extension to Ada 83 not strictly compatible with the reference manual.
28728 In GNAT, we are constrained to be exactly compatible with the standard,
28729 and this means we cannot provide this capability. In HP Ada 83, the
28730 point of this definition is to deal with a call like:
28732 @smallexample @c ada
28733 TO_ADDRESS (16#12777#);
28737 Normally, according to the Ada 83 standard, one would expect this to be
28738 ambiguous, since it matches both the INTEGER and UNSIGNED_LONGWORD forms
28739 of TO_ADDRESS@. However, in HP Ada 83, there is no ambiguity, since the
28740 definition using @i{universal_integer} takes precedence.
28742 In GNAT, since the version with @i{universal_integer} cannot be supplied, it
28743 is not possible to be 100% compatible. Since there are many programs using
28744 numeric constants for the argument to TO_ADDRESS, the decision in GNAT was
28745 to change the name of the function in the UNSIGNED_LONGWORD case, so the
28746 declarations provided in the GNAT version of AUX_Dec are:
28748 @smallexample @c ada
28749 function To_Address (X : Integer) return Address;
28750 pragma Pure_Function (To_Address);
28752 function To_Address_Long (X : Unsigned_Longword)
28754 pragma Pure_Function (To_Address_Long);
28758 This means that programs using TO_ADDRESS for UNSIGNED_LONGWORD must
28759 change the name to TO_ADDRESS_LONG@.
28761 @item Task_Id values
28762 The Task_Id values assigned will be different in the two systems, and GNAT
28763 does not provide a specified value for the Task_Id of the environment task,
28764 which in GNAT is treated like any other declared task.
28768 For full details on these and other less significant compatibility issues,
28769 see appendix E of the HP publication entitled @cite{HP Ada, Technical
28770 Overview and Comparison on HP Platforms}.
28772 For GNAT running on other than VMS systems, all the HP Ada 83 pragmas and
28773 attributes are recognized, although only a subset of them can sensibly
28774 be implemented. The description of pragmas in @ref{Implementation
28775 Defined Pragmas,,, gnat_rm, GNAT Reference Manual}
28776 indicates whether or not they are applicable to non-VMS systems.
28780 @node Transitioning to 64-Bit GNAT for OpenVMS
28781 @section Transitioning to 64-Bit @value{EDITION} for OpenVMS
28784 This section is meant to assist users of pre-2006 @value{EDITION}
28785 for Alpha OpenVMS who are transitioning to 64-bit @value{EDITION},
28786 the version of the GNAT technology supplied in 2006 and later for
28787 OpenVMS on both Alpha and I64.
28790 * Introduction to transitioning::
28791 * Migration of 32 bit code::
28792 * Taking advantage of 64 bit addressing::
28793 * Technical details::
28796 @node Introduction to transitioning
28797 @subsection Introduction
28800 64-bit @value{EDITION} for Open VMS has been designed to meet
28805 Providing a full conforming implementation of Ada 95 and Ada 2005
28808 Allowing maximum backward compatibility, thus easing migration of existing
28812 Supplying a path for exploiting the full 64-bit address range
28816 Ada's strong typing semantics has made it
28817 impractical to have different 32-bit and 64-bit modes. As soon as
28818 one object could possibly be outside the 32-bit address space, this
28819 would make it necessary for the @code{System.Address} type to be 64 bits.
28820 In particular, this would cause inconsistencies if 32-bit code is
28821 called from 64-bit code that raises an exception.
28823 This issue has been resolved by always using 64-bit addressing
28824 at the system level, but allowing for automatic conversions between
28825 32-bit and 64-bit addresses where required. Thus users who
28826 do not currently require 64-bit addressing capabilities, can
28827 recompile their code with only minimal changes (and indeed
28828 if the code is written in portable Ada, with no assumptions about
28829 the size of the @code{Address} type, then no changes at all are necessary).
28831 this approach provides a simple, gradual upgrade path to future
28832 use of larger memories than available for 32-bit systems.
28833 Also, newly written applications or libraries will by default
28834 be fully compatible with future systems exploiting 64-bit
28835 addressing capabilities.
28837 @ref{Migration of 32 bit code}, will focus on porting applications
28838 that do not require more than 2 GB of
28839 addressable memory. This code will be referred to as
28840 @emph{32-bit code}.
28841 For applications intending to exploit the full 64-bit address space,
28842 @ref{Taking advantage of 64 bit addressing},
28843 will consider further changes that may be required.
28844 Such code will be referred to below as @emph{64-bit code}.
28846 @node Migration of 32 bit code
28847 @subsection Migration of 32-bit code
28851 * Access types and 32/64-bit allocation::
28852 * Unchecked conversions::
28853 * Predefined constants::
28854 * Interfacing with C::
28855 * 32/64-bit descriptors::
28856 * Experience with source compatibility::
28859 @node Address types
28860 @subsubsection Address types
28863 To solve the problem of mixing 64-bit and 32-bit addressing,
28864 while maintaining maximum backward compatibility, the following
28865 approach has been taken:
28869 @code{System.Address} always has a size of 64 bits
28870 @cindex @code{System.Address} size
28871 @cindex @code{Address} size
28874 @code{System.Short_Address} is a 32-bit subtype of @code{System.Address}
28875 @cindex @code{System.Short_Address} size
28876 @cindex @code{Short_Address} size
28880 Since @code{System.Short_Address} is a subtype of @code{System.Address},
28881 a @code{Short_Address}
28882 may be used where an @code{Address} is required, and vice versa, without
28883 needing explicit type conversions.
28884 By virtue of the Open VMS parameter passing conventions,
28886 and exported subprograms that have 32-bit address parameters are
28887 compatible with those that have 64-bit address parameters.
28888 (See @ref{Making code 64 bit clean} for details.)
28890 The areas that may need attention are those where record types have
28891 been defined that contain components of the type @code{System.Address}, and
28892 where objects of this type are passed to code expecting a record layout with
28895 Different compilers on different platforms cannot be
28896 expected to represent the same type in the same way,
28897 since alignment constraints
28898 and other system-dependent properties affect the compiler's decision.
28899 For that reason, Ada code
28900 generally uses representation clauses to specify the expected
28901 layout where required.
28903 If such a representation clause uses 32 bits for a component having
28904 the type @code{System.Address}, 64-bit @value{EDITION} for OpenVMS
28905 will detect that error and produce a specific diagnostic message.
28906 The developer should then determine whether the representation
28907 should be 64 bits or not and make either of two changes:
28908 change the size to 64 bits and leave the type as @code{System.Address}, or
28909 leave the size as 32 bits and change the type to @code{System.Short_Address}.
28910 Since @code{Short_Address} is a subtype of @code{Address}, no changes are
28911 required in any code setting or accessing the field; the compiler will
28912 automatically perform any needed conversions between address
28915 @node Access types and 32/64-bit allocation
28916 @subsubsection Access types and 32/64-bit allocation
28917 @cindex 32-bit allocation
28918 @cindex 64-bit allocation
28921 By default, objects designated by access values are always allocated in
28922 the 64-bit address space, and access values themselves are represented
28923 in 64 bits. If these defaults are not appropriate, and 32-bit allocation
28924 is required (for example if the address of an allocated object is assigned
28925 to a @code{Short_Address} variable), then several alternatives are available:
28929 A pool-specific access type (ie, an @w{Ada 83} access type, whose
28930 definition is @code{access T} versus @code{access all T} or
28931 @code{access constant T}), may be declared with a @code{'Size} representation
28932 clause that establishes the size as 32 bits.
28933 In such circumstances allocations for that type will
28934 be from the 32-bit heap. Such a clause is not permitted
28935 for a general access type (declared with @code{access all} or
28936 @code{access constant}) as values of such types must be able to refer
28937 to any object of the designated type, including objects residing outside
28938 the 32-bit address range. Existing @w{Ada 83} code will not contain such
28939 type definitions, however, since general access types were introduced
28943 Switches for @command{GNAT BIND} control whether the internal GNAT
28944 allocation routine @code{__gnat_malloc} uses 64-bit or 32-bit allocations.
28945 @cindex @code{__gnat_malloc}
28946 The switches are respectively @option{-H64} (the default) and
28948 @cindex @option{-H32} (@command{gnatbind})
28949 @cindex @option{-H64} (@command{gnatbind})
28952 The environment variable (logical name) @code{GNAT$NO_MALLOC_64}
28953 @cindex @code{GNAT$NO_MALLOC_64} environment variable
28954 may be used to force @code{__gnat_malloc} to use 32-bit allocation.
28955 If this variable is left
28956 undefined, or defined as @code{"DISABLE"}, @code{"FALSE"}, or @code{"0"},
28957 then the default (64-bit) allocation is used.
28958 If defined as @code{"ENABLE"}, @code{"TRUE"}, or @code{"1"},
28959 then 32-bit allocation is used. The gnatbind qualifiers described above
28960 override this logical name.
28963 A ^gcc switch^gcc switch^ for OpenVMS, @option{-mno-malloc64}, operates
28964 @cindex @option{-mno-malloc64} (^gcc^gcc^)
28965 at a low level to convert explicit calls to @code{malloc} and related
28966 functions from the C run-time library so that they perform allocations
28967 in the 32-bit heap.
28968 Since all internal allocations from GNAT use @code{__gnat_malloc},
28969 this switch is not required unless the program makes explicit calls on
28970 @code{malloc} (or related functions) from interfaced C code.
28974 @node Unchecked conversions
28975 @subsubsection Unchecked conversions
28978 In the case of an @code{Unchecked_Conversion} where the source type is a
28979 64-bit access type or the type @code{System.Address}, and the target
28980 type is a 32-bit type, the compiler will generate a warning.
28981 Even though the generated code will still perform the required
28982 conversions, it is highly recommended in these cases to use
28983 respectively a 32-bit access type or @code{System.Short_Address}
28984 as the source type.
28986 @node Predefined constants
28987 @subsubsection Predefined constants
28990 The following table shows the correspondence between pre-2006 versions of
28991 @value{EDITION} on Alpha OpenVMS (``Old'') and 64-bit @value{EDITION}
28994 @multitable {@code{System.Short_Memory_Size}} {2**32} {2**64}
28995 @item @b{Constant} @tab @b{Old} @tab @b{New}
28996 @item @code{System.Word_Size} @tab 32 @tab 64
28997 @item @code{System.Memory_Size} @tab 2**32 @tab 2**64
28998 @item @code{System.Short_Memory_Size} @tab 2**32 @tab 2**32
28999 @item @code{System.Address_Size} @tab 32 @tab 64
29003 If you need to refer to the specific
29004 memory size of a 32-bit implementation, instead of the
29005 actual memory size, use @code{System.Short_Memory_Size}
29006 rather than @code{System.Memory_Size}.
29007 Similarly, references to @code{System.Address_Size} may need
29008 to be replaced by @code{System.Short_Address'Size}.
29009 The program @command{gnatfind} may be useful for locating
29010 references to the above constants, so that you can verify that they
29013 @node Interfacing with C
29014 @subsubsection Interfacing with C
29017 In order to minimize the impact of the transition to 64-bit addresses on
29018 legacy programs, some fundamental types in the @code{Interfaces.C}
29019 package hierarchy continue to be represented in 32 bits.
29020 These types are: @code{ptrdiff_t}, @code{size_t}, and @code{chars_ptr}.
29021 This eases integration with the default HP C layout choices, for example
29022 as found in the system routines in @code{DECC$SHR.EXE}.
29023 Because of this implementation choice, the type fully compatible with
29024 @code{chars_ptr} is now @code{Short_Address} and not @code{Address}.
29025 Depending on the context the compiler will issue a
29026 warning or an error when type @code{Address} is used, alerting the user to a
29027 potential problem. Otherwise 32-bit programs that use
29028 @code{Interfaces.C} should normally not require code modifications
29030 The other issue arising with C interfacing concerns pragma @code{Convention}.
29031 For VMS 64-bit systems, there is an issue of the appropriate default size
29032 of C convention pointers in the absence of an explicit size clause. The HP
29033 C compiler can choose either 32 or 64 bits depending on compiler options.
29034 GNAT chooses 32-bits rather than 64-bits in the default case where no size
29035 clause is given. This proves a better choice for porting 32-bit legacy
29036 applications. In order to have a 64-bit representation, it is necessary to
29037 specify a size representation clause. For example:
29039 @smallexample @c ada
29040 type int_star is access Interfaces.C.int;
29041 pragma Convention(C, int_star);
29042 for int_star'Size use 64; -- Necessary to get 64 and not 32 bits
29045 @node 32/64-bit descriptors
29046 @subsubsection 32/64-bit descriptors
29049 By default, GNAT uses a 64-bit descriptor mechanism. For an imported
29050 subprogram (i.e., a subprogram identified by pragma @code{Import_Function},
29051 @code{Import_Procedure}, or @code{Import_Valued_Procedure}) that specifies
29052 @code{Short_Descriptor} as its mechanism, a 32-bit descriptor is used.
29053 @cindex @code{Short_Descriptor} mechanism for imported subprograms
29055 If the configuration pragma @code{Short_Descriptors} is supplied, then
29056 all descriptors will be 32 bits.
29057 @cindex pragma @code{Short_Descriptors}
29059 @node Experience with source compatibility
29060 @subsubsection Experience with source compatibility
29063 The Security Server and STARLET on I64 provide an interesting ``test case''
29064 for source compatibility issues, since it is in such system code
29065 where assumptions about @code{Address} size might be expected to occur.
29066 Indeed, there were a small number of occasions in the Security Server
29067 file @file{jibdef.ads}
29068 where a representation clause for a record type specified
29069 32 bits for a component of type @code{Address}.
29070 All of these errors were detected by the compiler.
29071 The repair was obvious and immediate; to simply replace @code{Address} by
29072 @code{Short_Address}.
29074 In the case of STARLET, there were several record types that should
29075 have had representation clauses but did not. In these record types
29076 there was an implicit assumption that an @code{Address} value occupied
29078 These compiled without error, but their usage resulted in run-time error
29079 returns from STARLET system calls.
29080 Future GNAT technology enhancements may include a tool that detects and flags
29081 these sorts of potential source code porting problems.
29083 @c ****************************************
29084 @node Taking advantage of 64 bit addressing
29085 @subsection Taking advantage of 64-bit addressing
29088 * Making code 64 bit clean::
29089 * Allocating memory from the 64 bit storage pool::
29090 * Restrictions on use of 64 bit objects::
29091 * STARLET and other predefined libraries::
29094 @node Making code 64 bit clean
29095 @subsubsection Making code 64-bit clean
29098 In order to prevent problems that may occur when (parts of) a
29099 system start using memory outside the 32-bit address range,
29100 we recommend some additional guidelines:
29104 For imported subprograms that take parameters of the
29105 type @code{System.Address}, ensure that these subprograms can
29106 indeed handle 64-bit addresses. If not, or when in doubt,
29107 change the subprogram declaration to specify
29108 @code{System.Short_Address} instead.
29111 Resolve all warnings related to size mismatches in
29112 unchecked conversions. Failing to do so causes
29113 erroneous execution if the source object is outside
29114 the 32-bit address space.
29117 (optional) Explicitly use the 32-bit storage pool
29118 for access types used in a 32-bit context, or use
29119 generic access types where possible
29120 (@pxref{Restrictions on use of 64 bit objects}).
29124 If these rules are followed, the compiler will automatically insert
29125 any necessary checks to ensure that no addresses or access values
29126 passed to 32-bit code ever refer to objects outside the 32-bit
29128 Any attempt to do this will raise @code{Constraint_Error}.
29130 @node Allocating memory from the 64 bit storage pool
29131 @subsubsection Allocating memory from the 64-bit storage pool
29134 By default, all allocations -- for both pool-specific and general
29135 access types -- use the 64-bit storage pool. To override
29136 this default, for an individual access type or globally, see
29137 @ref{Access types and 32/64-bit allocation}.
29139 @node Restrictions on use of 64 bit objects
29140 @subsubsection Restrictions on use of 64-bit objects
29143 Taking the address of an object allocated from a 64-bit storage pool,
29144 and then passing this address to a subprogram expecting
29145 @code{System.Short_Address},
29146 or assigning it to a variable of type @code{Short_Address}, will cause
29147 @code{Constraint_Error} to be raised. In case the code is not 64-bit clean
29148 (@pxref{Making code 64 bit clean}), or checks are suppressed,
29149 no exception is raised and execution
29150 will become erroneous.
29152 @node STARLET and other predefined libraries
29153 @subsubsection STARLET and other predefined libraries
29156 All code that comes as part of GNAT is 64-bit clean, but the
29157 restrictions given in @ref{Restrictions on use of 64 bit objects},
29158 still apply. Look at the package
29159 specs to see in which contexts objects allocated
29160 in 64-bit address space are acceptable.
29162 @node Technical details
29163 @subsection Technical details
29166 64-bit @value{EDITION} for Open VMS takes advantage of the freedom given in the
29167 Ada standard with respect to the type of @code{System.Address}. Previous
29168 versions of @value{EDITION} have defined this type as private and implemented it as a
29171 In order to allow defining @code{System.Short_Address} as a proper subtype,
29172 and to match the implicit sign extension in parameter passing,
29173 in 64-bit @value{EDITION} for Open VMS, @code{System.Address} is defined as a
29174 visible (i.e., non-private) integer type.
29175 Standard operations on the type, such as the binary operators ``+'', ``-'',
29176 etc., that take @code{Address} operands and return an @code{Address} result,
29177 have been hidden by declaring these
29178 @code{abstract}, a feature introduced in Ada 95 that helps avoid the potential
29179 ambiguities that would otherwise result from overloading.
29180 (Note that, although @code{Address} is a visible integer type,
29181 good programming practice dictates against exploiting the type's
29182 integer properties such as literals, since this will compromise
29185 Defining @code{Address} as a visible integer type helps achieve
29186 maximum compatibility for existing Ada code,
29187 without sacrificing the capabilities of the 64-bit architecture.
29190 @c ************************************************
29191 @node Microsoft Windows Topics
29192 @appendix Microsoft Windows Topics
29198 This chapter describes topics that are specific to the Microsoft Windows
29199 platforms (NT, 2000, and XP Professional).
29202 @ifclear FSFEDITION
29203 * Installing from the Command Line::
29205 * Using GNAT on Windows::
29206 * Using a network installation of GNAT::
29207 * CONSOLE and WINDOWS subsystems::
29208 * Temporary Files::
29209 * Mixed-Language Programming on Windows::
29210 * Windows Calling Conventions::
29211 * Introduction to Dynamic Link Libraries (DLLs)::
29212 * Using DLLs with GNAT::
29213 * Building DLLs with GNAT Project files::
29214 * Building DLLs with GNAT::
29215 * Building DLLs with gnatdll::
29216 * GNAT and Windows Resources::
29217 * Debugging a DLL::
29218 * Setting Stack Size from gnatlink::
29219 * Setting Heap Size from gnatlink::
29222 @ifclear FSFEDITION
29223 @node Installing from the Command Line
29224 @section Installing from the Command Line
29225 @cindex Batch installation
29226 @cindex Silent installation
29227 @cindex Unassisted installation
29230 By default the @value{EDITION} installers display a GUI that prompts the user
29231 to enter installation path and similar information, and guide him through the
29232 installation process. It is also possible to perform silent installations
29233 using the command-line interface.
29235 In order to install one of the @value{EDITION} installers from the command
29236 line you should pass parameter @code{/S} (and, optionally,
29237 @code{/D=<directory>}) as command-line arguments.
29240 For example, for an unattended installation of
29241 @value{EDITION} 7.0.2 into the default directory
29242 @code{C:\GNATPRO\7.0.2} you would run:
29245 gnatpro-7.0.2-i686-pc-mingw32-bin.exe /S
29248 To install into a custom directory, say, @code{C:\TOOLS\GNATPRO\7.0.2}:
29251 gnatpro-7.0.2-i686-pc-mingw32-bin /S /D=C:\TOOLS\GNATPRO\7.0.2
29256 For example, for an unattended installation of
29257 @value{EDITION} 2012 into @code{C:\GNAT\2012}:
29260 gnat-gpl-2012-i686-pc-mingw32-bin /S /D=C:\GNAT\2012
29264 You can use the same syntax for all installers.
29266 Note that unattended installations don't modify system path, nor create file
29267 associations, so such activities need to be done by hand.
29270 @node Using GNAT on Windows
29271 @section Using GNAT on Windows
29274 One of the strengths of the GNAT technology is that its tool set
29275 (@command{gcc}, @command{gnatbind}, @command{gnatlink}, @command{gnatmake}, the
29276 @code{gdb} debugger, etc.) is used in the same way regardless of the
29279 On Windows this tool set is complemented by a number of Microsoft-specific
29280 tools that have been provided to facilitate interoperability with Windows
29281 when this is required. With these tools:
29286 You can build applications using the @code{CONSOLE} or @code{WINDOWS}
29290 You can use any Dynamically Linked Library (DLL) in your Ada code (both
29291 relocatable and non-relocatable DLLs are supported).
29294 You can build Ada DLLs for use in other applications. These applications
29295 can be written in a language other than Ada (e.g., C, C++, etc). Again both
29296 relocatable and non-relocatable Ada DLLs are supported.
29299 You can include Windows resources in your Ada application.
29302 You can use or create COM/DCOM objects.
29306 Immediately below are listed all known general GNAT-for-Windows restrictions.
29307 Other restrictions about specific features like Windows Resources and DLLs
29308 are listed in separate sections below.
29313 It is not possible to use @code{GetLastError} and @code{SetLastError}
29314 when tasking, protected records, or exceptions are used. In these
29315 cases, in order to implement Ada semantics, the GNAT run-time system
29316 calls certain Win32 routines that set the last error variable to 0 upon
29317 success. It should be possible to use @code{GetLastError} and
29318 @code{SetLastError} when tasking, protected record, and exception
29319 features are not used, but it is not guaranteed to work.
29322 It is not possible to link against Microsoft C++ libraries except for
29323 import libraries. Interfacing must be done by the mean of DLLs.
29326 It is possible to link against Microsoft C libraries. Yet the preferred
29327 solution is to use C/C++ compiler that comes with @value{EDITION}, since it
29328 doesn't require having two different development environments and makes the
29329 inter-language debugging experience smoother.
29332 When the compilation environment is located on FAT32 drives, users may
29333 experience recompilations of the source files that have not changed if
29334 Daylight Saving Time (DST) state has changed since the last time files
29335 were compiled. NTFS drives do not have this problem.
29338 No components of the GNAT toolset use any entries in the Windows
29339 registry. The only entries that can be created are file associations and
29340 PATH settings, provided the user has chosen to create them at installation
29341 time, as well as some minimal book-keeping information needed to correctly
29342 uninstall or integrate different GNAT products.
29345 @node Using a network installation of GNAT
29346 @section Using a network installation of GNAT
29349 Make sure the system on which GNAT is installed is accessible from the
29350 current machine, i.e., the install location is shared over the network.
29351 Shared resources are accessed on Windows by means of UNC paths, which
29352 have the format @code{\\server\sharename\path}
29354 In order to use such a network installation, simply add the UNC path of the
29355 @file{bin} directory of your GNAT installation in front of your PATH. For
29356 example, if GNAT is installed in @file{\GNAT} directory of a share location
29357 called @file{c-drive} on a machine @file{LOKI}, the following command will
29360 @code{@ @ @ path \\loki\c-drive\gnat\bin;%path%}
29362 Be aware that every compilation using the network installation results in the
29363 transfer of large amounts of data across the network and will likely cause
29364 serious performance penalty.
29366 @node CONSOLE and WINDOWS subsystems
29367 @section CONSOLE and WINDOWS subsystems
29368 @cindex CONSOLE Subsystem
29369 @cindex WINDOWS Subsystem
29373 There are two main subsystems under Windows. The @code{CONSOLE} subsystem
29374 (which is the default subsystem) will always create a console when
29375 launching the application. This is not something desirable when the
29376 application has a Windows GUI. To get rid of this console the
29377 application must be using the @code{WINDOWS} subsystem. To do so
29378 the @option{-mwindows} linker option must be specified.
29381 $ gnatmake winprog -largs -mwindows
29384 @node Temporary Files
29385 @section Temporary Files
29386 @cindex Temporary files
29389 It is possible to control where temporary files gets created by setting
29390 the @env{TMP} environment variable. The file will be created:
29393 @item Under the directory pointed to by the @env{TMP} environment variable if
29394 this directory exists.
29396 @item Under @file{c:\temp}, if the @env{TMP} environment variable is not
29397 set (or not pointing to a directory) and if this directory exists.
29399 @item Under the current working directory otherwise.
29403 This allows you to determine exactly where the temporary
29404 file will be created. This is particularly useful in networked
29405 environments where you may not have write access to some
29408 @node Mixed-Language Programming on Windows
29409 @section Mixed-Language Programming on Windows
29412 Developing pure Ada applications on Windows is no different than on
29413 other GNAT-supported platforms. However, when developing or porting an
29414 application that contains a mix of Ada and C/C++, the choice of your
29415 Windows C/C++ development environment conditions your overall
29416 interoperability strategy.
29418 If you use @command{gcc} or Microsoft C to compile the non-Ada part of
29419 your application, there are no Windows-specific restrictions that
29420 affect the overall interoperability with your Ada code. If you do want
29421 to use the Microsoft tools for your C++ code, you have two choices:
29425 Encapsulate your C++ code in a DLL to be linked with your Ada
29426 application. In this case, use the Microsoft or whatever environment to
29427 build the DLL and use GNAT to build your executable
29428 (@pxref{Using DLLs with GNAT}).
29431 Or you can encapsulate your Ada code in a DLL to be linked with the
29432 other part of your application. In this case, use GNAT to build the DLL
29433 (@pxref{Building DLLs with GNAT Project files}) and use the Microsoft
29434 or whatever environment to build your executable.
29437 In addition to the description about C main in
29438 @pxref{Mixed Language Programming} section, if the C main uses a
29439 stand-alone library it is required on x86-windows to
29440 setup the SEH context. For this the C main must looks like this:
29444 extern void adainit (void);
29445 extern void adafinal (void);
29446 extern void __gnat_initialize(void*);
29447 extern void call_to_ada (void);
29449 int main (int argc, char *argv[])
29453 /* Initialize the SEH context */
29454 __gnat_initialize (&SEH);
29458 /* Then call Ada services in the stand-alone library */
29466 Note that this is not needed on x86_64-windows where the Windows
29467 native SEH support is used.
29469 @node Windows Calling Conventions
29470 @section Windows Calling Conventions
29474 This section pertain only to Win32. On Win64 there is a single native
29475 calling convention. All convention specifiers are ignored on this
29479 * C Calling Convention::
29480 * Stdcall Calling Convention::
29481 * Win32 Calling Convention::
29482 * DLL Calling Convention::
29486 When a subprogram @code{F} (caller) calls a subprogram @code{G}
29487 (callee), there are several ways to push @code{G}'s parameters on the
29488 stack and there are several possible scenarios to clean up the stack
29489 upon @code{G}'s return. A calling convention is an agreed upon software
29490 protocol whereby the responsibilities between the caller (@code{F}) and
29491 the callee (@code{G}) are clearly defined. Several calling conventions
29492 are available for Windows:
29496 @code{C} (Microsoft defined)
29499 @code{Stdcall} (Microsoft defined)
29502 @code{Win32} (GNAT specific)
29505 @code{DLL} (GNAT specific)
29508 @node C Calling Convention
29509 @subsection @code{C} Calling Convention
29512 This is the default calling convention used when interfacing to C/C++
29513 routines compiled with either @command{gcc} or Microsoft Visual C++.
29515 In the @code{C} calling convention subprogram parameters are pushed on the
29516 stack by the caller from right to left. The caller itself is in charge of
29517 cleaning up the stack after the call. In addition, the name of a routine
29518 with @code{C} calling convention is mangled by adding a leading underscore.
29520 The name to use on the Ada side when importing (or exporting) a routine
29521 with @code{C} calling convention is the name of the routine. For
29522 instance the C function:
29525 int get_val (long);
29529 should be imported from Ada as follows:
29531 @smallexample @c ada
29533 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
29534 pragma Import (C, Get_Val, External_Name => "get_val");
29539 Note that in this particular case the @code{External_Name} parameter could
29540 have been omitted since, when missing, this parameter is taken to be the
29541 name of the Ada entity in lower case. When the @code{Link_Name} parameter
29542 is missing, as in the above example, this parameter is set to be the
29543 @code{External_Name} with a leading underscore.
29545 When importing a variable defined in C, you should always use the @code{C}
29546 calling convention unless the object containing the variable is part of a
29547 DLL (in which case you should use the @code{Stdcall} calling
29548 convention, @pxref{Stdcall Calling Convention}).
29550 @node Stdcall Calling Convention
29551 @subsection @code{Stdcall} Calling Convention
29554 This convention, which was the calling convention used for Pascal
29555 programs, is used by Microsoft for all the routines in the Win32 API for
29556 efficiency reasons. It must be used to import any routine for which this
29557 convention was specified.
29559 In the @code{Stdcall} calling convention subprogram parameters are pushed
29560 on the stack by the caller from right to left. The callee (and not the
29561 caller) is in charge of cleaning the stack on routine exit. In addition,
29562 the name of a routine with @code{Stdcall} calling convention is mangled by
29563 adding a leading underscore (as for the @code{C} calling convention) and a
29564 trailing @code{@@}@code{@var{nn}}, where @var{nn} is the overall size (in
29565 bytes) of the parameters passed to the routine.
29567 The name to use on the Ada side when importing a C routine with a
29568 @code{Stdcall} calling convention is the name of the C routine. The leading
29569 underscore and trailing @code{@@}@code{@var{nn}} are added automatically by
29570 the compiler. For instance the Win32 function:
29573 @b{APIENTRY} int get_val (long);
29577 should be imported from Ada as follows:
29579 @smallexample @c ada
29581 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
29582 pragma Import (Stdcall, Get_Val);
29583 -- On the x86 a long is 4 bytes, so the Link_Name is "_get_val@@4"
29588 As for the @code{C} calling convention, when the @code{External_Name}
29589 parameter is missing, it is taken to be the name of the Ada entity in lower
29590 case. If instead of writing the above import pragma you write:
29592 @smallexample @c ada
29594 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
29595 pragma Import (Stdcall, Get_Val, External_Name => "retrieve_val");
29600 then the imported routine is @code{_retrieve_val@@4}. However, if instead
29601 of specifying the @code{External_Name} parameter you specify the
29602 @code{Link_Name} as in the following example:
29604 @smallexample @c ada
29606 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
29607 pragma Import (Stdcall, Get_Val, Link_Name => "retrieve_val");
29612 then the imported routine is @code{retrieve_val}, that is, there is no
29613 decoration at all. No leading underscore and no Stdcall suffix
29614 @code{@@}@code{@var{nn}}.
29617 This is especially important as in some special cases a DLL's entry
29618 point name lacks a trailing @code{@@}@code{@var{nn}} while the exported
29619 name generated for a call has it.
29622 It is also possible to import variables defined in a DLL by using an
29623 import pragma for a variable. As an example, if a DLL contains a
29624 variable defined as:
29631 then, to access this variable from Ada you should write:
29633 @smallexample @c ada
29635 My_Var : Interfaces.C.int;
29636 pragma Import (Stdcall, My_Var);
29641 Note that to ease building cross-platform bindings this convention
29642 will be handled as a @code{C} calling convention on non-Windows platforms.
29644 @node Win32 Calling Convention
29645 @subsection @code{Win32} Calling Convention
29648 This convention, which is GNAT-specific is fully equivalent to the
29649 @code{Stdcall} calling convention described above.
29651 @node DLL Calling Convention
29652 @subsection @code{DLL} Calling Convention
29655 This convention, which is GNAT-specific is fully equivalent to the
29656 @code{Stdcall} calling convention described above.
29658 @node Introduction to Dynamic Link Libraries (DLLs)
29659 @section Introduction to Dynamic Link Libraries (DLLs)
29663 A Dynamically Linked Library (DLL) is a library that can be shared by
29664 several applications running under Windows. A DLL can contain any number of
29665 routines and variables.
29667 One advantage of DLLs is that you can change and enhance them without
29668 forcing all the applications that depend on them to be relinked or
29669 recompiled. However, you should be aware than all calls to DLL routines are
29670 slower since, as you will understand below, such calls are indirect.
29672 To illustrate the remainder of this section, suppose that an application
29673 wants to use the services of a DLL @file{API.dll}. To use the services
29674 provided by @file{API.dll} you must statically link against the DLL or
29675 an import library which contains a jump table with an entry for each
29676 routine and variable exported by the DLL. In the Microsoft world this
29677 import library is called @file{API.lib}. When using GNAT this import
29678 library is called either @file{libAPI.dll.a}, @file{libapi.dll.a},
29679 @file{libAPI.a} or @file{libapi.a} (names are case insensitive).
29681 After you have linked your application with the DLL or the import library
29682 and you run your application, here is what happens:
29686 Your application is loaded into memory.
29689 The DLL @file{API.dll} is mapped into the address space of your
29690 application. This means that:
29694 The DLL will use the stack of the calling thread.
29697 The DLL will use the virtual address space of the calling process.
29700 The DLL will allocate memory from the virtual address space of the calling
29704 Handles (pointers) can be safely exchanged between routines in the DLL
29705 routines and routines in the application using the DLL.
29709 The entries in the jump table (from the import library @file{libAPI.dll.a}
29710 or @file{API.lib} or automatically created when linking against a DLL)
29711 which is part of your application are initialized with the addresses
29712 of the routines and variables in @file{API.dll}.
29715 If present in @file{API.dll}, routines @code{DllMain} or
29716 @code{DllMainCRTStartup} are invoked. These routines typically contain
29717 the initialization code needed for the well-being of the routines and
29718 variables exported by the DLL.
29722 There is an additional point which is worth mentioning. In the Windows
29723 world there are two kind of DLLs: relocatable and non-relocatable
29724 DLLs. Non-relocatable DLLs can only be loaded at a very specific address
29725 in the target application address space. If the addresses of two
29726 non-relocatable DLLs overlap and these happen to be used by the same
29727 application, a conflict will occur and the application will run
29728 incorrectly. Hence, when possible, it is always preferable to use and
29729 build relocatable DLLs. Both relocatable and non-relocatable DLLs are
29730 supported by GNAT. Note that the @option{-s} linker option (see GNU Linker
29731 User's Guide) removes the debugging symbols from the DLL but the DLL can
29732 still be relocated.
29734 As a side note, an interesting difference between Microsoft DLLs and
29735 Unix shared libraries, is the fact that on most Unix systems all public
29736 routines are exported by default in a Unix shared library, while under
29737 Windows it is possible (but not required) to list exported routines in
29738 a definition file (@pxref{The Definition File}).
29740 @node Using DLLs with GNAT
29741 @section Using DLLs with GNAT
29744 * Creating an Ada Spec for the DLL Services::
29745 * Creating an Import Library::
29749 To use the services of a DLL, say @file{API.dll}, in your Ada application
29754 The Ada spec for the routines and/or variables you want to access in
29755 @file{API.dll}. If not available this Ada spec must be built from the C/C++
29756 header files provided with the DLL.
29759 The import library (@file{libAPI.dll.a} or @file{API.lib}). As previously
29760 mentioned an import library is a statically linked library containing the
29761 import table which will be filled at load time to point to the actual
29762 @file{API.dll} routines. Sometimes you don't have an import library for the
29763 DLL you want to use. The following sections will explain how to build
29764 one. Note that this is optional.
29767 The actual DLL, @file{API.dll}.
29771 Once you have all the above, to compile an Ada application that uses the
29772 services of @file{API.dll} and whose main subprogram is @code{My_Ada_App},
29773 you simply issue the command
29776 $ gnatmake my_ada_app -largs -lAPI
29780 The argument @option{-largs -lAPI} at the end of the @command{gnatmake} command
29781 tells the GNAT linker to look for an import library. The linker will
29782 look for a library name in this specific order:
29785 @item @file{libAPI.dll.a}
29786 @item @file{API.dll.a}
29787 @item @file{libAPI.a}
29788 @item @file{API.lib}
29789 @item @file{libAPI.dll}
29790 @item @file{API.dll}
29793 The first three are the GNU style import libraries. The third is the
29794 Microsoft style import libraries. The last two are the actual DLL names.
29796 Note that if the Ada package spec for @file{API.dll} contains the
29799 @smallexample @c ada
29800 pragma Linker_Options ("-lAPI");
29804 you do not have to add @option{-largs -lAPI} at the end of the
29805 @command{gnatmake} command.
29807 If any one of the items above is missing you will have to create it
29808 yourself. The following sections explain how to do so using as an
29809 example a fictitious DLL called @file{API.dll}.
29811 @node Creating an Ada Spec for the DLL Services
29812 @subsection Creating an Ada Spec for the DLL Services
29815 A DLL typically comes with a C/C++ header file which provides the
29816 definitions of the routines and variables exported by the DLL. The Ada
29817 equivalent of this header file is a package spec that contains definitions
29818 for the imported entities. If the DLL you intend to use does not come with
29819 an Ada spec you have to generate one such spec yourself. For example if
29820 the header file of @file{API.dll} is a file @file{api.h} containing the
29821 following two definitions:
29833 then the equivalent Ada spec could be:
29835 @smallexample @c ada
29838 with Interfaces.C.Strings;
29843 function Get (Str : C.Strings.Chars_Ptr) return C.int;
29846 pragma Import (C, Get);
29847 pragma Import (DLL, Some_Var);
29853 @node Creating an Import Library
29854 @subsection Creating an Import Library
29855 @cindex Import library
29858 * The Definition File::
29859 * GNAT-Style Import Library::
29860 * Microsoft-Style Import Library::
29864 If a Microsoft-style import library @file{API.lib} or a GNAT-style
29865 import library @file{libAPI.dll.a} or @file{libAPI.a} is available
29866 with @file{API.dll} you can skip this section. You can also skip this
29867 section if @file{API.dll} or @file{libAPI.dll} is built with GNU tools
29868 as in this case it is possible to link directly against the
29869 DLL. Otherwise read on.
29871 @node The Definition File
29872 @subsubsection The Definition File
29873 @cindex Definition file
29877 As previously mentioned, and unlike Unix systems, the list of symbols
29878 that are exported from a DLL must be provided explicitly in Windows.
29879 The main goal of a definition file is precisely that: list the symbols
29880 exported by a DLL. A definition file (usually a file with a @code{.def}
29881 suffix) has the following structure:
29886 @r{[}LIBRARY @var{name}@r{]}
29887 @r{[}DESCRIPTION @var{string}@r{]}
29897 @item LIBRARY @var{name}
29898 This section, which is optional, gives the name of the DLL.
29900 @item DESCRIPTION @var{string}
29901 This section, which is optional, gives a description string that will be
29902 embedded in the import library.
29905 This section gives the list of exported symbols (procedures, functions or
29906 variables). For instance in the case of @file{API.dll} the @code{EXPORTS}
29907 section of @file{API.def} looks like:
29921 Note that you must specify the correct suffix (@code{@@}@code{@var{nn}})
29922 (@pxref{Windows Calling Conventions}) for a Stdcall
29923 calling convention function in the exported symbols list.
29926 There can actually be other sections in a definition file, but these
29927 sections are not relevant to the discussion at hand.
29929 @node GNAT-Style Import Library
29930 @subsubsection GNAT-Style Import Library
29933 To create a static import library from @file{API.dll} with the GNAT tools
29934 you should proceed as follows:
29938 Create the definition file @file{API.def} (@pxref{The Definition File}).
29939 For that use the @code{dll2def} tool as follows:
29942 $ dll2def API.dll > API.def
29946 @code{dll2def} is a very simple tool: it takes as input a DLL and prints
29947 to standard output the list of entry points in the DLL. Note that if
29948 some routines in the DLL have the @code{Stdcall} convention
29949 (@pxref{Windows Calling Conventions}) with stripped @code{@@}@var{nn}
29950 suffix then you'll have to edit @file{api.def} to add it, and specify
29951 @option{-k} to @command{gnatdll} when creating the import library.
29954 Here are some hints to find the right @code{@@}@var{nn} suffix.
29958 If you have the Microsoft import library (.lib), it is possible to get
29959 the right symbols by using Microsoft @code{dumpbin} tool (see the
29960 corresponding Microsoft documentation for further details).
29963 $ dumpbin /exports api.lib
29967 If you have a message about a missing symbol at link time the compiler
29968 tells you what symbol is expected. You just have to go back to the
29969 definition file and add the right suffix.
29973 Build the import library @code{libAPI.dll.a}, using @code{gnatdll}
29974 (@pxref{Using gnatdll}) as follows:
29977 $ gnatdll -e API.def -d API.dll
29981 @code{gnatdll} takes as input a definition file @file{API.def} and the
29982 name of the DLL containing the services listed in the definition file
29983 @file{API.dll}. The name of the static import library generated is
29984 computed from the name of the definition file as follows: if the
29985 definition file name is @var{xyz}@code{.def}, the import library name will
29986 be @code{lib}@var{xyz}@code{.a}. Note that in the previous example option
29987 @option{-e} could have been removed because the name of the definition
29988 file (before the ``@code{.def}'' suffix) is the same as the name of the
29989 DLL (@pxref{Using gnatdll} for more information about @code{gnatdll}).
29992 @node Microsoft-Style Import Library
29993 @subsubsection Microsoft-Style Import Library
29996 With GNAT you can either use a GNAT-style or Microsoft-style import
29997 library. A Microsoft import library is needed only if you plan to make an
29998 Ada DLL available to applications developed with Microsoft
29999 tools (@pxref{Mixed-Language Programming on Windows}).
30001 To create a Microsoft-style import library for @file{API.dll} you
30002 should proceed as follows:
30006 Create the definition file @file{API.def} from the DLL. For this use either
30007 the @code{dll2def} tool as described above or the Microsoft @code{dumpbin}
30008 tool (see the corresponding Microsoft documentation for further details).
30011 Build the actual import library using Microsoft's @code{lib} utility:
30014 $ lib -machine:IX86 -def:API.def -out:API.lib
30018 If you use the above command the definition file @file{API.def} must
30019 contain a line giving the name of the DLL:
30026 See the Microsoft documentation for further details about the usage of
30030 @node Building DLLs with GNAT Project files
30031 @section Building DLLs with GNAT Project files
30032 @cindex DLLs, building
30035 There is nothing specific to Windows in the build process.
30036 @pxref{Library Projects}.
30039 Due to a system limitation, it is not possible under Windows to create threads
30040 when inside the @code{DllMain} routine which is used for auto-initialization
30041 of shared libraries, so it is not possible to have library level tasks in SALs.
30043 @node Building DLLs with GNAT
30044 @section Building DLLs with GNAT
30045 @cindex DLLs, building
30048 This section explain how to build DLLs using the GNAT built-in DLL
30049 support. With the following procedure it is straight forward to build
30050 and use DLLs with GNAT.
30054 @item building object files
30056 The first step is to build all objects files that are to be included
30057 into the DLL. This is done by using the standard @command{gnatmake} tool.
30059 @item building the DLL
30061 To build the DLL you must use @command{gcc}'s @option{-shared} and
30062 @option{-shared-libgcc} options. It is quite simple to use this method:
30065 $ gcc -shared -shared-libgcc -o api.dll obj1.o obj2.o @dots{}
30068 It is important to note that in this case all symbols found in the
30069 object files are automatically exported. It is possible to restrict
30070 the set of symbols to export by passing to @command{gcc} a definition
30071 file, @pxref{The Definition File}. For example:
30074 $ gcc -shared -shared-libgcc -o api.dll api.def obj1.o obj2.o @dots{}
30077 If you use a definition file you must export the elaboration procedures
30078 for every package that required one. Elaboration procedures are named
30079 using the package name followed by "_E".
30081 @item preparing DLL to be used
30083 For the DLL to be used by client programs the bodies must be hidden
30084 from it and the .ali set with read-only attribute. This is very important
30085 otherwise GNAT will recompile all packages and will not actually use
30086 the code in the DLL. For example:
30090 $ copy *.ads *.ali api.dll apilib
30091 $ attrib +R apilib\*.ali
30096 At this point it is possible to use the DLL by directly linking
30097 against it. Note that you must use the GNAT shared runtime when using
30098 GNAT shared libraries. This is achieved by using @option{-shared} binder's
30102 $ gnatmake main -Iapilib -bargs -shared -largs -Lapilib -lAPI
30105 @node Building DLLs with gnatdll
30106 @section Building DLLs with gnatdll
30107 @cindex DLLs, building
30110 * Limitations When Using Ada DLLs from Ada::
30111 * Exporting Ada Entities::
30112 * Ada DLLs and Elaboration::
30113 * Ada DLLs and Finalization::
30114 * Creating a Spec for Ada DLLs::
30115 * Creating the Definition File::
30120 Note that it is preferred to use GNAT Project files
30121 (@pxref{Building DLLs with GNAT Project files}) or the built-in GNAT
30122 DLL support (@pxref{Building DLLs with GNAT}) or to build DLLs.
30124 This section explains how to build DLLs containing Ada code using
30125 @code{gnatdll}. These DLLs will be referred to as Ada DLLs in the
30126 remainder of this section.
30128 The steps required to build an Ada DLL that is to be used by Ada as well as
30129 non-Ada applications are as follows:
30133 You need to mark each Ada @i{entity} exported by the DLL with a @code{C} or
30134 @code{Stdcall} calling convention to avoid any Ada name mangling for the
30135 entities exported by the DLL (@pxref{Exporting Ada Entities}). You can
30136 skip this step if you plan to use the Ada DLL only from Ada applications.
30139 Your Ada code must export an initialization routine which calls the routine
30140 @code{adainit} generated by @command{gnatbind} to perform the elaboration of
30141 the Ada code in the DLL (@pxref{Ada DLLs and Elaboration}). The initialization
30142 routine exported by the Ada DLL must be invoked by the clients of the DLL
30143 to initialize the DLL.
30146 When useful, the DLL should also export a finalization routine which calls
30147 routine @code{adafinal} generated by @command{gnatbind} to perform the
30148 finalization of the Ada code in the DLL (@pxref{Ada DLLs and Finalization}).
30149 The finalization routine exported by the Ada DLL must be invoked by the
30150 clients of the DLL when the DLL services are no further needed.
30153 You must provide a spec for the services exported by the Ada DLL in each
30154 of the programming languages to which you plan to make the DLL available.
30157 You must provide a definition file listing the exported entities
30158 (@pxref{The Definition File}).
30161 Finally you must use @code{gnatdll} to produce the DLL and the import
30162 library (@pxref{Using gnatdll}).
30166 Note that a relocatable DLL stripped using the @code{strip}
30167 binutils tool will not be relocatable anymore. To build a DLL without
30168 debug information pass @code{-largs -s} to @code{gnatdll}. This
30169 restriction does not apply to a DLL built using a Library Project.
30170 @pxref{Library Projects}.
30172 @node Limitations When Using Ada DLLs from Ada
30173 @subsection Limitations When Using Ada DLLs from Ada
30176 When using Ada DLLs from Ada applications there is a limitation users
30177 should be aware of. Because on Windows the GNAT run time is not in a DLL of
30178 its own, each Ada DLL includes a part of the GNAT run time. Specifically,
30179 each Ada DLL includes the services of the GNAT run time that are necessary
30180 to the Ada code inside the DLL. As a result, when an Ada program uses an
30181 Ada DLL there are two independent GNAT run times: one in the Ada DLL and
30182 one in the main program.
30184 It is therefore not possible to exchange GNAT run-time objects between the
30185 Ada DLL and the main Ada program. Example of GNAT run-time objects are file
30186 handles (e.g.@: @code{Text_IO.File_Type}), tasks types, protected objects
30189 It is completely safe to exchange plain elementary, array or record types,
30190 Windows object handles, etc.
30192 @node Exporting Ada Entities
30193 @subsection Exporting Ada Entities
30194 @cindex Export table
30197 Building a DLL is a way to encapsulate a set of services usable from any
30198 application. As a result, the Ada entities exported by a DLL should be
30199 exported with the @code{C} or @code{Stdcall} calling conventions to avoid
30200 any Ada name mangling. As an example here is an Ada package
30201 @code{API}, spec and body, exporting two procedures, a function, and a
30204 @smallexample @c ada
30207 with Interfaces.C; use Interfaces;
30209 Count : C.int := 0;
30210 function Factorial (Val : C.int) return C.int;
30212 procedure Initialize_API;
30213 procedure Finalize_API;
30214 -- Initialization & Finalization routines. More in the next section.
30216 pragma Export (C, Initialize_API);
30217 pragma Export (C, Finalize_API);
30218 pragma Export (C, Count);
30219 pragma Export (C, Factorial);
30225 @smallexample @c ada
30228 package body API is
30229 function Factorial (Val : C.int) return C.int is
30232 Count := Count + 1;
30233 for K in 1 .. Val loop
30239 procedure Initialize_API is
30241 pragma Import (C, Adainit);
30244 end Initialize_API;
30246 procedure Finalize_API is
30247 procedure Adafinal;
30248 pragma Import (C, Adafinal);
30258 If the Ada DLL you are building will only be used by Ada applications
30259 you do not have to export Ada entities with a @code{C} or @code{Stdcall}
30260 convention. As an example, the previous package could be written as
30263 @smallexample @c ada
30267 Count : Integer := 0;
30268 function Factorial (Val : Integer) return Integer;
30270 procedure Initialize_API;
30271 procedure Finalize_API;
30272 -- Initialization and Finalization routines.
30278 @smallexample @c ada
30281 package body API is
30282 function Factorial (Val : Integer) return Integer is
30283 Fact : Integer := 1;
30285 Count := Count + 1;
30286 for K in 1 .. Val loop
30293 -- The remainder of this package body is unchanged.
30300 Note that if you do not export the Ada entities with a @code{C} or
30301 @code{Stdcall} convention you will have to provide the mangled Ada names
30302 in the definition file of the Ada DLL
30303 (@pxref{Creating the Definition File}).
30305 @node Ada DLLs and Elaboration
30306 @subsection Ada DLLs and Elaboration
30307 @cindex DLLs and elaboration
30310 The DLL that you are building contains your Ada code as well as all the
30311 routines in the Ada library that are needed by it. The first thing a
30312 user of your DLL must do is elaborate the Ada code
30313 (@pxref{Elaboration Order Handling in GNAT}).
30315 To achieve this you must export an initialization routine
30316 (@code{Initialize_API} in the previous example), which must be invoked
30317 before using any of the DLL services. This elaboration routine must call
30318 the Ada elaboration routine @code{adainit} generated by the GNAT binder
30319 (@pxref{Binding with Non-Ada Main Programs}). See the body of
30320 @code{Initialize_Api} for an example. Note that the GNAT binder is
30321 automatically invoked during the DLL build process by the @code{gnatdll}
30322 tool (@pxref{Using gnatdll}).
30324 When a DLL is loaded, Windows systematically invokes a routine called
30325 @code{DllMain}. It would therefore be possible to call @code{adainit}
30326 directly from @code{DllMain} without having to provide an explicit
30327 initialization routine. Unfortunately, it is not possible to call
30328 @code{adainit} from the @code{DllMain} if your program has library level
30329 tasks because access to the @code{DllMain} entry point is serialized by
30330 the system (that is, only a single thread can execute ``through'' it at a
30331 time), which means that the GNAT run time will deadlock waiting for the
30332 newly created task to complete its initialization.
30334 @node Ada DLLs and Finalization
30335 @subsection Ada DLLs and Finalization
30336 @cindex DLLs and finalization
30339 When the services of an Ada DLL are no longer needed, the client code should
30340 invoke the DLL finalization routine, if available. The DLL finalization
30341 routine is in charge of releasing all resources acquired by the DLL. In the
30342 case of the Ada code contained in the DLL, this is achieved by calling
30343 routine @code{adafinal} generated by the GNAT binder
30344 (@pxref{Binding with Non-Ada Main Programs}).
30345 See the body of @code{Finalize_Api} for an
30346 example. As already pointed out the GNAT binder is automatically invoked
30347 during the DLL build process by the @code{gnatdll} tool
30348 (@pxref{Using gnatdll}).
30350 @node Creating a Spec for Ada DLLs
30351 @subsection Creating a Spec for Ada DLLs
30354 To use the services exported by the Ada DLL from another programming
30355 language (e.g.@: C), you have to translate the specs of the exported Ada
30356 entities in that language. For instance in the case of @code{API.dll},
30357 the corresponding C header file could look like:
30362 extern int *_imp__count;
30363 #define count (*_imp__count)
30364 int factorial (int);
30370 It is important to understand that when building an Ada DLL to be used by
30371 other Ada applications, you need two different specs for the packages
30372 contained in the DLL: one for building the DLL and the other for using
30373 the DLL. This is because the @code{DLL} calling convention is needed to
30374 use a variable defined in a DLL, but when building the DLL, the variable
30375 must have either the @code{Ada} or @code{C} calling convention. As an
30376 example consider a DLL comprising the following package @code{API}:
30378 @smallexample @c ada
30382 Count : Integer := 0;
30384 -- Remainder of the package omitted.
30391 After producing a DLL containing package @code{API}, the spec that
30392 must be used to import @code{API.Count} from Ada code outside of the
30395 @smallexample @c ada
30400 pragma Import (DLL, Count);
30406 @node Creating the Definition File
30407 @subsection Creating the Definition File
30410 The definition file is the last file needed to build the DLL. It lists
30411 the exported symbols. As an example, the definition file for a DLL
30412 containing only package @code{API} (where all the entities are exported
30413 with a @code{C} calling convention) is:
30428 If the @code{C} calling convention is missing from package @code{API},
30429 then the definition file contains the mangled Ada names of the above
30430 entities, which in this case are:
30439 api__initialize_api
30444 @node Using gnatdll
30445 @subsection Using @code{gnatdll}
30449 * gnatdll Example::
30450 * gnatdll behind the Scenes::
30455 @code{gnatdll} is a tool to automate the DLL build process once all the Ada
30456 and non-Ada sources that make up your DLL have been compiled.
30457 @code{gnatdll} is actually in charge of two distinct tasks: build the
30458 static import library for the DLL and the actual DLL. The form of the
30459 @code{gnatdll} command is
30463 @c $ gnatdll @ovar{switches} @var{list-of-files} @r{[}-largs @var{opts}@r{]}
30464 @c Expanding @ovar macro inline (explanation in macro def comments)
30465 $ gnatdll @r{[}@var{switches}@r{]} @var{list-of-files} @r{[}-largs @var{opts}@r{]}
30470 where @var{list-of-files} is a list of ALI and object files. The object
30471 file list must be the exact list of objects corresponding to the non-Ada
30472 sources whose services are to be included in the DLL. The ALI file list
30473 must be the exact list of ALI files for the corresponding Ada sources
30474 whose services are to be included in the DLL. If @var{list-of-files} is
30475 missing, only the static import library is generated.
30478 You may specify any of the following switches to @code{gnatdll}:
30481 @c @item -a@ovar{address}
30482 @c Expanding @ovar macro inline (explanation in macro def comments)
30483 @item -a@r{[}@var{address}@r{]}
30484 @cindex @option{-a} (@code{gnatdll})
30485 Build a non-relocatable DLL at @var{address}. If @var{address} is not
30486 specified the default address @var{0x11000000} will be used. By default,
30487 when this switch is missing, @code{gnatdll} builds relocatable DLL. We
30488 advise the reader to build relocatable DLL.
30490 @item -b @var{address}
30491 @cindex @option{-b} (@code{gnatdll})
30492 Set the relocatable DLL base address. By default the address is
30495 @item -bargs @var{opts}
30496 @cindex @option{-bargs} (@code{gnatdll})
30497 Binder options. Pass @var{opts} to the binder.
30499 @item -d @var{dllfile}
30500 @cindex @option{-d} (@code{gnatdll})
30501 @var{dllfile} is the name of the DLL. This switch must be present for
30502 @code{gnatdll} to do anything. The name of the generated import library is
30503 obtained algorithmically from @var{dllfile} as shown in the following
30504 example: if @var{dllfile} is @code{xyz.dll}, the import library name is
30505 @code{libxyz.dll.a}. The name of the definition file to use (if not specified
30506 by option @option{-e}) is obtained algorithmically from @var{dllfile}
30507 as shown in the following example:
30508 if @var{dllfile} is @code{xyz.dll}, the definition
30509 file used is @code{xyz.def}.
30511 @item -e @var{deffile}
30512 @cindex @option{-e} (@code{gnatdll})
30513 @var{deffile} is the name of the definition file.
30516 @cindex @option{-g} (@code{gnatdll})
30517 Generate debugging information. This information is stored in the object
30518 file and copied from there to the final DLL file by the linker,
30519 where it can be read by the debugger. You must use the
30520 @option{-g} switch if you plan on using the debugger or the symbolic
30524 @cindex @option{-h} (@code{gnatdll})
30525 Help mode. Displays @code{gnatdll} switch usage information.
30528 @cindex @option{-I} (@code{gnatdll})
30529 Direct @code{gnatdll} to search the @var{dir} directory for source and
30530 object files needed to build the DLL.
30531 (@pxref{Search Paths and the Run-Time Library (RTL)}).
30534 @cindex @option{-k} (@code{gnatdll})
30535 Removes the @code{@@}@var{nn} suffix from the import library's exported
30536 names, but keeps them for the link names. You must specify this
30537 option if you want to use a @code{Stdcall} function in a DLL for which
30538 the @code{@@}@var{nn} suffix has been removed. This is the case for most
30539 of the Windows NT DLL for example. This option has no effect when
30540 @option{-n} option is specified.
30542 @item -l @var{file}
30543 @cindex @option{-l} (@code{gnatdll})
30544 The list of ALI and object files used to build the DLL are listed in
30545 @var{file}, instead of being given in the command line. Each line in
30546 @var{file} contains the name of an ALI or object file.
30549 @cindex @option{-n} (@code{gnatdll})
30550 No Import. Do not create the import library.
30553 @cindex @option{-q} (@code{gnatdll})
30554 Quiet mode. Do not display unnecessary messages.
30557 @cindex @option{-v} (@code{gnatdll})
30558 Verbose mode. Display extra information.
30560 @item -largs @var{opts}
30561 @cindex @option{-largs} (@code{gnatdll})
30562 Linker options. Pass @var{opts} to the linker.
30565 @node gnatdll Example
30566 @subsubsection @code{gnatdll} Example
30569 As an example the command to build a relocatable DLL from @file{api.adb}
30570 once @file{api.adb} has been compiled and @file{api.def} created is
30573 $ gnatdll -d api.dll api.ali
30577 The above command creates two files: @file{libapi.dll.a} (the import
30578 library) and @file{api.dll} (the actual DLL). If you want to create
30579 only the DLL, just type:
30582 $ gnatdll -d api.dll -n api.ali
30586 Alternatively if you want to create just the import library, type:
30589 $ gnatdll -d api.dll
30592 @node gnatdll behind the Scenes
30593 @subsubsection @code{gnatdll} behind the Scenes
30596 This section details the steps involved in creating a DLL. @code{gnatdll}
30597 does these steps for you. Unless you are interested in understanding what
30598 goes on behind the scenes, you should skip this section.
30600 We use the previous example of a DLL containing the Ada package @code{API},
30601 to illustrate the steps necessary to build a DLL. The starting point is a
30602 set of objects that will make up the DLL and the corresponding ALI
30603 files. In the case of this example this means that @file{api.o} and
30604 @file{api.ali} are available. To build a relocatable DLL, @code{gnatdll} does
30609 @code{gnatdll} builds the base file (@file{api.base}). A base file gives
30610 the information necessary to generate relocation information for the
30616 $ gnatlink api -o api.jnk -mdll -Wl,--base-file,api.base
30621 In addition to the base file, the @command{gnatlink} command generates an
30622 output file @file{api.jnk} which can be discarded. The @option{-mdll} switch
30623 asks @command{gnatlink} to generate the routines @code{DllMain} and
30624 @code{DllMainCRTStartup} that are called by the Windows loader when the DLL
30625 is loaded into memory.
30628 @code{gnatdll} uses @code{dlltool} (@pxref{Using dlltool}) to build the
30629 export table (@file{api.exp}). The export table contains the relocation
30630 information in a form which can be used during the final link to ensure
30631 that the Windows loader is able to place the DLL anywhere in memory.
30635 $ dlltool --dllname api.dll --def api.def --base-file api.base \
30636 --output-exp api.exp
30641 @code{gnatdll} builds the base file using the new export table. Note that
30642 @command{gnatbind} must be called once again since the binder generated file
30643 has been deleted during the previous call to @command{gnatlink}.
30648 $ gnatlink api -o api.jnk api.exp -mdll
30649 -Wl,--base-file,api.base
30654 @code{gnatdll} builds the new export table using the new base file and
30655 generates the DLL import library @file{libAPI.dll.a}.
30659 $ dlltool --dllname api.dll --def api.def --base-file api.base \
30660 --output-exp api.exp --output-lib libAPI.a
30665 Finally @code{gnatdll} builds the relocatable DLL using the final export
30671 $ gnatlink api api.exp -o api.dll -mdll
30676 @node Using dlltool
30677 @subsubsection Using @code{dlltool}
30680 @code{dlltool} is the low-level tool used by @code{gnatdll} to build
30681 DLLs and static import libraries. This section summarizes the most
30682 common @code{dlltool} switches. The form of the @code{dlltool} command
30686 @c $ dlltool @ovar{switches}
30687 @c Expanding @ovar macro inline (explanation in macro def comments)
30688 $ dlltool @r{[}@var{switches}@r{]}
30692 @code{dlltool} switches include:
30695 @item --base-file @var{basefile}
30696 @cindex @option{--base-file} (@command{dlltool})
30697 Read the base file @var{basefile} generated by the linker. This switch
30698 is used to create a relocatable DLL.
30700 @item --def @var{deffile}
30701 @cindex @option{--def} (@command{dlltool})
30702 Read the definition file.
30704 @item --dllname @var{name}
30705 @cindex @option{--dllname} (@command{dlltool})
30706 Gives the name of the DLL. This switch is used to embed the name of the
30707 DLL in the static import library generated by @code{dlltool} with switch
30708 @option{--output-lib}.
30711 @cindex @option{-k} (@command{dlltool})
30712 Kill @code{@@}@var{nn} from exported names
30713 (@pxref{Windows Calling Conventions}
30714 for a discussion about @code{Stdcall}-style symbols.
30717 @cindex @option{--help} (@command{dlltool})
30718 Prints the @code{dlltool} switches with a concise description.
30720 @item --output-exp @var{exportfile}
30721 @cindex @option{--output-exp} (@command{dlltool})
30722 Generate an export file @var{exportfile}. The export file contains the
30723 export table (list of symbols in the DLL) and is used to create the DLL.
30725 @item --output-lib @var{libfile}
30726 @cindex @option{--output-lib} (@command{dlltool})
30727 Generate a static import library @var{libfile}.
30730 @cindex @option{-v} (@command{dlltool})
30733 @item --as @var{assembler-name}
30734 @cindex @option{--as} (@command{dlltool})
30735 Use @var{assembler-name} as the assembler. The default is @code{as}.
30738 @node GNAT and Windows Resources
30739 @section GNAT and Windows Resources
30740 @cindex Resources, windows
30743 * Building Resources::
30744 * Compiling Resources::
30745 * Using Resources::
30749 Resources are an easy way to add Windows specific objects to your
30750 application. The objects that can be added as resources include:
30759 @item string tables
30769 @item version information
30772 For example, a version information resource can be defined as follow and
30773 embedded into an executable or DLL:
30775 A version information resource can be used to embed information into an
30776 executable or a DLL. These information can be viewed using the file properties
30777 from the Windows Explorer. Here is an example of a version information
30783 FILEVERSION 1,0,0,0
30784 PRODUCTVERSION 1,0,0,0
30786 BLOCK "StringFileInfo"
30790 VALUE "CompanyName", "My Company Name"
30791 VALUE "FileDescription", "My application"
30792 VALUE "FileVersion", "1.0"
30793 VALUE "InternalName", "my_app"
30794 VALUE "LegalCopyright", "My Name"
30795 VALUE "OriginalFilename", "my_app.exe"
30796 VALUE "ProductName", "My App"
30797 VALUE "ProductVersion", "1.0"
30801 BLOCK "VarFileInfo"
30803 VALUE "Translation", 0x809, 1252
30809 The value @code{0809} (langID) is for the U.K English language and
30810 @code{04E4} (charsetID), which is equal to @code{1252} decimal, for
30814 This section explains how to build, compile and use resources. Note that this
30815 section does not cover all resource objects, for a complete description see
30816 the corresponding Microsoft documentation.
30818 @node Building Resources
30819 @subsection Building Resources
30820 @cindex Resources, building
30823 A resource file is an ASCII file. By convention resource files have an
30824 @file{.rc} extension.
30825 The easiest way to build a resource file is to use Microsoft tools
30826 such as @code{imagedit.exe} to build bitmaps, icons and cursors and
30827 @code{dlgedit.exe} to build dialogs.
30828 It is always possible to build an @file{.rc} file yourself by writing a
30831 It is not our objective to explain how to write a resource file. A
30832 complete description of the resource script language can be found in the
30833 Microsoft documentation.
30835 @node Compiling Resources
30836 @subsection Compiling Resources
30839 @cindex Resources, compiling
30842 This section describes how to build a GNAT-compatible (COFF) object file
30843 containing the resources. This is done using the Resource Compiler
30844 @code{windres} as follows:
30847 $ windres -i myres.rc -o myres.o
30851 By default @code{windres} will run @command{gcc} to preprocess the @file{.rc}
30852 file. You can specify an alternate preprocessor (usually named
30853 @file{cpp.exe}) using the @code{windres} @option{--preprocessor}
30854 parameter. A list of all possible options may be obtained by entering
30855 the command @code{windres} @option{--help}.
30857 It is also possible to use the Microsoft resource compiler @code{rc.exe}
30858 to produce a @file{.res} file (binary resource file). See the
30859 corresponding Microsoft documentation for further details. In this case
30860 you need to use @code{windres} to translate the @file{.res} file to a
30861 GNAT-compatible object file as follows:
30864 $ windres -i myres.res -o myres.o
30867 @node Using Resources
30868 @subsection Using Resources
30869 @cindex Resources, using
30872 To include the resource file in your program just add the
30873 GNAT-compatible object file for the resource(s) to the linker
30874 arguments. With @command{gnatmake} this is done by using the @option{-largs}
30878 $ gnatmake myprog -largs myres.o
30881 @node Debugging a DLL
30882 @section Debugging a DLL
30883 @cindex DLL debugging
30886 * Program and DLL Both Built with GCC/GNAT::
30887 * Program Built with Foreign Tools and DLL Built with GCC/GNAT::
30891 Debugging a DLL is similar to debugging a standard program. But
30892 we have to deal with two different executable parts: the DLL and the
30893 program that uses it. We have the following four possibilities:
30897 The program and the DLL are built with @code{GCC/GNAT}.
30899 The program is built with foreign tools and the DLL is built with
30902 The program is built with @code{GCC/GNAT} and the DLL is built with
30907 In this section we address only cases one and two above.
30908 There is no point in trying to debug
30909 a DLL with @code{GNU/GDB}, if there is no GDB-compatible debugging
30910 information in it. To do so you must use a debugger compatible with the
30911 tools suite used to build the DLL.
30913 @node Program and DLL Both Built with GCC/GNAT
30914 @subsection Program and DLL Both Built with GCC/GNAT
30917 This is the simplest case. Both the DLL and the program have @code{GDB}
30918 compatible debugging information. It is then possible to break anywhere in
30919 the process. Let's suppose here that the main procedure is named
30920 @code{ada_main} and that in the DLL there is an entry point named
30924 The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) and
30925 program must have been built with the debugging information (see GNAT -g
30926 switch). Here are the step-by-step instructions for debugging it:
30929 @item Launch @code{GDB} on the main program.
30935 @item Start the program and stop at the beginning of the main procedure
30942 This step is required to be able to set a breakpoint inside the DLL. As long
30943 as the program is not run, the DLL is not loaded. This has the
30944 consequence that the DLL debugging information is also not loaded, so it is not
30945 possible to set a breakpoint in the DLL.
30947 @item Set a breakpoint inside the DLL
30950 (gdb) break ada_dll
30957 At this stage a breakpoint is set inside the DLL. From there on
30958 you can use the standard approach to debug the whole program
30959 (@pxref{Running and Debugging Ada Programs}).
30962 @c This used to work, probably because the DLLs were non-relocatable
30963 @c keep this section around until the problem is sorted out.
30965 To break on the @code{DllMain} routine it is not possible to follow
30966 the procedure above. At the time the program stop on @code{ada_main}
30967 the @code{DllMain} routine as already been called. Either you can use
30968 the procedure below @pxref{Debugging the DLL Directly} or this procedure:
30971 @item Launch @code{GDB} on the main program.
30977 @item Load DLL symbols
30980 (gdb) add-sym api.dll
30983 @item Set a breakpoint inside the DLL
30986 (gdb) break ada_dll.adb:45
30989 Note that at this point it is not possible to break using the routine symbol
30990 directly as the program is not yet running. The solution is to break
30991 on the proper line (break in @file{ada_dll.adb} line 45).
30993 @item Start the program
31002 @node Program Built with Foreign Tools and DLL Built with GCC/GNAT
31003 @subsection Program Built with Foreign Tools and DLL Built with GCC/GNAT
31006 * Debugging the DLL Directly::
31007 * Attaching to a Running Process::
31011 In this case things are slightly more complex because it is not possible to
31012 start the main program and then break at the beginning to load the DLL and the
31013 associated DLL debugging information. It is not possible to break at the
31014 beginning of the program because there is no @code{GDB} debugging information,
31015 and therefore there is no direct way of getting initial control. This
31016 section addresses this issue by describing some methods that can be used
31017 to break somewhere in the DLL to debug it.
31020 First suppose that the main procedure is named @code{main} (this is for
31021 example some C code built with Microsoft Visual C) and that there is a
31022 DLL named @code{test.dll} containing an Ada entry point named
31026 The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) must have
31027 been built with debugging information (see GNAT -g option).
31029 @node Debugging the DLL Directly
31030 @subsubsection Debugging the DLL Directly
31034 Find out the executable starting address
31037 $ objdump --file-header main.exe
31040 The starting address is reported on the last line. For example:
31043 main.exe: file format pei-i386
31044 architecture: i386, flags 0x0000010a:
31045 EXEC_P, HAS_DEBUG, D_PAGED
31046 start address 0x00401010
31050 Launch the debugger on the executable.
31057 Set a breakpoint at the starting address, and launch the program.
31060 $ (gdb) break *0x00401010
31064 The program will stop at the given address.
31067 Set a breakpoint on a DLL subroutine.
31070 (gdb) break ada_dll.adb:45
31073 Or if you want to break using a symbol on the DLL, you need first to
31074 select the Ada language (language used by the DLL).
31077 (gdb) set language ada
31078 (gdb) break ada_dll
31082 Continue the program.
31089 This will run the program until it reaches the breakpoint that has been
31090 set. From that point you can use the standard way to debug a program
31091 as described in (@pxref{Running and Debugging Ada Programs}).
31096 It is also possible to debug the DLL by attaching to a running process.
31098 @node Attaching to a Running Process
31099 @subsubsection Attaching to a Running Process
31100 @cindex DLL debugging, attach to process
31103 With @code{GDB} it is always possible to debug a running process by
31104 attaching to it. It is possible to debug a DLL this way. The limitation
31105 of this approach is that the DLL must run long enough to perform the
31106 attach operation. It may be useful for instance to insert a time wasting
31107 loop in the code of the DLL to meet this criterion.
31111 @item Launch the main program @file{main.exe}.
31117 @item Use the Windows @i{Task Manager} to find the process ID. Let's say
31118 that the process PID for @file{main.exe} is 208.
31126 @item Attach to the running process to be debugged.
31132 @item Load the process debugging information.
31135 (gdb) symbol-file main.exe
31138 @item Break somewhere in the DLL.
31141 (gdb) break ada_dll
31144 @item Continue process execution.
31153 This last step will resume the process execution, and stop at
31154 the breakpoint we have set. From there you can use the standard
31155 approach to debug a program as described in
31156 (@pxref{Running and Debugging Ada Programs}).
31158 @node Setting Stack Size from gnatlink
31159 @section Setting Stack Size from @command{gnatlink}
31162 It is possible to specify the program stack size at link time. On modern
31163 versions of Windows, starting with XP, this is mostly useful to set the size of
31164 the main stack (environment task). The other task stacks are set with pragma
31165 Storage_Size or with the @command{gnatbind -d} command.
31167 Since older versions of Windows (2000, NT4, etc.) do not allow setting the
31168 reserve size of individual tasks, the link-time stack size applies to all
31169 tasks, and pragma Storage_Size has no effect.
31170 In particular, Stack Overflow checks are made against this
31171 link-time specified size.
31173 This setting can be done with
31174 @command{gnatlink} using either:
31178 @item using @option{-Xlinker} linker option
31181 $ gnatlink hello -Xlinker --stack=0x10000,0x1000
31184 This sets the stack reserve size to 0x10000 bytes and the stack commit
31185 size to 0x1000 bytes.
31187 @item using @option{-Wl} linker option
31190 $ gnatlink hello -Wl,--stack=0x1000000
31193 This sets the stack reserve size to 0x1000000 bytes. Note that with
31194 @option{-Wl} option it is not possible to set the stack commit size
31195 because the coma is a separator for this option.
31199 @node Setting Heap Size from gnatlink
31200 @section Setting Heap Size from @command{gnatlink}
31203 Under Windows systems, it is possible to specify the program heap size from
31204 @command{gnatlink} using either:
31208 @item using @option{-Xlinker} linker option
31211 $ gnatlink hello -Xlinker --heap=0x10000,0x1000
31214 This sets the heap reserve size to 0x10000 bytes and the heap commit
31215 size to 0x1000 bytes.
31217 @item using @option{-Wl} linker option
31220 $ gnatlink hello -Wl,--heap=0x1000000
31223 This sets the heap reserve size to 0x1000000 bytes. Note that with
31224 @option{-Wl} option it is not possible to set the heap commit size
31225 because the coma is a separator for this option.
31229 @node Mac OS Topics
31230 @appendix Mac OS Topics
31234 This chapter describes topics that are specific to Apple's OS X
31238 * Codesigning the Debugger::
31241 @node Codesigning the Debugger
31242 @section Codesigning the Debugger
31245 The Darwin Kernel requires the debugger to have special permissions
31246 before it is allowed to control other processes. These permissions
31247 are granted by codesigning the GDB executable. Without these
31248 permissions, the debugger will report error messages such as:
31251 Starting program: /x/y/foo
31252 Unable to find Mach task port for process-id 28885: (os/kern) failure (0x5).
31253 (please check gdb is codesigned - see taskgated(8))
31256 Codesigning requires a certificate. The following procedure explains
31260 @item Start the Keychain Access application (in
31261 /Applications/Utilities/Keychain Access.app)
31263 @item Select the Keychain Access -> Certificate Assistant ->
31264 Create a Certificate... menu
31269 @item Choose a name for the new certificate (this procedure will use
31270 "gdb-cert" as an example)
31272 @item Set "Identity Type" to "Self Signed Root"
31274 @item Set "Certificate Type" to "Code Signing"
31276 @item Activate the "Let me override defaults" option
31280 @item Click several times on "Continue" until the "Specify a Location
31281 For The Certificate" screen appears, then set "Keychain" to "System"
31283 @item Click on "Continue" until the certificate is created
31285 @item Finally, in the view, double-click on the new certificate,
31286 and set "When using this certificate" to "Always Trust"
31288 @item Exit the Keychain Access application and restart the computer
31289 (this is unfortunately required)
31293 Once a certificate has been created, the debugger can be codesigned
31294 as follow. In a Terminal, run the following command...
31297 codesign -f -s "gdb-cert" <gnat_install_prefix>/bin/gdb
31300 ... where "gdb-cert" should be replaced by the actual certificate
31301 name chosen above, and <gnat_install_prefix> should be replaced by
31302 the location where you installed GNAT.
31304 @c **********************************
31305 @c * GNU Free Documentation License *
31306 @c **********************************
31308 @c GNU Free Documentation License
31316 @c Put table of contents at end, otherwise it precedes the "title page" in
31317 @c the .txt version
31318 @c Edit the pdf file to move the contents to the beginning, after the title