2 \input texinfo @c -*-texinfo-*-
5 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
7 @c GNAT DOCUMENTATION o
11 @c Copyright (C) 1992-2014, Free Software Foundation, Inc. o
13 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
15 @setfilename gnat_ugn.info
18 Copyright @copyright{} 1995-2014 Free Software Foundation,
21 Permission is granted to copy, distribute and/or modify this document
22 under the terms of the GNU Free Documentation License, Version 1.3 or
23 any later version published by the Free Software Foundation; with no
24 Invariant Sections, with no Front-Cover Texts and with no Back-Cover
25 Texts. A copy of the license is included in the section entitled
26 ``GNU Free Documentation License''.
29 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
31 @c GNAT_UGN Style Guide
33 @c 1. Always put a @noindent on the line before the first paragraph
34 @c after any of these commands:
46 @c 2. DO NOT use @example. Use @smallexample instead.
47 @c a) DO NOT use highlighting commands (@b{}, @i{}) inside an @smallexample
48 @c context. These can interfere with the readability of the texi
49 @c source file. Instead, use one of the following annotated
50 @c @smallexample commands, and preprocess the texi file with the
51 @c ada2texi tool (which generates appropriate highlighting):
52 @c @smallexample @c ada
53 @c @smallexample @c adanocomment
54 @c @smallexample @c projectfile
55 @c b) The "@c ada" markup will result in boldface for reserved words
56 @c and italics for comments
57 @c c) The "@c adanocomment" markup will result only in boldface for
58 @c reserved words (comments are left alone)
59 @c d) The "@c projectfile" markup is like "@c ada" except that the set
60 @c of reserved words include the new reserved words for project files
62 @c 3. Each @chapter, @section, @subsection, @subsubsection, etc.
63 @c command must be preceded by two empty lines
65 @c 4. The @item command should be on a line of its own if it is in an
66 @c @itemize or @enumerate command.
68 @c 5. When talking about ALI files use "ALI" (all uppercase), not "Ali"
71 @c 6. DO NOT put trailing spaces at the end of a line. Such spaces will
72 @c cause the document build to fail.
74 @c 7. DO NOT use @cartouche for examples that are longer than around 10 lines.
75 @c This command inhibits page breaks, so long examples in a @cartouche can
76 @c lead to large, ugly patches of empty space on a page.
78 @c NOTE: This file should be submitted to xgnatugn with either the vms flag
79 @c or the unw flag set. The unw flag covers topics for both Unix and
82 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
85 @c This flag is used where the text refers to conditions that exist when the
86 @c text was entered into the document but which may change over time.
87 @c Update the setting for the flag, and (if necessary) the text surrounding,
88 @c the references to the flag, on future doc revisions:
89 @c search for @value{NOW}.
100 @set PLATFORM OpenVMS
101 @set TITLESUFFIX for OpenVMS
106 @c The ARG is an optional argument. To be used for macro arguments in
107 @c their documentation (@defmac).
109 @r{[}@var{\varname\}@r{]}@c
111 @c Status as of November 2009:
112 @c Unfortunately texi2pdf and texi2html treat the trailing "@c"
113 @c differently, and faulty output is produced by one or the other
114 @c depending on whether the "@c" is present or absent.
115 @c As a result, the @ovar macro is not used, and all invocations
116 @c of the @ovar macro have been expanded inline.
119 @settitle @value{EDITION} User's Guide @value{TITLESUFFIX}
120 @dircategory GNU Ada tools
122 * @value{EDITION} User's Guide: (gnat_ugn). @value{PLATFORM}
125 @include gcc-common.texi
127 @setchapternewpage odd
132 @title @value{EDITION} User's Guide
136 @titlefont{@i{@value{PLATFORM}}}
142 @subtitle GNAT, The GNU Ada Development Environment
147 @vskip 0pt plus 1filll
154 @node Top, About This Guide, (dir), (dir)
155 @top @value{EDITION} User's Guide
158 @value{EDITION} User's Guide @value{PLATFORM}
161 GNAT, The GNU Ada Development Environment@*
162 GCC version @value{version-GCC}@*
169 * Getting Started with GNAT::
170 * The GNAT Compilation Model::
171 * Compiling with gcc::
172 * Binding with gnatbind::
173 * Linking with gnatlink::
174 * The GNAT Make Program gnatmake::
175 * Improving Performance::
176 * Renaming Files with gnatchop::
177 * Configuration Pragmas::
178 * Handling Arbitrary File Naming Conventions with gnatname::
179 * GNAT Project Manager::
180 * Tools Supporting Project Files::
181 * The Cross-Referencing Tools gnatxref and gnatfind::
183 * The GNAT Pretty-Printer gnatpp::
185 * The Ada-to-XML converter gnat2xml::
187 * The GNAT Metrics Tool gnatmetric::
189 * File Name Krunching with gnatkr::
190 * Preprocessing with gnatprep::
191 * The GNAT Library Browser gnatls::
192 * Cleaning Up with gnatclean::
194 * GNAT and Libraries::
195 * Using the GNU make Utility::
197 * Memory Management Issues::
198 * Stack Related Facilities::
200 * Verifying Properties with gnatcheck::
201 * Creating Sample Bodies with gnatstub::
202 * Creating Unit Tests with gnattest::
204 * Performing Dimensionality Analysis in GNAT::
205 * Generating Ada Bindings for C and C++ headers::
206 * Other Utility Programs::
208 * Code Coverage and Profiling::
210 * Running and Debugging Ada Programs::
212 * Compatibility with HP Ada::
214 * Platform-Specific Information for the Run-Time Libraries::
215 * Example of Binder Output File::
216 * Elaboration Order Handling in GNAT::
217 * Overflow Check Handling in GNAT::
218 * Conditional Compilation::
220 * Compatibility and Porting Guide::
221 * Microsoft Windows Topics::
223 * GNU Free Documentation License::
228 @node About This Guide
229 @unnumbered About This Guide
233 This guide describes the use of @value{EDITION},
234 a compiler and software development toolset for the full Ada
235 programming language, implemented on OpenVMS for HP's Alpha and
236 Integrity server (I64) platforms.
239 This guide describes the use of @value{EDITION},
240 a compiler and software development
241 toolset for the full Ada programming language.
243 It documents the features of the compiler and tools, and explains
244 how to use them to build Ada applications.
246 @value{EDITION} implements Ada 95, Ada 2005 and Ada 2012, and it may also be
247 invoked in Ada 83 compatibility mode.
248 By default, @value{EDITION} assumes Ada 2012, but you can override with a
249 compiler switch (@pxref{Compiling Different Versions of Ada})
250 to explicitly specify the language version.
251 Throughout this manual, references to ``Ada'' without a year suffix
252 apply to all Ada 95/2005/2012 versions of the language.
255 For ease of exposition, ``@value{EDITION}'' will be referred to simply as
256 ``GNAT'' in the remainder of this document.
261 * What This Guide Contains::
262 * What You Should Know before Reading This Guide::
263 * Related Information::
267 @node What This Guide Contains
268 @unnumberedsec What This Guide Contains
271 This guide contains the following chapters:
275 @ref{Getting Started with GNAT}, describes how to get started compiling
276 and running Ada programs with the GNAT Ada programming environment.
278 @ref{The GNAT Compilation Model}, describes the compilation model used
282 @ref{Compiling with gcc}, describes how to compile
283 Ada programs with @command{gcc}, the Ada compiler.
286 @ref{Binding with gnatbind}, describes how to
287 perform binding of Ada programs with @code{gnatbind}, the GNAT binding
291 @ref{Linking with gnatlink},
292 describes @command{gnatlink}, a
293 program that provides for linking using the GNAT run-time library to
294 construct a program. @command{gnatlink} can also incorporate foreign language
295 object units into the executable.
298 @ref{The GNAT Make Program gnatmake}, describes @command{gnatmake}, a
299 utility that automatically determines the set of sources
300 needed by an Ada compilation unit, and executes the necessary compilations
304 @ref{Improving Performance}, shows various techniques for making your
305 Ada program run faster or take less space and describes the effect of
306 the compiler's optimization switch.
309 the @command{gnatelim} tool and
311 unused subprogram/data elimination.
314 @ref{Renaming Files with gnatchop}, describes
315 @code{gnatchop}, a utility that allows you to preprocess a file that
316 contains Ada source code, and split it into one or more new files, one
317 for each compilation unit.
320 @ref{Configuration Pragmas}, describes the configuration pragmas
324 @ref{Handling Arbitrary File Naming Conventions with gnatname},
325 shows how to override the default GNAT file naming conventions,
326 either for an individual unit or globally.
329 @ref{GNAT Project Manager}, describes how to use project files
330 to organize large projects.
333 @ref{The Cross-Referencing Tools gnatxref and gnatfind}, discusses
334 @code{gnatxref} and @code{gnatfind}, two tools that provide an easy
335 way to navigate through sources.
339 @ref{The GNAT Pretty-Printer gnatpp}, shows how to produce a reformatted
340 version of an Ada source file with control over casing, indentation,
341 comment placement, and other elements of program presentation style.
347 @ref{The Ada-to-XML converter gnat2xml}, shows how to convert Ada
348 source code into XML.
354 @ref{The GNAT Metrics Tool gnatmetric}, shows how to compute various
355 metrics for an Ada source file, such as the number of types and subprograms,
356 and assorted complexity measures.
360 @ref{File Name Krunching with gnatkr}, describes the @code{gnatkr}
361 file name krunching utility, used to handle shortened
362 file names on operating systems with a limit on the length of names.
365 @ref{Preprocessing with gnatprep}, describes @code{gnatprep}, a
366 preprocessor utility that allows a single source file to be used to
367 generate multiple or parameterized source files by means of macro
371 @ref{The GNAT Library Browser gnatls}, describes @code{gnatls}, a
372 utility that displays information about compiled units, including dependences
373 on the corresponding sources files, and consistency of compilations.
376 @ref{Cleaning Up with gnatclean}, describes @code{gnatclean}, a utility
377 to delete files that are produced by the compiler, binder and linker.
381 @ref{GNAT and Libraries}, describes the process of creating and using
382 Libraries with GNAT. It also describes how to recompile the GNAT run-time
386 @ref{Using the GNU make Utility}, describes some techniques for using
387 the GNAT toolset in Makefiles.
391 @ref{Memory Management Issues}, describes some useful predefined storage pools
392 and in particular the GNAT Debug Pool facility, which helps detect incorrect
396 It also describes @command{gnatmem}, a utility that monitors dynamic
397 allocation and deallocation and helps detect ``memory leaks''.
402 @ref{Stack Related Facilities}, describes some useful tools associated with
403 stack checking and analysis.
407 @ref{Verifying Properties with gnatcheck}, discusses @code{gnatcheck},
408 a utility that checks Ada code against a set of rules.
411 @ref{Creating Sample Bodies with gnatstub}, discusses @code{gnatstub},
412 a utility that generates empty but compilable bodies for library units.
417 @ref{Creating Unit Tests with gnattest}, discusses @code{gnattest},
418 a utility that generates unit testing templates for library units.
422 @ref{Performing Dimensionality Analysis in GNAT}, describes the Ada 2012
423 facilities used in GNAT to declare dimensioned objects, and to verify that
424 uses of these objects are consistent with their given physical dimensions
425 (so that meters cannot be assigned to kilograms, and so on).
428 @ref{Generating Ada Bindings for C and C++ headers}, describes how to
429 generate automatically Ada bindings from C and C++ headers.
432 @ref{Other Utility Programs}, discusses several other GNAT utilities,
433 including @code{gnathtml}.
437 @ref{Code Coverage and Profiling}, describes how to perform a structural
438 coverage and profile the execution of Ada programs.
442 @ref{Running and Debugging Ada Programs}, describes how to run and debug
447 @ref{Compatibility with HP Ada}, details the compatibility of GNAT with
448 HP Ada 83 @footnote{``HP Ada'' refers to the legacy product originally
449 developed by Digital Equipment Corporation and currently supported by HP.}
450 for OpenVMS Alpha. This product was formerly known as DEC Ada,
453 historical compatibility reasons, the relevant libraries still use the
458 @ref{Platform-Specific Information for the Run-Time Libraries},
459 describes the various run-time
460 libraries supported by GNAT on various platforms and explains how to
461 choose a particular library.
464 @ref{Example of Binder Output File}, shows the source code for the binder
465 output file for a sample program.
468 @ref{Elaboration Order Handling in GNAT}, describes how GNAT helps
469 you deal with elaboration order issues.
472 @ref{Overflow Check Handling in GNAT}, describes how GNAT helps
473 you deal with arithmetic overflow issues.
476 @ref{Conditional Compilation}, describes how to model conditional compilation,
477 both with Ada in general and with GNAT facilities in particular.
480 @ref{Inline Assembler}, shows how to use the inline assembly facility
484 @ref{Compatibility and Porting Guide}, contains sections on compatibility
485 of GNAT with other Ada development environments (including Ada 83 systems),
486 to assist in porting code from those environments.
490 @ref{Microsoft Windows Topics}, presents information relevant to the
491 Microsoft Windows platform.
494 @ref{Mac OS Topics}, presents information relevant to Apple's OS X
499 @c *************************************************
500 @node What You Should Know before Reading This Guide
501 @c *************************************************
502 @unnumberedsec What You Should Know before Reading This Guide
504 @cindex Ada 95 Language Reference Manual
505 @cindex Ada 2005 Language Reference Manual
507 This guide assumes a basic familiarity with the Ada 95 language, as
508 described in the International Standard ANSI/ISO/IEC-8652:1995, January
510 It does not require knowledge of the new features introduced by Ada 2005,
511 (officially known as ISO/IEC 8652:1995 with Technical Corrigendum 1
513 Both reference manuals are included in the GNAT documentation
516 @node Related Information
517 @unnumberedsec Related Information
520 For further information about related tools, refer to the following
525 @xref{Top, GNAT Reference Manual, About This Guide, gnat_rm, GNAT
526 Reference Manual}, which contains all reference material for the GNAT
527 implementation of Ada.
531 @cite{Using the GNAT Programming Studio}, which describes the GPS
532 Integrated Development Environment.
535 @cite{GNAT Programming Studio Tutorial}, which introduces the
536 main GPS features through examples.
540 @cite{Ada 95 Reference Manual}, which contains reference
541 material for the Ada 95 programming language.
544 @cite{Ada 2005 Reference Manual}, which contains reference
545 material for the Ada 2005 programming language.
548 @xref{Top,, Debugging with GDB, gdb, Debugging with GDB},
550 in the GNU:[DOCS] directory,
552 for all details on the use of the GNU source-level debugger.
555 @xref{Top,, The extensible self-documenting text editor, emacs,
558 located in the GNU:[DOCS] directory if the EMACS kit is installed,
560 for full information on the extensible editor and programming
567 @unnumberedsec Conventions
569 @cindex Typographical conventions
572 Following are examples of the typographical and graphic conventions used
577 @code{Functions}, @command{utility program names}, @code{standard names},
581 @option{Option flags}
584 @file{File names}, @samp{button names}, and @samp{field names}.
587 @code{Variables}, @env{environment variables}, and @var{metasyntactic
594 @r{[}optional information or parameters@r{]}
597 Examples are described by text
599 and then shown this way.
604 Commands that are entered by the user are preceded in this manual by the
605 characters @w{``@code{$ }''} (dollar sign followed by space). If your system
606 uses this sequence as a prompt, then the commands will appear exactly as
607 you see them in the manual. If your system uses some other prompt, then
608 the command will appear with the @code{$} replaced by whatever prompt
609 character you are using.
612 Full file names are shown with the ``@code{/}'' character
613 as the directory separator; e.g., @file{parent-dir/subdir/myfile.adb}.
614 If you are using GNAT on a Windows platform, please note that
615 the ``@code{\}'' character should be used instead.
618 @c ****************************
619 @node Getting Started with GNAT
620 @chapter Getting Started with GNAT
623 This chapter describes some simple ways of using GNAT to build
624 executable Ada programs.
626 @ref{Running GNAT}, through @ref{Using the gnatmake Utility},
627 show how to use the command line environment.
628 @ref{Introduction to GPS}, provides a brief
629 introduction to the GNAT Programming Studio, a visually-oriented
630 Integrated Development Environment for GNAT.
631 GPS offers a graphical ``look and feel'', support for development in
632 other programming languages, comprehensive browsing features, and
633 many other capabilities.
634 For information on GPS please refer to
635 @cite{Using the GNAT Programming Studio}.
640 * Running a Simple Ada Program::
641 * Running a Program with Multiple Units::
642 * Using the gnatmake Utility::
644 * Editing with Emacs::
647 * Introduction to GPS::
652 @section Running GNAT
655 Three steps are needed to create an executable file from an Ada source
660 The source file(s) must be compiled.
662 The file(s) must be bound using the GNAT binder.
664 All appropriate object files must be linked to produce an executable.
668 All three steps are most commonly handled by using the @command{gnatmake}
669 utility program that, given the name of the main program, automatically
670 performs the necessary compilation, binding and linking steps.
672 @node Running a Simple Ada Program
673 @section Running a Simple Ada Program
676 Any text editor may be used to prepare an Ada program.
678 used, the optional Ada mode may be helpful in laying out the program.)
680 program text is a normal text file. We will assume in our initial
681 example that you have used your editor to prepare the following
682 standard format text file:
686 with Ada.Text_IO; use Ada.Text_IO;
689 Put_Line ("Hello WORLD!");
695 This file should be named @file{hello.adb}.
696 With the normal default file naming conventions, GNAT requires
698 contain a single compilation unit whose file name is the
700 with periods replaced by hyphens; the
701 extension is @file{ads} for a
702 spec and @file{adb} for a body.
703 You can override this default file naming convention by use of the
704 special pragma @code{Source_File_Name} (@pxref{Using Other File Names}).
705 Alternatively, if you want to rename your files according to this default
706 convention, which is probably more convenient if you will be using GNAT
707 for all your compilations, then the @code{gnatchop} utility
708 can be used to generate correctly-named source files
709 (@pxref{Renaming Files with gnatchop}).
711 You can compile the program using the following command (@code{$} is used
712 as the command prompt in the examples in this document):
719 @command{gcc} is the command used to run the compiler. This compiler is
720 capable of compiling programs in several languages, including Ada and
721 C. It assumes that you have given it an Ada program if the file extension is
722 either @file{.ads} or @file{.adb}, and it will then call
723 the GNAT compiler to compile the specified file.
726 The @option{-c} switch is required. It tells @command{gcc} to only do a
727 compilation. (For C programs, @command{gcc} can also do linking, but this
728 capability is not used directly for Ada programs, so the @option{-c}
729 switch must always be present.)
732 This compile command generates a file
733 @file{hello.o}, which is the object
734 file corresponding to your Ada program. It also generates
735 an ``Ada Library Information'' file @file{hello.ali},
736 which contains additional information used to check
737 that an Ada program is consistent.
738 To build an executable file,
739 use @code{gnatbind} to bind the program
740 and @command{gnatlink} to link it. The
741 argument to both @code{gnatbind} and @command{gnatlink} is the name of the
742 @file{ALI} file, but the default extension of @file{.ali} can
743 be omitted. This means that in the most common case, the argument
744 is simply the name of the main program:
752 A simpler method of carrying out these steps is to use
754 a master program that invokes all the required
755 compilation, binding and linking tools in the correct order. In particular,
756 @command{gnatmake} automatically recompiles any sources that have been
757 modified since they were last compiled, or sources that depend
758 on such modified sources, so that ``version skew'' is avoided.
759 @cindex Version skew (avoided by @command{gnatmake})
766 The result is an executable program called @file{hello}, which can be
774 assuming that the current directory is on the search path
775 for executable programs.
778 and, if all has gone well, you will see
785 appear in response to this command.
787 @c ****************************************
788 @node Running a Program with Multiple Units
789 @section Running a Program with Multiple Units
792 Consider a slightly more complicated example that has three files: a
793 main program, and the spec and body of a package:
803 with Ada.Text_IO; use Ada.Text_IO;
804 package body Greetings is
807 Put_Line ("Hello WORLD!");
812 Put_Line ("Goodbye WORLD!");
829 Following the one-unit-per-file rule, place this program in the
830 following three separate files:
834 spec of package @code{Greetings}
837 body of package @code{Greetings}
844 To build an executable version of
845 this program, we could use four separate steps to compile, bind, and link
846 the program, as follows:
850 $ gcc -c greetings.adb
856 Note that there is no required order of compilation when using GNAT.
857 In particular it is perfectly fine to compile the main program first.
858 Also, it is not necessary to compile package specs in the case where
859 there is an accompanying body; you only need to compile the body. If you want
860 to submit these files to the compiler for semantic checking and not code
861 generation, then use the
862 @option{-gnatc} switch:
865 $ gcc -c greetings.ads -gnatc
869 Although the compilation can be done in separate steps as in the
870 above example, in practice it is almost always more convenient
871 to use the @command{gnatmake} tool. All you need to know in this case
872 is the name of the main program's source file. The effect of the above four
873 commands can be achieved with a single one:
880 In the next section we discuss the advantages of using @command{gnatmake} in
883 @c *****************************
884 @node Using the gnatmake Utility
885 @section Using the @command{gnatmake} Utility
888 If you work on a program by compiling single components at a time using
889 @command{gcc}, you typically keep track of the units you modify. In order to
890 build a consistent system, you compile not only these units, but also any
891 units that depend on the units you have modified.
892 For example, in the preceding case,
893 if you edit @file{gmain.adb}, you only need to recompile that file. But if
894 you edit @file{greetings.ads}, you must recompile both
895 @file{greetings.adb} and @file{gmain.adb}, because both files contain
896 units that depend on @file{greetings.ads}.
898 @code{gnatbind} will warn you if you forget one of these compilation
899 steps, so that it is impossible to generate an inconsistent program as a
900 result of forgetting to do a compilation. Nevertheless it is tedious and
901 error-prone to keep track of dependencies among units.
902 One approach to handle the dependency-bookkeeping is to use a
903 makefile. However, makefiles present maintenance problems of their own:
904 if the dependencies change as you change the program, you must make
905 sure that the makefile is kept up-to-date manually, which is also an
908 The @command{gnatmake} utility takes care of these details automatically.
909 Invoke it using either one of the following forms:
913 $ gnatmake ^gmain^GMAIN^
917 The argument is the name of the file containing the main program;
918 you may omit the extension. @command{gnatmake}
919 examines the environment, automatically recompiles any files that need
920 recompiling, and binds and links the resulting set of object files,
921 generating the executable file, @file{^gmain^GMAIN.EXE^}.
922 In a large program, it
923 can be extremely helpful to use @command{gnatmake}, because working out by hand
924 what needs to be recompiled can be difficult.
926 Note that @command{gnatmake}
927 takes into account all the Ada rules that
928 establish dependencies among units. These include dependencies that result
929 from inlining subprogram bodies, and from
930 generic instantiation. Unlike some other
931 Ada make tools, @command{gnatmake} does not rely on the dependencies that were
932 found by the compiler on a previous compilation, which may possibly
933 be wrong when sources change. @command{gnatmake} determines the exact set of
934 dependencies from scratch each time it is run.
937 @node Editing with Emacs
938 @section Editing with Emacs
942 Emacs is an extensible self-documenting text editor that is available in a
943 separate VMSINSTAL kit.
945 Invoke Emacs by typing @kbd{Emacs} at the command prompt. To get started,
946 click on the Emacs Help menu and run the Emacs Tutorial.
947 In a character cell terminal, Emacs help is invoked with @kbd{Ctrl-h} (also
948 written as @kbd{C-h}), and the tutorial by @kbd{C-h t}.
950 Documentation on Emacs and other tools is available in Emacs under the
951 pull-down menu button: @code{Help - Info}. After selecting @code{Info},
952 use the middle mouse button to select a topic (e.g.@: Emacs).
954 In a character cell terminal, do @kbd{C-h i} to invoke info, and then @kbd{m}
955 (stands for menu) followed by the menu item desired, as in @kbd{m Emacs}, to
956 get to the Emacs manual.
957 Help on Emacs is also available by typing @kbd{HELP EMACS} at the DCL command
960 The tutorial is highly recommended in order to learn the intricacies of Emacs,
961 which is sufficiently extensible to provide for a complete programming
962 environment and shell for the sophisticated user.
966 @node Introduction to GPS
967 @section Introduction to GPS
968 @cindex GPS (GNAT Programming Studio)
969 @cindex GNAT Programming Studio (GPS)
971 Although the command line interface (@command{gnatmake}, etc.) alone
972 is sufficient, a graphical Interactive Development
973 Environment can make it easier for you to compose, navigate, and debug
974 programs. This section describes the main features of GPS
975 (``GNAT Programming Studio''), the GNAT graphical IDE.
976 You will see how to use GPS to build and debug an executable, and
977 you will also learn some of the basics of the GNAT ``project'' facility.
979 GPS enables you to do much more than is presented here;
980 e.g., you can produce a call graph, interface to a third-party
981 Version Control System, and inspect the generated assembly language
983 Indeed, GPS also supports languages other than Ada.
984 Such additional information, and an explanation of all of the GPS menu
985 items. may be found in the on-line help, which includes
986 a user's guide and a tutorial (these are also accessible from the GNAT
990 * Building a New Program with GPS::
991 * Simple Debugging with GPS::
994 @node Building a New Program with GPS
995 @subsection Building a New Program with GPS
997 GPS invokes the GNAT compilation tools using information
998 contained in a @emph{project} (also known as a @emph{project file}):
999 a collection of properties such
1000 as source directories, identities of main subprograms, tool switches, etc.,
1001 and their associated values.
1002 See @ref{GNAT Project Manager} for details.
1003 In order to run GPS, you will need to either create a new project
1004 or else open an existing one.
1006 This section will explain how you can use GPS to create a project,
1007 to associate Ada source files with a project, and to build and run
1011 @item @emph{Creating a project}
1013 Invoke GPS, either from the command line or the platform's IDE.
1014 After it starts, GPS will display a ``Welcome'' screen with three
1019 @code{Start with default project in directory}
1022 @code{Create new project with wizard}
1025 @code{Open existing project}
1029 Select @code{Create new project with wizard} and press @code{OK}.
1030 A new window will appear. In the text box labeled with
1031 @code{Enter the name of the project to create}, type @file{sample}
1032 as the project name.
1033 In the next box, browse to choose the directory in which you
1034 would like to create the project file.
1035 After selecting an appropriate directory, press @code{Forward}.
1037 A window will appear with the title
1038 @code{Version Control System Configuration}.
1039 Simply press @code{Forward}.
1041 A window will appear with the title
1042 @code{Please select the source directories for this project}.
1043 The directory that you specified for the project file will be selected
1044 by default as the one to use for sources; simply press @code{Forward}.
1046 A window will appear with the title
1047 @code{Please select the build directory for this project}.
1048 The directory that you specified for the project file will be selected
1049 by default for object files and executables;
1050 simply press @code{Forward}.
1052 A window will appear with the title
1053 @code{Please select the main units for this project}.
1054 You will supply this information later, after creating the source file.
1055 Simply press @code{Forward} for now.
1057 A window will appear with the title
1058 @code{Please select the switches to build the project}.
1059 Press @code{Apply}. This will create a project file named
1060 @file{sample.prj} in the directory that you had specified.
1062 @item @emph{Creating and saving the source file}
1064 After you create the new project, a GPS window will appear, which is
1065 partitioned into two main sections:
1069 A @emph{Workspace area}, initially greyed out, which you will use for
1070 creating and editing source files
1073 Directly below, a @emph{Messages area}, which initially displays a
1074 ``Welcome'' message.
1075 (If the Messages area is not visible, drag its border upward to expand it.)
1079 Select @code{File} on the menu bar, and then the @code{New} command.
1080 The Workspace area will become white, and you can now
1081 enter the source program explicitly.
1082 Type the following text
1084 @smallexample @c ada
1086 with Ada.Text_IO; use Ada.Text_IO;
1089 Put_Line("Hello from GPS!");
1095 Select @code{File}, then @code{Save As}, and enter the source file name
1097 The file will be saved in the same directory you specified as the
1098 location of the default project file.
1100 @item @emph{Updating the project file}
1102 You need to add the new source file to the project.
1104 the @code{Project} menu and then @code{Edit project properties}.
1105 Click the @code{Main files} tab on the left, and then the
1107 Choose @file{hello.adb} from the list, and press @code{Open}.
1108 The project settings window will reflect this action.
1111 @item @emph{Building and running the program}
1113 In the main GPS window, now choose the @code{Build} menu, then @code{Make},
1114 and select @file{hello.adb}.
1115 The Messages window will display the resulting invocations of @command{gcc},
1116 @command{gnatbind}, and @command{gnatlink}
1117 (reflecting the default switch settings from the
1118 project file that you created) and then a ``successful compilation/build''
1121 To run the program, choose the @code{Build} menu, then @code{Run}, and
1122 select @command{hello}.
1123 An @emph{Arguments Selection} window will appear.
1124 There are no command line arguments, so just click @code{OK}.
1126 The Messages window will now display the program's output (the string
1127 @code{Hello from GPS}), and at the bottom of the GPS window a status
1128 update is displayed (@code{Run: hello}).
1129 Close the GPS window (or select @code{File}, then @code{Exit}) to
1130 terminate this GPS session.
1133 @node Simple Debugging with GPS
1134 @subsection Simple Debugging with GPS
1136 This section illustrates basic debugging techniques (setting breakpoints,
1137 examining/modifying variables, single stepping).
1140 @item @emph{Opening a project}
1142 Start GPS and select @code{Open existing project}; browse to
1143 specify the project file @file{sample.prj} that you had created in the
1146 @item @emph{Creating a source file}
1148 Select @code{File}, then @code{New}, and type in the following program:
1150 @smallexample @c ada
1152 with Ada.Text_IO; use Ada.Text_IO;
1153 procedure Example is
1154 Line : String (1..80);
1157 Put_Line("Type a line of text at each prompt; an empty line to exit");
1161 Put_Line (Line (1..N) );
1169 Select @code{File}, then @code{Save as}, and enter the file name
1172 @item @emph{Updating the project file}
1174 Add @code{Example} as a new main unit for the project:
1177 Select @code{Project}, then @code{Edit Project Properties}.
1180 Select the @code{Main files} tab, click @code{Add}, then
1181 select the file @file{example.adb} from the list, and
1183 You will see the file name appear in the list of main units
1189 @item @emph{Building/running the executable}
1191 To build the executable
1192 select @code{Build}, then @code{Make}, and then choose @file{example.adb}.
1194 Run the program to see its effect (in the Messages area).
1195 Each line that you enter is displayed; an empty line will
1196 cause the loop to exit and the program to terminate.
1198 @item @emph{Debugging the program}
1200 Note that the @option{-g} switches to @command{gcc} and @command{gnatlink},
1201 which are required for debugging, are on by default when you create
1203 Thus unless you intentionally remove these settings, you will be able
1204 to debug any program that you develop using GPS.
1207 @item @emph{Initializing}
1209 Select @code{Debug}, then @code{Initialize}, then @file{example}
1211 @item @emph{Setting a breakpoint}
1213 After performing the initialization step, you will observe a small
1214 icon to the right of each line number.
1215 This serves as a toggle for breakpoints; clicking the icon will
1216 set a breakpoint at the corresponding line (the icon will change to
1217 a red circle with an ``x''), and clicking it again
1218 will remove the breakpoint / reset the icon.
1220 For purposes of this example, set a breakpoint at line 10 (the
1221 statement @code{Put_Line@ (Line@ (1..N));}
1223 @item @emph{Starting program execution}
1225 Select @code{Debug}, then @code{Run}. When the
1226 @code{Program Arguments} window appears, click @code{OK}.
1227 A console window will appear; enter some line of text,
1228 e.g.@: @code{abcde}, at the prompt.
1229 The program will pause execution when it gets to the
1230 breakpoint, and the corresponding line is highlighted.
1232 @item @emph{Examining a variable}
1234 Move the mouse over one of the occurrences of the variable @code{N}.
1235 You will see the value (5) displayed, in ``tool tip'' fashion.
1236 Right click on @code{N}, select @code{Debug}, then select @code{Display N}.
1237 You will see information about @code{N} appear in the @code{Debugger Data}
1238 pane, showing the value as 5.
1240 @item @emph{Assigning a new value to a variable}
1242 Right click on the @code{N} in the @code{Debugger Data} pane, and
1243 select @code{Set value of N}.
1244 When the input window appears, enter the value @code{4} and click
1246 This value does not automatically appear in the @code{Debugger Data}
1247 pane; to see it, right click again on the @code{N} in the
1248 @code{Debugger Data} pane and select @code{Update value}.
1249 The new value, 4, will appear in red.
1251 @item @emph{Single stepping}
1253 Select @code{Debug}, then @code{Next}.
1254 This will cause the next statement to be executed, in this case the
1255 call of @code{Put_Line} with the string slice.
1256 Notice in the console window that the displayed string is simply
1257 @code{abcd} and not @code{abcde} which you had entered.
1258 This is because the upper bound of the slice is now 4 rather than 5.
1260 @item @emph{Removing a breakpoint}
1262 Toggle the breakpoint icon at line 10.
1264 @item @emph{Resuming execution from a breakpoint}
1266 Select @code{Debug}, then @code{Continue}.
1267 The program will reach the next iteration of the loop, and
1268 wait for input after displaying the prompt.
1269 This time, just hit the @kbd{Enter} key.
1270 The value of @code{N} will be 0, and the program will terminate.
1271 The console window will disappear.
1276 @node The GNAT Compilation Model
1277 @chapter The GNAT Compilation Model
1278 @cindex GNAT compilation model
1279 @cindex Compilation model
1282 * Source Representation::
1283 * Foreign Language Representation::
1284 * File Naming Rules::
1285 * Using Other File Names::
1286 * Alternative File Naming Schemes::
1287 * Generating Object Files::
1288 * Source Dependencies::
1289 * The Ada Library Information Files::
1290 * Binding an Ada Program::
1291 * Mixed Language Programming::
1293 * Building Mixed Ada & C++ Programs::
1294 * Comparison between GNAT and C/C++ Compilation Models::
1296 * Comparison between GNAT and Conventional Ada Library Models::
1298 * Placement of temporary files::
1303 This chapter describes the compilation model used by GNAT. Although
1304 similar to that used by other languages, such as C and C++, this model
1305 is substantially different from the traditional Ada compilation models,
1306 which are based on a library. The model is initially described without
1307 reference to the library-based model. If you have not previously used an
1308 Ada compiler, you need only read the first part of this chapter. The
1309 last section describes and discusses the differences between the GNAT
1310 model and the traditional Ada compiler models. If you have used other
1311 Ada compilers, this section will help you to understand those
1312 differences, and the advantages of the GNAT model.
1314 @node Source Representation
1315 @section Source Representation
1319 Ada source programs are represented in standard text files, using
1320 Latin-1 coding. Latin-1 is an 8-bit code that includes the familiar
1321 7-bit ASCII set, plus additional characters used for
1322 representing foreign languages (@pxref{Foreign Language Representation}
1323 for support of non-USA character sets). The format effector characters
1324 are represented using their standard ASCII encodings, as follows:
1329 Vertical tab, @code{16#0B#}
1333 Horizontal tab, @code{16#09#}
1337 Carriage return, @code{16#0D#}
1341 Line feed, @code{16#0A#}
1345 Form feed, @code{16#0C#}
1349 Source files are in standard text file format. In addition, GNAT will
1350 recognize a wide variety of stream formats, in which the end of
1351 physical lines is marked by any of the following sequences:
1352 @code{LF}, @code{CR}, @code{CR-LF}, or @code{LF-CR}. This is useful
1353 in accommodating files that are imported from other operating systems.
1355 @cindex End of source file
1356 @cindex Source file, end
1358 The end of a source file is normally represented by the physical end of
1359 file. However, the control character @code{16#1A#} (@code{SUB}) is also
1360 recognized as signalling the end of the source file. Again, this is
1361 provided for compatibility with other operating systems where this
1362 code is used to represent the end of file.
1364 Each file contains a single Ada compilation unit, including any pragmas
1365 associated with the unit. For example, this means you must place a
1366 package declaration (a package @dfn{spec}) and the corresponding body in
1367 separate files. An Ada @dfn{compilation} (which is a sequence of
1368 compilation units) is represented using a sequence of files. Similarly,
1369 you will place each subunit or child unit in a separate file.
1371 @node Foreign Language Representation
1372 @section Foreign Language Representation
1375 GNAT supports the standard character sets defined in Ada as well as
1376 several other non-standard character sets for use in localized versions
1377 of the compiler (@pxref{Character Set Control}).
1380 * Other 8-Bit Codes::
1381 * Wide_Character Encodings::
1382 * Wide_Wide_Character Encodings::
1390 The basic character set is Latin-1. This character set is defined by ISO
1391 standard 8859, part 1. The lower half (character codes @code{16#00#}
1392 @dots{} @code{16#7F#)} is identical to standard ASCII coding, but the upper
1393 half is used to represent additional characters. These include extended letters
1394 used by European languages, such as French accents, the vowels with umlauts
1395 used in German, and the extra letter A-ring used in Swedish.
1397 @findex Ada.Characters.Latin_1
1398 For a complete list of Latin-1 codes and their encodings, see the source
1399 file of library unit @code{Ada.Characters.Latin_1} in file
1400 @file{a-chlat1.ads}.
1401 You may use any of these extended characters freely in character or
1402 string literals. In addition, the extended characters that represent
1403 letters can be used in identifiers.
1405 @node Other 8-Bit Codes
1406 @subsection Other 8-Bit Codes
1409 GNAT also supports several other 8-bit coding schemes:
1412 @item ISO 8859-2 (Latin-2)
1415 Latin-2 letters allowed in identifiers, with uppercase and lowercase
1418 @item ISO 8859-3 (Latin-3)
1421 Latin-3 letters allowed in identifiers, with uppercase and lowercase
1424 @item ISO 8859-4 (Latin-4)
1427 Latin-4 letters allowed in identifiers, with uppercase and lowercase
1430 @item ISO 8859-5 (Cyrillic)
1433 ISO 8859-5 letters (Cyrillic) allowed in identifiers, with uppercase and
1434 lowercase equivalence.
1436 @item ISO 8859-15 (Latin-9)
1439 ISO 8859-15 (Latin-9) letters allowed in identifiers, with uppercase and
1440 lowercase equivalence
1442 @item IBM PC (code page 437)
1443 @cindex code page 437
1444 This code page is the normal default for PCs in the U.S. It corresponds
1445 to the original IBM PC character set. This set has some, but not all, of
1446 the extended Latin-1 letters, but these letters do not have the same
1447 encoding as Latin-1. In this mode, these letters are allowed in
1448 identifiers with uppercase and lowercase equivalence.
1450 @item IBM PC (code page 850)
1451 @cindex code page 850
1452 This code page is a modification of 437 extended to include all the
1453 Latin-1 letters, but still not with the usual Latin-1 encoding. In this
1454 mode, all these letters are allowed in identifiers with uppercase and
1455 lowercase equivalence.
1457 @item Full Upper 8-bit
1458 Any character in the range 80-FF allowed in identifiers, and all are
1459 considered distinct. In other words, there are no uppercase and lowercase
1460 equivalences in this range. This is useful in conjunction with
1461 certain encoding schemes used for some foreign character sets (e.g.,
1462 the typical method of representing Chinese characters on the PC).
1465 No upper-half characters in the range 80-FF are allowed in identifiers.
1466 This gives Ada 83 compatibility for identifier names.
1470 For precise data on the encodings permitted, and the uppercase and lowercase
1471 equivalences that are recognized, see the file @file{csets.adb} in
1472 the GNAT compiler sources. You will need to obtain a full source release
1473 of GNAT to obtain this file.
1475 @node Wide_Character Encodings
1476 @subsection Wide_Character Encodings
1479 GNAT allows wide character codes to appear in character and string
1480 literals, and also optionally in identifiers, by means of the following
1481 possible encoding schemes:
1486 In this encoding, a wide character is represented by the following five
1494 Where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal
1495 characters (using uppercase letters) of the wide character code. For
1496 example, ESC A345 is used to represent the wide character with code
1498 This scheme is compatible with use of the full Wide_Character set.
1500 @item Upper-Half Coding
1501 @cindex Upper-Half Coding
1502 The wide character with encoding @code{16#abcd#} where the upper bit is on
1503 (in other words, ``a'' is in the range 8-F) is represented as two bytes,
1504 @code{16#ab#} and @code{16#cd#}. The second byte cannot be a format control
1505 character, but is not required to be in the upper half. This method can
1506 be also used for shift-JIS or EUC, where the internal coding matches the
1509 @item Shift JIS Coding
1510 @cindex Shift JIS Coding
1511 A wide character is represented by a two-character sequence,
1513 @code{16#cd#}, with the restrictions described for upper-half encoding as
1514 described above. The internal character code is the corresponding JIS
1515 character according to the standard algorithm for Shift-JIS
1516 conversion. Only characters defined in the JIS code set table can be
1517 used with this encoding method.
1521 A wide character is represented by a two-character sequence
1523 @code{16#cd#}, with both characters being in the upper half. The internal
1524 character code is the corresponding JIS character according to the EUC
1525 encoding algorithm. Only characters defined in the JIS code set table
1526 can be used with this encoding method.
1529 A wide character is represented using
1530 UCS Transformation Format 8 (UTF-8) as defined in Annex R of ISO
1531 10646-1/Am.2. Depending on the character value, the representation
1532 is a one, two, or three byte sequence:
1537 16#0000#-16#007f#: 2#0@var{xxxxxxx}#
1538 16#0080#-16#07ff#: 2#110@var{xxxxx}# 2#10@var{xxxxxx}#
1539 16#0800#-16#ffff#: 2#1110@var{xxxx}# 2#10@var{xxxxxx}# 2#10@var{xxxxxx}#
1544 where the @var{xxx} bits correspond to the left-padded bits of the
1545 16-bit character value. Note that all lower half ASCII characters
1546 are represented as ASCII bytes and all upper half characters and
1547 other wide characters are represented as sequences of upper-half
1548 (The full UTF-8 scheme allows for encoding 31-bit characters as
1549 6-byte sequences, and in the following section on wide wide
1550 characters, the use of these sequences is documented).
1552 @item Brackets Coding
1553 In this encoding, a wide character is represented by the following eight
1561 Where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal
1562 characters (using uppercase letters) of the wide character code. For
1563 example, [``A345''] is used to represent the wide character with code
1564 @code{16#A345#}. It is also possible (though not required) to use the
1565 Brackets coding for upper half characters. For example, the code
1566 @code{16#A3#} can be represented as @code{[``A3'']}.
1568 This scheme is compatible with use of the full Wide_Character set,
1569 and is also the method used for wide character encoding in some standard
1570 ACATS (Ada Conformity Assessment Test Suite) test suite distributions.
1575 Note: Some of these coding schemes do not permit the full use of the
1576 Ada character set. For example, neither Shift JIS, nor EUC allow the
1577 use of the upper half of the Latin-1 set.
1579 @node Wide_Wide_Character Encodings
1580 @subsection Wide_Wide_Character Encodings
1583 GNAT allows wide wide character codes to appear in character and string
1584 literals, and also optionally in identifiers, by means of the following
1585 possible encoding schemes:
1590 A wide character is represented using
1591 UCS Transformation Format 8 (UTF-8) as defined in Annex R of ISO
1592 10646-1/Am.2. Depending on the character value, the representation
1593 of character codes with values greater than 16#FFFF# is a
1594 is a four, five, or six byte sequence:
1600 16#01_0000#-16#10_FFFF#: 11110xxx 10xxxxxx 10xxxxxx
1602 16#0020_0000#-16#03FF_FFFF#: 111110xx 10xxxxxx 10xxxxxx
1604 16#0400_0000#-16#7FFF_FFFF#: 1111110x 10xxxxxx 10xxxxxx
1605 10xxxxxx 10xxxxxx 10xxxxxx
1609 where the @var{xxx} bits correspond to the left-padded bits of the
1610 32-bit character value.
1612 @item Brackets Coding
1613 In this encoding, a wide wide character is represented by the following ten or
1614 twelve byte character sequence:
1618 [ " a b c d e f g h " ]
1622 Where @code{a-h} are the six or eight hexadecimal
1623 characters (using uppercase letters) of the wide wide character code. For
1624 example, ["1F4567"] is used to represent the wide wide character with code
1625 @code{16#001F_4567#}.
1627 This scheme is compatible with use of the full Wide_Wide_Character set,
1628 and is also the method used for wide wide character encoding in some standard
1629 ACATS (Ada Conformity Assessment Test Suite) test suite distributions.
1633 @node File Naming Rules
1634 @section File Naming Rules
1637 The default file name is determined by the name of the unit that the
1638 file contains. The name is formed by taking the full expanded name of
1639 the unit and replacing the separating dots with hyphens and using
1640 ^lowercase^uppercase^ for all letters.
1642 An exception arises if the file name generated by the above rules starts
1643 with one of the characters
1645 @samp{A}, @samp{G}, @samp{I}, or @samp{S},
1648 @samp{a}, @samp{g}, @samp{i}, or @samp{s},
1650 and the second character is a
1651 minus. In this case, the character ^tilde^dollar sign^ is used in place
1652 of the minus. The reason for this special rule is to avoid clashes with
1653 the standard names for child units of the packages System, Ada,
1654 Interfaces, and GNAT, which use the prefixes
1656 @samp{S-}, @samp{A-}, @samp{I-}, and @samp{G-},
1659 @samp{s-}, @samp{a-}, @samp{i-}, and @samp{g-},
1663 The file extension is @file{.ads} for a spec and
1664 @file{.adb} for a body. The following list shows some
1665 examples of these rules.
1672 @item arith_functions.ads
1673 Arith_Functions (package spec)
1674 @item arith_functions.adb
1675 Arith_Functions (package body)
1677 Func.Spec (child package spec)
1679 Func.Spec (child package body)
1681 Sub (subunit of Main)
1682 @item ^a~bad.adb^A$BAD.ADB^
1683 A.Bad (child package body)
1687 Following these rules can result in excessively long
1688 file names if corresponding
1689 unit names are long (for example, if child units or subunits are
1690 heavily nested). An option is available to shorten such long file names
1691 (called file name ``krunching''). This may be particularly useful when
1692 programs being developed with GNAT are to be used on operating systems
1693 with limited file name lengths. @xref{Using gnatkr}.
1695 Of course, no file shortening algorithm can guarantee uniqueness over
1696 all possible unit names; if file name krunching is used, it is your
1697 responsibility to ensure no name clashes occur. Alternatively you
1698 can specify the exact file names that you want used, as described
1699 in the next section. Finally, if your Ada programs are migrating from a
1700 compiler with a different naming convention, you can use the gnatchop
1701 utility to produce source files that follow the GNAT naming conventions.
1702 (For details @pxref{Renaming Files with gnatchop}.)
1704 Note: in the case of @code{Windows NT/XP} or @code{OpenVMS} operating
1705 systems, case is not significant. So for example on @code{Windows XP}
1706 if the canonical name is @code{main-sub.adb}, you can use the file name
1707 @code{Main-Sub.adb} instead. However, case is significant for other
1708 operating systems, so for example, if you want to use other than
1709 canonically cased file names on a Unix system, you need to follow
1710 the procedures described in the next section.
1712 @node Using Other File Names
1713 @section Using Other File Names
1717 In the previous section, we have described the default rules used by
1718 GNAT to determine the file name in which a given unit resides. It is
1719 often convenient to follow these default rules, and if you follow them,
1720 the compiler knows without being explicitly told where to find all
1723 However, in some cases, particularly when a program is imported from
1724 another Ada compiler environment, it may be more convenient for the
1725 programmer to specify which file names contain which units. GNAT allows
1726 arbitrary file names to be used by means of the Source_File_Name pragma.
1727 The form of this pragma is as shown in the following examples:
1728 @cindex Source_File_Name pragma
1730 @smallexample @c ada
1732 pragma Source_File_Name (My_Utilities.Stacks,
1733 Spec_File_Name => "myutilst_a.ada");
1734 pragma Source_File_name (My_Utilities.Stacks,
1735 Body_File_Name => "myutilst.ada");
1740 As shown in this example, the first argument for the pragma is the unit
1741 name (in this example a child unit). The second argument has the form
1742 of a named association. The identifier
1743 indicates whether the file name is for a spec or a body;
1744 the file name itself is given by a string literal.
1746 The source file name pragma is a configuration pragma, which means that
1747 normally it will be placed in the @file{gnat.adc}
1748 file used to hold configuration
1749 pragmas that apply to a complete compilation environment.
1750 For more details on how the @file{gnat.adc} file is created and used
1751 see @ref{Handling of Configuration Pragmas}.
1752 @cindex @file{gnat.adc}
1755 GNAT allows completely arbitrary file names to be specified using the
1756 source file name pragma. However, if the file name specified has an
1757 extension other than @file{.ads} or @file{.adb} it is necessary to use
1758 a special syntax when compiling the file. The name in this case must be
1759 preceded by the special sequence @option{-x} followed by a space and the name
1760 of the language, here @code{ada}, as in:
1763 $ gcc -c -x ada peculiar_file_name.sim
1768 @command{gnatmake} handles non-standard file names in the usual manner (the
1769 non-standard file name for the main program is simply used as the
1770 argument to gnatmake). Note that if the extension is also non-standard,
1771 then it must be included in the @command{gnatmake} command, it may not
1774 @node Alternative File Naming Schemes
1775 @section Alternative File Naming Schemes
1776 @cindex File naming schemes, alternative
1779 In the previous section, we described the use of the @code{Source_File_Name}
1780 pragma to allow arbitrary names to be assigned to individual source files.
1781 However, this approach requires one pragma for each file, and especially in
1782 large systems can result in very long @file{gnat.adc} files, and also create
1783 a maintenance problem.
1785 GNAT also provides a facility for specifying systematic file naming schemes
1786 other than the standard default naming scheme previously described. An
1787 alternative scheme for naming is specified by the use of
1788 @code{Source_File_Name} pragmas having the following format:
1789 @cindex Source_File_Name pragma
1791 @smallexample @c ada
1792 pragma Source_File_Name (
1793 Spec_File_Name => FILE_NAME_PATTERN
1794 @r{[},Casing => CASING_SPEC@r{]}
1795 @r{[},Dot_Replacement => STRING_LITERAL@r{]});
1797 pragma Source_File_Name (
1798 Body_File_Name => FILE_NAME_PATTERN
1799 @r{[},Casing => CASING_SPEC@r{]}
1800 @r{[},Dot_Replacement => STRING_LITERAL@r{]});
1802 pragma Source_File_Name (
1803 Subunit_File_Name => FILE_NAME_PATTERN
1804 @r{[},Casing => CASING_SPEC@r{]}
1805 @r{[},Dot_Replacement => STRING_LITERAL@r{]});
1807 FILE_NAME_PATTERN ::= STRING_LITERAL
1808 CASING_SPEC ::= Lowercase | Uppercase | Mixedcase
1812 The @code{FILE_NAME_PATTERN} string shows how the file name is constructed.
1813 It contains a single asterisk character, and the unit name is substituted
1814 systematically for this asterisk. The optional parameter
1815 @code{Casing} indicates
1816 whether the unit name is to be all upper-case letters, all lower-case letters,
1817 or mixed-case. If no
1818 @code{Casing} parameter is used, then the default is all
1819 ^lower-case^upper-case^.
1821 The optional @code{Dot_Replacement} string is used to replace any periods
1822 that occur in subunit or child unit names. If no @code{Dot_Replacement}
1823 argument is used then separating dots appear unchanged in the resulting
1825 Although the above syntax indicates that the
1826 @code{Casing} argument must appear
1827 before the @code{Dot_Replacement} argument, but it
1828 is also permissible to write these arguments in the opposite order.
1830 As indicated, it is possible to specify different naming schemes for
1831 bodies, specs, and subunits. Quite often the rule for subunits is the
1832 same as the rule for bodies, in which case, there is no need to give
1833 a separate @code{Subunit_File_Name} rule, and in this case the
1834 @code{Body_File_name} rule is used for subunits as well.
1836 The separate rule for subunits can also be used to implement the rather
1837 unusual case of a compilation environment (e.g.@: a single directory) which
1838 contains a subunit and a child unit with the same unit name. Although
1839 both units cannot appear in the same partition, the Ada Reference Manual
1840 allows (but does not require) the possibility of the two units coexisting
1841 in the same environment.
1843 The file name translation works in the following steps:
1848 If there is a specific @code{Source_File_Name} pragma for the given unit,
1849 then this is always used, and any general pattern rules are ignored.
1852 If there is a pattern type @code{Source_File_Name} pragma that applies to
1853 the unit, then the resulting file name will be used if the file exists. If
1854 more than one pattern matches, the latest one will be tried first, and the
1855 first attempt resulting in a reference to a file that exists will be used.
1858 If no pattern type @code{Source_File_Name} pragma that applies to the unit
1859 for which the corresponding file exists, then the standard GNAT default
1860 naming rules are used.
1865 As an example of the use of this mechanism, consider a commonly used scheme
1866 in which file names are all lower case, with separating periods copied
1867 unchanged to the resulting file name, and specs end with @file{.1.ada}, and
1868 bodies end with @file{.2.ada}. GNAT will follow this scheme if the following
1871 @smallexample @c ada
1872 pragma Source_File_Name
1873 (Spec_File_Name => "*.1.ada");
1874 pragma Source_File_Name
1875 (Body_File_Name => "*.2.ada");
1879 The default GNAT scheme is actually implemented by providing the following
1880 default pragmas internally:
1882 @smallexample @c ada
1883 pragma Source_File_Name
1884 (Spec_File_Name => "*.ads", Dot_Replacement => "-");
1885 pragma Source_File_Name
1886 (Body_File_Name => "*.adb", Dot_Replacement => "-");
1890 Our final example implements a scheme typically used with one of the
1891 Ada 83 compilers, where the separator character for subunits was ``__''
1892 (two underscores), specs were identified by adding @file{_.ADA}, bodies
1893 by adding @file{.ADA}, and subunits by
1894 adding @file{.SEP}. All file names were
1895 upper case. Child units were not present of course since this was an
1896 Ada 83 compiler, but it seems reasonable to extend this scheme to use
1897 the same double underscore separator for child units.
1899 @smallexample @c ada
1900 pragma Source_File_Name
1901 (Spec_File_Name => "*_.ADA",
1902 Dot_Replacement => "__",
1903 Casing = Uppercase);
1904 pragma Source_File_Name
1905 (Body_File_Name => "*.ADA",
1906 Dot_Replacement => "__",
1907 Casing = Uppercase);
1908 pragma Source_File_Name
1909 (Subunit_File_Name => "*.SEP",
1910 Dot_Replacement => "__",
1911 Casing = Uppercase);
1914 @node Generating Object Files
1915 @section Generating Object Files
1918 An Ada program consists of a set of source files, and the first step in
1919 compiling the program is to generate the corresponding object files.
1920 These are generated by compiling a subset of these source files.
1921 The files you need to compile are the following:
1925 If a package spec has no body, compile the package spec to produce the
1926 object file for the package.
1929 If a package has both a spec and a body, compile the body to produce the
1930 object file for the package. The source file for the package spec need
1931 not be compiled in this case because there is only one object file, which
1932 contains the code for both the spec and body of the package.
1935 For a subprogram, compile the subprogram body to produce the object file
1936 for the subprogram. The spec, if one is present, is as usual in a
1937 separate file, and need not be compiled.
1941 In the case of subunits, only compile the parent unit. A single object
1942 file is generated for the entire subunit tree, which includes all the
1946 Compile child units independently of their parent units
1947 (though, of course, the spec of all the ancestor unit must be present in order
1948 to compile a child unit).
1952 Compile generic units in the same manner as any other units. The object
1953 files in this case are small dummy files that contain at most the
1954 flag used for elaboration checking. This is because GNAT always handles generic
1955 instantiation by means of macro expansion. However, it is still necessary to
1956 compile generic units, for dependency checking and elaboration purposes.
1960 The preceding rules describe the set of files that must be compiled to
1961 generate the object files for a program. Each object file has the same
1962 name as the corresponding source file, except that the extension is
1965 You may wish to compile other files for the purpose of checking their
1966 syntactic and semantic correctness. For example, in the case where a
1967 package has a separate spec and body, you would not normally compile the
1968 spec. However, it is convenient in practice to compile the spec to make
1969 sure it is error-free before compiling clients of this spec, because such
1970 compilations will fail if there is an error in the spec.
1972 GNAT provides an option for compiling such files purely for the
1973 purposes of checking correctness; such compilations are not required as
1974 part of the process of building a program. To compile a file in this
1975 checking mode, use the @option{-gnatc} switch.
1977 @node Source Dependencies
1978 @section Source Dependencies
1981 A given object file clearly depends on the source file which is compiled
1982 to produce it. Here we are using @dfn{depends} in the sense of a typical
1983 @code{make} utility; in other words, an object file depends on a source
1984 file if changes to the source file require the object file to be
1986 In addition to this basic dependency, a given object may depend on
1987 additional source files as follows:
1991 If a file being compiled @code{with}'s a unit @var{X}, the object file
1992 depends on the file containing the spec of unit @var{X}. This includes
1993 files that are @code{with}'ed implicitly either because they are parents
1994 of @code{with}'ed child units or they are run-time units required by the
1995 language constructs used in a particular unit.
1998 If a file being compiled instantiates a library level generic unit, the
1999 object file depends on both the spec and body files for this generic
2003 If a file being compiled instantiates a generic unit defined within a
2004 package, the object file depends on the body file for the package as
2005 well as the spec file.
2009 @cindex @option{-gnatn} switch
2010 If a file being compiled contains a call to a subprogram for which
2011 pragma @code{Inline} applies and inlining is activated with the
2012 @option{-gnatn} switch, the object file depends on the file containing the
2013 body of this subprogram as well as on the file containing the spec. Note
2014 that for inlining to actually occur as a result of the use of this switch,
2015 it is necessary to compile in optimizing mode.
2017 @cindex @option{-gnatN} switch
2018 The use of @option{-gnatN} activates inlining optimization
2019 that is performed by the front end of the compiler. This inlining does
2020 not require that the code generation be optimized. Like @option{-gnatn},
2021 the use of this switch generates additional dependencies.
2023 When using a gcc-based back end (in practice this means using any version
2024 of GNAT other than the JGNAT, .NET or GNAAMP versions), then the use of
2025 @option{-gnatN} is deprecated, and the use of @option{-gnatn} is preferred.
2026 Historically front end inlining was more extensive than the gcc back end
2027 inlining, but that is no longer the case.
2030 If an object file @file{O} depends on the proper body of a subunit through
2031 inlining or instantiation, it depends on the parent unit of the subunit.
2032 This means that any modification of the parent unit or one of its subunits
2033 affects the compilation of @file{O}.
2036 The object file for a parent unit depends on all its subunit body files.
2039 The previous two rules meant that for purposes of computing dependencies and
2040 recompilation, a body and all its subunits are treated as an indivisible whole.
2043 These rules are applied transitively: if unit @code{A} @code{with}'s
2044 unit @code{B}, whose elaboration calls an inlined procedure in package
2045 @code{C}, the object file for unit @code{A} will depend on the body of
2046 @code{C}, in file @file{c.adb}.
2048 The set of dependent files described by these rules includes all the
2049 files on which the unit is semantically dependent, as dictated by the
2050 Ada language standard. However, it is a superset of what the
2051 standard describes, because it includes generic, inline, and subunit
2054 An object file must be recreated by recompiling the corresponding source
2055 file if any of the source files on which it depends are modified. For
2056 example, if the @code{make} utility is used to control compilation,
2057 the rule for an Ada object file must mention all the source files on
2058 which the object file depends, according to the above definition.
2059 The determination of the necessary
2060 recompilations is done automatically when one uses @command{gnatmake}.
2063 @node The Ada Library Information Files
2064 @section The Ada Library Information Files
2065 @cindex Ada Library Information files
2066 @cindex @file{ALI} files
2069 Each compilation actually generates two output files. The first of these
2070 is the normal object file that has a @file{.o} extension. The second is a
2071 text file containing full dependency information. It has the same
2072 name as the source file, but an @file{.ali} extension.
2073 This file is known as the Ada Library Information (@file{ALI}) file.
2074 The following information is contained in the @file{ALI} file.
2078 Version information (indicates which version of GNAT was used to compile
2079 the unit(s) in question)
2082 Main program information (including priority and time slice settings,
2083 as well as the wide character encoding used during compilation).
2086 List of arguments used in the @command{gcc} command for the compilation
2089 Attributes of the unit, including configuration pragmas used, an indication
2090 of whether the compilation was successful, exception model used etc.
2093 A list of relevant restrictions applying to the unit (used for consistency)
2097 Categorization information (e.g.@: use of pragma @code{Pure}).
2100 Information on all @code{with}'ed units, including presence of
2101 @code{Elaborate} or @code{Elaborate_All} pragmas.
2104 Information from any @code{Linker_Options} pragmas used in the unit
2107 Information on the use of @code{Body_Version} or @code{Version}
2108 attributes in the unit.
2111 Dependency information. This is a list of files, together with
2112 time stamp and checksum information. These are files on which
2113 the unit depends in the sense that recompilation is required
2114 if any of these units are modified.
2117 Cross-reference data. Contains information on all entities referenced
2118 in the unit. Used by tools like @code{gnatxref} and @code{gnatfind} to
2119 provide cross-reference information.
2124 For a full detailed description of the format of the @file{ALI} file,
2125 see the source of the body of unit @code{Lib.Writ}, contained in file
2126 @file{lib-writ.adb} in the GNAT compiler sources.
2128 @node Binding an Ada Program
2129 @section Binding an Ada Program
2132 When using languages such as C and C++, once the source files have been
2133 compiled the only remaining step in building an executable program
2134 is linking the object modules together. This means that it is possible to
2135 link an inconsistent version of a program, in which two units have
2136 included different versions of the same header.
2138 The rules of Ada do not permit such an inconsistent program to be built.
2139 For example, if two clients have different versions of the same package,
2140 it is illegal to build a program containing these two clients.
2141 These rules are enforced by the GNAT binder, which also determines an
2142 elaboration order consistent with the Ada rules.
2144 The GNAT binder is run after all the object files for a program have
2145 been created. It is given the name of the main program unit, and from
2146 this it determines the set of units required by the program, by reading the
2147 corresponding ALI files. It generates error messages if the program is
2148 inconsistent or if no valid order of elaboration exists.
2150 If no errors are detected, the binder produces a main program, in Ada by
2151 default, that contains calls to the elaboration procedures of those
2152 compilation unit that require them, followed by
2153 a call to the main program. This Ada program is compiled to generate the
2154 object file for the main program. The name of
2155 the Ada file is @file{b~@var{xxx}.adb} (with the corresponding spec
2156 @file{b~@var{xxx}.ads}) where @var{xxx} is the name of the
2159 Finally, the linker is used to build the resulting executable program,
2160 using the object from the main program from the bind step as well as the
2161 object files for the Ada units of the program.
2163 @node Mixed Language Programming
2164 @section Mixed Language Programming
2165 @cindex Mixed Language Programming
2168 This section describes how to develop a mixed-language program,
2169 specifically one that comprises units in both Ada and C.
2172 * Interfacing to C::
2173 * Calling Conventions::
2176 @node Interfacing to C
2177 @subsection Interfacing to C
2179 Interfacing Ada with a foreign language such as C involves using
2180 compiler directives to import and/or export entity definitions in each
2181 language---using @code{extern} statements in C, for instance, and the
2182 @code{Import}, @code{Export}, and @code{Convention} pragmas in Ada.
2183 A full treatment of these topics is provided in Appendix B, section 1
2184 of the Ada Reference Manual.
2186 There are two ways to build a program using GNAT that contains some Ada
2187 sources and some foreign language sources, depending on whether or not
2188 the main subprogram is written in Ada. Here is a source example with
2189 the main subprogram in Ada:
2195 void print_num (int num)
2197 printf ("num is %d.\n", num);
2203 /* num_from_Ada is declared in my_main.adb */
2204 extern int num_from_Ada;
2208 return num_from_Ada;
2212 @smallexample @c ada
2214 procedure My_Main is
2216 -- Declare then export an Integer entity called num_from_Ada
2217 My_Num : Integer := 10;
2218 pragma Export (C, My_Num, "num_from_Ada");
2220 -- Declare an Ada function spec for Get_Num, then use
2221 -- C function get_num for the implementation.
2222 function Get_Num return Integer;
2223 pragma Import (C, Get_Num, "get_num");
2225 -- Declare an Ada procedure spec for Print_Num, then use
2226 -- C function print_num for the implementation.
2227 procedure Print_Num (Num : Integer);
2228 pragma Import (C, Print_Num, "print_num");
2231 Print_Num (Get_Num);
2237 To build this example, first compile the foreign language files to
2238 generate object files:
2240 ^gcc -c file1.c^gcc -c FILE1.C^
2241 ^gcc -c file2.c^gcc -c FILE2.C^
2245 Then, compile the Ada units to produce a set of object files and ALI
2248 gnatmake ^-c^/ACTIONS=COMPILE^ my_main.adb
2252 Run the Ada binder on the Ada main program:
2254 gnatbind my_main.ali
2258 Link the Ada main program, the Ada objects and the other language
2261 gnatlink my_main.ali file1.o file2.o
2265 The last three steps can be grouped in a single command:
2267 gnatmake my_main.adb -largs file1.o file2.o
2270 @cindex Binder output file
2272 If the main program is in a language other than Ada, then you may have
2273 more than one entry point into the Ada subsystem. You must use a special
2274 binder option to generate callable routines that initialize and
2275 finalize the Ada units (@pxref{Binding with Non-Ada Main Programs}).
2276 Calls to the initialization and finalization routines must be inserted
2277 in the main program, or some other appropriate point in the code. The
2278 call to initialize the Ada units must occur before the first Ada
2279 subprogram is called, and the call to finalize the Ada units must occur
2280 after the last Ada subprogram returns. The binder will place the
2281 initialization and finalization subprograms into the
2282 @file{b~@var{xxx}.adb} file where they can be accessed by your C
2283 sources. To illustrate, we have the following example:
2287 extern void adainit (void);
2288 extern void adafinal (void);
2289 extern int add (int, int);
2290 extern int sub (int, int);
2292 int main (int argc, char *argv[])
2298 /* Should print "21 + 7 = 28" */
2299 printf ("%d + %d = %d\n", a, b, add (a, b));
2300 /* Should print "21 - 7 = 14" */
2301 printf ("%d - %d = %d\n", a, b, sub (a, b));
2307 @smallexample @c ada
2310 function Add (A, B : Integer) return Integer;
2311 pragma Export (C, Add, "add");
2315 package body Unit1 is
2316 function Add (A, B : Integer) return Integer is
2324 function Sub (A, B : Integer) return Integer;
2325 pragma Export (C, Sub, "sub");
2329 package body Unit2 is
2330 function Sub (A, B : Integer) return Integer is
2339 The build procedure for this application is similar to the last
2340 example's. First, compile the foreign language files to generate object
2343 ^gcc -c main.c^gcc -c main.c^
2347 Next, compile the Ada units to produce a set of object files and ALI
2350 gnatmake ^-c^/ACTIONS=COMPILE^ unit1.adb
2351 gnatmake ^-c^/ACTIONS=COMPILE^ unit2.adb
2355 Run the Ada binder on every generated ALI file. Make sure to use the
2356 @option{-n} option to specify a foreign main program:
2358 gnatbind ^-n^/NOMAIN^ unit1.ali unit2.ali
2362 Link the Ada main program, the Ada objects and the foreign language
2363 objects. You need only list the last ALI file here:
2365 gnatlink unit2.ali main.o -o exec_file
2368 This procedure yields a binary executable called @file{exec_file}.
2372 Depending on the circumstances (for example when your non-Ada main object
2373 does not provide symbol @code{main}), you may also need to instruct the
2374 GNAT linker not to include the standard startup objects by passing the
2375 @option{^-nostartfiles^/NOSTART_FILES^} switch to @command{gnatlink}.
2377 @node Calling Conventions
2378 @subsection Calling Conventions
2379 @cindex Foreign Languages
2380 @cindex Calling Conventions
2381 GNAT follows standard calling sequence conventions and will thus interface
2382 to any other language that also follows these conventions. The following
2383 Convention identifiers are recognized by GNAT:
2386 @cindex Interfacing to Ada
2387 @cindex Other Ada compilers
2388 @cindex Convention Ada
2390 This indicates that the standard Ada calling sequence will be
2391 used and all Ada data items may be passed without any limitations in the
2392 case where GNAT is used to generate both the caller and callee. It is also
2393 possible to mix GNAT generated code and code generated by another Ada
2394 compiler. In this case, the data types should be restricted to simple
2395 cases, including primitive types. Whether complex data types can be passed
2396 depends on the situation. Probably it is safe to pass simple arrays, such
2397 as arrays of integers or floats. Records may or may not work, depending
2398 on whether both compilers lay them out identically. Complex structures
2399 involving variant records, access parameters, tasks, or protected types,
2400 are unlikely to be able to be passed.
2402 Note that in the case of GNAT running
2403 on a platform that supports HP Ada 83, a higher degree of compatibility
2404 can be guaranteed, and in particular records are laid out in an identical
2405 manner in the two compilers. Note also that if output from two different
2406 compilers is mixed, the program is responsible for dealing with elaboration
2407 issues. Probably the safest approach is to write the main program in the
2408 version of Ada other than GNAT, so that it takes care of its own elaboration
2409 requirements, and then call the GNAT-generated adainit procedure to ensure
2410 elaboration of the GNAT components. Consult the documentation of the other
2411 Ada compiler for further details on elaboration.
2413 However, it is not possible to mix the tasking run time of GNAT and
2414 HP Ada 83, All the tasking operations must either be entirely within
2415 GNAT compiled sections of the program, or entirely within HP Ada 83
2416 compiled sections of the program.
2418 @cindex Interfacing to Assembly
2419 @cindex Convention Assembler
2421 Specifies assembler as the convention. In practice this has the
2422 same effect as convention Ada (but is not equivalent in the sense of being
2423 considered the same convention).
2425 @cindex Convention Asm
2428 Equivalent to Assembler.
2430 @cindex Interfacing to COBOL
2431 @cindex Convention COBOL
2434 Data will be passed according to the conventions described
2435 in section B.4 of the Ada Reference Manual.
2438 @cindex Interfacing to C
2439 @cindex Convention C
2441 Data will be passed according to the conventions described
2442 in section B.3 of the Ada Reference Manual.
2444 A note on interfacing to a C ``varargs'' function:
2445 @findex C varargs function
2446 @cindex Interfacing to C varargs function
2447 @cindex varargs function interfaces
2451 In C, @code{varargs} allows a function to take a variable number of
2452 arguments. There is no direct equivalent in this to Ada. One
2453 approach that can be used is to create a C wrapper for each
2454 different profile and then interface to this C wrapper. For
2455 example, to print an @code{int} value using @code{printf},
2456 create a C function @code{printfi} that takes two arguments, a
2457 pointer to a string and an int, and calls @code{printf}.
2458 Then in the Ada program, use pragma @code{Import} to
2459 interface to @code{printfi}.
2462 It may work on some platforms to directly interface to
2463 a @code{varargs} function by providing a specific Ada profile
2464 for a particular call. However, this does not work on
2465 all platforms, since there is no guarantee that the
2466 calling sequence for a two argument normal C function
2467 is the same as for calling a @code{varargs} C function with
2468 the same two arguments.
2471 @cindex Convention Default
2476 @cindex Convention External
2483 @cindex Interfacing to C++
2484 @cindex Convention C++
2485 @item C_Plus_Plus (or CPP)
2486 This stands for C++. For most purposes this is identical to C.
2487 See the separate description of the specialized GNAT pragmas relating to
2488 C++ interfacing for further details.
2492 @cindex Interfacing to Fortran
2493 @cindex Convention Fortran
2495 Data will be passed according to the conventions described
2496 in section B.5 of the Ada Reference Manual.
2499 This applies to an intrinsic operation, as defined in the Ada
2500 Reference Manual. If a pragma Import (Intrinsic) applies to a subprogram,
2501 this means that the body of the subprogram is provided by the compiler itself,
2502 usually by means of an efficient code sequence, and that the user does not
2503 supply an explicit body for it. In an application program, the pragma may
2504 be applied to the following sets of names:
2508 Rotate_Left, Rotate_Right, Shift_Left, Shift_Right,
2509 Shift_Right_Arithmetic. The corresponding subprogram declaration must have
2510 two formal parameters. The
2511 first one must be a signed integer type or a modular type with a binary
2512 modulus, and the second parameter must be of type Natural.
2513 The return type must be the same as the type of the first argument. The size
2514 of this type can only be 8, 16, 32, or 64.
2517 Binary arithmetic operators: ``+'', ``-'', ``*'', ``/''
2518 The corresponding operator declaration must have parameters and result type
2519 that have the same root numeric type (for example, all three are long_float
2520 types). This simplifies the definition of operations that use type checking
2521 to perform dimensional checks:
2523 @smallexample @c ada
2524 type Distance is new Long_Float;
2525 type Time is new Long_Float;
2526 type Velocity is new Long_Float;
2527 function "/" (D : Distance; T : Time)
2529 pragma Import (Intrinsic, "/");
2533 This common idiom is often programmed with a generic definition and an
2534 explicit body. The pragma makes it simpler to introduce such declarations.
2535 It incurs no overhead in compilation time or code size, because it is
2536 implemented as a single machine instruction.
2539 General subprogram entities, to bind an Ada subprogram declaration to
2540 a compiler builtin by name with back-ends where such interfaces are
2541 available. A typical example is the set of ``__builtin'' functions
2542 exposed by the GCC back-end, as in the following example:
2544 @smallexample @c ada
2545 function builtin_sqrt (F : Float) return Float;
2546 pragma Import (Intrinsic, builtin_sqrt, "__builtin_sqrtf");
2549 Most of the GCC builtins are accessible this way, and as for other
2550 import conventions (e.g. C), it is the user's responsibility to ensure
2551 that the Ada subprogram profile matches the underlying builtin
2559 @cindex Convention Stdcall
2561 This is relevant only to Windows XP/2000/NT implementations of GNAT,
2562 and specifies that the @code{Stdcall} calling sequence will be used,
2563 as defined by the NT API. Nevertheless, to ease building
2564 cross-platform bindings this convention will be handled as a @code{C} calling
2565 convention on non-Windows platforms.
2568 @cindex Convention DLL
2570 This is equivalent to @code{Stdcall}.
2573 @cindex Convention Win32
2575 This is equivalent to @code{Stdcall}.
2579 @cindex Convention Stubbed
2581 This is a special convention that indicates that the compiler
2582 should provide a stub body that raises @code{Program_Error}.
2586 GNAT additionally provides a useful pragma @code{Convention_Identifier}
2587 that can be used to parameterize conventions and allow additional synonyms
2588 to be specified. For example if you have legacy code in which the convention
2589 identifier Fortran77 was used for Fortran, you can use the configuration
2592 @smallexample @c ada
2593 pragma Convention_Identifier (Fortran77, Fortran);
2597 And from now on the identifier Fortran77 may be used as a convention
2598 identifier (for example in an @code{Import} pragma) with the same
2602 @node Building Mixed Ada & C++ Programs
2603 @section Building Mixed Ada and C++ Programs
2606 A programmer inexperienced with mixed-language development may find that
2607 building an application containing both Ada and C++ code can be a
2608 challenge. This section gives a few
2609 hints that should make this task easier. The first section addresses
2610 the differences between interfacing with C and interfacing with C++.
2612 looks into the delicate problem of linking the complete application from
2613 its Ada and C++ parts. The last section gives some hints on how the GNAT
2614 run-time library can be adapted in order to allow inter-language dispatching
2615 with a new C++ compiler.
2618 * Interfacing to C++::
2619 * Linking a Mixed C++ & Ada Program::
2620 * A Simple Example::
2621 * Interfacing with C++ constructors::
2622 * Interfacing with C++ at the Class Level::
2625 @node Interfacing to C++
2626 @subsection Interfacing to C++
2629 GNAT supports interfacing with the G++ compiler (or any C++ compiler
2630 generating code that is compatible with the G++ Application Binary
2631 Interface ---see http://www.codesourcery.com/archives/cxx-abi).
2634 Interfacing can be done at 3 levels: simple data, subprograms, and
2635 classes. In the first two cases, GNAT offers a specific @code{Convention
2636 C_Plus_Plus} (or @code{CPP}) that behaves exactly like @code{Convention C}.
2637 Usually, C++ mangles the names of subprograms. To generate proper mangled
2638 names automatically, see @ref{Generating Ada Bindings for C and C++ headers}).
2639 This problem can also be addressed manually in two ways:
2643 by modifying the C++ code in order to force a C convention using
2644 the @code{extern "C"} syntax.
2647 by figuring out the mangled name (using e.g. @command{nm}) and using it as the
2648 Link_Name argument of the pragma import.
2652 Interfacing at the class level can be achieved by using the GNAT specific
2653 pragmas such as @code{CPP_Constructor}. @xref{Interfacing to C++,,,
2654 gnat_rm, GNAT Reference Manual}, for additional information.
2656 @node Linking a Mixed C++ & Ada Program
2657 @subsection Linking a Mixed C++ & Ada Program
2660 Usually the linker of the C++ development system must be used to link
2661 mixed applications because most C++ systems will resolve elaboration
2662 issues (such as calling constructors on global class instances)
2663 transparently during the link phase. GNAT has been adapted to ease the
2664 use of a foreign linker for the last phase. Three cases can be
2669 Using GNAT and G++ (GNU C++ compiler) from the same GCC installation:
2670 The C++ linker can simply be called by using the C++ specific driver
2673 Note that if the C++ code uses inline functions, you will need to
2674 compile your C++ code with the @code{-fkeep-inline-functions} switch in
2675 order to provide an existing function implementation that the Ada code can
2679 $ g++ -c -fkeep-inline-functions file1.C
2680 $ g++ -c -fkeep-inline-functions file2.C
2681 $ gnatmake ada_unit -largs file1.o file2.o --LINK=g++
2685 Using GNAT and G++ from two different GCC installations: If both
2686 compilers are on the @env{PATH}, the previous method may be used. It is
2687 important to note that environment variables such as
2688 @env{C_INCLUDE_PATH}, @env{GCC_EXEC_PREFIX}, @env{BINUTILS_ROOT}, and
2689 @env{GCC_ROOT} will affect both compilers
2690 at the same time and may make one of the two compilers operate
2691 improperly if set during invocation of the wrong compiler. It is also
2692 very important that the linker uses the proper @file{libgcc.a} GCC
2693 library -- that is, the one from the C++ compiler installation. The
2694 implicit link command as suggested in the @command{gnatmake} command
2695 from the former example can be replaced by an explicit link command with
2696 the full-verbosity option in order to verify which library is used:
2699 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=c++
2701 If there is a problem due to interfering environment variables, it can
2702 be worked around by using an intermediate script. The following example
2703 shows the proper script to use when GNAT has not been installed at its
2704 default location and g++ has been installed at its default location:
2712 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=./my_script
2716 Using a non-GNU C++ compiler: The commands previously described can be
2717 used to insure that the C++ linker is used. Nonetheless, you need to add
2718 a few more parameters to the link command line, depending on the exception
2721 If the @code{setjmp/longjmp} exception mechanism is used, only the paths
2722 to the libgcc libraries are required:
2727 CC $* `gcc -print-file-name=libgcc.a` `gcc -print-file-name=libgcc_eh.a`
2728 $ gnatlink ada_unit file1.o file2.o --LINK=./my_script
2731 Where CC is the name of the non-GNU C++ compiler.
2733 If the @code{zero cost} exception mechanism is used, and the platform
2734 supports automatic registration of exception tables (e.g.@: Solaris),
2735 paths to more objects are required:
2740 CC `gcc -print-file-name=crtbegin.o` $* \
2741 `gcc -print-file-name=libgcc.a` `gcc -print-file-name=libgcc_eh.a` \
2742 `gcc -print-file-name=crtend.o`
2743 $ gnatlink ada_unit file1.o file2.o --LINK=./my_script
2746 If the @code{zero cost} exception mechanism is used, and the platform
2747 doesn't support automatic registration of exception tables (e.g.@: HP-UX
2748 or AIX), the simple approach described above will not work and
2749 a pre-linking phase using GNAT will be necessary.
2753 Another alternative is to use the @command{gprbuild} multi-language builder
2754 which has a large knowledge base and knows how to link Ada and C++ code
2755 together automatically in most cases.
2757 @node A Simple Example
2758 @subsection A Simple Example
2760 The following example, provided as part of the GNAT examples, shows how
2761 to achieve procedural interfacing between Ada and C++ in both
2762 directions. The C++ class A has two methods. The first method is exported
2763 to Ada by the means of an extern C wrapper function. The second method
2764 calls an Ada subprogram. On the Ada side, The C++ calls are modelled by
2765 a limited record with a layout comparable to the C++ class. The Ada
2766 subprogram, in turn, calls the C++ method. So, starting from the C++
2767 main program, the process passes back and forth between the two
2771 Here are the compilation commands:
2773 $ gnatmake -c simple_cpp_interface
2776 $ gnatbind -n simple_cpp_interface
2777 $ gnatlink simple_cpp_interface -o cpp_main --LINK=g++
2778 -lstdc++ ex7.o cpp_main.o
2782 Here are the corresponding sources:
2790 void adainit (void);
2791 void adafinal (void);
2792 void method1 (A *t);
2814 class A : public Origin @{
2816 void method1 (void);
2817 void method2 (int v);
2827 extern "C" @{ void ada_method2 (A *t, int v);@}
2829 void A::method1 (void)
2832 printf ("in A::method1, a_value = %d \n",a_value);
2836 void A::method2 (int v)
2838 ada_method2 (this, v);
2839 printf ("in A::method2, a_value = %d \n",a_value);
2846 printf ("in A::A, a_value = %d \n",a_value);
2850 @smallexample @c ada
2852 package body Simple_Cpp_Interface is
2854 procedure Ada_Method2 (This : in out A; V : Integer) is
2860 end Simple_Cpp_Interface;
2863 package Simple_Cpp_Interface is
2866 Vptr : System.Address;
2870 pragma Convention (C, A);
2872 procedure Method1 (This : in out A);
2873 pragma Import (C, Method1);
2875 procedure Ada_Method2 (This : in out A; V : Integer);
2876 pragma Export (C, Ada_Method2);
2878 end Simple_Cpp_Interface;
2881 @node Interfacing with C++ constructors
2882 @subsection Interfacing with C++ constructors
2885 In order to interface with C++ constructors GNAT provides the
2886 @code{pragma CPP_Constructor} (@xref{Interfacing to C++,,,
2887 gnat_rm, GNAT Reference Manual}, for additional information).
2888 In this section we present some common uses of C++ constructors
2889 in mixed-languages programs in GNAT.
2891 Let us assume that we need to interface with the following
2899 @b{virtual} int Get_Value ();
2900 Root(); // Default constructor
2901 Root(int v); // 1st non-default constructor
2902 Root(int v, int w); // 2nd non-default constructor
2906 For this purpose we can write the following package spec (further
2907 information on how to build this spec is available in
2908 @ref{Interfacing with C++ at the Class Level} and
2909 @ref{Generating Ada Bindings for C and C++ headers}).
2911 @smallexample @c ada
2912 with Interfaces.C; use Interfaces.C;
2914 type Root is tagged limited record
2918 pragma Import (CPP, Root);
2920 function Get_Value (Obj : Root) return int;
2921 pragma Import (CPP, Get_Value);
2923 function Constructor return Root;
2924 pragma Cpp_Constructor (Constructor, "_ZN4RootC1Ev");
2926 function Constructor (v : Integer) return Root;
2927 pragma Cpp_Constructor (Constructor, "_ZN4RootC1Ei");
2929 function Constructor (v, w : Integer) return Root;
2930 pragma Cpp_Constructor (Constructor, "_ZN4RootC1Eii");
2934 On the Ada side the constructor is represented by a function (whose
2935 name is arbitrary) that returns the classwide type corresponding to
2936 the imported C++ class. Although the constructor is described as a
2937 function, it is typically a procedure with an extra implicit argument
2938 (the object being initialized) at the implementation level. GNAT
2939 issues the appropriate call, whatever it is, to get the object
2940 properly initialized.
2942 Constructors can only appear in the following contexts:
2946 On the right side of an initialization of an object of type @var{T}.
2948 On the right side of an initialization of a record component of type @var{T}.
2950 In an Ada 2005 limited aggregate.
2952 In an Ada 2005 nested limited aggregate.
2954 In an Ada 2005 limited aggregate that initializes an object built in
2955 place by an extended return statement.
2959 In a declaration of an object whose type is a class imported from C++,
2960 either the default C++ constructor is implicitly called by GNAT, or
2961 else the required C++ constructor must be explicitly called in the
2962 expression that initializes the object. For example:
2964 @smallexample @c ada
2966 Obj2 : Root := Constructor;
2967 Obj3 : Root := Constructor (v => 10);
2968 Obj4 : Root := Constructor (30, 40);
2971 The first two declarations are equivalent: in both cases the default C++
2972 constructor is invoked (in the former case the call to the constructor is
2973 implicit, and in the latter case the call is explicit in the object
2974 declaration). @code{Obj3} is initialized by the C++ non-default constructor
2975 that takes an integer argument, and @code{Obj4} is initialized by the
2976 non-default C++ constructor that takes two integers.
2978 Let us derive the imported C++ class in the Ada side. For example:
2980 @smallexample @c ada
2981 type DT is new Root with record
2982 C_Value : Natural := 2009;
2986 In this case the components DT inherited from the C++ side must be
2987 initialized by a C++ constructor, and the additional Ada components
2988 of type DT are initialized by GNAT. The initialization of such an
2989 object is done either by default, or by means of a function returning
2990 an aggregate of type DT, or by means of an extension aggregate.
2992 @smallexample @c ada
2994 Obj6 : DT := Function_Returning_DT (50);
2995 Obj7 : DT := (Constructor (30,40) with C_Value => 50);
2998 The declaration of @code{Obj5} invokes the default constructors: the
2999 C++ default constructor of the parent type takes care of the initialization
3000 of the components inherited from Root, and GNAT takes care of the default
3001 initialization of the additional Ada components of type DT (that is,
3002 @code{C_Value} is initialized to value 2009). The order of invocation of
3003 the constructors is consistent with the order of elaboration required by
3004 Ada and C++. That is, the constructor of the parent type is always called
3005 before the constructor of the derived type.
3007 Let us now consider a record that has components whose type is imported
3008 from C++. For example:
3010 @smallexample @c ada
3011 type Rec1 is limited record
3012 Data1 : Root := Constructor (10);
3013 Value : Natural := 1000;
3016 type Rec2 (D : Integer := 20) is limited record
3018 Data2 : Root := Constructor (D, 30);
3022 The initialization of an object of type @code{Rec2} will call the
3023 non-default C++ constructors specified for the imported components.
3026 @smallexample @c ada
3030 Using Ada 2005 we can use limited aggregates to initialize an object
3031 invoking C++ constructors that differ from those specified in the type
3032 declarations. For example:
3034 @smallexample @c ada
3035 Obj9 : Rec2 := (Rec => (Data1 => Constructor (15, 16),
3040 The above declaration uses an Ada 2005 limited aggregate to
3041 initialize @code{Obj9}, and the C++ constructor that has two integer
3042 arguments is invoked to initialize the @code{Data1} component instead
3043 of the constructor specified in the declaration of type @code{Rec1}. In
3044 Ada 2005 the box in the aggregate indicates that unspecified components
3045 are initialized using the expression (if any) available in the component
3046 declaration. That is, in this case discriminant @code{D} is initialized
3047 to value @code{20}, @code{Value} is initialized to value 1000, and the
3048 non-default C++ constructor that handles two integers takes care of
3049 initializing component @code{Data2} with values @code{20,30}.
3051 In Ada 2005 we can use the extended return statement to build the Ada
3052 equivalent to C++ non-default constructors. For example:
3054 @smallexample @c ada
3055 function Constructor (V : Integer) return Rec2 is
3057 return Obj : Rec2 := (Rec => (Data1 => Constructor (V, 20),
3060 -- Further actions required for construction of
3061 -- objects of type Rec2
3067 In this example the extended return statement construct is used to
3068 build in place the returned object whose components are initialized
3069 by means of a limited aggregate. Any further action associated with
3070 the constructor can be placed inside the construct.
3072 @node Interfacing with C++ at the Class Level
3073 @subsection Interfacing with C++ at the Class Level
3075 In this section we demonstrate the GNAT features for interfacing with
3076 C++ by means of an example making use of Ada 2005 abstract interface
3077 types. This example consists of a classification of animals; classes
3078 have been used to model our main classification of animals, and
3079 interfaces provide support for the management of secondary
3080 classifications. We first demonstrate a case in which the types and
3081 constructors are defined on the C++ side and imported from the Ada
3082 side, and latter the reverse case.
3084 The root of our derivation will be the @code{Animal} class, with a
3085 single private attribute (the @code{Age} of the animal) and two public
3086 primitives to set and get the value of this attribute.
3091 @b{virtual} void Set_Age (int New_Age);
3092 @b{virtual} int Age ();
3098 Abstract interface types are defined in C++ by means of classes with pure
3099 virtual functions and no data members. In our example we will use two
3100 interfaces that provide support for the common management of @code{Carnivore}
3101 and @code{Domestic} animals:
3104 @b{class} Carnivore @{
3106 @b{virtual} int Number_Of_Teeth () = 0;
3109 @b{class} Domestic @{
3111 @b{virtual void} Set_Owner (char* Name) = 0;
3115 Using these declarations, we can now say that a @code{Dog} is an animal that is
3116 both Carnivore and Domestic, that is:
3119 @b{class} Dog : Animal, Carnivore, Domestic @{
3121 @b{virtual} int Number_Of_Teeth ();
3122 @b{virtual} void Set_Owner (char* Name);
3124 Dog(); // Constructor
3131 In the following examples we will assume that the previous declarations are
3132 located in a file named @code{animals.h}. The following package demonstrates
3133 how to import these C++ declarations from the Ada side:
3135 @smallexample @c ada
3136 with Interfaces.C.Strings; use Interfaces.C.Strings;
3138 type Carnivore is interface;
3139 pragma Convention (C_Plus_Plus, Carnivore);
3140 function Number_Of_Teeth (X : Carnivore)
3141 return Natural is abstract;
3143 type Domestic is interface;
3144 pragma Convention (C_Plus_Plus, Set_Owner);
3146 (X : in out Domestic;
3147 Name : Chars_Ptr) is abstract;
3149 type Animal is tagged record
3152 pragma Import (C_Plus_Plus, Animal);
3154 procedure Set_Age (X : in out Animal; Age : Integer);
3155 pragma Import (C_Plus_Plus, Set_Age);
3157 function Age (X : Animal) return Integer;
3158 pragma Import (C_Plus_Plus, Age);
3160 type Dog is new Animal and Carnivore and Domestic with record
3161 Tooth_Count : Natural;
3162 Owner : String (1 .. 30);
3164 pragma Import (C_Plus_Plus, Dog);
3166 function Number_Of_Teeth (A : Dog) return Integer;
3167 pragma Import (C_Plus_Plus, Number_Of_Teeth);
3169 procedure Set_Owner (A : in out Dog; Name : Chars_Ptr);
3170 pragma Import (C_Plus_Plus, Set_Owner);
3172 function New_Dog return Dog;
3173 pragma CPP_Constructor (New_Dog);
3174 pragma Import (CPP, New_Dog, "_ZN3DogC2Ev");
3178 Thanks to the compatibility between GNAT run-time structures and the C++ ABI,
3179 interfacing with these C++ classes is easy. The only requirement is that all
3180 the primitives and components must be declared exactly in the same order in
3183 Regarding the abstract interfaces, we must indicate to the GNAT compiler by
3184 means of a @code{pragma Convention (C_Plus_Plus)}, the convention used to pass
3185 the arguments to the called primitives will be the same as for C++. For the
3186 imported classes we use @code{pragma Import} with convention @code{C_Plus_Plus}
3187 to indicate that they have been defined on the C++ side; this is required
3188 because the dispatch table associated with these tagged types will be built
3189 in the C++ side and therefore will not contain the predefined Ada primitives
3190 which Ada would otherwise expect.
3192 As the reader can see there is no need to indicate the C++ mangled names
3193 associated with each subprogram because it is assumed that all the calls to
3194 these primitives will be dispatching calls. The only exception is the
3195 constructor, which must be registered with the compiler by means of
3196 @code{pragma CPP_Constructor} and needs to provide its associated C++
3197 mangled name because the Ada compiler generates direct calls to it.
3199 With the above packages we can now declare objects of type Dog on the Ada side
3200 and dispatch calls to the corresponding subprograms on the C++ side. We can
3201 also extend the tagged type Dog with further fields and primitives, and
3202 override some of its C++ primitives on the Ada side. For example, here we have
3203 a type derivation defined on the Ada side that inherits all the dispatching
3204 primitives of the ancestor from the C++ side.
3207 @b{with} Animals; @b{use} Animals;
3208 @b{package} Vaccinated_Animals @b{is}
3209 @b{type} Vaccinated_Dog @b{is new} Dog @b{with null record};
3210 @b{function} Vaccination_Expired (A : Vaccinated_Dog) @b{return} Boolean;
3211 @b{end} Vaccinated_Animals;
3214 It is important to note that, because of the ABI compatibility, the programmer
3215 does not need to add any further information to indicate either the object
3216 layout or the dispatch table entry associated with each dispatching operation.
3218 Now let us define all the types and constructors on the Ada side and export
3219 them to C++, using the same hierarchy of our previous example:
3221 @smallexample @c ada
3222 with Interfaces.C.Strings;
3223 use Interfaces.C.Strings;
3225 type Carnivore is interface;
3226 pragma Convention (C_Plus_Plus, Carnivore);
3227 function Number_Of_Teeth (X : Carnivore)
3228 return Natural is abstract;
3230 type Domestic is interface;
3231 pragma Convention (C_Plus_Plus, Set_Owner);
3233 (X : in out Domestic;
3234 Name : Chars_Ptr) is abstract;
3236 type Animal is tagged record
3239 pragma Convention (C_Plus_Plus, Animal);
3241 procedure Set_Age (X : in out Animal; Age : Integer);
3242 pragma Export (C_Plus_Plus, Set_Age);
3244 function Age (X : Animal) return Integer;
3245 pragma Export (C_Plus_Plus, Age);
3247 type Dog is new Animal and Carnivore and Domestic with record
3248 Tooth_Count : Natural;
3249 Owner : String (1 .. 30);
3251 pragma Convention (C_Plus_Plus, Dog);
3253 function Number_Of_Teeth (A : Dog) return Integer;
3254 pragma Export (C_Plus_Plus, Number_Of_Teeth);
3256 procedure Set_Owner (A : in out Dog; Name : Chars_Ptr);
3257 pragma Export (C_Plus_Plus, Set_Owner);
3259 function New_Dog return Dog'Class;
3260 pragma Export (C_Plus_Plus, New_Dog);
3264 Compared with our previous example the only difference is the use of
3265 @code{pragma Export} to indicate to the GNAT compiler that the primitives will
3266 be available to C++. Thanks to the ABI compatibility, on the C++ side there is
3267 nothing else to be done; as explained above, the only requirement is that all
3268 the primitives and components are declared in exactly the same order.
3270 For completeness, let us see a brief C++ main program that uses the
3271 declarations available in @code{animals.h} (presented in our first example) to
3272 import and use the declarations from the Ada side, properly initializing and
3273 finalizing the Ada run-time system along the way:
3276 @b{#include} "animals.h"
3277 @b{#include} <iostream>
3278 @b{using namespace} std;
3280 void Check_Carnivore (Carnivore *obj) @{@dots{}@}
3281 void Check_Domestic (Domestic *obj) @{@dots{}@}
3282 void Check_Animal (Animal *obj) @{@dots{}@}
3283 void Check_Dog (Dog *obj) @{@dots{}@}
3286 void adainit (void);
3287 void adafinal (void);
3293 Dog *obj = new_dog(); // Ada constructor
3294 Check_Carnivore (obj); // Check secondary DT
3295 Check_Domestic (obj); // Check secondary DT
3296 Check_Animal (obj); // Check primary DT
3297 Check_Dog (obj); // Check primary DT
3302 adainit (); test(); adafinal ();
3307 @node Comparison between GNAT and C/C++ Compilation Models
3308 @section Comparison between GNAT and C/C++ Compilation Models
3311 The GNAT model of compilation is close to the C and C++ models. You can
3312 think of Ada specs as corresponding to header files in C. As in C, you
3313 don't need to compile specs; they are compiled when they are used. The
3314 Ada @code{with} is similar in effect to the @code{#include} of a C
3317 One notable difference is that, in Ada, you may compile specs separately
3318 to check them for semantic and syntactic accuracy. This is not always
3319 possible with C headers because they are fragments of programs that have
3320 less specific syntactic or semantic rules.
3322 The other major difference is the requirement for running the binder,
3323 which performs two important functions. First, it checks for
3324 consistency. In C or C++, the only defense against assembling
3325 inconsistent programs lies outside the compiler, in a makefile, for
3326 example. The binder satisfies the Ada requirement that it be impossible
3327 to construct an inconsistent program when the compiler is used in normal
3330 @cindex Elaboration order control
3331 The other important function of the binder is to deal with elaboration
3332 issues. There are also elaboration issues in C++ that are handled
3333 automatically. This automatic handling has the advantage of being
3334 simpler to use, but the C++ programmer has no control over elaboration.
3335 Where @code{gnatbind} might complain there was no valid order of
3336 elaboration, a C++ compiler would simply construct a program that
3337 malfunctioned at run time.
3340 @node Comparison between GNAT and Conventional Ada Library Models
3341 @section Comparison between GNAT and Conventional Ada Library Models
3344 This section is intended for Ada programmers who have
3345 used an Ada compiler implementing the traditional Ada library
3346 model, as described in the Ada Reference Manual.
3348 @cindex GNAT library
3349 In GNAT, there is no ``library'' in the normal sense. Instead, the set of
3350 source files themselves acts as the library. Compiling Ada programs does
3351 not generate any centralized information, but rather an object file and
3352 a ALI file, which are of interest only to the binder and linker.
3353 In a traditional system, the compiler reads information not only from
3354 the source file being compiled, but also from the centralized library.
3355 This means that the effect of a compilation depends on what has been
3356 previously compiled. In particular:
3360 When a unit is @code{with}'ed, the unit seen by the compiler corresponds
3361 to the version of the unit most recently compiled into the library.
3364 Inlining is effective only if the necessary body has already been
3365 compiled into the library.
3368 Compiling a unit may obsolete other units in the library.
3372 In GNAT, compiling one unit never affects the compilation of any other
3373 units because the compiler reads only source files. Only changes to source
3374 files can affect the results of a compilation. In particular:
3378 When a unit is @code{with}'ed, the unit seen by the compiler corresponds
3379 to the source version of the unit that is currently accessible to the
3384 Inlining requires the appropriate source files for the package or
3385 subprogram bodies to be available to the compiler. Inlining is always
3386 effective, independent of the order in which units are complied.
3389 Compiling a unit never affects any other compilations. The editing of
3390 sources may cause previous compilations to be out of date if they
3391 depended on the source file being modified.
3395 The most important result of these differences is that order of compilation
3396 is never significant in GNAT. There is no situation in which one is
3397 required to do one compilation before another. What shows up as order of
3398 compilation requirements in the traditional Ada library becomes, in
3399 GNAT, simple source dependencies; in other words, there is only a set
3400 of rules saying what source files must be present when a file is
3404 @node Placement of temporary files
3405 @section Placement of temporary files
3406 @cindex Temporary files (user control over placement)
3409 GNAT creates temporary files in the directory designated by the environment
3410 variable @env{TMPDIR}.
3411 (See the HP @emph{C RTL Reference Manual} on the function @code{getenv()}
3412 for detailed information on how environment variables are resolved.
3413 For most users the easiest way to make use of this feature is to simply
3414 define @env{TMPDIR} as a job level logical name).
3415 For example, if you wish to use a Ramdisk (assuming DECRAM is installed)
3416 for compiler temporary files, then you can include something like the
3417 following command in your @file{LOGIN.COM} file:
3420 $ define/job TMPDIR "/disk$scratchram/000000/temp/"
3424 If @env{TMPDIR} is not defined, then GNAT uses the directory designated by
3425 @env{TMP}; if @env{TMP} is not defined, then GNAT uses the directory
3426 designated by @env{TEMP}.
3427 If none of these environment variables are defined then GNAT uses the
3428 directory designated by the logical name @code{SYS$SCRATCH:}
3429 (by default the user's home directory). If all else fails
3430 GNAT uses the current directory for temporary files.
3433 @c *************************
3434 @node Compiling with gcc
3435 @chapter Compiling with @command{gcc}
3438 This chapter discusses how to compile Ada programs using the @command{gcc}
3439 command. It also describes the set of switches
3440 that can be used to control the behavior of the compiler.
3442 * Compiling Programs::
3443 * Switches for gcc::
3444 * Search Paths and the Run-Time Library (RTL)::
3445 * Order of Compilation Issues::
3449 @node Compiling Programs
3450 @section Compiling Programs
3453 The first step in creating an executable program is to compile the units
3454 of the program using the @command{gcc} command. You must compile the
3459 the body file (@file{.adb}) for a library level subprogram or generic
3463 the spec file (@file{.ads}) for a library level package or generic
3464 package that has no body
3467 the body file (@file{.adb}) for a library level package
3468 or generic package that has a body
3473 You need @emph{not} compile the following files
3478 the spec of a library unit which has a body
3485 because they are compiled as part of compiling related units. GNAT
3487 when the corresponding body is compiled, and subunits when the parent is
3490 @cindex cannot generate code
3491 If you attempt to compile any of these files, you will get one of the
3492 following error messages (where @var{fff} is the name of the file you
3496 cannot generate code for file @var{fff} (package spec)
3497 to check package spec, use -gnatc
3499 cannot generate code for file @var{fff} (missing subunits)
3500 to check parent unit, use -gnatc
3502 cannot generate code for file @var{fff} (subprogram spec)
3503 to check subprogram spec, use -gnatc
3505 cannot generate code for file @var{fff} (subunit)
3506 to check subunit, use -gnatc
3510 As indicated by the above error messages, if you want to submit
3511 one of these files to the compiler to check for correct semantics
3512 without generating code, then use the @option{-gnatc} switch.
3514 The basic command for compiling a file containing an Ada unit is
3517 @c $ gcc -c @ovar{switches} @file{file name}
3518 @c Expanding @ovar macro inline (explanation in macro def comments)
3519 $ gcc -c @r{[}@var{switches}@r{]} @file{file name}
3523 where @var{file name} is the name of the Ada file (usually
3525 @file{.ads} for a spec or @file{.adb} for a body).
3528 @option{-c} switch to tell @command{gcc} to compile, but not link, the file.
3530 The result of a successful compilation is an object file, which has the
3531 same name as the source file but an extension of @file{.o} and an Ada
3532 Library Information (ALI) file, which also has the same name as the
3533 source file, but with @file{.ali} as the extension. GNAT creates these
3534 two output files in the current directory, but you may specify a source
3535 file in any directory using an absolute or relative path specification
3536 containing the directory information.
3539 @command{gcc} is actually a driver program that looks at the extensions of
3540 the file arguments and loads the appropriate compiler. For example, the
3541 GNU C compiler is @file{cc1}, and the Ada compiler is @file{gnat1}.
3542 These programs are in directories known to the driver program (in some
3543 configurations via environment variables you set), but need not be in
3544 your path. The @command{gcc} driver also calls the assembler and any other
3545 utilities needed to complete the generation of the required object
3548 It is possible to supply several file names on the same @command{gcc}
3549 command. This causes @command{gcc} to call the appropriate compiler for
3550 each file. For example, the following command lists two separate
3551 files to be compiled:
3554 $ gcc -c x.adb y.adb
3558 calls @code{gnat1} (the Ada compiler) twice to compile @file{x.adb} and
3560 The compiler generates two object files @file{x.o} and @file{y.o}
3561 and the two ALI files @file{x.ali} and @file{y.ali}.
3562 Any switches apply to all the files ^listed,^listed.^
3564 @node Switches for gcc
3565 @section Switches for @command{gcc}
3568 The @command{gcc} command accepts switches that control the
3569 compilation process. These switches are fully described in this section.
3570 First we briefly list all the switches, in alphabetical order, then we
3571 describe the switches in more detail in functionally grouped sections.
3573 More switches exist for GCC than those documented here, especially
3574 for specific targets. However, their use is not recommended as
3575 they may change code generation in ways that are incompatible with
3576 the Ada run-time library, or can cause inconsistencies between
3580 * Output and Error Message Control::
3581 * Warning Message Control::
3582 * Debugging and Assertion Control::
3583 * Validity Checking::
3586 * Using gcc for Syntax Checking::
3587 * Using gcc for Semantic Checking::
3588 * Compiling Different Versions of Ada::
3589 * Character Set Control::
3590 * File Naming Control::
3591 * Subprogram Inlining Control::
3592 * Auxiliary Output Control::
3593 * Debugging Control::
3594 * Exception Handling Control::
3595 * Units to Sources Mapping Files::
3596 * Integrated Preprocessing::
3597 * Code Generation Control::
3606 @cindex @option{-b} (@command{gcc})
3607 @item -b @var{target}
3608 Compile your program to run on @var{target}, which is the name of a
3609 system configuration. You must have a GNAT cross-compiler built if
3610 @var{target} is not the same as your host system.
3613 @cindex @option{-B} (@command{gcc})
3614 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
3615 from @var{dir} instead of the default location. Only use this switch
3616 when multiple versions of the GNAT compiler are available.
3617 @xref{Directory Options,, Options for Directory Search, gcc, Using the
3618 GNU Compiler Collection (GCC)}, for further details. You would normally
3619 use the @option{-b} or @option{-V} switch instead.
3622 @cindex @option{-c} (@command{gcc})
3623 Compile. Always use this switch when compiling Ada programs.
3625 Note: for some other languages when using @command{gcc}, notably in
3626 the case of C and C++, it is possible to use
3627 use @command{gcc} without a @option{-c} switch to
3628 compile and link in one step. In the case of GNAT, you
3629 cannot use this approach, because the binder must be run
3630 and @command{gcc} cannot be used to run the GNAT binder.
3633 @item -fcallgraph-info@r{[}=su,da@r{]}
3634 @cindex @option{-fcallgraph-info} (@command{gcc})
3635 Makes the compiler output callgraph information for the program, on a
3636 per-file basis. The information is generated in the VCG format. It can
3637 be decorated with additional, per-node and/or per-edge information, if a
3638 list of comma-separated markers is additionally specified. When the
3639 @var{su} marker is specified, the callgraph is decorated with stack usage information; it is equivalent to @option{-fstack-usage}. When the @var{da}
3640 marker is specified, the callgraph is decorated with information about
3641 dynamically allocated objects.
3644 @cindex @option{-fdump-scos} (@command{gcc})
3645 Generates SCO (Source Coverage Obligation) information in the ALI file.
3646 This information is used by advanced coverage tools. See unit @file{SCOs}
3647 in the compiler sources for details in files @file{scos.ads} and
3651 @cindex @option{-fdump-xref} (@command{gcc})
3652 Generates cross reference information in GLI files for C and C++ sources.
3653 The GLI files have the same syntax as the ALI files for Ada, and can be used
3654 for source navigation in IDEs and on the command line using e.g. gnatxref
3655 and the @option{--ext=gli} switch.
3657 @item -flto@r{[}=n@r{]}
3658 @cindex @option{-flto} (@command{gcc})
3659 Enables Link Time Optimization. This switch must be used in conjunction
3660 with the traditional @option{-Ox} switches and instructs the compiler to
3661 defer most optimizations until the link stage. The advantage of this
3662 approach is that the compiler can do a whole-program analysis and choose
3663 the best interprocedural optimization strategy based on a complete view
3664 of the program, instead of a fragmentary view with the usual approach.
3665 This can also speed up the compilation of huge programs and reduce the
3666 size of the final executable, compared with a per-unit compilation with
3667 full inlining across modules enabled with the @option{-gnatn2} switch.
3668 The drawback of this approach is that it may require much more memory.
3669 The switch, as well as the accompanying @option{-Ox} switches, must be
3670 specified both for the compilation and the link phases.
3671 If the @var{n} parameter is specified, the optimization and final code
3672 generation at link time are executed using @var{n} parallel jobs by
3673 means of an installed @command{make} program.
3676 @cindex @option{-fno-inline} (@command{gcc})
3677 Suppresses all inlining, even if other optimization or inlining
3678 switches are set. This includes suppression of inlining that
3679 results from the use of the pragma @code{Inline_Always}.
3680 Any occurrences of pragma @code{Inline} or @code{Inline_Always}
3681 are ignored, and @option{-gnatn} and @option{-gnatN} have no
3682 effects if this switch is present. Note that inlining can also
3683 be suppressed on a finer-grained basis with pragma @code{No_Inline}.
3685 @item -fno-inline-functions
3686 @cindex @option{-fno-inline-functions} (@command{gcc})
3687 Suppresses automatic inlining of subprograms, which is enabled
3688 if @option{-O3} is used.
3690 @item -fno-inline-small-functions
3691 @cindex @option{-fno-inline-small-functions} (@command{gcc})
3692 Suppresses automatic inlining of small subprograms, which is enabled
3693 if @option{-O2} is used.
3695 @item -fno-inline-functions-called-once
3696 @cindex @option{-fno-inline-functions-called-once} (@command{gcc})
3697 Suppresses inlining of subprograms local to the unit and called once
3698 from within it, which is enabled if @option{-O1} is used.
3701 @cindex @option{-fno-ivopts} (@command{gcc})
3702 Suppresses high-level loop induction variable optimizations, which are
3703 enabled if @option{-O1} is used. These optimizations are generally
3704 profitable but, for some specific cases of loops with numerous uses
3705 of the iteration variable that follow a common pattern, they may end
3706 up destroying the regularity that could be exploited at a lower level
3707 and thus producing inferior code.
3709 @item -fno-strict-aliasing
3710 @cindex @option{-fno-strict-aliasing} (@command{gcc})
3711 Causes the compiler to avoid assumptions regarding non-aliasing
3712 of objects of different types. See
3713 @ref{Optimization and Strict Aliasing} for details.
3716 @cindex @option{-fstack-check} (@command{gcc})
3717 Activates stack checking.
3718 See @ref{Stack Overflow Checking} for details.
3721 @cindex @option{-fstack-usage} (@command{gcc})
3722 Makes the compiler output stack usage information for the program, on a
3723 per-subprogram basis. See @ref{Static Stack Usage Analysis} for details.
3726 @cindex @option{^-g^/DEBUG^} (@command{gcc})
3727 Generate debugging information. This information is stored in the object
3728 file and copied from there to the final executable file by the linker,
3729 where it can be read by the debugger. You must use the
3730 @option{^-g^/DEBUG^} switch if you plan on using the debugger.
3733 @cindex @option{-gnat83} (@command{gcc})
3734 Enforce Ada 83 restrictions.
3737 @cindex @option{-gnat95} (@command{gcc})
3738 Enforce Ada 95 restrictions.
3741 @cindex @option{-gnat05} (@command{gcc})
3742 Allow full Ada 2005 features.
3745 @cindex @option{-gnat2005} (@command{gcc})
3746 Allow full Ada 2005 features (same as @option{-gnat05})
3749 @cindex @option{-gnat12} (@command{gcc})
3752 @cindex @option{-gnat2012} (@command{gcc})
3753 Allow full Ada 2012 features (same as @option{-gnat12})
3756 @cindex @option{-gnata} (@command{gcc})
3757 Assertions enabled. @code{Pragma Assert} and @code{pragma Debug} to be
3758 activated. Note that these pragmas can also be controlled using the
3759 configuration pragmas @code{Assertion_Policy} and @code{Debug_Policy}.
3760 It also activates pragmas @code{Check}, @code{Precondition}, and
3761 @code{Postcondition}. Note that these pragmas can also be controlled
3762 using the configuration pragma @code{Check_Policy}. In Ada 2012, it
3763 also activates all assertions defined in the RM as aspects: preconditions,
3764 postconditions, type invariants and (sub)type predicates. In all Ada modes,
3765 corresponding pragmas for type invariants and (sub)type predicates are
3769 @cindex @option{-gnatA} (@command{gcc})
3770 Avoid processing @file{gnat.adc}. If a @file{gnat.adc} file is present,
3774 @cindex @option{-gnatb} (@command{gcc})
3775 Generate brief messages to @file{stderr} even if verbose mode set.
3778 @cindex @option{-gnatB} (@command{gcc})
3779 Assume no invalid (bad) values except for 'Valid attribute use
3780 (@pxref{Validity Checking}).
3783 @cindex @option{-gnatc} (@command{gcc})
3784 Check syntax and semantics only (no code generation attempted). When the
3785 compiler is invoked by @command{gnatmake}, if the switch @option{-gnatc} is
3786 only given to the compiler (after @option{-cargs} or in package Compiler of
3787 the project file, @command{gnatmake} will fail because it will not find the
3788 object file after compilation. If @command{gnatmake} is called with
3789 @option{-gnatc} as a builder switch (before @option{-cargs} or in package
3790 Builder of the project file) then @command{gnatmake} will not fail because
3791 it will not look for the object files after compilation, and it will not try
3792 to build and link. This switch may not be given if a previous @code{-gnatR}
3793 switch has been given, since @code{-gnatR} requires that the code generator
3794 be called to complete determination of representation information.
3797 @cindex @option{-gnatC} (@command{gcc})
3798 Generate CodePeer intermediate format (no code generation attempted).
3799 This switch will generate an intermediate representation suitable for
3800 use by CodePeer (@file{.scil} files). This switch is not compatible with
3801 code generation (it will, among other things, disable some switches such
3802 as -gnatn, and enable others such as -gnata).
3805 @cindex @option{-gnatd} (@command{gcc})
3806 Specify debug options for the compiler. The string of characters after
3807 the @option{-gnatd} specify the specific debug options. The possible
3808 characters are 0-9, a-z, A-Z, optionally preceded by a dot. See
3809 compiler source file @file{debug.adb} for details of the implemented
3810 debug options. Certain debug options are relevant to applications
3811 programmers, and these are documented at appropriate points in this
3816 @cindex @option{-gnatD[nn]} (@command{gcc})
3819 @item /XDEBUG /LXDEBUG=nnn
3821 Create expanded source files for source level debugging. This switch
3822 also suppress generation of cross-reference information
3823 (see @option{-gnatx}). Note that this switch is not allowed if a previous
3824 -gnatR switch has been given, since these two switches are not compatible.
3826 @item ^-gnateA^/ALIASING_CHECK^
3827 @cindex @option{-gnateA} (@command{gcc})
3828 Check that the actual parameters of a subprogram call are not aliases of one
3829 another. To qualify as aliasing, the actuals must denote objects of a composite
3830 type, their memory locations must be identical or overlapping, and at least one
3831 of the corresponding formal parameters must be of mode OUT or IN OUT.
3834 type Rec_Typ is record
3835 Data : Integer := 0;
3838 function Self (Val : Rec_Typ) return Rec_Typ is
3843 procedure Detect_Aliasing (Val_1 : in out Rec_Typ; Val_2 : Rec_Typ) is
3846 end Detect_Aliasing;
3850 Detect_Aliasing (Obj, Obj);
3851 Detect_Aliasing (Obj, Self (Obj));
3854 In the example above, the first call to @code{Detect_Aliasing} fails with a
3855 @code{Program_Error} at runtime because the actuals for @code{Val_1} and
3856 @code{Val_2} denote the same object. The second call executes without raising
3857 an exception because @code{Self(Obj)} produces an anonymous object which does
3858 not share the memory location of @code{Obj}.
3860 @item -gnatec=@var{path}
3861 @cindex @option{-gnatec} (@command{gcc})
3862 Specify a configuration pragma file
3864 (the equal sign is optional)
3866 (@pxref{The Configuration Pragmas Files}).
3869 @cindex @option{-gnateC} (@command{gcc})
3870 Generate CodePeer messages in a compiler-like format. This switch is only
3871 effective if @option{-gnatcC} is also specified and requires an installation
3874 @item ^-gnated^/DISABLE_ATOMIC_SYNCHRONIZATION^
3875 @cindex @option{-gnated} (@command{gcc})
3876 Disable atomic synchronization
3878 @item ^-gnateD^/DATA_PREPROCESSING=^symbol@r{[}=@var{value}@r{]}
3879 @cindex @option{-gnateD} (@command{gcc})
3880 Defines a symbol, associated with @var{value}, for preprocessing.
3881 (@pxref{Integrated Preprocessing}).
3884 @cindex @option{-gnateE} (@command{gcc})
3885 Generate extra information in exception messages. In particular, display
3886 extra column information and the value and range associated with index and
3887 range check failures, and extra column information for access checks.
3888 In cases where the compiler is able to determine at compile time that
3889 a check will fail, it gives a warning, and the extra information is not
3890 produced at run time.
3893 @cindex @option{-gnatef} (@command{gcc})
3894 Display full source path name in brief error messages.
3897 @cindex @option{-gnateF} (@command{gcc})
3898 Check for overflow on all floating-point operations, including those
3899 for unconstrained predefined types. See description of pragma
3900 @code{Check_Float_Overflow} in GNAT RM.
3903 @cindex @option{-gnateG} (@command{gcc})
3904 Save result of preprocessing in a text file.
3906 @item -gnatei@var{nnn}
3907 @cindex @option{-gnatei} (@command{gcc})
3908 Set maximum number of instantiations during compilation of a single unit to
3909 @var{nnn}. This may be useful in increasing the default maximum of 8000 for
3910 the rare case when a single unit legitimately exceeds this limit.
3912 @item -gnateI@var{nnn}
3913 @cindex @option{-gnateI} (@command{gcc})
3914 Indicates that the source is a multi-unit source and that the index of the
3915 unit to compile is @var{nnn}. @var{nnn} needs to be a positive number and need
3916 to be a valid index in the multi-unit source.
3919 @cindex @option{-gnatel} (@command{gcc})
3920 This switch can be used with the static elaboration model to issue info
3922 where implicit @code{pragma Elaborate} and @code{pragma Elaborate_All}
3923 are generated. This is useful in diagnosing elaboration circularities
3924 caused by these implicit pragmas when using the static elaboration
3925 model. See See the section in this guide on elaboration checking for
3926 further details. These messages are not generated by default, and are
3927 intended only for temporary use when debugging circularity problems.
3930 @cindex @option{-gnatel} (@command{gcc})
3931 This switch turns off the info messages about implicit elaboration pragmas.
3933 @item -gnatem=@var{path}
3934 @cindex @option{-gnatem} (@command{gcc})
3935 Specify a mapping file
3937 (the equal sign is optional)
3939 (@pxref{Units to Sources Mapping Files}).
3941 @item -gnatep=@var{file}
3942 @cindex @option{-gnatep} (@command{gcc})
3943 Specify a preprocessing data file
3945 (the equal sign is optional)
3947 (@pxref{Integrated Preprocessing}).
3950 @cindex @option{-gnateP} (@command{gcc})
3951 Turn categorization dependency errors into warnings.
3952 Ada requires that units that WITH one another have compatible categories, for
3953 example a Pure unit cannot WITH a Preelaborate unit. If this switch is used,
3954 these errors become warnings (which can be ignored, or suppressed in the usual
3955 manner). This can be useful in some specialized circumstances such as the
3956 temporary use of special test software.
3959 @cindex @option{-gnateS} (@command{gcc})
3960 Synonym of @option{-fdump-scos}, kept for backwards compatibility.
3962 @item -gnatet=@var{path}
3963 @cindex @option{-gnatet=file} (@command{gcc})
3964 Generate target dependent information. The format of the output file is
3965 described in the section about switch @option{-gnateT}.
3967 @item -gnateT=@var{path}
3968 @cindex @option{-gnateT} (@command{gcc})
3969 Read target dependent information, such as endianness or sizes and alignments
3970 of base type. If this switch is passed, the default target dependent
3971 information of the compiler is replaced by the one read from the input file.
3972 This is used by tools other than the compiler, e.g. to do
3973 semantic analysis of programs that will run on some other target than
3974 the machine on which the tool is run.
3976 The following target dependent values should be defined,
3977 where @code{Nat} denotes a natural integer value, @code{Pos} denotes a
3978 positive integer value, and fields marked with a question mark are
3979 boolean fields, where a value of 0 is False, and a value of 1 is True:
3982 Bits_BE : Nat; -- Bits stored big-endian?
3983 Bits_Per_Unit : Pos; -- Bits in a storage unit
3984 Bits_Per_Word : Pos; -- Bits in a word
3985 Bytes_BE : Nat; -- Bytes stored big-endian?
3986 Char_Size : Pos; -- Standard.Character'Size
3987 Double_Float_Alignment : Nat; -- Alignment of double float
3988 Double_Scalar_Alignment : Nat; -- Alignment of double length scalar
3989 Double_Size : Pos; -- Standard.Long_Float'Size
3990 Float_Size : Pos; -- Standard.Float'Size
3991 Float_Words_BE : Nat; -- Float words stored big-endian?
3992 Int_Size : Pos; -- Standard.Integer'Size
3993 Long_Double_Size : Pos; -- Standard.Long_Long_Float'Size
3994 Long_Long_Size : Pos; -- Standard.Long_Long_Integer'Size
3995 Long_Size : Pos; -- Standard.Long_Integer'Size
3996 Maximum_Alignment : Pos; -- Maximum permitted alignment
3997 Max_Unaligned_Field : Pos; -- Maximum size for unaligned bit field
3998 Pointer_Size : Pos; -- System.Address'Size
3999 Short_Enums : Nat; -- Short foreign convention enums?
4000 Short_Size : Pos; -- Standard.Short_Integer'Size
4001 Strict_Alignment : Nat; -- Strict alignment?
4002 System_Allocator_Alignment : Nat; -- Alignment for malloc calls
4003 Wchar_T_Size : Pos; -- Interfaces.C.wchar_t'Size
4004 Words_BE : Nat; -- Words stored big-endian?
4007 The format of the input file is as follows. First come the values of
4008 the variables defined above, with one line per value:
4014 where @code{name} is the name of the parameter, spelled out in full,
4015 and cased as in the above list, and @code{value} is an unsigned decimal
4016 integer. Two or more blanks separates the name from the value.
4018 All the variables must be present, in alphabetical order (i.e. the
4019 same order as the list above).
4021 Then there is a blank line to separate the two parts of the file. Then
4022 come the lines showing the floating-point types to be registered, with
4023 one line per registered mode:
4026 name digs float_rep size alignment
4029 where @code{name} is the string name of the type (which can have
4030 single spaces embedded in the name (e.g. long double), @code{digs} is
4031 the number of digits for the floating-point type, @code{float_rep} is
4032 the float representation (I/V/A for IEEE-754-Binary, Vax_Native,
4033 AAMP), @code{size} is the size in bits, @code{alignment} is the
4034 alignment in bits. The name is followed by at least two blanks, fields
4035 are separated by at least one blank, and a LF character immediately
4036 follows the alignment field.
4038 Here is an example of a target parameterization file:
4046 Double_Float_Alignment 0
4047 Double_Scalar_Alignment 0
4052 Long_Double_Size 128
4055 Maximum_Alignment 16
4056 Max_Unaligned_Field 64
4060 System_Allocator_Alignment 16
4066 long double 18 I 80 128
4071 @cindex @option{-gnateu} (@command{gcc})
4072 Ignore unrecognized validity, warning, and style switches that
4073 appear after this switch is given. This may be useful when
4074 compiling sources developed on a later version of the compiler
4075 with an earlier version. Of course the earlier version must
4076 support this switch.
4078 @item ^-gnateV^/PARAMETER_VALIDITY_CHECK^
4079 @cindex @option{-gnateV} (@command{gcc})
4080 Check that all actual parameters of a subprogram call are valid according to
4081 the rules of validity checking (@pxref{Validity Checking}).
4083 @item ^-gnateY^/IGNORE_SUPPRESS_SYLE_CHECK_PRAGMAS^
4084 @cindex @option{-gnateY} (@command{gcc})
4085 Ignore all STYLE_CHECKS pragmas. Full legality checks
4086 are still carried out, but the pragmas have no effect
4087 on what style checks are active. This allows all style
4088 checking options to be controlled from the command line.
4091 @cindex @option{-gnatE} (@command{gcc})
4092 Full dynamic elaboration checks.
4095 @cindex @option{-gnatf} (@command{gcc})
4096 Full errors. Multiple errors per line, all undefined references, do not
4097 attempt to suppress cascaded errors.
4100 @cindex @option{-gnatF} (@command{gcc})
4101 Externals names are folded to all uppercase.
4103 @item ^-gnatg^/GNAT_INTERNAL^
4104 @cindex @option{^-gnatg^/GNAT_INTERNAL^} (@command{gcc})
4105 Internal GNAT implementation mode. This should not be used for
4106 applications programs, it is intended only for use by the compiler
4107 and its run-time library. For documentation, see the GNAT sources.
4108 Note that @option{^-gnatg^/GNAT_INTERNAL^} implies
4109 @option{^-gnatw.ge^/WARNINGS=GNAT,ERRORS^} and
4110 @option{^-gnatyg^/STYLE_CHECKS=GNAT^}
4111 so that all standard warnings and all standard style options are turned on.
4112 All warnings and style messages are treated as errors.
4116 @cindex @option{-gnatG[nn]} (@command{gcc})
4119 @item /EXPAND_SOURCE, /LEXPAND_SOURCE=nnn
4121 List generated expanded code in source form.
4123 @item ^-gnath^/HELP^
4124 @cindex @option{^-gnath^/HELP^} (@command{gcc})
4125 Output usage information. The output is written to @file{stdout}.
4127 @item ^-gnati^/IDENTIFIER_CHARACTER_SET=^@var{c}
4128 @cindex @option{^-gnati^/IDENTIFIER_CHARACTER_SET^} (@command{gcc})
4129 Identifier character set
4131 (@var{c}=1/2/3/4/8/9/p/f/n/w).
4133 For details of the possible selections for @var{c},
4134 see @ref{Character Set Control}.
4136 @item ^-gnatI^/IGNORE_REP_CLAUSES^
4137 @cindex @option{^-gnatI^IGNORE_REP_CLAUSES^} (@command{gcc})
4138 Ignore representation clauses. When this switch is used,
4139 representation clauses are treated as comments. This is useful
4140 when initially porting code where you want to ignore rep clause
4141 problems, and also for compiling foreign code (particularly
4142 for use with ASIS). The representation clauses that are ignored
4143 are: enumeration_representation_clause, record_representation_clause,
4144 and attribute_definition_clause for the following attributes:
4145 Address, Alignment, Bit_Order, Component_Size, Machine_Radix,
4146 Object_Size, Size, Small, Stream_Size, and Value_Size.
4147 Note that this option should be used only for compiling -- the
4148 code is likely to malfunction at run time.
4150 Note that when @code{-gnatct} is used to generate trees for input
4151 into @code{ASIS} tools, these representation clauses are removed
4152 from the tree and ignored. This means that the tool will not see them.
4155 @cindex @option{-gnatjnn} (@command{gcc})
4156 Reformat error messages to fit on nn character lines
4158 @item -gnatk=@var{n}
4159 @cindex @option{-gnatk} (@command{gcc})
4160 Limit file names to @var{n} (1-999) characters ^(@code{k} = krunch)^^.
4163 @cindex @option{-gnatl} (@command{gcc})
4164 Output full source listing with embedded error messages.
4167 @cindex @option{-gnatL} (@command{gcc})
4168 Used in conjunction with -gnatG or -gnatD to intersperse original
4169 source lines (as comment lines with line numbers) in the expanded
4172 @item -gnatm=@var{n}
4173 @cindex @option{-gnatm} (@command{gcc})
4174 Limit number of detected error or warning messages to @var{n}
4175 where @var{n} is in the range 1..999999. The default setting if
4176 no switch is given is 9999. If the number of warnings reaches this
4177 limit, then a message is output and further warnings are suppressed,
4178 but the compilation is continued. If the number of error messages
4179 reaches this limit, then a message is output and the compilation
4180 is abandoned. The equal sign here is optional. A value of zero
4181 means that no limit applies.
4184 @cindex @option{-gnatn} (@command{gcc})
4185 Activate inlining for subprograms for which pragma @code{Inline} is
4186 specified. This inlining is performed by the GCC back-end. An optional
4187 digit sets the inlining level: 1 for moderate inlining across modules
4188 or 2 for full inlining across modules. If no inlining level is specified,
4189 the compiler will pick it based on the optimization level.
4192 @cindex @option{-gnatN} (@command{gcc})
4193 Activate front end inlining for subprograms for which
4194 pragma @code{Inline} is specified. This inlining is performed
4195 by the front end and will be visible in the
4196 @option{-gnatG} output.
4198 When using a gcc-based back end (in practice this means using any version
4199 of GNAT other than the JGNAT, .NET or GNAAMP versions), then the use of
4200 @option{-gnatN} is deprecated, and the use of @option{-gnatn} is preferred.
4201 Historically front end inlining was more extensive than the gcc back end
4202 inlining, but that is no longer the case.
4205 @cindex @option{-gnato??} (@command{gcc})
4206 Set default mode for handling generation of code to avoid intermediate
4207 arithmetic overflow. Here `@code{??}' is two digits, a
4208 single digit, or nothing. Each digit is one of the digits `@code{1}'
4213 all intermediate overflows checked against base type (@code{STRICT})
4215 minimize intermediate overflows (@code{MINIMIZED})
4217 eliminate intermediate overflows (@code{ELIMINATED})
4220 If only one digit appears then it applies to all
4221 cases; if two digits are given, then the first applies outside
4222 assertions, and the second within assertions.
4224 If no digits follow the @option{-gnato}, then it is equivalent to
4225 @option{^-gnato11^/OVERFLOW_CHECKS=11^},
4226 causing all intermediate overflows to be handled in strict mode.
4228 This switch also causes arithmetic overflow checking to be performed
4229 (as though pragma @code{Unsuppress (Overflow_Mode)} has been specified.
4231 The default if no option @option{-gnato} is given is that overflow handling
4232 is in @code{STRICT} mode (computations done using the base type), and that
4233 overflow checking is suppressed.
4235 Note that division by zero is a separate check that is not
4236 controlled by this switch (division by zero checking is on by default).
4238 See also @ref{Specifying the Desired Mode}.
4241 @cindex @option{-gnatp} (@command{gcc})
4242 Suppress all checks. See @ref{Run-Time Checks} for details. This switch
4243 has no effect if cancelled by a subsequent @option{-gnat-p} switch.
4246 @cindex @option{-gnat-p} (@command{gcc})
4247 Cancel effect of previous @option{-gnatp} switch.
4250 @cindex @option{-gnatP} (@command{gcc})
4251 Enable polling. This is required on some systems (notably Windows NT) to
4252 obtain asynchronous abort and asynchronous transfer of control capability.
4253 @xref{Pragma Polling,,, gnat_rm, GNAT Reference Manual}, for full
4257 @cindex @option{-gnatq} (@command{gcc})
4258 Don't quit. Try semantics, even if parse errors.
4261 @cindex @option{-gnatQ} (@command{gcc})
4262 Don't quit. Generate @file{ALI} and tree files even if illegalities.
4263 Note that code generation is still suppressed in the presence of any
4264 errors, so even with @option{-gnatQ} no object file is generated.
4267 @cindex @option{-gnatr} (@command{gcc})
4268 Treat pragma Restrictions as Restriction_Warnings.
4270 @item ^-gnatR@r{[}0@r{/}1@r{/}2@r{/}3@r{[}s@r{]]}^/REPRESENTATION_INFO^
4271 @cindex @option{-gnatR} (@command{gcc})
4272 Output representation information for declared types and objects.
4273 Note that this switch is not allowed if a previous @code{-gnatD} switch has
4274 been given, since these two switches are not compatible.
4276 @item ^-gnatRm[s]^/REPRESENTATION_INFO^
4277 Output convention and parameter passing mechanisms for all subprograms.
4280 @cindex @option{-gnats} (@command{gcc})
4284 @cindex @option{-gnatS} (@command{gcc})
4285 Print package Standard.
4288 @cindex @option{-gnatt} (@command{gcc})
4289 Generate tree output file.
4291 @item ^-gnatT^/TABLE_MULTIPLIER=^@var{nnn}
4292 @cindex @option{^-gnatT^/TABLE_MULTIPLIER^} (@command{gcc})
4293 All compiler tables start at @var{nnn} times usual starting size.
4296 @cindex @option{-gnatu} (@command{gcc})
4297 List units for this compilation.
4300 @cindex @option{-gnatU} (@command{gcc})
4301 Tag all error messages with the unique string ``error:''
4304 @cindex @option{-gnatv} (@command{gcc})
4305 Verbose mode. Full error output with source lines to @file{stdout}.
4308 @cindex @option{-gnatV} (@command{gcc})
4309 Control level of validity checking (@pxref{Validity Checking}).
4311 @item ^-gnatw@var{xxx}^/WARNINGS=(@var{option}@r{[},@dots{}@r{]})^
4312 @cindex @option{^-gnatw^/WARNINGS^} (@command{gcc})
4314 ^@var{xxx} is a string of option letters that^the list of options^ denotes
4315 the exact warnings that
4316 are enabled or disabled (@pxref{Warning Message Control}).
4318 @item ^-gnatW^/WIDE_CHARACTER_ENCODING=^@var{e}
4319 @cindex @option{^-gnatW^/WIDE_CHARACTER_ENCODING^} (@command{gcc})
4320 Wide character encoding method
4322 (@var{e}=n/h/u/s/e/8).
4325 (@var{e}=@code{BRACKETS, NONE, HEX, UPPER, SHIFT_JIS, EUC, UTF8})
4329 @cindex @option{-gnatx} (@command{gcc})
4330 Suppress generation of cross-reference information.
4333 @cindex @option{-gnatX} (@command{gcc})
4334 Enable GNAT implementation extensions and latest Ada version.
4336 @item ^-gnaty^/STYLE_CHECKS=(option,option@dots{})^
4337 @cindex @option{^-gnaty^/STYLE_CHECKS^} (@command{gcc})
4338 Enable built-in style checks (@pxref{Style Checking}).
4340 @item ^-gnatz^/DISTRIBUTION_STUBS=^@var{m}
4341 @cindex @option{^-gnatz^/DISTRIBUTION_STUBS^} (@command{gcc})
4342 Distribution stub generation and compilation
4344 (@var{m}=r/c for receiver/caller stubs).
4347 (@var{m}=@code{RECEIVER} or @code{CALLER} to specify the type of stubs
4348 to be generated and compiled).
4351 @item ^-I^/SEARCH=^@var{dir}
4352 @cindex @option{^-I^/SEARCH^} (@command{gcc})
4354 Direct GNAT to search the @var{dir} directory for source files needed by
4355 the current compilation
4356 (@pxref{Search Paths and the Run-Time Library (RTL)}).
4358 @item ^-I-^/NOCURRENT_DIRECTORY^
4359 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gcc})
4361 Except for the source file named in the command line, do not look for source
4362 files in the directory containing the source file named in the command line
4363 (@pxref{Search Paths and the Run-Time Library (RTL)}).
4367 @cindex @option{-mbig-switch} (@command{gcc})
4368 @cindex @code{case} statement (effect of @option{-mbig-switch} option)
4369 This standard gcc switch causes the compiler to use larger offsets in its
4370 jump table representation for @code{case} statements.
4371 This may result in less efficient code, but is sometimes necessary
4372 (for example on HP-UX targets)
4373 @cindex HP-UX and @option{-mbig-switch} option
4374 in order to compile large and/or nested @code{case} statements.
4377 @cindex @option{-o} (@command{gcc})
4378 This switch is used in @command{gcc} to redirect the generated object file
4379 and its associated ALI file. Beware of this switch with GNAT, because it may
4380 cause the object file and ALI file to have different names which in turn
4381 may confuse the binder and the linker.
4385 @cindex @option{-nostdinc} (@command{gcc})
4386 Inhibit the search of the default location for the GNAT Run Time
4387 Library (RTL) source files.
4390 @cindex @option{-nostdlib} (@command{gcc})
4391 Inhibit the search of the default location for the GNAT Run Time
4392 Library (RTL) ALI files.
4396 @c Expanding @ovar macro inline (explanation in macro def comments)
4397 @item -O@r{[}@var{n}@r{]}
4398 @cindex @option{-O} (@command{gcc})
4399 @var{n} controls the optimization level.
4403 No optimization, the default setting if no @option{-O} appears
4406 Normal optimization, the default if you specify @option{-O} without
4407 an operand. A good compromise between code quality and compilation
4411 Extensive optimization, may improve execution time, possibly at the cost of
4412 substantially increased compilation time.
4415 Same as @option{-O2}, and also includes inline expansion for small subprograms
4419 Optimize space usage
4423 See also @ref{Optimization Levels}.
4428 @cindex @option{/NOOPTIMIZE} (@code{GNAT COMPILE})
4429 Equivalent to @option{/OPTIMIZE=NONE}.
4430 This is the default behavior in the absence of an @option{/OPTIMIZE}
4433 @item /OPTIMIZE@r{[}=(keyword@r{[},@dots{}@r{]})@r{]}
4434 @cindex @option{/OPTIMIZE} (@code{GNAT COMPILE})
4435 Selects the level of optimization for your program. The supported
4436 keywords are as follows:
4439 Perform most optimizations, including those that
4441 This is the default if the @option{/OPTIMIZE} qualifier is supplied
4442 without keyword options.
4445 Do not do any optimizations. Same as @code{/NOOPTIMIZE}.
4448 Perform some optimizations, but omit ones that are costly.
4451 Same as @code{SOME}.
4454 Full optimization as in @option{/OPTIMIZE=ALL}, and also attempts
4455 automatic inlining of small subprograms within a unit
4458 Try to unroll loops. This keyword may be specified together with
4459 any keyword above other than @code{NONE}. Loop unrolling
4460 usually, but not always, improves the performance of programs.
4463 Optimize space usage
4467 See also @ref{Optimization Levels}.
4471 @item -pass-exit-codes
4472 @cindex @option{-pass-exit-codes} (@command{gcc})
4473 Catch exit codes from the compiler and use the most meaningful as
4477 @item --RTS=@var{rts-path}
4478 @cindex @option{--RTS} (@command{gcc})
4479 Specifies the default location of the runtime library. Same meaning as the
4480 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
4483 @cindex @option{^-S^/ASM^} (@command{gcc})
4484 ^Used in place of @option{-c} to^Used to^
4485 cause the assembler source file to be
4486 generated, using @file{^.s^.S^} as the extension,
4487 instead of the object file.
4488 This may be useful if you need to examine the generated assembly code.
4490 @item ^-fverbose-asm^/VERBOSE_ASM^
4491 @cindex @option{^-fverbose-asm^/VERBOSE_ASM^} (@command{gcc})
4492 ^Used in conjunction with @option{-S}^Used in place of @option{/ASM}^
4493 to cause the generated assembly code file to be annotated with variable
4494 names, making it significantly easier to follow.
4497 @cindex @option{^-v^/VERBOSE^} (@command{gcc})
4498 Show commands generated by the @command{gcc} driver. Normally used only for
4499 debugging purposes or if you need to be sure what version of the
4500 compiler you are executing.
4504 @cindex @option{-V} (@command{gcc})
4505 Execute @var{ver} version of the compiler. This is the @command{gcc}
4506 version, not the GNAT version.
4509 @item ^-w^/NO_BACK_END_WARNINGS^
4510 @cindex @option{-w} (@command{gcc})
4511 Turn off warnings generated by the back end of the compiler. Use of
4512 this switch also causes the default for front end warnings to be set
4513 to suppress (as though @option{-gnatws} had appeared at the start of
4519 @c Combining qualifiers does not work on VMS
4520 You may combine a sequence of GNAT switches into a single switch. For
4521 example, the combined switch
4523 @cindex Combining GNAT switches
4529 is equivalent to specifying the following sequence of switches:
4532 -gnato -gnatf -gnati3
4537 The following restrictions apply to the combination of switches
4542 The switch @option{-gnatc} if combined with other switches must come
4543 first in the string.
4546 The switch @option{-gnats} if combined with other switches must come
4547 first in the string.
4551 ^^@option{/DISTRIBUTION_STUBS=},^
4552 @option{-gnatzc} and @option{-gnatzr} may not be combined with any other
4553 switches, and only one of them may appear in the command line.
4556 The switch @option{-gnat-p} may not be combined with any other switch.
4560 Once a ``y'' appears in the string (that is a use of the @option{-gnaty}
4561 switch), then all further characters in the switch are interpreted
4562 as style modifiers (see description of @option{-gnaty}).
4565 Once a ``d'' appears in the string (that is a use of the @option{-gnatd}
4566 switch), then all further characters in the switch are interpreted
4567 as debug flags (see description of @option{-gnatd}).
4570 Once a ``w'' appears in the string (that is a use of the @option{-gnatw}
4571 switch), then all further characters in the switch are interpreted
4572 as warning mode modifiers (see description of @option{-gnatw}).
4575 Once a ``V'' appears in the string (that is a use of the @option{-gnatV}
4576 switch), then all further characters in the switch are interpreted
4577 as validity checking options (@pxref{Validity Checking}).
4580 Option ``em'', ``ec'', ``ep'', ``l='' and ``R'' must be the last options in
4581 a combined list of options.
4585 @node Output and Error Message Control
4586 @subsection Output and Error Message Control
4590 The standard default format for error messages is called ``brief format''.
4591 Brief format messages are written to @file{stderr} (the standard error
4592 file) and have the following form:
4595 e.adb:3:04: Incorrect spelling of keyword "function"
4596 e.adb:4:20: ";" should be "is"
4600 The first integer after the file name is the line number in the file,
4601 and the second integer is the column number within the line.
4603 @code{GPS} can parse the error messages
4604 and point to the referenced character.
4606 The following switches provide control over the error message
4612 @cindex @option{-gnatv} (@command{gcc})
4615 The v stands for verbose.
4617 The effect of this setting is to write long-format error
4618 messages to @file{stdout} (the standard output file.
4619 The same program compiled with the
4620 @option{-gnatv} switch would generate:
4624 3. funcion X (Q : Integer)
4626 >>> Incorrect spelling of keyword "function"
4629 >>> ";" should be "is"
4634 The vertical bar indicates the location of the error, and the @samp{>>>}
4635 prefix can be used to search for error messages. When this switch is
4636 used the only source lines output are those with errors.
4639 @cindex @option{-gnatl} (@command{gcc})
4641 The @code{l} stands for list.
4643 This switch causes a full listing of
4644 the file to be generated. In the case where a body is
4645 compiled, the corresponding spec is also listed, along
4646 with any subunits. Typical output from compiling a package
4647 body @file{p.adb} might look like:
4649 @smallexample @c ada
4653 1. package body p is
4655 3. procedure a is separate;
4666 2. pragma Elaborate_Body
4690 When you specify the @option{-gnatv} or @option{-gnatl} switches and
4691 standard output is redirected, a brief summary is written to
4692 @file{stderr} (standard error) giving the number of error messages and
4693 warning messages generated.
4695 @item ^-gnatl^/OUTPUT_FILE^=file
4696 @cindex @option{^-gnatl^/OUTPUT_FILE^=fname} (@command{gcc})
4697 This has the same effect as @option{-gnatl} except that the output is
4698 written to a file instead of to standard output. If the given name
4699 @file{fname} does not start with a period, then it is the full name
4700 of the file to be written. If @file{fname} is an extension, it is
4701 appended to the name of the file being compiled. For example, if
4702 file @file{xyz.adb} is compiled with @option{^-gnatl^/OUTPUT_FILE^=.lst},
4703 then the output is written to file ^xyz.adb.lst^xyz.adb_lst^.
4706 @cindex @option{-gnatU} (@command{gcc})
4707 This switch forces all error messages to be preceded by the unique
4708 string ``error:''. This means that error messages take a few more
4709 characters in space, but allows easy searching for and identification
4713 @cindex @option{-gnatb} (@command{gcc})
4715 The @code{b} stands for brief.
4717 This switch causes GNAT to generate the
4718 brief format error messages to @file{stderr} (the standard error
4719 file) as well as the verbose
4720 format message or full listing (which as usual is written to
4721 @file{stdout} (the standard output file).
4723 @item -gnatm=@var{n}
4724 @cindex @option{-gnatm} (@command{gcc})
4726 The @code{m} stands for maximum.
4728 @var{n} is a decimal integer in the
4729 range of 1 to 999999 and limits the number of error or warning
4730 messages to be generated. For example, using
4731 @option{-gnatm2} might yield
4734 e.adb:3:04: Incorrect spelling of keyword "function"
4735 e.adb:5:35: missing ".."
4736 fatal error: maximum number of errors detected
4737 compilation abandoned
4741 The default setting if
4742 no switch is given is 9999. If the number of warnings reaches this
4743 limit, then a message is output and further warnings are suppressed,
4744 but the compilation is continued. If the number of error messages
4745 reaches this limit, then a message is output and the compilation
4746 is abandoned. A value of zero means that no limit applies.
4749 Note that the equal sign is optional, so the switches
4750 @option{-gnatm2} and @option{-gnatm=2} are equivalent.
4753 @cindex @option{-gnatf} (@command{gcc})
4754 @cindex Error messages, suppressing
4756 The @code{f} stands for full.
4758 Normally, the compiler suppresses error messages that are likely to be
4759 redundant. This switch causes all error
4760 messages to be generated. In particular, in the case of
4761 references to undefined variables. If a given variable is referenced
4762 several times, the normal format of messages is
4764 e.adb:7:07: "V" is undefined (more references follow)
4768 where the parenthetical comment warns that there are additional
4769 references to the variable @code{V}. Compiling the same program with the
4770 @option{-gnatf} switch yields
4773 e.adb:7:07: "V" is undefined
4774 e.adb:8:07: "V" is undefined
4775 e.adb:8:12: "V" is undefined
4776 e.adb:8:16: "V" is undefined
4777 e.adb:9:07: "V" is undefined
4778 e.adb:9:12: "V" is undefined
4782 The @option{-gnatf} switch also generates additional information for
4783 some error messages. Some examples are:
4787 Details on possibly non-portable unchecked conversion
4789 List possible interpretations for ambiguous calls
4791 Additional details on incorrect parameters
4795 @cindex @option{-gnatjnn} (@command{gcc})
4796 In normal operation mode (or if @option{-gnatj0} is used), then error messages
4797 with continuation lines are treated as though the continuation lines were
4798 separate messages (and so a warning with two continuation lines counts as
4799 three warnings, and is listed as three separate messages).
4801 If the @option{-gnatjnn} switch is used with a positive value for nn, then
4802 messages are output in a different manner. A message and all its continuation
4803 lines are treated as a unit, and count as only one warning or message in the
4804 statistics totals. Furthermore, the message is reformatted so that no line
4805 is longer than nn characters.
4808 @cindex @option{-gnatq} (@command{gcc})
4810 The @code{q} stands for quit (really ``don't quit'').
4812 In normal operation mode, the compiler first parses the program and
4813 determines if there are any syntax errors. If there are, appropriate
4814 error messages are generated and compilation is immediately terminated.
4816 GNAT to continue with semantic analysis even if syntax errors have been
4817 found. This may enable the detection of more errors in a single run. On
4818 the other hand, the semantic analyzer is more likely to encounter some
4819 internal fatal error when given a syntactically invalid tree.
4822 @cindex @option{-gnatQ} (@command{gcc})
4823 In normal operation mode, the @file{ALI} file is not generated if any
4824 illegalities are detected in the program. The use of @option{-gnatQ} forces
4825 generation of the @file{ALI} file. This file is marked as being in
4826 error, so it cannot be used for binding purposes, but it does contain
4827 reasonably complete cross-reference information, and thus may be useful
4828 for use by tools (e.g., semantic browsing tools or integrated development
4829 environments) that are driven from the @file{ALI} file. This switch
4830 implies @option{-gnatq}, since the semantic phase must be run to get a
4831 meaningful ALI file.
4833 In addition, if @option{-gnatt} is also specified, then the tree file is
4834 generated even if there are illegalities. It may be useful in this case
4835 to also specify @option{-gnatq} to ensure that full semantic processing
4836 occurs. The resulting tree file can be processed by ASIS, for the purpose
4837 of providing partial information about illegal units, but if the error
4838 causes the tree to be badly malformed, then ASIS may crash during the
4841 When @option{-gnatQ} is used and the generated @file{ALI} file is marked as
4842 being in error, @command{gnatmake} will attempt to recompile the source when it
4843 finds such an @file{ALI} file, including with switch @option{-gnatc}.
4845 Note that @option{-gnatQ} has no effect if @option{-gnats} is specified,
4846 since ALI files are never generated if @option{-gnats} is set.
4850 @node Warning Message Control
4851 @subsection Warning Message Control
4852 @cindex Warning messages
4854 In addition to error messages, which correspond to illegalities as defined
4855 in the Ada Reference Manual, the compiler detects two kinds of warning
4858 First, the compiler considers some constructs suspicious and generates a
4859 warning message to alert you to a possible error. Second, if the
4860 compiler detects a situation that is sure to raise an exception at
4861 run time, it generates a warning message. The following shows an example
4862 of warning messages:
4864 e.adb:4:24: warning: creation of object may raise Storage_Error
4865 e.adb:10:17: warning: static value out of range
4866 e.adb:10:17: warning: "Constraint_Error" will be raised at run time
4870 GNAT considers a large number of situations as appropriate
4871 for the generation of warning messages. As always, warnings are not
4872 definite indications of errors. For example, if you do an out-of-range
4873 assignment with the deliberate intention of raising a
4874 @code{Constraint_Error} exception, then the warning that may be
4875 issued does not indicate an error. Some of the situations for which GNAT
4876 issues warnings (at least some of the time) are given in the following
4877 list. This list is not complete, and new warnings are often added to
4878 subsequent versions of GNAT. The list is intended to give a general idea
4879 of the kinds of warnings that are generated.
4883 Possible infinitely recursive calls
4886 Out-of-range values being assigned
4889 Possible order of elaboration problems
4892 Size not a multiple of alignment for a record type
4895 Assertions (pragma Assert) that are sure to fail
4901 Address clauses with possibly unaligned values, or where an attempt is
4902 made to overlay a smaller variable with a larger one.
4905 Fixed-point type declarations with a null range
4908 Direct_IO or Sequential_IO instantiated with a type that has access values
4911 Variables that are never assigned a value
4914 Variables that are referenced before being initialized
4917 Task entries with no corresponding @code{accept} statement
4920 Duplicate accepts for the same task entry in a @code{select}
4923 Objects that take too much storage
4926 Unchecked conversion between types of differing sizes
4929 Missing @code{return} statement along some execution path in a function
4932 Incorrect (unrecognized) pragmas
4935 Incorrect external names
4938 Allocation from empty storage pool
4941 Potentially blocking operation in protected type
4944 Suspicious parenthesization of expressions
4947 Mismatching bounds in an aggregate
4950 Attempt to return local value by reference
4953 Premature instantiation of a generic body
4956 Attempt to pack aliased components
4959 Out of bounds array subscripts
4962 Wrong length on string assignment
4965 Violations of style rules if style checking is enabled
4968 Unused @code{with} clauses
4971 @code{Bit_Order} usage that does not have any effect
4974 @code{Standard.Duration} used to resolve universal fixed expression
4977 Dereference of possibly null value
4980 Declaration that is likely to cause storage error
4983 Internal GNAT unit @code{with}'ed by application unit
4986 Values known to be out of range at compile time
4989 Unreferenced or unmodified variables. Note that a special
4990 exemption applies to variables which contain any of the substrings
4991 @code{DISCARD, DUMMY, IGNORE, JUNK, UNUSED}, in any casing. Such variables
4992 are considered likely to be intentionally used in a situation where
4993 otherwise a warning would be given, so warnings of this kind are
4994 always suppressed for such variables.
4997 Address overlays that could clobber memory
5000 Unexpected initialization when address clause present
5003 Bad alignment for address clause
5006 Useless type conversions
5009 Redundant assignment statements and other redundant constructs
5012 Useless exception handlers
5015 Accidental hiding of name by child unit
5018 Access before elaboration detected at compile time
5021 A range in a @code{for} loop that is known to be null or might be null
5026 The following section lists compiler switches that are available
5027 to control the handling of warning messages. It is also possible
5028 to exercise much finer control over what warnings are issued and
5029 suppressed using the GNAT pragma Warnings, @xref{Pragma Warnings,,,
5030 gnat_rm, GNAT Reference manual}.
5035 @emph{Activate most optional warnings.}
5036 @cindex @option{-gnatwa} (@command{gcc})
5037 This switch activates most optional warning messages. See the remaining list
5038 in this section for details on optional warning messages that can be
5039 individually controlled. The warnings that are not turned on by this
5043 @option{-gnatwd} (implicit dereferencing)
5044 @option{-gnatw.d} (tag warnings with -gnatw switch)
5045 @option{-gnatwh} (hiding)
5046 @option{-gnatw.h} (holes in record layouts)
5047 @option{-gnatw.k} (redefinition of names in standard)
5048 @option{-gnatwl} (elaboration warnings)
5049 @option{-gnatw.l} (inherited aspects)
5050 @option{-gnatw.n} (atomic synchronization)
5051 @option{-gnatwo} (address clause overlay)
5052 @option{-gnatw.o} (values set by out parameters ignored)
5053 @option{-gnatw.s} (overridden size clause)
5054 @option{-gnatwt} (tracking of deleted conditional code)
5055 @option{-gnatw.u} (unordered enumeration)
5056 @option{-gnatw.w} (use of Warnings Off)
5057 @option{-gnatw.y} (reasons for package needing body)
5060 All other optional warnings are turned on.
5063 @emph{Suppress all optional errors.}
5064 @cindex @option{-gnatwA} (@command{gcc})
5065 This switch suppresses all optional warning messages, see remaining list
5066 in this section for details on optional warning messages that can be
5067 individually controlled. Note that unlike switch @option{-gnatws}, the
5068 use of switch @option{-gnatwA} does not suppress warnings that are
5069 normally given unconditionally and cannot be individually controlled
5070 (for example, the warning about a missing exit path in a function).
5071 Also, again unlike switch @option{-gnatws}, warnings suppressed by
5072 the use of switch @option{-gnatwA} can be individually turned back
5073 on. For example the use of switch @option{-gnatwA} followed by
5074 switch @option{-gnatwd} will suppress all optional warnings except
5075 the warnings for implicit dereferencing.
5078 @emph{Activate warnings on failing assertions.}
5079 @cindex @option{-gnatw.a} (@command{gcc})
5080 @cindex Assert failures
5081 This switch activates warnings for assertions where the compiler can tell at
5082 compile time that the assertion will fail. Note that this warning is given
5083 even if assertions are disabled. The default is that such warnings are
5087 @emph{Suppress warnings on failing assertions.}
5088 @cindex @option{-gnatw.A} (@command{gcc})
5089 @cindex Assert failures
5090 This switch suppresses warnings for assertions where the compiler can tell at
5091 compile time that the assertion will fail.
5094 @emph{Activate warnings on bad fixed values.}
5095 @cindex @option{-gnatwb} (@command{gcc})
5096 @cindex Bad fixed values
5097 @cindex Fixed-point Small value
5099 This switch activates warnings for static fixed-point expressions whose
5100 value is not an exact multiple of Small. Such values are implementation
5101 dependent, since an implementation is free to choose either of the multiples
5102 that surround the value. GNAT always chooses the closer one, but this is not
5103 required behavior, and it is better to specify a value that is an exact
5104 multiple, ensuring predictable execution. The default is that such warnings
5108 @emph{Suppress warnings on bad fixed values.}
5109 @cindex @option{-gnatwB} (@command{gcc})
5110 This switch suppresses warnings for static fixed-point expressions whose
5111 value is not an exact multiple of Small.
5114 @emph{Activate warnings on biased representation.}
5115 @cindex @option{-gnatw.b} (@command{gcc})
5116 @cindex Biased representation
5117 This switch activates warnings when a size clause, value size clause, component
5118 clause, or component size clause forces the use of biased representation for an
5119 integer type (e.g. representing a range of 10..11 in a single bit by using 0/1
5120 to represent 10/11). The default is that such warnings are generated.
5123 @emph{Suppress warnings on biased representation.}
5124 @cindex @option{-gnatwB} (@command{gcc})
5125 This switch suppresses warnings for representation clauses that force the use
5126 of biased representation.
5129 @emph{Activate warnings on conditionals.}
5130 @cindex @option{-gnatwc} (@command{gcc})
5131 @cindex Conditionals, constant
5132 This switch activates warnings for conditional expressions used in
5133 tests that are known to be True or False at compile time. The default
5134 is that such warnings are not generated.
5135 Note that this warning does
5136 not get issued for the use of boolean variables or constants whose
5137 values are known at compile time, since this is a standard technique
5138 for conditional compilation in Ada, and this would generate too many
5139 false positive warnings.
5141 This warning option also activates a special test for comparisons using
5142 the operators ``>='' and`` <=''.
5143 If the compiler can tell that only the equality condition is possible,
5144 then it will warn that the ``>'' or ``<'' part of the test
5145 is useless and that the operator could be replaced by ``=''.
5146 An example would be comparing a @code{Natural} variable <= 0.
5148 This warning option also generates warnings if
5149 one or both tests is optimized away in a membership test for integer
5150 values if the result can be determined at compile time. Range tests on
5151 enumeration types are not included, since it is common for such tests
5152 to include an end point.
5154 This warning can also be turned on using @option{-gnatwa}.
5157 @emph{Suppress warnings on conditionals.}
5158 @cindex @option{-gnatwC} (@command{gcc})
5159 This switch suppresses warnings for conditional expressions used in
5160 tests that are known to be True or False at compile time.
5163 @emph{Activate warnings on missing component clauses.}
5164 @cindex @option{-gnatw.c} (@command{gcc})
5165 @cindex Component clause, missing
5166 This switch activates warnings for record components where a record
5167 representation clause is present and has component clauses for the
5168 majority, but not all, of the components. A warning is given for each
5169 component for which no component clause is present.
5172 @emph{Suppress warnings on missing component clauses.}
5173 @cindex @option{-gnatwC} (@command{gcc})
5174 This switch suppresses warnings for record components that are
5175 missing a component clause in the situation described above.
5178 @emph{Activate warnings on implicit dereferencing.}
5179 @cindex @option{-gnatwd} (@command{gcc})
5180 If this switch is set, then the use of a prefix of an access type
5181 in an indexed component, slice, or selected component without an
5182 explicit @code{.all} will generate a warning. With this warning
5183 enabled, access checks occur only at points where an explicit
5184 @code{.all} appears in the source code (assuming no warnings are
5185 generated as a result of this switch). The default is that such
5186 warnings are not generated.
5189 @emph{Suppress warnings on implicit dereferencing.}
5190 @cindex @option{-gnatwD} (@command{gcc})
5191 @cindex Implicit dereferencing
5192 @cindex Dereferencing, implicit
5193 This switch suppresses warnings for implicit dereferences in
5194 indexed components, slices, and selected components.
5197 @emph{Activate tagging of warning and info messages.}
5198 @cindex @option{-gnatw.d} (@command{gcc})
5199 If this switch is set, then warning messages are tagged, with one of the
5205 Used to tag warnings controlled by the switch @option{-gnatwx} where x
5209 Used to tag warnings controlled by the switch @option{-gnatw.x} where x
5213 Used to tag elaboration information (info) messages generated when the
5214 static model of elaboration is used and the @option{-gnatel} switch is set.
5216 @item [restriction warning]
5217 Used to tag warning messages for restriction violations, activated by use
5218 of the pragma @option{Restriction_Warnings}.
5220 @item [warning-as-error]
5221 Used to tag warning messages that have been converted to error messages by
5222 use of the pragma Warning_As_Error. Note that such warnings are prefixed by
5223 the string "error: " rather than "warning: ".
5225 @item [enabled by default]
5226 Used to tag all other warnings that are always given by default, unless
5227 warnings are completely suppressed using pragma @option{Warnings(Off)} or
5228 the switch @option{-gnatws}.
5233 @emph{Deactivate tagging of warning and info messages messages.}
5234 @cindex @option{-gnatw.d} (@command{gcc})
5235 If this switch is set, then warning messages return to the default
5236 mode in which warnings and info messages are not tagged as described above for
5240 @emph{Treat warnings and style checks as errors.}
5241 @cindex @option{-gnatwe} (@command{gcc})
5242 @cindex Warnings, treat as error
5243 This switch causes warning messages and style check messages to be
5245 The warning string still appears, but the warning messages are counted
5246 as errors, and prevent the generation of an object file. Note that this
5247 is the only -gnatw switch that affects the handling of style check messages.
5250 @emph{Activate every optional warning}
5251 @cindex @option{-gnatw.e} (@command{gcc})
5252 @cindex Warnings, activate every optional warning
5253 This switch activates all optional warnings, including those which
5254 are not activated by @code{-gnatwa}. The use of this switch is not
5255 recommended for normal use. If you turn this switch on, it is almost
5256 certain that you will get large numbers of useless warnings. The
5257 warnings that are excluded from @code{-gnatwa} are typically highly
5258 specialized warnings that are suitable for use only in code that has
5259 been specifically designed according to specialized coding rules.
5262 @emph{Activate warnings on unreferenced formals.}
5263 @cindex @option{-gnatwf} (@command{gcc})
5264 @cindex Formals, unreferenced
5265 This switch causes a warning to be generated if a formal parameter
5266 is not referenced in the body of the subprogram. This warning can
5267 also be turned on using @option{-gnatwu}. The
5268 default is that these warnings are not generated.
5271 @emph{Suppress warnings on unreferenced formals.}
5272 @cindex @option{-gnatwF} (@command{gcc})
5273 This switch suppresses warnings for unreferenced formal
5274 parameters. Note that the
5275 combination @option{-gnatwu} followed by @option{-gnatwF} has the
5276 effect of warning on unreferenced entities other than subprogram
5280 @emph{Activate warnings on unrecognized pragmas.}
5281 @cindex @option{-gnatwg} (@command{gcc})
5282 @cindex Pragmas, unrecognized
5283 This switch causes a warning to be generated if an unrecognized
5284 pragma is encountered. Apart from issuing this warning, the
5285 pragma is ignored and has no effect. The default
5286 is that such warnings are issued (satisfying the Ada Reference
5287 Manual requirement that such warnings appear).
5290 @emph{Suppress warnings on unrecognized pragmas.}
5291 @cindex @option{-gnatwG} (@command{gcc})
5292 This switch suppresses warnings for unrecognized pragmas.
5295 @emph{Warnings used for GNAT sources}
5296 @cindex @option{-gnatw.g} (@command{gcc})
5297 This switch sets the warning categories that are used by the standard
5298 GNAT style. Currently this is equivalent to
5299 @option{-gnatwAao.sI.C.V.X}
5300 but more warnings may be added in the future without advanced notice.
5303 @emph{Activate warnings on hiding.}
5304 @cindex @option{-gnatwh} (@command{gcc})
5305 @cindex Hiding of Declarations
5306 This switch activates warnings on hiding declarations.
5307 A declaration is considered hiding
5308 if it is for a non-overloadable entity, and it declares an entity with the
5309 same name as some other entity that is directly or use-visible. The default
5310 is that such warnings are not generated.
5313 @emph{Suppress warnings on hiding.}
5314 @cindex @option{-gnatwH} (@command{gcc})
5315 This switch suppresses warnings on hiding declarations.
5318 @emph{Activate warnings on holes/gaps in records.}
5319 @cindex @option{-gnatw.h} (@command{gcc})
5320 @cindex Record Representation (gaps)
5321 This switch activates warnings on component clauses in record
5322 representation clauses that leave holes (gaps) in the record layout.
5323 If this warning option is active, then record representation clauses
5324 should specify a contiguous layout, adding unused fill fields if needed.
5327 @emph{Suppress warnings on holes/gaps in records.}
5328 @cindex @option{-gnatw.H} (@command{gcc})
5329 This switch suppresses warnings on component clauses in record
5330 representation clauses that leave holes (haps) in the record layout.
5333 @emph{Activate warnings on implementation units.}
5334 @cindex @option{-gnatwi} (@command{gcc})
5335 This switch activates warnings for a @code{with} of an internal GNAT
5336 implementation unit, defined as any unit from the @code{Ada},
5337 @code{Interfaces}, @code{GNAT},
5338 ^^@code{DEC},^ or @code{System}
5339 hierarchies that is not
5340 documented in either the Ada Reference Manual or the GNAT
5341 Programmer's Reference Manual. Such units are intended only
5342 for internal implementation purposes and should not be @code{with}'ed
5343 by user programs. The default is that such warnings are generated
5346 @emph{Disable warnings on implementation units.}
5347 @cindex @option{-gnatwI} (@command{gcc})
5348 This switch disables warnings for a @code{with} of an internal GNAT
5349 implementation unit.
5352 @emph{Activate warnings on overlapping actuals.}
5353 @cindex @option{-gnatw.i} (@command{gcc})
5354 This switch enables a warning on statically detectable overlapping actuals in
5355 a subprogram call, when one of the actuals is an in-out parameter, and the
5356 types of the actuals are not by-copy types. This warning is off by default.
5359 @emph{Disable warnings on overlapping actuals.}
5360 @cindex @option{-gnatw.I} (@command{gcc})
5361 This switch disables warnings on overlapping actuals in a call..
5364 @emph{Activate warnings on obsolescent features (Annex J).}
5365 @cindex @option{-gnatwj} (@command{gcc})
5366 @cindex Features, obsolescent
5367 @cindex Obsolescent features
5368 If this warning option is activated, then warnings are generated for
5369 calls to subprograms marked with @code{pragma Obsolescent} and
5370 for use of features in Annex J of the Ada Reference Manual. In the
5371 case of Annex J, not all features are flagged. In particular use
5372 of the renamed packages (like @code{Text_IO}) and use of package
5373 @code{ASCII} are not flagged, since these are very common and
5374 would generate many annoying positive warnings. The default is that
5375 such warnings are not generated.
5377 In addition to the above cases, warnings are also generated for
5378 GNAT features that have been provided in past versions but which
5379 have been superseded (typically by features in the new Ada standard).
5380 For example, @code{pragma Ravenscar} will be flagged since its
5381 function is replaced by @code{pragma Profile(Ravenscar)}, and
5382 @code{pragma Interface_Name} will be flagged since its function
5383 is replaced by @code{pragma Import}.
5385 Note that this warning option functions differently from the
5386 restriction @code{No_Obsolescent_Features} in two respects.
5387 First, the restriction applies only to annex J features.
5388 Second, the restriction does flag uses of package @code{ASCII}.
5391 @emph{Suppress warnings on obsolescent features (Annex J).}
5392 @cindex @option{-gnatwJ} (@command{gcc})
5393 This switch disables warnings on use of obsolescent features.
5396 @emph{Activate warnings on variables that could be constants.}
5397 @cindex @option{-gnatwk} (@command{gcc})
5398 This switch activates warnings for variables that are initialized but
5399 never modified, and then could be declared constants. The default is that
5400 such warnings are not given.
5403 @emph{Suppress warnings on variables that could be constants.}
5404 @cindex @option{-gnatwK} (@command{gcc})
5405 This switch disables warnings on variables that could be declared constants.
5408 @emph{Activate warnings on redefinition of names in standard.}
5409 @cindex @option{-gnatw.k} (@command{gcc})
5410 This switch activates warnings for declarations that declare a name that
5411 is defined in package Standard. Such declarations can be confusing,
5412 especially since the names in package Standard continue to be directly
5413 visible, meaning that use visibiliy on such redeclared names does not
5414 work as expected. Names of discriminants and components in records are
5415 not included in this check.
5418 @emph{Suppress warnings on variables that could be constants.}
5419 @cindex @option{-gnatwK} (@command{gcc})
5420 This switch activates warnings for declarations that declare a name that
5421 is defined in package Standard.
5424 @emph{Activate warnings for elaboration pragmas.}
5425 @cindex @option{-gnatwl} (@command{gcc})
5426 @cindex Elaboration, warnings
5427 This switch activates warnings on missing
5428 for possible elaboration problems, including suspicious use
5429 of @code{Elaborate} pragmas, when using the static elaboration model, and
5430 possible situations that may raise @code{Program_Error} when using the
5431 dynamic elaboration model.
5432 See the section in this guide on elaboration checking for further details.
5433 The default is that such warnings
5437 @emph{Suppress warnings for elaboration pragmas.}
5438 @cindex @option{-gnatwL} (@command{gcc})
5439 This switch suppresses warnings for possible elaboration problems.
5442 @emph{List inherited aspects.}
5443 @cindex @option{-gnatw.l} (@command{gcc})
5444 This switch causes the compiler to list inherited invariants,
5445 preconditions, and postconditions from Type_Invariant'Class, Invariant'Class,
5446 Pre'Class, and Post'Class aspects. Also list inherited subtype predicates.
5449 @emph{Suppress listing of inherited aspects.}
5450 @cindex @option{-gnatw.L} (@command{gcc})
5451 This switch suppresses listing of inherited aspects.
5454 @emph{Activate warnings on modified but unreferenced variables.}
5455 @cindex @option{-gnatwm} (@command{gcc})
5456 This switch activates warnings for variables that are assigned (using
5457 an initialization value or with one or more assignment statements) but
5458 whose value is never read. The warning is suppressed for volatile
5459 variables and also for variables that are renamings of other variables
5460 or for which an address clause is given.
5461 The default is that these warnings are not given.
5464 @emph{Disable warnings on modified but unreferenced variables.}
5465 @cindex @option{-gnatwM} (@command{gcc})
5466 This switch disables warnings for variables that are assigned or
5467 initialized, but never read.
5470 @emph{Activate warnings on suspicious modulus values.}
5471 @cindex @option{-gnatw.m} (@command{gcc})
5472 This switch activates warnings for modulus values that seem suspicious.
5473 The cases caught are where the size is the same as the modulus (e.g.
5474 a modulus of 7 with a size of 7 bits), and modulus values of 32 or 64
5475 with no size clause. The guess in both cases is that 2**x was intended
5476 rather than x. In addition expressions of the form 2*x for small x
5477 generate a warning (the almost certainly accurate guess being that
5478 2**x was intended). The default is that these warnings are given.
5481 @emph{Disable warnings on suspicious modulus values.}
5482 @cindex @option{-gnatw.M} (@command{gcc})
5483 This switch disables warnings for suspicious modulus values.
5486 @emph{Set normal warnings mode.}
5487 @cindex @option{-gnatwn} (@command{gcc})
5488 This switch sets normal warning mode, in which enabled warnings are
5489 issued and treated as warnings rather than errors. This is the default
5490 mode. the switch @option{-gnatwn} can be used to cancel the effect of
5491 an explicit @option{-gnatws} or
5492 @option{-gnatwe}. It also cancels the effect of the
5493 implicit @option{-gnatwe} that is activated by the
5494 use of @option{-gnatg}.
5497 @emph{Activate warnings on atomic synchronization.}
5498 @cindex @option{-gnatw.n} (@command{gcc})
5499 @cindex Atomic Synchronization, warnings
5500 This switch actives warnings when an access to an atomic variable
5501 requires the generation of atomic synchronization code. These
5502 warnings are off by default.
5504 @emph{Suppress warnings on atomic synchronization.}
5505 @cindex @option{-gnatw.n} (@command{gcc})
5506 @cindex Atomic Synchronization, warnings
5507 This switch suppresses warnings when an access to an atomic variable
5508 requires the generation of atomic synchronization code.
5511 @emph{Activate warnings on address clause overlays.}
5512 @cindex @option{-gnatwo} (@command{gcc})
5513 @cindex Address Clauses, warnings
5514 This switch activates warnings for possibly unintended initialization
5515 effects of defining address clauses that cause one variable to overlap
5516 another. The default is that such warnings are generated.
5519 @emph{Suppress warnings on address clause overlays.}
5520 @cindex @option{-gnatwO} (@command{gcc})
5521 This switch suppresses warnings on possibly unintended initialization
5522 effects of defining address clauses that cause one variable to overlap
5526 @emph{Activate warnings on modified but unreferenced out parameters.}
5527 @cindex @option{-gnatw.o} (@command{gcc})
5528 This switch activates warnings for variables that are modified by using
5529 them as actuals for a call to a procedure with an out mode formal, where
5530 the resulting assigned value is never read. It is applicable in the case
5531 where there is more than one out mode formal. If there is only one out
5532 mode formal, the warning is issued by default (controlled by -gnatwu).
5533 The warning is suppressed for volatile
5534 variables and also for variables that are renamings of other variables
5535 or for which an address clause is given.
5536 The default is that these warnings are not given.
5539 @emph{Disable warnings on modified but unreferenced out parameters.}
5540 @cindex @option{-gnatw.O} (@command{gcc})
5541 This switch suppresses warnings for variables that are modified by using
5542 them as actuals for a call to a procedure with an out mode formal, where
5543 the resulting assigned value is never read.
5546 @emph{Activate warnings on ineffective pragma Inlines.}
5547 @cindex @option{-gnatwp} (@command{gcc})
5548 @cindex Inlining, warnings
5549 This switch activates warnings for failure of front end inlining
5550 (activated by @option{-gnatN}) to inline a particular call. There are
5551 many reasons for not being able to inline a call, including most
5552 commonly that the call is too complex to inline. The default is
5553 that such warnings are not given.
5554 Warnings on ineffective inlining by the gcc back-end can be activated
5555 separately, using the gcc switch -Winline.
5558 @emph{Suppress warnings on ineffective pragma Inlines.}
5559 @cindex @option{-gnatwP} (@command{gcc})
5560 This switch suppresses warnings on ineffective pragma Inlines. If the
5561 inlining mechanism cannot inline a call, it will simply ignore the
5565 @emph{Activate warnings on parameter ordering.}
5566 @cindex @option{-gnatw.p} (@command{gcc})
5567 @cindex Parameter order, warnings
5568 This switch activates warnings for cases of suspicious parameter
5569 ordering when the list of arguments are all simple identifiers that
5570 match the names of the formals, but are in a different order. The
5571 warning is suppressed if any use of named parameter notation is used,
5572 so this is the appropriate way to suppress a false positive (and
5573 serves to emphasize that the "misordering" is deliberate). The
5574 default is that such warnings are not given.
5577 @emph{Suppress warnings on parameter ordering.}
5578 @cindex @option{-gnatw.P} (@command{gcc})
5579 This switch suppresses warnings on cases of suspicious parameter
5583 @emph{Activate warnings on questionable missing parentheses.}
5584 @cindex @option{-gnatwq} (@command{gcc})
5585 @cindex Parentheses, warnings
5586 This switch activates warnings for cases where parentheses are not used and
5587 the result is potential ambiguity from a readers point of view. For example
5588 (not a > b) when a and b are modular means ((not a) > b) and very likely the
5589 programmer intended (not (a > b)). Similarly (-x mod 5) means (-(x mod 5)) and
5590 quite likely ((-x) mod 5) was intended. In such situations it seems best to
5591 follow the rule of always parenthesizing to make the association clear, and
5592 this warning switch warns if such parentheses are not present. The default
5593 is that these warnings are given.
5596 @emph{Suppress warnings on questionable missing parentheses.}
5597 @cindex @option{-gnatwQ} (@command{gcc})
5598 This switch suppresses warnings for cases where the association is not
5599 clear and the use of parentheses is preferred.
5602 @emph{Activate warnings on redundant constructs.}
5603 @cindex @option{-gnatwr} (@command{gcc})
5604 This switch activates warnings for redundant constructs. The following
5605 is the current list of constructs regarded as redundant:
5609 Assignment of an item to itself.
5611 Type conversion that converts an expression to its own type.
5613 Use of the attribute @code{Base} where @code{typ'Base} is the same
5616 Use of pragma @code{Pack} when all components are placed by a record
5617 representation clause.
5619 Exception handler containing only a reraise statement (raise with no
5620 operand) which has no effect.
5622 Use of the operator abs on an operand that is known at compile time
5625 Comparison of boolean expressions to an explicit True value.
5628 The default is that warnings for redundant constructs are not given.
5631 @emph{Suppress warnings on redundant constructs.}
5632 @cindex @option{-gnatwR} (@command{gcc})
5633 This switch suppresses warnings for redundant constructs.
5636 @emph{Activate warnings for object renaming function.}
5637 @cindex @option{-gnatw.r} (@command{gcc})
5638 This switch activates warnings for an object renaming that renames a
5639 function call, which is equivalent to a constant declaration (as
5640 opposed to renaming the function itself). The default is that these
5644 @emph{Suppress warnings for object renaming function.}
5645 @cindex @option{-gnatwT} (@command{gcc})
5646 This switch suppresses warnings for object renaming function.
5649 @emph{Suppress all warnings.}
5650 @cindex @option{-gnatws} (@command{gcc})
5651 This switch completely suppresses the
5652 output of all warning messages from the GNAT front end, including
5653 both warnings that can be controlled by switches described in this
5654 section, and those that are normally given unconditionally. The
5655 effect of this suppress action can only be cancelled by a subsequent
5656 use of the switch @option{-gnatwn}.
5658 Note that switch @option{-gnatws} does not suppress
5659 warnings from the @command{gcc} back end.
5660 To suppress these back end warnings as well, use the switch @option{-w}
5661 in addition to @option{-gnatws}. Also this switch has no effect on the
5662 handling of style check messages.
5665 @emph{Activate warnings on overridden size clauses.}
5666 @cindex @option{-gnatw.s} (@command{gcc})
5667 @cindex Record Representation (component sizes)
5668 This switch activates warnings on component clauses in record
5669 representation clauses where the length given overrides that
5670 specified by an explicit size clause for the component type. A
5671 warning is similarly given in the array case if a specified
5672 component size overrides an explicit size clause for the array
5676 @emph{Suppress warnings on overridden size clauses.}
5677 @cindex @option{-gnatw.S} (@command{gcc})
5678 This switch suppresses warnings on component clauses in record
5679 representation clauses that override size clauses, and similar
5680 warnings when an array component size overrides a size clause.
5683 @emph{Activate warnings for tracking of deleted conditional code.}
5684 @cindex @option{-gnatwt} (@command{gcc})
5685 @cindex Deactivated code, warnings
5686 @cindex Deleted code, warnings
5687 This switch activates warnings for tracking of code in conditionals (IF and
5688 CASE statements) that is detected to be dead code which cannot be executed, and
5689 which is removed by the front end. This warning is off by default. This may be
5690 useful for detecting deactivated code in certified applications.
5693 @emph{Suppress warnings for tracking of deleted conditional code.}
5694 @cindex @option{-gnatwT} (@command{gcc})
5695 This switch suppresses warnings for tracking of deleted conditional code.
5698 @emph{Activate warnings on suspicious contracts.}
5699 @cindex @option{-gnatw.t} (@command{gcc})
5700 This switch activates warnings on suspicious postconditions (whether a
5701 pragma @code{Postcondition} or a @code{Post} aspect in Ada 2012)
5702 and suspicious contract cases (pragma @code{Contract_Cases}). A
5703 function postcondition or contract case is suspicious when no postcondition
5704 or contract case for this function mentions the result of the function.
5705 A procedure postcondition or contract case is suspicious when it only
5706 refers to the pre-state of the procedure, because in that case it should
5707 rather be expressed as a precondition. The default is that such warnings
5711 @emph{Suppress warnings on suspicious contracts.}
5712 @cindex @option{-gnatw.T} (@command{gcc})
5713 This switch suppresses warnings on suspicious postconditions.
5716 @emph{Activate warnings on unused entities.}
5717 @cindex @option{-gnatwu} (@command{gcc})
5718 This switch activates warnings to be generated for entities that
5719 are declared but not referenced, and for units that are @code{with}'ed
5721 referenced. In the case of packages, a warning is also generated if
5722 no entities in the package are referenced. This means that if a with'ed
5723 package is referenced but the only references are in @code{use}
5724 clauses or @code{renames}
5725 declarations, a warning is still generated. A warning is also generated
5726 for a generic package that is @code{with}'ed but never instantiated.
5727 In the case where a package or subprogram body is compiled, and there
5728 is a @code{with} on the corresponding spec
5729 that is only referenced in the body,
5730 a warning is also generated, noting that the
5731 @code{with} can be moved to the body. The default is that
5732 such warnings are not generated.
5733 This switch also activates warnings on unreferenced formals
5734 (it includes the effect of @option{-gnatwf}).
5737 @emph{Suppress warnings on unused entities.}
5738 @cindex @option{-gnatwU} (@command{gcc})
5739 This switch suppresses warnings for unused entities and packages.
5740 It also turns off warnings on unreferenced formals (and thus includes
5741 the effect of @option{-gnatwF}).
5744 @emph{Activate warnings on unordered enumeration types.}
5745 @cindex @option{-gnatw.u} (@command{gcc})
5746 This switch causes enumeration types to be considered as conceptually
5747 unordered, unless an explicit pragma @code{Ordered} is given for the type.
5748 The effect is to generate warnings in clients that use explicit comparisons
5749 or subranges, since these constructs both treat objects of the type as
5750 ordered. (A @emph{client} is defined as a unit that is other than the unit in
5751 which the type is declared, or its body or subunits.) Please refer to
5752 the description of pragma @code{Ordered} in the
5753 @cite{@value{EDITION} Reference Manual} for further details.
5754 The default is that such warnings are not generated.
5757 @emph{Deactivate warnings on unordered enumeration types.}
5758 @cindex @option{-gnatw.U} (@command{gcc})
5759 This switch causes all enumeration types to be considered as ordered, so
5760 that no warnings are given for comparisons or subranges for any type.
5763 @emph{Activate warnings on unassigned variables.}
5764 @cindex @option{-gnatwv} (@command{gcc})
5765 @cindex Unassigned variable warnings
5766 This switch activates warnings for access to variables which
5767 may not be properly initialized. The default is that
5768 such warnings are generated.
5771 @emph{Suppress warnings on unassigned variables.}
5772 @cindex @option{-gnatwV} (@command{gcc})
5773 This switch suppresses warnings for access to variables which
5774 may not be properly initialized.
5775 For variables of a composite type, the warning can also be suppressed in
5776 Ada 2005 by using a default initialization with a box. For example, if
5777 Table is an array of records whose components are only partially uninitialized,
5778 then the following code:
5780 @smallexample @c ada
5781 Tab : Table := (others => <>);
5784 will suppress warnings on subsequent statements that access components
5788 @emph{Activate info messages for non-default bit order.}
5789 @cindex @option{-gnatw.v} (@command{gcc})
5790 @cindex bit order warnings
5791 This switch activates messages (labeled "info", they are not warnings,
5792 just informational messages) about the effects of non-default bit-order
5793 on records to which a component clause is applied. The effect of specifying
5794 non-default bit ordering is a bit subtle (and changed with Ada 2005), so
5795 these messages, which are given by default, are useful in understanding the
5796 exact consequences of using this feature.
5799 @emph{Suppress info messages for non-default bit order.}
5800 @cindex @option{-gnatw.V} (@command{gcc})
5801 This switch suppresses information messages for the effects of specifying
5802 non-default bit order on record components with component clauses.
5805 @emph{Activate warnings on wrong low bound assumption.}
5806 @cindex @option{-gnatww} (@command{gcc})
5807 @cindex String indexing warnings
5808 This switch activates warnings for indexing an unconstrained string parameter
5809 with a literal or S'Length. This is a case where the code is assuming that the
5810 low bound is one, which is in general not true (for example when a slice is
5811 passed). The default is that such warnings are generated.
5814 @emph{Suppress warnings on wrong low bound assumption.}
5815 @cindex @option{-gnatwW} (@command{gcc})
5816 This switch suppresses warnings for indexing an unconstrained string parameter
5817 with a literal or S'Length. Note that this warning can also be suppressed
5818 in a particular case by adding an
5819 assertion that the lower bound is 1,
5820 as shown in the following example.
5822 @smallexample @c ada
5823 procedure K (S : String) is
5824 pragma Assert (S'First = 1);
5829 @emph{Activate warnings on Warnings Off pragmas}
5830 @cindex @option{-gnatw.w} (@command{gcc})
5831 @cindex Warnings Off control
5832 This switch activates warnings for use of @code{pragma Warnings (Off, entity)}
5833 where either the pragma is entirely useless (because it suppresses no
5834 warnings), or it could be replaced by @code{pragma Unreferenced} or
5835 @code{pragma Unmodified}.
5836 Also activates warnings for the case of
5837 Warnings (Off, String), where either there is no matching
5838 Warnings (On, String), or the Warnings (Off) did not suppress any warning.
5839 The default is that these warnings are not given.
5842 @emph{Suppress warnings on unnecessary Warnings Off pragmas}
5843 @cindex @option{-gnatw.W} (@command{gcc})
5844 This switch suppresses warnings for use of @code{pragma Warnings (Off, ...)}.
5847 @emph{Activate warnings on Export/Import pragmas.}
5848 @cindex @option{-gnatwx} (@command{gcc})
5849 @cindex Export/Import pragma warnings
5850 This switch activates warnings on Export/Import pragmas when
5851 the compiler detects a possible conflict between the Ada and
5852 foreign language calling sequences. For example, the use of
5853 default parameters in a convention C procedure is dubious
5854 because the C compiler cannot supply the proper default, so
5855 a warning is issued. The default is that such warnings are
5859 @emph{Suppress warnings on Export/Import pragmas.}
5860 @cindex @option{-gnatwX} (@command{gcc})
5861 This switch suppresses warnings on Export/Import pragmas.
5862 The sense of this is that you are telling the compiler that
5863 you know what you are doing in writing the pragma, and it
5864 should not complain at you.
5867 @emph{Activate warnings for No_Exception_Propagation mode.}
5868 @cindex @option{-gnatwm} (@command{gcc})
5869 This switch activates warnings for exception usage when pragma Restrictions
5870 (No_Exception_Propagation) is in effect. Warnings are given for implicit or
5871 explicit exception raises which are not covered by a local handler, and for
5872 exception handlers which do not cover a local raise. The default is that these
5873 warnings are not given.
5876 @emph{Disable warnings for No_Exception_Propagation mode.}
5877 This switch disables warnings for exception usage when pragma Restrictions
5878 (No_Exception_Propagation) is in effect.
5881 @emph{Activate warnings for Ada compatibility issues.}
5882 @cindex @option{-gnatwy} (@command{gcc})
5883 @cindex Ada compatibility issues warnings
5884 For the most part, newer versions of Ada are upwards compatible
5885 with older versions. For example, Ada 2005 programs will almost
5886 always work when compiled as Ada 2012.
5887 However there are some exceptions (for example the fact that
5888 @code{some} is now a reserved word in Ada 2012). This
5889 switch activates several warnings to help in identifying
5890 and correcting such incompatibilities. The default is that
5891 these warnings are generated. Note that at one point Ada 2005
5892 was called Ada 0Y, hence the choice of character.
5895 @emph{Disable warnings for Ada compatibility issues.}
5896 @cindex @option{-gnatwY} (@command{gcc})
5897 @cindex Ada compatibility issues warnings
5898 This switch suppresses the warnings intended to help in identifying
5899 incompatibilities between Ada language versions.
5902 @emph{Activate information messages for why package spec needs body}
5903 @cindex @option{-gnatw.y} (@command{gcc})
5904 @cindex Package spec needing body
5905 There are a number of cases in which a package spec needs a body.
5906 For example, the use of pragma Elaborate_Body, or the declaration
5907 of a procedure specification requiring a completion. This switch
5908 causes information messages to be output showing why a package
5909 specification requires a body. This can be useful in the case of
5910 a large package specification which is unexpectedly requiring a
5911 body. The default is that such information messages are not output.
5914 @emph{Disable information messages for why package spec needs body}
5915 @cindex @option{-gnatw.Y} (@command{gcc})
5916 @cindex No information messages for why package spec needs body
5917 This switch suppresses the output of information messages showing why
5918 a package specification needs a body.
5921 @emph{Activate warnings on unchecked conversions.}
5922 @cindex @option{-gnatwz} (@command{gcc})
5923 @cindex Unchecked_Conversion warnings
5924 This switch activates warnings for unchecked conversions
5925 where the types are known at compile time to have different
5927 is that such warnings are generated. Warnings are also
5928 generated for subprogram pointers with different conventions,
5929 and, on VMS only, for data pointers with different conventions.
5932 @emph{Suppress warnings on unchecked conversions.}
5933 @cindex @option{-gnatwZ} (@command{gcc})
5934 This switch suppresses warnings for unchecked conversions
5935 where the types are known at compile time to have different
5936 sizes or conventions.
5939 @emph{Activate warnings for size not a multiple of alignment.}
5940 @cindex @option{-gnatw.z} (@command{gcc})
5941 @cindex Size/Alignment warnings
5942 This switch activates warnings for cases of record types with
5943 specified @code{Size} and @code{Alignment} attributes where the
5944 size is not a multiple of the alignment, resulting in an object
5945 size that is greater than the specified size. The default
5946 is that such warnings are generated.
5949 @emph{Suppress warnings for size not a multiple of alignment.}
5950 @cindex @option{-gnatw.Z} (@command{gcc})
5951 @cindex Size/Alignment warnings
5952 This switch suppresses warnings for cases of record types with
5953 specified @code{Size} and @code{Alignment} attributes where the
5954 size is not a multiple of the alignment, resulting in an object
5955 size that is greater than the specified size.
5956 The warning can also be
5957 suppressed by giving an explicit @code{Object_Size} value.
5959 @item ^-Wunused^WARNINGS=UNUSED^
5960 @cindex @option{-Wunused}
5961 The warnings controlled by the @option{-gnatw} switch are generated by
5962 the front end of the compiler. The @option{GCC} back end can provide
5963 additional warnings and they are controlled by the @option{-W} switch.
5964 For example, @option{^-Wunused^WARNINGS=UNUSED^} activates back end
5965 warnings for entities that are declared but not referenced.
5967 @item ^-Wuninitialized^WARNINGS=UNINITIALIZED^
5968 @cindex @option{-Wuninitialized}
5969 Similarly, @option{^-Wuninitialized^WARNINGS=UNINITIALIZED^} activates
5970 the back end warning for uninitialized variables. This switch must be
5971 used in conjunction with an optimization level greater than zero.
5973 @item -Wstack-usage=@var{len}
5974 @cindex @option{-Wstack-usage}
5975 Warn if the stack usage of a subprogram might be larger than @var{len} bytes.
5976 See @ref{Static Stack Usage Analysis} for details.
5978 @item ^-Wall^/ALL_BACK_END_WARNINGS^
5979 @cindex @option{-Wall}
5980 This switch enables most warnings from the @option{GCC} back end.
5981 The code generator detects a number of warning situations that are missed
5982 by the @option{GNAT} front end, and this switch can be used to activate them.
5983 The use of this switch also sets the default front end warning mode to
5984 @option{-gnatwa}, that is, most front end warnings activated as well.
5986 @item ^-w^/NO_BACK_END_WARNINGS^
5988 Conversely, this switch suppresses warnings from the @option{GCC} back end.
5989 The use of this switch also sets the default front end warning mode to
5990 @option{-gnatws}, that is, front end warnings suppressed as well.
5993 @cindex @option{-Werror}
5994 This switch causes warnings from the @option{GCC} back end to be treated as
5995 errors. The warning string still appears, but the warning messages are
5996 counted as errors, and prevent the generation of an object file.
6002 A string of warning parameters can be used in the same parameter. For example:
6009 will turn on all optional warnings except for unrecognized pragma warnings,
6010 and also specify that warnings should be treated as errors.
6013 When no switch @option{^-gnatw^/WARNINGS^} is used, this is equivalent to:
6056 @node Debugging and Assertion Control
6057 @subsection Debugging and Assertion Control
6061 @cindex @option{-gnata} (@command{gcc})
6067 The pragmas @code{Assert} and @code{Debug} normally have no effect and
6068 are ignored. This switch, where @samp{a} stands for assert, causes
6069 @code{Assert} and @code{Debug} pragmas to be activated.
6071 The pragmas have the form:
6075 @b{pragma} Assert (@var{Boolean-expression} @r{[},
6076 @var{static-string-expression}@r{]})
6077 @b{pragma} Debug (@var{procedure call})
6082 The @code{Assert} pragma causes @var{Boolean-expression} to be tested.
6083 If the result is @code{True}, the pragma has no effect (other than
6084 possible side effects from evaluating the expression). If the result is
6085 @code{False}, the exception @code{Assert_Failure} declared in the package
6086 @code{System.Assertions} is
6087 raised (passing @var{static-string-expression}, if present, as the
6088 message associated with the exception). If no string expression is
6089 given the default is a string giving the file name and line number
6092 The @code{Debug} pragma causes @var{procedure} to be called. Note that
6093 @code{pragma Debug} may appear within a declaration sequence, allowing
6094 debugging procedures to be called between declarations.
6097 @item /DEBUG@r{[}=debug-level@r{]}
6099 Specifies how much debugging information is to be included in
6100 the resulting object file where 'debug-level' is one of the following:
6103 Include both debugger symbol records and traceback
6105 This is the default setting.
6107 Include both debugger symbol records and traceback in
6110 Excludes both debugger symbol records and traceback
6111 the object file. Same as /NODEBUG.
6113 Includes only debugger symbol records in the object
6114 file. Note that this doesn't include traceback information.
6119 @node Validity Checking
6120 @subsection Validity Checking
6121 @findex Validity Checking
6124 The Ada Reference Manual defines the concept of invalid values (see
6125 RM 13.9.1). The primary source of invalid values is uninitialized
6126 variables. A scalar variable that is left uninitialized may contain
6127 an invalid value; the concept of invalid does not apply to access or
6130 It is an error to read an invalid value, but the RM does not require
6131 run-time checks to detect such errors, except for some minimal
6132 checking to prevent erroneous execution (i.e. unpredictable
6133 behavior). This corresponds to the @option{-gnatVd} switch below,
6134 which is the default. For example, by default, if the expression of a
6135 case statement is invalid, it will raise Constraint_Error rather than
6136 causing a wild jump, and if an array index on the left-hand side of an
6137 assignment is invalid, it will raise Constraint_Error rather than
6138 overwriting an arbitrary memory location.
6140 The @option{-gnatVa} may be used to enable additional validity checks,
6141 which are not required by the RM. These checks are often very
6142 expensive (which is why the RM does not require them). These checks
6143 are useful in tracking down uninitialized variables, but they are
6144 not usually recommended for production builds, and in particular
6145 we do not recommend using these extra validity checking options in
6146 combination with optimization, since this can confuse the optimizer.
6147 If performance is a consideration, leading to the need to optimize,
6148 then the validity checking options should not be used.
6150 The other @option{-gnatV^@var{x}^^} switches below allow finer-grained
6151 control; you can enable whichever validity checks you desire. However,
6152 for most debugging purposes, @option{-gnatVa} is sufficient, and the
6153 default @option{-gnatVd} (i.e. standard Ada behavior) is usually
6154 sufficient for non-debugging use.
6156 The @option{-gnatB} switch tells the compiler to assume that all
6157 values are valid (that is, within their declared subtype range)
6158 except in the context of a use of the Valid attribute. This means
6159 the compiler can generate more efficient code, since the range
6160 of values is better known at compile time. However, an uninitialized
6161 variable can cause wild jumps and memory corruption in this mode.
6163 The @option{-gnatV^@var{x}^^} switch allows control over the validity
6164 checking mode as described below.
6166 The @code{x} argument is a string of letters that
6167 indicate validity checks that are performed or not performed in addition
6168 to the default checks required by Ada as described above.
6171 The options allowed for this qualifier
6172 indicate validity checks that are performed or not performed in addition
6173 to the default checks required by Ada as described above.
6179 @emph{All validity checks.}
6180 @cindex @option{-gnatVa} (@command{gcc})
6181 All validity checks are turned on.
6183 That is, @option{-gnatVa} is
6184 equivalent to @option{gnatVcdfimorst}.
6188 @emph{Validity checks for copies.}
6189 @cindex @option{-gnatVc} (@command{gcc})
6190 The right hand side of assignments, and the initializing values of
6191 object declarations are validity checked.
6194 @emph{Default (RM) validity checks.}
6195 @cindex @option{-gnatVd} (@command{gcc})
6196 Some validity checks are done by default following normal Ada semantics
6198 A check is done in case statements that the expression is within the range
6199 of the subtype. If it is not, Constraint_Error is raised.
6200 For assignments to array components, a check is done that the expression used
6201 as index is within the range. If it is not, Constraint_Error is raised.
6202 Both these validity checks may be turned off using switch @option{-gnatVD}.
6203 They are turned on by default. If @option{-gnatVD} is specified, a subsequent
6204 switch @option{-gnatVd} will leave the checks turned on.
6205 Switch @option{-gnatVD} should be used only if you are sure that all such
6206 expressions have valid values. If you use this switch and invalid values
6207 are present, then the program is erroneous, and wild jumps or memory
6208 overwriting may occur.
6211 @emph{Validity checks for elementary components.}
6212 @cindex @option{-gnatVe} (@command{gcc})
6213 In the absence of this switch, assignments to record or array components are
6214 not validity checked, even if validity checks for assignments generally
6215 (@option{-gnatVc}) are turned on. In Ada, assignment of composite values do not
6216 require valid data, but assignment of individual components does. So for
6217 example, there is a difference between copying the elements of an array with a
6218 slice assignment, compared to assigning element by element in a loop. This
6219 switch allows you to turn off validity checking for components, even when they
6220 are assigned component by component.
6223 @emph{Validity checks for floating-point values.}
6224 @cindex @option{-gnatVf} (@command{gcc})
6225 In the absence of this switch, validity checking occurs only for discrete
6226 values. If @option{-gnatVf} is specified, then validity checking also applies
6227 for floating-point values, and NaNs and infinities are considered invalid,
6228 as well as out of range values for constrained types. Note that this means
6229 that standard IEEE infinity mode is not allowed. The exact contexts
6230 in which floating-point values are checked depends on the setting of other
6231 options. For example,
6232 @option{^-gnatVif^VALIDITY_CHECKING=(IN_PARAMS,FLOATS)^} or
6233 @option{^-gnatVfi^VALIDITY_CHECKING=(FLOATS,IN_PARAMS)^}
6234 (the order does not matter) specifies that floating-point parameters of mode
6235 @code{in} should be validity checked.
6238 @emph{Validity checks for @code{in} mode parameters}
6239 @cindex @option{-gnatVi} (@command{gcc})
6240 Arguments for parameters of mode @code{in} are validity checked in function
6241 and procedure calls at the point of call.
6244 @emph{Validity checks for @code{in out} mode parameters.}
6245 @cindex @option{-gnatVm} (@command{gcc})
6246 Arguments for parameters of mode @code{in out} are validity checked in
6247 procedure calls at the point of call. The @code{'m'} here stands for
6248 modify, since this concerns parameters that can be modified by the call.
6249 Note that there is no specific option to test @code{out} parameters,
6250 but any reference within the subprogram will be tested in the usual
6251 manner, and if an invalid value is copied back, any reference to it
6252 will be subject to validity checking.
6255 @emph{No validity checks.}
6256 @cindex @option{-gnatVn} (@command{gcc})
6257 This switch turns off all validity checking, including the default checking
6258 for case statements and left hand side subscripts. Note that the use of
6259 the switch @option{-gnatp} suppresses all run-time checks, including
6260 validity checks, and thus implies @option{-gnatVn}. When this switch
6261 is used, it cancels any other @option{-gnatV} previously issued.
6264 @emph{Validity checks for operator and attribute operands.}
6265 @cindex @option{-gnatVo} (@command{gcc})
6266 Arguments for predefined operators and attributes are validity checked.
6267 This includes all operators in package @code{Standard},
6268 the shift operators defined as intrinsic in package @code{Interfaces}
6269 and operands for attributes such as @code{Pos}. Checks are also made
6270 on individual component values for composite comparisons, and on the
6271 expressions in type conversions and qualified expressions. Checks are
6272 also made on explicit ranges using @samp{..} (e.g.@: slices, loops etc).
6275 @emph{Validity checks for parameters.}
6276 @cindex @option{-gnatVp} (@command{gcc})
6277 This controls the treatment of parameters within a subprogram (as opposed
6278 to @option{-gnatVi} and @option{-gnatVm} which control validity testing
6279 of parameters on a call. If either of these call options is used, then
6280 normally an assumption is made within a subprogram that the input arguments
6281 have been validity checking at the point of call, and do not need checking
6282 again within a subprogram). If @option{-gnatVp} is set, then this assumption
6283 is not made, and parameters are not assumed to be valid, so their validity
6284 will be checked (or rechecked) within the subprogram.
6287 @emph{Validity checks for function returns.}
6288 @cindex @option{-gnatVr} (@command{gcc})
6289 The expression in @code{return} statements in functions is validity
6293 @emph{Validity checks for subscripts.}
6294 @cindex @option{-gnatVs} (@command{gcc})
6295 All subscripts expressions are checked for validity, whether they appear
6296 on the right side or left side (in default mode only left side subscripts
6297 are validity checked).
6300 @emph{Validity checks for tests.}
6301 @cindex @option{-gnatVt} (@command{gcc})
6302 Expressions used as conditions in @code{if}, @code{while} or @code{exit}
6303 statements are checked, as well as guard expressions in entry calls.
6308 The @option{-gnatV} switch may be followed by
6309 ^a string of letters^a list of options^
6310 to turn on a series of validity checking options.
6312 @option{^-gnatVcr^/VALIDITY_CHECKING=(COPIES, RETURNS)^}
6313 specifies that in addition to the default validity checking, copies and
6314 function return expressions are to be validity checked.
6315 In order to make it easier
6316 to specify the desired combination of effects,
6318 the upper case letters @code{CDFIMORST} may
6319 be used to turn off the corresponding lower case option.
6322 the prefix @code{NO} on an option turns off the corresponding validity
6325 @item @code{NOCOPIES}
6326 @item @code{NODEFAULT}
6327 @item @code{NOFLOATS}
6328 @item @code{NOIN_PARAMS}
6329 @item @code{NOMOD_PARAMS}
6330 @item @code{NOOPERANDS}
6331 @item @code{NORETURNS}
6332 @item @code{NOSUBSCRIPTS}
6333 @item @code{NOTESTS}
6337 @option{^-gnatVaM^/VALIDITY_CHECKING=(ALL, NOMOD_PARAMS)^}
6338 turns on all validity checking options except for
6339 checking of @code{@b{in out}} procedure arguments.
6341 The specification of additional validity checking generates extra code (and
6342 in the case of @option{-gnatVa} the code expansion can be substantial).
6343 However, these additional checks can be very useful in detecting
6344 uninitialized variables, incorrect use of unchecked conversion, and other
6345 errors leading to invalid values. The use of pragma @code{Initialize_Scalars}
6346 is useful in conjunction with the extra validity checking, since this
6347 ensures that wherever possible uninitialized variables have invalid values.
6349 See also the pragma @code{Validity_Checks} which allows modification of
6350 the validity checking mode at the program source level, and also allows for
6351 temporary disabling of validity checks.
6353 @node Style Checking
6354 @subsection Style Checking
6355 @findex Style checking
6358 The @option{-gnaty^x^(option,option,@dots{})^} switch
6359 @cindex @option{-gnaty} (@command{gcc})
6360 causes the compiler to
6361 enforce specified style rules. A limited set of style rules has been used
6362 in writing the GNAT sources themselves. This switch allows user programs
6363 to activate all or some of these checks. If the source program fails a
6364 specified style check, an appropriate message is given, preceded by
6365 the character sequence ``(style)''. This message does not prevent
6366 successful compilation (unless the @option{-gnatwe} switch is used).
6368 Note that this is by no means intended to be a general facility for
6369 checking arbitrary coding standards. It is simply an embedding of the
6370 style rules we have chosen for the GNAT sources. If you are starting
6371 a project which does not have established style standards, you may
6372 find it useful to adopt the entire set of GNAT coding standards, or
6373 some subset of them.
6375 If you already have an established set of coding
6376 standards, then the selected style checking options may
6377 indeed correspond to choices you have made, but for general checking
6378 of an existing set of coding rules, you should look to the gnatcheck
6379 tool, which is designed for that purpose.
6383 @code{(option,option,@dots{})} is a sequence of keywords
6386 The string @var{x} is a sequence of letters or digits
6388 indicating the particular style
6389 checks to be performed. The following checks are defined:
6394 @emph{Specify indentation level.}
6395 If a digit from 1-9 appears
6396 ^in the string after @option{-gnaty}^as an option for /STYLE_CHECKS^
6397 then proper indentation is checked, with the digit indicating the
6398 indentation level required. A value of zero turns off this style check.
6399 The general style of required indentation is as specified by
6400 the examples in the Ada Reference Manual. Full line comments must be
6401 aligned with the @code{--} starting on a column that is a multiple of
6402 the alignment level, or they may be aligned the same way as the following
6403 non-blank line (this is useful when full line comments appear in the middle
6404 of a statement, or they may be aligned with the source line on the previous
6408 @emph{Check attribute casing.}
6409 Attribute names, including the case of keywords such as @code{digits}
6410 used as attributes names, must be written in mixed case, that is, the
6411 initial letter and any letter following an underscore must be uppercase.
6412 All other letters must be lowercase.
6414 @item ^A^ARRAY_INDEXES^
6415 @emph{Use of array index numbers in array attributes.}
6416 When using the array attributes First, Last, Range,
6417 or Length, the index number must be omitted for one-dimensional arrays
6418 and is required for multi-dimensional arrays.
6421 @emph{Blanks not allowed at statement end.}
6422 Trailing blanks are not allowed at the end of statements. The purpose of this
6423 rule, together with h (no horizontal tabs), is to enforce a canonical format
6424 for the use of blanks to separate source tokens.
6426 @item ^B^BOOLEAN_OPERATORS^
6427 @emph{Check Boolean operators.}
6428 The use of AND/OR operators is not permitted except in the cases of modular
6429 operands, array operands, and simple stand-alone boolean variables or
6430 boolean constants. In all other cases @code{and then}/@code{or else} are
6434 @emph{Check comments, double space.}
6435 Comments must meet the following set of rules:
6440 The ``@code{--}'' that starts the column must either start in column one,
6441 or else at least one blank must precede this sequence.
6444 Comments that follow other tokens on a line must have at least one blank
6445 following the ``@code{--}'' at the start of the comment.
6448 Full line comments must have at least two blanks following the
6449 ``@code{--}'' that starts the comment, with the following exceptions.
6452 A line consisting only of the ``@code{--}'' characters, possibly preceded
6453 by blanks is permitted.
6456 A comment starting with ``@code{--x}'' where @code{x} is a special character
6458 This allows proper processing of the output generated by specialized tools
6459 including @command{gnatprep} (where ``@code{--!}'' is used) and the SPARK
6461 language (where ``@code{--#}'' is used). For the purposes of this rule, a
6462 special character is defined as being in one of the ASCII ranges
6463 @code{16#21#@dots{}16#2F#} or @code{16#3A#@dots{}16#3F#}.
6464 Note that this usage is not permitted
6465 in GNAT implementation units (i.e., when @option{-gnatg} is used).
6468 A line consisting entirely of minus signs, possibly preceded by blanks, is
6469 permitted. This allows the construction of box comments where lines of minus
6470 signs are used to form the top and bottom of the box.
6473 A comment that starts and ends with ``@code{--}'' is permitted as long as at
6474 least one blank follows the initial ``@code{--}''. Together with the preceding
6475 rule, this allows the construction of box comments, as shown in the following
6478 ---------------------------
6479 -- This is a box comment --
6480 -- with two text lines. --
6481 ---------------------------
6486 @emph{Check comments, single space.}
6487 This is identical to @code{^c^COMMENTS^} except that only one space
6488 is required following the @code{--} of a comment instead of two.
6490 @item ^d^DOS_LINE_ENDINGS^
6491 @emph{Check no DOS line terminators present.}
6492 All lines must be terminated by a single ASCII.LF
6493 character (in particular the DOS line terminator sequence CR/LF is not
6497 @emph{Check end/exit labels.}
6498 Optional labels on @code{end} statements ending subprograms and on
6499 @code{exit} statements exiting named loops, are required to be present.
6502 @emph{No form feeds or vertical tabs.}
6503 Neither form feeds nor vertical tab characters are permitted
6507 @emph{GNAT style mode.}
6508 The set of style check switches is set to match that used by the GNAT sources.
6509 This may be useful when developing code that is eventually intended to be
6510 incorporated into GNAT. Currently this is equivalent to @option{-gnatwydISux})
6511 but additional style switches may be added to this set in the future without
6515 @emph{No horizontal tabs.}
6516 Horizontal tab characters are not permitted in the source text.
6517 Together with the b (no blanks at end of line) check, this
6518 enforces a canonical form for the use of blanks to separate
6522 @emph{Check if-then layout.}
6523 The keyword @code{then} must appear either on the same
6524 line as corresponding @code{if}, or on a line on its own, lined
6525 up under the @code{if}.
6528 @emph{check mode IN keywords.}
6529 Mode @code{in} (the default mode) is not
6530 allowed to be given explicitly. @code{in out} is fine,
6531 but not @code{in} on its own.
6534 @emph{Check keyword casing.}
6535 All keywords must be in lower case (with the exception of keywords
6536 such as @code{digits} used as attribute names to which this check
6540 @emph{Check layout.}
6541 Layout of statement and declaration constructs must follow the
6542 recommendations in the Ada Reference Manual, as indicated by the
6543 form of the syntax rules. For example an @code{else} keyword must
6544 be lined up with the corresponding @code{if} keyword.
6546 There are two respects in which the style rule enforced by this check
6547 option are more liberal than those in the Ada Reference Manual. First
6548 in the case of record declarations, it is permissible to put the
6549 @code{record} keyword on the same line as the @code{type} keyword, and
6550 then the @code{end} in @code{end record} must line up under @code{type}.
6551 This is also permitted when the type declaration is split on two lines.
6552 For example, any of the following three layouts is acceptable:
6554 @smallexample @c ada
6577 Second, in the case of a block statement, a permitted alternative
6578 is to put the block label on the same line as the @code{declare} or
6579 @code{begin} keyword, and then line the @code{end} keyword up under
6580 the block label. For example both the following are permitted:
6582 @smallexample @c ada
6600 The same alternative format is allowed for loops. For example, both of
6601 the following are permitted:
6603 @smallexample @c ada
6605 Clear : while J < 10 loop
6616 @item ^Lnnn^MAX_NESTING=nnn^
6617 @emph{Set maximum nesting level.}
6618 The maximum level of nesting of constructs (including subprograms, loops,
6619 blocks, packages, and conditionals) may not exceed the given value
6620 @option{nnn}. A value of zero disconnects this style check.
6622 @item ^m^LINE_LENGTH^
6623 @emph{Check maximum line length.}
6624 The length of source lines must not exceed 79 characters, including
6625 any trailing blanks. The value of 79 allows convenient display on an
6626 80 character wide device or window, allowing for possible special
6627 treatment of 80 character lines. Note that this count is of
6628 characters in the source text. This means that a tab character counts
6629 as one character in this count and a wide character sequence counts as
6630 a single character (however many bytes are needed in the encoding).
6632 @item ^Mnnn^MAX_LENGTH=nnn^
6633 @emph{Set maximum line length.}
6634 The length of lines must not exceed the
6635 given value @option{nnn}. The maximum value that can be specified is 32767.
6636 If neither style option for setting the line length is used, then the
6637 default is 255. This also controls the maximum length of lexical elements,
6638 where the only restriction is that they must fit on a single line.
6640 @item ^n^STANDARD_CASING^
6641 @emph{Check casing of entities in Standard.}
6642 Any identifier from Standard must be cased
6643 to match the presentation in the Ada Reference Manual (for example,
6644 @code{Integer} and @code{ASCII.NUL}).
6647 @emph{Turn off all style checks.}
6648 All style check options are turned off.
6650 @item ^o^ORDERED_SUBPROGRAMS^
6651 @emph{Check order of subprogram bodies.}
6652 All subprogram bodies in a given scope
6653 (e.g.@: a package body) must be in alphabetical order. The ordering
6654 rule uses normal Ada rules for comparing strings, ignoring casing
6655 of letters, except that if there is a trailing numeric suffix, then
6656 the value of this suffix is used in the ordering (e.g.@: Junk2 comes
6659 @item ^O^OVERRIDING_INDICATORS^
6660 @emph{Check that overriding subprograms are explicitly marked as such.}
6661 The declaration of a primitive operation of a type extension that overrides
6662 an inherited operation must carry an overriding indicator.
6665 @emph{Check pragma casing.}
6666 Pragma names must be written in mixed case, that is, the
6667 initial letter and any letter following an underscore must be uppercase.
6668 All other letters must be lowercase. An exception is that SPARK_Mode is
6669 allowed as an alternative for Spark_Mode.
6671 @item ^r^REFERENCES^
6672 @emph{Check references.}
6673 All identifier references must be cased in the same way as the
6674 corresponding declaration. No specific casing style is imposed on
6675 identifiers. The only requirement is for consistency of references
6679 @emph{Check separate specs.}
6680 Separate declarations (``specs'') are required for subprograms (a
6681 body is not allowed to serve as its own declaration). The only
6682 exception is that parameterless library level procedures are
6683 not required to have a separate declaration. This exception covers
6684 the most frequent form of main program procedures.
6686 @item ^S^STATEMENTS_AFTER_THEN_ELSE^
6687 @emph{Check no statements after @code{then}/@code{else}.}
6688 No statements are allowed
6689 on the same line as a @code{then} or @code{else} keyword following the
6690 keyword in an @code{if} statement. @code{or else} and @code{and then} are not
6691 affected, and a special exception allows a pragma to appear after @code{else}.
6694 @emph{Check token spacing.}
6695 The following token spacing rules are enforced:
6700 The keywords @code{abs} and @code{not} must be followed by a space.
6703 The token @code{=>} must be surrounded by spaces.
6706 The token @code{<>} must be preceded by a space or a left parenthesis.
6709 Binary operators other than @code{**} must be surrounded by spaces.
6710 There is no restriction on the layout of the @code{**} binary operator.
6713 Colon must be surrounded by spaces.
6716 Colon-equal (assignment, initialization) must be surrounded by spaces.
6719 Comma must be the first non-blank character on the line, or be
6720 immediately preceded by a non-blank character, and must be followed
6724 If the token preceding a left parenthesis ends with a letter or digit, then
6725 a space must separate the two tokens.
6728 if the token following a right parenthesis starts with a letter or digit, then
6729 a space must separate the two tokens.
6732 A right parenthesis must either be the first non-blank character on
6733 a line, or it must be preceded by a non-blank character.
6736 A semicolon must not be preceded by a space, and must not be followed by
6737 a non-blank character.
6740 A unary plus or minus may not be followed by a space.
6743 A vertical bar must be surrounded by spaces.
6747 Exactly one blank (and no other white space) must appear between
6748 a @code{not} token and a following @code{in} token.
6750 @item ^u^UNNECESSARY_BLANK_LINES^
6751 @emph{Check unnecessary blank lines.}
6752 Unnecessary blank lines are not allowed. A blank line is considered
6753 unnecessary if it appears at the end of the file, or if more than
6754 one blank line occurs in sequence.
6756 @item ^x^XTRA_PARENS^
6757 @emph{Check extra parentheses.}
6758 Unnecessary extra level of parentheses (C-style) are not allowed
6759 around conditions in @code{if} statements, @code{while} statements and
6760 @code{exit} statements.
6762 @item ^y^ALL_BUILTIN^
6763 @emph{Set all standard style check options}
6764 This is equivalent to @code{gnaty3aAbcefhiklmnprst}, that is all checking
6765 options enabled with the exception of @option{-gnatyB}, @option{-gnatyd},
6766 @option{-gnatyI}, @option{-gnatyLnnn}, @option{-gnatyo}, @option{-gnatyO},
6767 @option{-gnatyS}, @option{-gnatyu}, and @option{-gnatyx}.
6771 @emph{Remove style check options}
6772 This causes any subsequent options in the string to act as canceling the
6773 corresponding style check option. To cancel maximum nesting level control,
6774 use @option{L} parameter witout any integer value after that, because any
6775 digit following @option{-} in the parameter string of the @option{-gnaty}
6776 option will be threated as canceling indentation check. The same is true
6777 for @option{M} parameter. @option{y} and @option{N} parameters are not
6778 allowed after @option{-}.
6781 This causes any subsequent options in the string to enable the corresponding
6782 style check option. That is, it cancels the effect of a previous ^-^REMOVE^,
6788 @emph{Removing style check options}
6789 If the name of a style check is preceded by @option{NO} then the corresponding
6790 style check is turned off. For example @option{NOCOMMENTS} turns off style
6791 checking for comments.
6796 In the above rules, appearing in column one is always permitted, that is,
6797 counts as meeting either a requirement for a required preceding space,
6798 or as meeting a requirement for no preceding space.
6800 Appearing at the end of a line is also always permitted, that is, counts
6801 as meeting either a requirement for a following space, or as meeting
6802 a requirement for no following space.
6805 If any of these style rules is violated, a message is generated giving
6806 details on the violation. The initial characters of such messages are
6807 always ``@code{(style)}''. Note that these messages are treated as warning
6808 messages, so they normally do not prevent the generation of an object
6809 file. The @option{-gnatwe} switch can be used to treat warning messages,
6810 including style messages, as fatal errors.
6814 @option{-gnaty} on its own (that is not
6815 followed by any letters or digits) is equivalent
6816 to the use of @option{-gnatyy} as described above, that is all
6817 built-in standard style check options are enabled.
6821 /STYLE_CHECKS=ALL_BUILTIN enables all checking options with
6822 the exception of ORDERED_SUBPROGRAMS, UNNECESSARY_BLANK_LINES,
6823 XTRA_PARENS, and DOS_LINE_ENDINGS. In addition
6833 clears any previously set style checks.
6835 @node Run-Time Checks
6836 @subsection Run-Time Checks
6837 @cindex Division by zero
6838 @cindex Access before elaboration
6839 @cindex Checks, division by zero
6840 @cindex Checks, access before elaboration
6841 @cindex Checks, stack overflow checking
6844 By default, the following checks are suppressed: integer overflow
6845 checks, stack overflow checks, and checks for access before
6846 elaboration on subprogram calls. All other checks, including range
6847 checks and array bounds checks, are turned on by default. The
6848 following @command{gcc} switches refine this default behavior.
6853 @cindex @option{-gnatp} (@command{gcc})
6854 @cindex Suppressing checks
6855 @cindex Checks, suppressing
6857 This switch causes the unit to be compiled
6858 as though @code{pragma Suppress (All_checks)}
6859 had been present in the source. Validity checks are also eliminated (in
6860 other words @option{-gnatp} also implies @option{-gnatVn}.
6861 Use this switch to improve the performance
6862 of the code at the expense of safety in the presence of invalid data or
6865 Note that when checks are suppressed, the compiler is allowed, but not
6866 required, to omit the checking code. If the run-time cost of the
6867 checking code is zero or near-zero, the compiler will generate it even
6868 if checks are suppressed. In particular, if the compiler can prove
6869 that a certain check will necessarily fail, it will generate code to
6870 do an unconditional ``raise'', even if checks are suppressed. The
6871 compiler warns in this case. Another case in which checks may not be
6872 eliminated is when they are embedded in certain run time routines such
6873 as math library routines.
6875 Of course, run-time checks are omitted whenever the compiler can prove
6876 that they will not fail, whether or not checks are suppressed.
6878 Note that if you suppress a check that would have failed, program
6879 execution is erroneous, which means the behavior is totally
6880 unpredictable. The program might crash, or print wrong answers, or
6881 do anything else. It might even do exactly what you wanted it to do
6882 (and then it might start failing mysteriously next week or next
6883 year). The compiler will generate code based on the assumption that
6884 the condition being checked is true, which can result in erroneous
6885 execution if that assumption is wrong.
6887 The checks subject to suppression include all the checks defined by
6888 the Ada standard, the additional implementation defined checks
6889 @code{Alignment_Check},
6890 @code{Duplicated_Tag_Check}, @code{Predicate_Check}, and
6891 @code{Validity_Check}, as well as any checks introduced using
6892 @code{pragma Check_Name}. Note that @code{Atomic_Synchronization}
6893 is not automatically suppressed by use of this option.
6895 If the code depends on certain checks being active, you can use
6896 pragma @code{Unsuppress} either as a configuration pragma or as
6897 a local pragma to make sure that a specified check is performed
6898 even if @option{gnatp} is specified.
6900 The @option{-gnatp} switch has no effect if a subsequent
6901 @option{-gnat-p} switch appears.
6904 @cindex @option{-gnat-p} (@command{gcc})
6905 @cindex Suppressing checks
6906 @cindex Checks, suppressing
6908 This switch cancels the effect of a previous @option{gnatp} switch.
6911 @cindex @option{-gnato??} (@command{gcc})
6912 @cindex Overflow checks
6913 @cindex Overflow mode
6914 @cindex Check, overflow
6915 This switch controls the mode used for computing intermediate
6916 arithmetic integer operations, and also enables overflow checking.
6917 For a full description of overflow mode and checking control, see
6918 the ``Overflow Check Handling in GNAT'' appendix in this
6921 Overflow checks are always enabled by this switch. The argument
6922 controls the mode, using the codes
6926 In STRICT mode, intermediate operations are always done using the
6927 base type, and overflow checking ensures that the result is within
6928 the base type range.
6931 In MINIMIZED mode, overflows in intermediate operations are avoided
6932 where possible by using a larger integer type for the computation
6933 (typically @code{Long_Long_Integer}). Overflow checking ensures that
6934 the result fits in this larger integer type.
6936 @item 3 = ELIMINATED
6937 In ELIMINATED mode, overflows in intermediate operations are avoided
6938 by using multi-precision arithmetic. In this case, overflow checking
6939 has no effect on intermediate operations (since overflow is impossible).
6942 If two digits are present after @option{-gnato} then the first digit
6943 sets the mode for expressions outside assertions, and the second digit
6944 sets the mode for expressions within assertions. Here assertions is used
6945 in the technical sense (which includes for example precondition and
6946 postcondition expressions).
6948 If one digit is present, the corresponding mode is applicable to both
6949 expressions within and outside assertion expressions.
6951 If no digits are present, the default is to enable overflow checks
6952 and set STRICT mode for both kinds of expressions. This is compatible
6953 with the use of @option{-gnato} in previous versions of GNAT.
6955 @findex Machine_Overflows
6956 Note that the @option{-gnato??} switch does not affect the code generated
6957 for any floating-point operations; it applies only to integer semantics.
6958 For floating-point, @value{EDITION} has the @code{Machine_Overflows}
6959 attribute set to @code{False} and the normal mode of operation is to
6960 generate IEEE NaN and infinite values on overflow or invalid operations
6961 (such as dividing 0.0 by 0.0).
6963 The reason that we distinguish overflow checking from other kinds of
6964 range constraint checking is that a failure of an overflow check, unlike
6965 for example the failure of a range check, can result in an incorrect
6966 value, but cannot cause random memory destruction (like an out of range
6967 subscript), or a wild jump (from an out of range case value). Overflow
6968 checking is also quite expensive in time and space, since in general it
6969 requires the use of double length arithmetic.
6971 Note again that the default is @option{^-gnato00^/OVERFLOW_CHECKS=00^},
6972 so overflow checking is not performed in default mode. This means that out of
6973 the box, with the default settings, @value{EDITION} does not do all the checks
6974 expected from the language description in the Ada Reference Manual.
6975 If you want all constraint checks to be performed, as described in this Manual,
6976 then you must explicitly use the @option{-gnato??}
6977 switch either on the @command{gnatmake} or @command{gcc} command.
6980 @cindex @option{-gnatE} (@command{gcc})
6981 @cindex Elaboration checks
6982 @cindex Check, elaboration
6983 Enables dynamic checks for access-before-elaboration
6984 on subprogram calls and generic instantiations.
6985 Note that @option{-gnatE} is not necessary for safety, because in the
6986 default mode, GNAT ensures statically that the checks would not fail.
6987 For full details of the effect and use of this switch,
6988 @xref{Compiling with gcc}.
6991 @cindex @option{-fstack-check} (@command{gcc})
6992 @cindex Stack Overflow Checking
6993 @cindex Checks, stack overflow checking
6994 Activates stack overflow checking. For full details of the effect and use of
6995 this switch see @ref{Stack Overflow Checking}.
7000 The setting of these switches only controls the default setting of the
7001 checks. You may modify them using either @code{Suppress} (to remove
7002 checks) or @code{Unsuppress} (to add back suppressed checks) pragmas in
7005 @node Using gcc for Syntax Checking
7006 @subsection Using @command{gcc} for Syntax Checking
7009 @cindex @option{-gnats} (@command{gcc})
7013 The @code{s} stands for ``syntax''.
7016 Run GNAT in syntax checking only mode. For
7017 example, the command
7020 $ gcc -c -gnats x.adb
7024 compiles file @file{x.adb} in syntax-check-only mode. You can check a
7025 series of files in a single command
7027 , and can use wild cards to specify such a group of files.
7028 Note that you must specify the @option{-c} (compile
7029 only) flag in addition to the @option{-gnats} flag.
7032 You may use other switches in conjunction with @option{-gnats}. In
7033 particular, @option{-gnatl} and @option{-gnatv} are useful to control the
7034 format of any generated error messages.
7036 When the source file is empty or contains only empty lines and/or comments,
7037 the output is a warning:
7040 $ gcc -c -gnats -x ada toto.txt
7041 toto.txt:1:01: warning: empty file, contains no compilation units
7045 Otherwise, the output is simply the error messages, if any. No object file or
7046 ALI file is generated by a syntax-only compilation. Also, no units other
7047 than the one specified are accessed. For example, if a unit @code{X}
7048 @code{with}'s a unit @code{Y}, compiling unit @code{X} in syntax
7049 check only mode does not access the source file containing unit
7052 @cindex Multiple units, syntax checking
7053 Normally, GNAT allows only a single unit in a source file. However, this
7054 restriction does not apply in syntax-check-only mode, and it is possible
7055 to check a file containing multiple compilation units concatenated
7056 together. This is primarily used by the @code{gnatchop} utility
7057 (@pxref{Renaming Files with gnatchop}).
7060 @node Using gcc for Semantic Checking
7061 @subsection Using @command{gcc} for Semantic Checking
7064 @cindex @option{-gnatc} (@command{gcc})
7068 The @code{c} stands for ``check''.
7070 Causes the compiler to operate in semantic check mode,
7071 with full checking for all illegalities specified in the
7072 Ada Reference Manual, but without generation of any object code
7073 (no object file is generated).
7075 Because dependent files must be accessed, you must follow the GNAT
7076 semantic restrictions on file structuring to operate in this mode:
7080 The needed source files must be accessible
7081 (@pxref{Search Paths and the Run-Time Library (RTL)}).
7084 Each file must contain only one compilation unit.
7087 The file name and unit name must match (@pxref{File Naming Rules}).
7090 The output consists of error messages as appropriate. No object file is
7091 generated. An @file{ALI} file is generated for use in the context of
7092 cross-reference tools, but this file is marked as not being suitable
7093 for binding (since no object file is generated).
7094 The checking corresponds exactly to the notion of
7095 legality in the Ada Reference Manual.
7097 Any unit can be compiled in semantics-checking-only mode, including
7098 units that would not normally be compiled (subunits,
7099 and specifications where a separate body is present).
7102 @node Compiling Different Versions of Ada
7103 @subsection Compiling Different Versions of Ada
7106 The switches described in this section allow you to explicitly specify
7107 the version of the Ada language that your programs are written in.
7108 The default mode is Ada 2012,
7109 but you can also specify Ada 95, Ada 2005 mode, or
7110 indicate Ada 83 compatibility mode.
7113 @cindex Compatibility with Ada 83
7115 @item -gnat83 (Ada 83 Compatibility Mode)
7116 @cindex @option{-gnat83} (@command{gcc})
7117 @cindex ACVC, Ada 83 tests
7121 Although GNAT is primarily an Ada 95 / Ada 2005 compiler, this switch
7122 specifies that the program is to be compiled in Ada 83 mode. With
7123 @option{-gnat83}, GNAT rejects most post-Ada 83 extensions and applies Ada 83
7124 semantics where this can be done easily.
7125 It is not possible to guarantee this switch does a perfect
7126 job; some subtle tests, such as are
7127 found in earlier ACVC tests (and that have been removed from the ACATS suite
7128 for Ada 95), might not compile correctly.
7129 Nevertheless, this switch may be useful in some circumstances, for example
7130 where, due to contractual reasons, existing code needs to be maintained
7131 using only Ada 83 features.
7133 With few exceptions (most notably the need to use @code{<>} on
7134 @cindex Generic formal parameters
7135 unconstrained generic formal parameters, the use of the new Ada 95 / Ada 2005
7136 reserved words, and the use of packages
7137 with optional bodies), it is not necessary to specify the
7138 @option{-gnat83} switch when compiling Ada 83 programs, because, with rare
7139 exceptions, Ada 95 and Ada 2005 are upwardly compatible with Ada 83. Thus
7140 a correct Ada 83 program is usually also a correct program
7141 in these later versions of the language standard.
7142 For further information, please refer to @ref{Compatibility and Porting Guide}.
7144 @item -gnat95 (Ada 95 mode)
7145 @cindex @option{-gnat95} (@command{gcc})
7149 This switch directs the compiler to implement the Ada 95 version of the
7151 Since Ada 95 is almost completely upwards
7152 compatible with Ada 83, Ada 83 programs may generally be compiled using
7153 this switch (see the description of the @option{-gnat83} switch for further
7154 information about Ada 83 mode).
7155 If an Ada 2005 program is compiled in Ada 95 mode,
7156 uses of the new Ada 2005 features will cause error
7157 messages or warnings.
7159 This switch also can be used to cancel the effect of a previous
7160 @option{-gnat83}, @option{-gnat05/2005}, or @option{-gnat12/2012}
7161 switch earlier in the command line.
7163 @item -gnat05 or -gnat2005 (Ada 2005 mode)
7164 @cindex @option{-gnat05} (@command{gcc})
7165 @cindex @option{-gnat2005} (@command{gcc})
7166 @cindex Ada 2005 mode
7169 This switch directs the compiler to implement the Ada 2005 version of the
7170 language, as documented in the official Ada standards document.
7171 Since Ada 2005 is almost completely upwards
7172 compatible with Ada 95 (and thus also with Ada 83), Ada 83 and Ada 95 programs
7173 may generally be compiled using this switch (see the description of the
7174 @option{-gnat83} and @option{-gnat95} switches for further
7177 @item -gnat12 or -gnat2012 (Ada 2012 mode)
7178 @cindex @option{-gnat12} (@command{gcc})
7179 @cindex @option{-gnat2012} (@command{gcc})
7180 @cindex Ada 2012 mode
7183 This switch directs the compiler to implement the Ada 2012 version of the
7184 language (also the default).
7185 Since Ada 2012 is almost completely upwards
7186 compatible with Ada 2005 (and thus also with Ada 83, and Ada 95),
7187 Ada 83 and Ada 95 programs
7188 may generally be compiled using this switch (see the description of the
7189 @option{-gnat83}, @option{-gnat95}, and @option{-gnat05/2005} switches
7190 for further information).
7192 @item -gnatX (Enable GNAT Extensions)
7193 @cindex @option{-gnatX} (@command{gcc})
7194 @cindex Ada language extensions
7195 @cindex GNAT extensions
7198 This switch directs the compiler to implement the latest version of the
7199 language (currently Ada 2012) and also to enable certain GNAT implementation
7200 extensions that are not part of any Ada standard. For a full list of these
7201 extensions, see the GNAT reference manual.
7205 @node Character Set Control
7206 @subsection Character Set Control
7208 @item ^-gnati^/IDENTIFIER_CHARACTER_SET=^@var{c}
7209 @cindex @option{^-gnati^/IDENTIFIER_CHARACTER_SET^} (@command{gcc})
7212 Normally GNAT recognizes the Latin-1 character set in source program
7213 identifiers, as described in the Ada Reference Manual.
7215 GNAT to recognize alternate character sets in identifiers. @var{c} is a
7216 single character ^^or word^ indicating the character set, as follows:
7220 ISO 8859-1 (Latin-1) identifiers
7223 ISO 8859-2 (Latin-2) letters allowed in identifiers
7226 ISO 8859-3 (Latin-3) letters allowed in identifiers
7229 ISO 8859-4 (Latin-4) letters allowed in identifiers
7232 ISO 8859-5 (Cyrillic) letters allowed in identifiers
7235 ISO 8859-15 (Latin-9) letters allowed in identifiers
7238 IBM PC letters (code page 437) allowed in identifiers
7241 IBM PC letters (code page 850) allowed in identifiers
7243 @item ^f^FULL_UPPER^
7244 Full upper-half codes allowed in identifiers
7247 No upper-half codes allowed in identifiers
7250 Wide-character codes (that is, codes greater than 255)
7251 allowed in identifiers
7254 @xref{Foreign Language Representation}, for full details on the
7255 implementation of these character sets.
7257 @item ^-gnatW^/WIDE_CHARACTER_ENCODING=^@var{e}
7258 @cindex @option{^-gnatW^/WIDE_CHARACTER_ENCODING^} (@command{gcc})
7259 Specify the method of encoding for wide characters.
7260 @var{e} is one of the following:
7265 Hex encoding (brackets coding also recognized)
7268 Upper half encoding (brackets encoding also recognized)
7271 Shift/JIS encoding (brackets encoding also recognized)
7274 EUC encoding (brackets encoding also recognized)
7277 UTF-8 encoding (brackets encoding also recognized)
7280 Brackets encoding only (default value)
7282 For full details on these encoding
7283 methods see @ref{Wide_Character Encodings}.
7284 Note that brackets coding is always accepted, even if one of the other
7285 options is specified, so for example @option{-gnatW8} specifies that both
7286 brackets and UTF-8 encodings will be recognized. The units that are
7287 with'ed directly or indirectly will be scanned using the specified
7288 representation scheme, and so if one of the non-brackets scheme is
7289 used, it must be used consistently throughout the program. However,
7290 since brackets encoding is always recognized, it may be conveniently
7291 used in standard libraries, allowing these libraries to be used with
7292 any of the available coding schemes.
7294 Note that brackets encoding only applies to program text. Within comments,
7295 brackets are considered to be normal graphic characters, and bracket sequences
7296 are never recognized as wide characters.
7298 If no @option{-gnatW?} parameter is present, then the default
7299 representation is normally Brackets encoding only. However, if the
7300 first three characters of the file are 16#EF# 16#BB# 16#BF# (the standard
7301 byte order mark or BOM for UTF-8), then these three characters are
7302 skipped and the default representation for the file is set to UTF-8.
7304 Note that the wide character representation that is specified (explicitly
7305 or by default) for the main program also acts as the default encoding used
7306 for Wide_Text_IO files if not specifically overridden by a WCEM form
7311 When no @option{-gnatW?} is specified, then characters (other than wide
7312 characters represented using brackets notation) are treated as 8-bit
7313 Latin-1 codes. The codes recognized are the Latin-1 graphic characters,
7314 and ASCII format effectors (CR, LF, HT, VT). Other lower half control
7315 characters in the range 16#00#..16#1F# are not accepted in program text
7316 or in comments. Upper half control characters (16#80#..16#9F#) are rejected
7317 in program text, but allowed and ignored in comments. Note in particular
7318 that the Next Line (NEL) character whose encoding is 16#85# is not recognized
7319 as an end of line in this default mode. If your source program contains
7320 instances of the NEL character used as a line terminator,
7321 you must use UTF-8 encoding for the whole
7322 source program. In default mode, all lines must be ended by a standard
7323 end of line sequence (CR, CR/LF, or LF).
7325 Note that the convention of simply accepting all upper half characters in
7326 comments means that programs that use standard ASCII for program text, but
7327 UTF-8 encoding for comments are accepted in default mode, providing that the
7328 comments are ended by an appropriate (CR, or CR/LF, or LF) line terminator.
7329 This is a common mode for many programs with foreign language comments.
7331 @node File Naming Control
7332 @subsection File Naming Control
7335 @item ^-gnatk^/FILE_NAME_MAX_LENGTH=^@var{n}
7336 @cindex @option{-gnatk} (@command{gcc})
7337 Activates file name ``krunching''. @var{n}, a decimal integer in the range
7338 1-999, indicates the maximum allowable length of a file name (not
7339 including the @file{.ads} or @file{.adb} extension). The default is not
7340 to enable file name krunching.
7342 For the source file naming rules, @xref{File Naming Rules}.
7345 @node Subprogram Inlining Control
7346 @subsection Subprogram Inlining Control
7351 @cindex @option{-gnatn} (@command{gcc})
7353 The @code{n} here is intended to suggest the first syllable of the
7356 GNAT recognizes and processes @code{Inline} pragmas. However, for the
7357 inlining to actually occur, optimization must be enabled and, in order
7358 to enable inlining of subprograms specified by pragma @code{Inline},
7359 you must also specify this switch.
7360 In the absence of this switch, GNAT does not attempt
7361 inlining and does not need to access the bodies of
7362 subprograms for which @code{pragma Inline} is specified if they are not
7363 in the current unit.
7365 You can optionally specify the inlining level: 1 for moderate inlining across
7366 modules, which is a good compromise between compilation times and performances
7367 at run time, or 2 for full inlining across modules, which may bring about
7368 longer compilation times. If no inlining level is specified, the compiler will
7369 pick it based on the optimization level: 1 for @option{-O1}, @option{-O2} or
7370 @option{-Os} and 2 for @option{-O3}.
7372 If you specify this switch the compiler will access these bodies,
7373 creating an extra source dependency for the resulting object file, and
7374 where possible, the call will be inlined.
7375 For further details on when inlining is possible
7376 see @ref{Inlining of Subprograms}.
7379 @cindex @option{-gnatN} (@command{gcc})
7380 This switch activates front-end inlining which also
7381 generates additional dependencies.
7383 When using a gcc-based back end (in practice this means using any version
7384 of GNAT other than the JGNAT, .NET or GNAAMP versions), then the use of
7385 @option{-gnatN} is deprecated, and the use of @option{-gnatn} is preferred.
7386 Historically front end inlining was more extensive than the gcc back end
7387 inlining, but that is no longer the case.
7390 @node Auxiliary Output Control
7391 @subsection Auxiliary Output Control
7395 @cindex @option{-gnatt} (@command{gcc})
7396 @cindex Writing internal trees
7397 @cindex Internal trees, writing to file
7398 Causes GNAT to write the internal tree for a unit to a file (with the
7399 extension @file{.adt}.
7400 This not normally required, but is used by separate analysis tools.
7402 these tools do the necessary compilations automatically, so you should
7403 not have to specify this switch in normal operation.
7404 Note that the combination of switches @option{-gnatct}
7405 generates a tree in the form required by ASIS applications.
7408 @cindex @option{-gnatu} (@command{gcc})
7409 Print a list of units required by this compilation on @file{stdout}.
7410 The listing includes all units on which the unit being compiled depends
7411 either directly or indirectly.
7414 @item -pass-exit-codes
7415 @cindex @option{-pass-exit-codes} (@command{gcc})
7416 If this switch is not used, the exit code returned by @command{gcc} when
7417 compiling multiple files indicates whether all source files have
7418 been successfully used to generate object files or not.
7420 When @option{-pass-exit-codes} is used, @command{gcc} exits with an extended
7421 exit status and allows an integrated development environment to better
7422 react to a compilation failure. Those exit status are:
7426 There was an error in at least one source file.
7428 At least one source file did not generate an object file.
7430 The compiler died unexpectedly (internal error for example).
7432 An object file has been generated for every source file.
7437 @node Debugging Control
7438 @subsection Debugging Control
7442 @cindex Debugging options
7445 @cindex @option{-gnatd} (@command{gcc})
7446 Activate internal debugging switches. @var{x} is a letter or digit, or
7447 string of letters or digits, which specifies the type of debugging
7448 outputs desired. Normally these are used only for internal development
7449 or system debugging purposes. You can find full documentation for these
7450 switches in the body of the @code{Debug} unit in the compiler source
7451 file @file{debug.adb}.
7455 @cindex @option{-gnatG} (@command{gcc})
7456 This switch causes the compiler to generate auxiliary output containing
7457 a pseudo-source listing of the generated expanded code. Like most Ada
7458 compilers, GNAT works by first transforming the high level Ada code into
7459 lower level constructs. For example, tasking operations are transformed
7460 into calls to the tasking run-time routines. A unique capability of GNAT
7461 is to list this expanded code in a form very close to normal Ada source.
7462 This is very useful in understanding the implications of various Ada
7463 usage on the efficiency of the generated code. There are many cases in
7464 Ada (e.g.@: the use of controlled types), where simple Ada statements can
7465 generate a lot of run-time code. By using @option{-gnatG} you can identify
7466 these cases, and consider whether it may be desirable to modify the coding
7467 approach to improve efficiency.
7469 The optional parameter @code{nn} if present after -gnatG specifies an
7470 alternative maximum line length that overrides the normal default of 72.
7471 This value is in the range 40-999999, values less than 40 being silently
7472 reset to 40. The equal sign is optional.
7474 The format of the output is very similar to standard Ada source, and is
7475 easily understood by an Ada programmer. The following special syntactic
7476 additions correspond to low level features used in the generated code that
7477 do not have any exact analogies in pure Ada source form. The following
7478 is a partial list of these special constructions. See the spec
7479 of package @code{Sprint} in file @file{sprint.ads} for a full list.
7481 If the switch @option{-gnatL} is used in conjunction with
7482 @cindex @option{-gnatL} (@command{gcc})
7483 @option{-gnatG}, then the original source lines are interspersed
7484 in the expanded source (as comment lines with the original line number).
7487 @item new @var{xxx} @r{[}storage_pool = @var{yyy}@r{]}
7488 Shows the storage pool being used for an allocator.
7490 @item at end @var{procedure-name};
7491 Shows the finalization (cleanup) procedure for a scope.
7493 @item (if @var{expr} then @var{expr} else @var{expr})
7494 Conditional expression equivalent to the @code{x?y:z} construction in C.
7496 @item @var{target}^^^(@var{source})
7497 A conversion with floating-point truncation instead of rounding.
7499 @item @var{target}?(@var{source})
7500 A conversion that bypasses normal Ada semantic checking. In particular
7501 enumeration types and fixed-point types are treated simply as integers.
7503 @item @var{target}?^^^(@var{source})
7504 Combines the above two cases.
7506 @item @var{x} #/ @var{y}
7507 @itemx @var{x} #mod @var{y}
7508 @itemx @var{x} #* @var{y}
7509 @itemx @var{x} #rem @var{y}
7510 A division or multiplication of fixed-point values which are treated as
7511 integers without any kind of scaling.
7513 @item free @var{expr} @r{[}storage_pool = @var{xxx}@r{]}
7514 Shows the storage pool associated with a @code{free} statement.
7516 @item [subtype or type declaration]
7517 Used to list an equivalent declaration for an internally generated
7518 type that is referenced elsewhere in the listing.
7520 @c @item freeze @var{type-name} @ovar{actions}
7521 @c Expanding @ovar macro inline (explanation in macro def comments)
7522 @item freeze @var{type-name} @r{[}@var{actions}@r{]}
7523 Shows the point at which @var{type-name} is frozen, with possible
7524 associated actions to be performed at the freeze point.
7526 @item reference @var{itype}
7527 Reference (and hence definition) to internal type @var{itype}.
7529 @item @var{function-name}! (@var{arg}, @var{arg}, @var{arg})
7530 Intrinsic function call.
7532 @item @var{label-name} : label
7533 Declaration of label @var{labelname}.
7535 @item #$ @var{subprogram-name}
7536 An implicit call to a run-time support routine
7537 (to meet the requirement of H.3.1(9) in a
7540 @item @var{expr} && @var{expr} && @var{expr} @dots{} && @var{expr}
7541 A multiple concatenation (same effect as @var{expr} & @var{expr} &
7542 @var{expr}, but handled more efficiently).
7544 @item [constraint_error]
7545 Raise the @code{Constraint_Error} exception.
7547 @item @var{expression}'reference
7548 A pointer to the result of evaluating @var{expression}.
7550 @item @var{target-type}!(@var{source-expression})
7551 An unchecked conversion of @var{source-expression} to @var{target-type}.
7553 @item [@var{numerator}/@var{denominator}]
7554 Used to represent internal real literals (that) have no exact
7555 representation in base 2-16 (for example, the result of compile time
7556 evaluation of the expression 1.0/27.0).
7560 @cindex @option{-gnatD} (@command{gcc})
7561 When used in conjunction with @option{-gnatG}, this switch causes
7562 the expanded source, as described above for
7563 @option{-gnatG} to be written to files with names
7564 @file{^xxx.dg^XXX_DG^}, where @file{xxx} is the normal file name,
7565 instead of to the standard output file. For
7566 example, if the source file name is @file{hello.adb}, then a file
7567 @file{^hello.adb.dg^HELLO.ADB_DG^} will be written. The debugging
7568 information generated by the @command{gcc} @option{^-g^/DEBUG^} switch
7569 will refer to the generated @file{^xxx.dg^XXX_DG^} file. This allows
7570 you to do source level debugging using the generated code which is
7571 sometimes useful for complex code, for example to find out exactly
7572 which part of a complex construction raised an exception. This switch
7573 also suppress generation of cross-reference information (see
7574 @option{-gnatx}) since otherwise the cross-reference information
7575 would refer to the @file{^.dg^.DG^} file, which would cause
7576 confusion since this is not the original source file.
7578 Note that @option{-gnatD} actually implies @option{-gnatG}
7579 automatically, so it is not necessary to give both options.
7580 In other words @option{-gnatD} is equivalent to @option{-gnatDG}).
7582 If the switch @option{-gnatL} is used in conjunction with
7583 @cindex @option{-gnatL} (@command{gcc})
7584 @option{-gnatDG}, then the original source lines are interspersed
7585 in the expanded source (as comment lines with the original line number).
7587 The optional parameter @code{nn} if present after -gnatD specifies an
7588 alternative maximum line length that overrides the normal default of 72.
7589 This value is in the range 40-999999, values less than 40 being silently
7590 reset to 40. The equal sign is optional.
7593 @cindex @option{-gnatr} (@command{gcc})
7594 @cindex pragma Restrictions
7595 This switch causes pragma Restrictions to be treated as Restriction_Warnings
7596 so that violation of restrictions causes warnings rather than illegalities.
7597 This is useful during the development process when new restrictions are added
7598 or investigated. The switch also causes pragma Profile to be treated as
7599 Profile_Warnings, and pragma Restricted_Run_Time and pragma Ravenscar set
7600 restriction warnings rather than restrictions.
7603 @item -gnatR@r{[}0@r{|}1@r{|}2@r{|}3@r{[}s@r{]]}
7604 @cindex @option{-gnatR} (@command{gcc})
7605 This switch controls output from the compiler of a listing showing
7606 representation information for declared types and objects. For
7607 @option{-gnatR0}, no information is output (equivalent to omitting
7608 the @option{-gnatR} switch). For @option{-gnatR1} (which is the default,
7609 so @option{-gnatR} with no parameter has the same effect), size and alignment
7610 information is listed for declared array and record types. For
7611 @option{-gnatR2}, size and alignment information is listed for all
7612 declared types and objects. The @code{Linker_Section} is also listed for any
7613 entity for which the @code{Linker_Section} is set explicitly or implicitly (the
7614 latter case occurs for objects of a type for which a @code{Linker_Section}
7617 Finally @option{-gnatR3} includes symbolic
7618 expressions for values that are computed at run time for
7619 variant records. These symbolic expressions have a mostly obvious
7620 format with #n being used to represent the value of the n'th
7621 discriminant. See source files @file{repinfo.ads/adb} in the
7622 @code{GNAT} sources for full details on the format of @option{-gnatR3}
7623 output. If the switch is followed by an s (e.g.@: @option{-gnatR2s}), then
7624 the output is to a file with the name @file{^file.rep^file_REP^} where
7625 file is the name of the corresponding source file.
7628 This form of the switch controls output of subprogram conventions
7629 and parameter passing mechanisms for all subprograms. A following
7630 @code{s} means output to a file as described above.
7633 @item /REPRESENTATION_INFO
7634 @cindex @option{/REPRESENTATION_INFO} (@command{gcc})
7635 This qualifier controls output from the compiler of a listing showing
7636 representation information for declared types and objects. For
7637 @option{/REPRESENTATION_INFO=NONE}, no information is output
7638 (equivalent to omitting the @option{/REPRESENTATION_INFO} qualifier).
7639 @option{/REPRESENTATION_INFO} without option is equivalent to
7640 @option{/REPRESENTATION_INFO=ARRAYS}.
7641 For @option{/REPRESENTATION_INFO=ARRAYS}, size and alignment
7642 information is listed for declared array and record types. For
7643 @option{/REPRESENTATION_INFO=OBJECTS}, size and alignment information
7644 is listed for all expression information for values that are computed
7645 at run time for variant records. These symbolic expressions have a mostly
7646 obvious format with #n being used to represent the value of the n'th
7647 discriminant. See source files @file{REPINFO.ADS/ADB} in the
7648 @code{GNAT} sources for full details on the format of
7649 @option{/REPRESENTATION_INFO=SYMBOLIC} output.
7650 If _FILE is added at the end of an option
7651 (e.g.@: @option{/REPRESENTATION_INFO=ARRAYS_FILE}),
7652 then the output is to a file with the name @file{file_REP} where
7653 file is the name of the corresponding source file.
7655 @item /REPRESENTATION_INFO=MECHANISMS
7656 This qualifier form controls output of subprogram conventions
7657 and parameter passing mechanisms for all subprograms. It is
7658 possible to append _FILE as described above to cause information
7659 to be written to a file.
7662 Note that it is possible for record components to have zero size. In
7663 this case, the component clause uses an obvious extension of permitted
7664 Ada syntax, for example @code{at 0 range 0 .. -1}.
7666 Representation information requires that code be generated (since it is the
7667 code generator that lays out complex data structures). If an attempt is made
7668 to output representation information when no code is generated, for example
7669 when a subunit is compiled on its own, then no information can be generated
7670 and the compiler outputs a message to this effect.
7673 @cindex @option{-gnatS} (@command{gcc})
7674 The use of the switch @option{-gnatS} for an
7675 Ada compilation will cause the compiler to output a
7676 representation of package Standard in a form very
7677 close to standard Ada. It is not quite possible to
7678 do this entirely in standard Ada (since new
7679 numeric base types cannot be created in standard
7680 Ada), but the output is easily
7681 readable to any Ada programmer, and is useful to
7682 determine the characteristics of target dependent
7683 types in package Standard.
7686 @cindex @option{-gnatx} (@command{gcc})
7687 Normally the compiler generates full cross-referencing information in
7688 the @file{ALI} file. This information is used by a number of tools,
7689 including @code{gnatfind} and @code{gnatxref}. The @option{-gnatx} switch
7690 suppresses this information. This saves some space and may slightly
7691 speed up compilation, but means that these tools cannot be used.
7694 @node Exception Handling Control
7695 @subsection Exception Handling Control
7698 GNAT uses two methods for handling exceptions at run-time. The
7699 @code{setjmp/longjmp} method saves the context when entering
7700 a frame with an exception handler. Then when an exception is
7701 raised, the context can be restored immediately, without the
7702 need for tracing stack frames. This method provides very fast
7703 exception propagation, but introduces significant overhead for
7704 the use of exception handlers, even if no exception is raised.
7706 The other approach is called ``zero cost'' exception handling.
7707 With this method, the compiler builds static tables to describe
7708 the exception ranges. No dynamic code is required when entering
7709 a frame containing an exception handler. When an exception is
7710 raised, the tables are used to control a back trace of the
7711 subprogram invocation stack to locate the required exception
7712 handler. This method has considerably poorer performance for
7713 the propagation of exceptions, but there is no overhead for
7714 exception handlers if no exception is raised. Note that in this
7715 mode and in the context of mixed Ada and C/C++ programming,
7716 to propagate an exception through a C/C++ code, the C/C++ code
7717 must be compiled with the @option{-funwind-tables} GCC's
7720 The following switches may be used to control which of the
7721 two exception handling methods is used.
7727 @cindex @option{--RTS=sjlj} (@command{gnatmake})
7728 This switch causes the setjmp/longjmp run-time (when available) to be used
7729 for exception handling. If the default
7730 mechanism for the target is zero cost exceptions, then
7731 this switch can be used to modify this default, and must be
7732 used for all units in the partition.
7733 This option is rarely used. One case in which it may be
7734 advantageous is if you have an application where exception
7735 raising is common and the overall performance of the
7736 application is improved by favoring exception propagation.
7739 @cindex @option{--RTS=zcx} (@command{gnatmake})
7740 @cindex Zero Cost Exceptions
7741 This switch causes the zero cost approach to be used
7742 for exception handling. If this is the default mechanism for the
7743 target (see below), then this switch is unneeded. If the default
7744 mechanism for the target is setjmp/longjmp exceptions, then
7745 this switch can be used to modify this default, and must be
7746 used for all units in the partition.
7747 This option can only be used if the zero cost approach
7748 is available for the target in use, otherwise it will generate an error.
7752 The same option @option{--RTS} must be used both for @command{gcc}
7753 and @command{gnatbind}. Passing this option to @command{gnatmake}
7754 (@pxref{Switches for gnatmake}) will ensure the required consistency
7755 through the compilation and binding steps.
7757 @node Units to Sources Mapping Files
7758 @subsection Units to Sources Mapping Files
7762 @item -gnatem=@var{path}
7763 @cindex @option{-gnatem} (@command{gcc})
7764 A mapping file is a way to communicate to the compiler two mappings:
7765 from unit names to file names (without any directory information) and from
7766 file names to path names (with full directory information). These mappings
7767 are used by the compiler to short-circuit the path search.
7769 The use of mapping files is not required for correct operation of the
7770 compiler, but mapping files can improve efficiency, particularly when
7771 sources are read over a slow network connection. In normal operation,
7772 you need not be concerned with the format or use of mapping files,
7773 and the @option{-gnatem} switch is not a switch that you would use
7774 explicitly. It is intended primarily for use by automatic tools such as
7775 @command{gnatmake} running under the project file facility. The
7776 description here of the format of mapping files is provided
7777 for completeness and for possible use by other tools.
7779 A mapping file is a sequence of sets of three lines. In each set, the
7780 first line is the unit name, in lower case, with @code{%s} appended
7781 for specs and @code{%b} appended for bodies; the second line is the
7782 file name; and the third line is the path name.
7788 /gnat/project1/sources/main.2.ada
7791 When the switch @option{-gnatem} is specified, the compiler will
7792 create in memory the two mappings from the specified file. If there is
7793 any problem (nonexistent file, truncated file or duplicate entries),
7794 no mapping will be created.
7796 Several @option{-gnatem} switches may be specified; however, only the
7797 last one on the command line will be taken into account.
7799 When using a project file, @command{gnatmake} creates a temporary
7800 mapping file and communicates it to the compiler using this switch.
7804 @node Integrated Preprocessing
7805 @subsection Integrated Preprocessing
7808 GNAT sources may be preprocessed immediately before compilation.
7809 In this case, the actual
7810 text of the source is not the text of the source file, but is derived from it
7811 through a process called preprocessing. Integrated preprocessing is specified
7812 through switches @option{-gnatep} and/or @option{-gnateD}. @option{-gnatep}
7813 indicates, through a text file, the preprocessing data to be used.
7814 @option{-gnateD} specifies or modifies the values of preprocessing symbol.
7815 Note that integrated preprocessing applies only to Ada source files, it is
7816 not available for configuration pragma files.
7819 Note that when integrated preprocessing is used, the output from the
7820 preprocessor is not written to any external file. Instead it is passed
7821 internally to the compiler. If you need to preserve the result of
7822 preprocessing in a file, then you should use @command{gnatprep}
7823 to perform the desired preprocessing in stand-alone mode.
7826 It is recommended that @command{gnatmake} switch ^-s^/SWITCH_CHECK^ should be
7827 used when Integrated Preprocessing is used. The reason is that preprocessing
7828 with another Preprocessing Data file without changing the sources will
7829 not trigger recompilation without this switch.
7832 Note that @command{gnatmake} switch ^-m^/MINIMAL_RECOMPILATION^ will almost
7833 always trigger recompilation for sources that are preprocessed,
7834 because @command{gnatmake} cannot compute the checksum of the source after
7838 The actual preprocessing function is described in details in section
7839 @ref{Preprocessing with gnatprep}. This section only describes how integrated
7840 preprocessing is triggered and parameterized.
7844 @item -gnatep=@var{file}
7845 @cindex @option{-gnatep} (@command{gcc})
7846 This switch indicates to the compiler the file name (without directory
7847 information) of the preprocessor data file to use. The preprocessor data file
7848 should be found in the source directories. Note that when the compiler is
7849 called by a builder such as (@command{gnatmake} with a project
7850 file, if the object directory is not also a source directory, the builder needs
7851 to be called with @option{-x}.
7854 A preprocessing data file is a text file with significant lines indicating
7855 how should be preprocessed either a specific source or all sources not
7856 mentioned in other lines. A significant line is a nonempty, non-comment line.
7857 Comments are similar to Ada comments.
7860 Each significant line starts with either a literal string or the character '*'.
7861 A literal string is the file name (without directory information) of the source
7862 to preprocess. A character '*' indicates the preprocessing for all the sources
7863 that are not specified explicitly on other lines (order of the lines is not
7864 significant). It is an error to have two lines with the same file name or two
7865 lines starting with the character '*'.
7868 After the file name or the character '*', another optional literal string
7869 indicating the file name of the definition file to be used for preprocessing
7870 (@pxref{Form of Definitions File}). The definition files are found by the
7871 compiler in one of the source directories. In some cases, when compiling
7872 a source in a directory other than the current directory, if the definition
7873 file is in the current directory, it may be necessary to add the current
7874 directory as a source directory through switch ^-I.^/SEARCH=[]^, otherwise
7875 the compiler would not find the definition file.
7878 Then, optionally, ^switches^switches^ similar to those of @code{gnatprep} may
7879 be found. Those ^switches^switches^ are:
7884 Causes both preprocessor lines and the lines deleted by
7885 preprocessing to be replaced by blank lines, preserving the line number.
7886 This ^switch^switch^ is always implied; however, if specified after @option{-c}
7887 it cancels the effect of @option{-c}.
7890 Causes both preprocessor lines and the lines deleted
7891 by preprocessing to be retained as comments marked
7892 with the special string ``@code{--! }''.
7894 @item -Dsymbol=value
7895 Define or redefine a symbol, associated with value. A symbol is an Ada
7896 identifier, or an Ada reserved word, with the exception of @code{if},
7897 @code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}.
7898 @code{value} is either a literal string, an Ada identifier or any Ada reserved
7899 word. A symbol declared with this ^switch^switch^ replaces a symbol with the
7900 same name defined in a definition file.
7903 Causes a sorted list of symbol names and values to be
7904 listed on the standard output file.
7907 Causes undefined symbols to be treated as having the value @code{FALSE}
7909 of a preprocessor test. In the absence of this option, an undefined symbol in
7910 a @code{#if} or @code{#elsif} test will be treated as an error.
7915 Examples of valid lines in a preprocessor data file:
7918 "toto.adb" "prep.def" -u
7919 -- preprocess "toto.adb", using definition file "prep.def",
7920 -- undefined symbol are False.
7923 -- preprocess all other sources without a definition file;
7924 -- suppressed lined are commented; symbol VERSION has the value V101.
7926 "titi.adb" "prep2.def" -s
7927 -- preprocess "titi.adb", using definition file "prep2.def";
7928 -- list all symbols with their values.
7931 @item ^-gnateD^/DATA_PREPROCESSING=^symbol@r{[}=value@r{]}
7932 @cindex @option{-gnateD} (@command{gcc})
7933 Define or redefine a preprocessing symbol, associated with value. If no value
7934 is given on the command line, then the value of the symbol is @code{True}.
7935 A symbol is an identifier, following normal Ada (case-insensitive)
7936 rules for its syntax, and value is either an arbitrary string between double
7937 quotes or any sequence (including an empty sequence) of characters from the
7938 set (letters, digits, period, underline).
7939 Ada reserved words may be used as symbols, with the exceptions of @code{if},
7940 @code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}.
7949 -gnateDFoo=\"Foo-Bar\"
7954 A symbol declared with this ^switch^switch^ on the command line replaces a
7955 symbol with the same name either in a definition file or specified with a
7956 ^switch^switch^ -D in the preprocessor data file.
7959 This switch is similar to switch @option{^-D^/ASSOCIATE^} of @code{gnatprep}.
7962 When integrated preprocessing is performed and the preprocessor modifies
7963 the source text, write the result of this preprocessing into a file
7964 <source>^.prep^_prep^.
7968 @node Code Generation Control
7969 @subsection Code Generation Control
7973 The GCC technology provides a wide range of target dependent
7974 @option{-m} switches for controlling
7975 details of code generation with respect to different versions of
7976 architectures. This includes variations in instruction sets (e.g.@:
7977 different members of the power pc family), and different requirements
7978 for optimal arrangement of instructions (e.g.@: different members of
7979 the x86 family). The list of available @option{-m} switches may be
7980 found in the GCC documentation.
7982 Use of these @option{-m} switches may in some cases result in improved
7985 The @value{EDITION} technology is tested and qualified without any
7986 @option{-m} switches,
7987 so generally the most reliable approach is to avoid the use of these
7988 switches. However, we generally expect most of these switches to work
7989 successfully with @value{EDITION}, and many customers have reported successful
7990 use of these options.
7992 Our general advice is to avoid the use of @option{-m} switches unless
7993 special needs lead to requirements in this area. In particular,
7994 there is no point in using @option{-m} switches to improve performance
7995 unless you actually see a performance improvement.
7999 @subsection Return Codes
8000 @cindex Return Codes
8001 @cindex @option{/RETURN_CODES=VMS}
8004 On VMS, GNAT compiled programs return POSIX-style codes by default,
8005 e.g.@: @option{/RETURN_CODES=POSIX}.
8007 To enable VMS style return codes, use GNAT BIND and LINK with the option
8008 @option{/RETURN_CODES=VMS}. For example:
8011 GNAT BIND MYMAIN.ALI /RETURN_CODES=VMS
8012 GNAT LINK MYMAIN.ALI /RETURN_CODES=VMS
8016 Programs built with /RETURN_CODES=VMS are suitable to be called in
8017 VMS DCL scripts. Programs compiled with the default /RETURN_CODES=POSIX
8018 are suitable for spawning with appropriate GNAT RTL routines.
8022 @node Search Paths and the Run-Time Library (RTL)
8023 @section Search Paths and the Run-Time Library (RTL)
8026 With the GNAT source-based library system, the compiler must be able to
8027 find source files for units that are needed by the unit being compiled.
8028 Search paths are used to guide this process.
8030 The compiler compiles one source file whose name must be given
8031 explicitly on the command line. In other words, no searching is done
8032 for this file. To find all other source files that are needed (the most
8033 common being the specs of units), the compiler examines the following
8034 directories, in the following order:
8038 The directory containing the source file of the main unit being compiled
8039 (the file name on the command line).
8042 Each directory named by an @option{^-I^/SOURCE_SEARCH^} switch given on the
8043 @command{gcc} command line, in the order given.
8046 @findex ADA_PRJ_INCLUDE_FILE
8047 Each of the directories listed in the text file whose name is given
8048 by the @env{ADA_PRJ_INCLUDE_FILE} ^environment variable^logical name^.
8051 @env{ADA_PRJ_INCLUDE_FILE} is normally set by gnatmake or by the ^gnat^GNAT^
8052 driver when project files are used. It should not normally be set
8056 @findex ADA_INCLUDE_PATH
8057 Each of the directories listed in the value of the
8058 @env{ADA_INCLUDE_PATH} ^environment variable^logical name^.
8060 Construct this value
8061 exactly as the @env{PATH} environment variable: a list of directory
8062 names separated by colons (semicolons when working with the NT version).
8065 Normally, define this value as a logical name containing a comma separated
8066 list of directory names.
8068 This variable can also be defined by means of an environment string
8069 (an argument to the HP C exec* set of functions).
8073 DEFINE ANOTHER_PATH FOO:[BAG]
8074 DEFINE ADA_INCLUDE_PATH ANOTHER_PATH,FOO:[BAM],FOO:[BAR]
8077 By default, the path includes GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB]
8078 first, followed by the standard Ada
8079 libraries in GNU:[LIB.OPENVMS7_x.2_8_x.ADAINCLUDE].
8080 If this is not redefined, the user will obtain the HP Ada 83 IO packages
8081 (Text_IO, Sequential_IO, etc)
8082 instead of the standard Ada packages. Thus, in order to get the standard Ada
8083 packages by default, ADA_INCLUDE_PATH must be redefined.
8087 The content of the @file{ada_source_path} file which is part of the GNAT
8088 installation tree and is used to store standard libraries such as the
8089 GNAT Run Time Library (RTL) source files.
8091 @ref{Installing a library}
8096 Specifying the switch @option{^-I-^/NOCURRENT_DIRECTORY^}
8097 inhibits the use of the directory
8098 containing the source file named in the command line. You can still
8099 have this directory on your search path, but in this case it must be
8100 explicitly requested with a @option{^-I^/SOURCE_SEARCH^} switch.
8102 Specifying the switch @option{-nostdinc}
8103 inhibits the search of the default location for the GNAT Run Time
8104 Library (RTL) source files.
8106 The compiler outputs its object files and ALI files in the current
8109 Caution: The object file can be redirected with the @option{-o} switch;
8110 however, @command{gcc} and @code{gnat1} have not been coordinated on this
8111 so the @file{ALI} file will not go to the right place. Therefore, you should
8112 avoid using the @option{-o} switch.
8116 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
8117 children make up the GNAT RTL, together with the simple @code{System.IO}
8118 package used in the @code{"Hello World"} example. The sources for these units
8119 are needed by the compiler and are kept together in one directory. Not
8120 all of the bodies are needed, but all of the sources are kept together
8121 anyway. In a normal installation, you need not specify these directory
8122 names when compiling or binding. Either the environment variables or
8123 the built-in defaults cause these files to be found.
8125 In addition to the language-defined hierarchies (@code{System}, @code{Ada} and
8126 @code{Interfaces}), the GNAT distribution provides a fourth hierarchy,
8127 consisting of child units of @code{GNAT}. This is a collection of generally
8128 useful types, subprograms, etc. @xref{Top, GNAT Reference Manual, About
8129 This Guid, gnat_rm, GNAT Reference Manual}, for further details.
8131 Besides simplifying access to the RTL, a major use of search paths is
8132 in compiling sources from multiple directories. This can make
8133 development environments much more flexible.
8135 @node Order of Compilation Issues
8136 @section Order of Compilation Issues
8139 If, in our earlier example, there was a spec for the @code{hello}
8140 procedure, it would be contained in the file @file{hello.ads}; yet this
8141 file would not have to be explicitly compiled. This is the result of the
8142 model we chose to implement library management. Some of the consequences
8143 of this model are as follows:
8147 There is no point in compiling specs (except for package
8148 specs with no bodies) because these are compiled as needed by clients. If
8149 you attempt a useless compilation, you will receive an error message.
8150 It is also useless to compile subunits because they are compiled as needed
8154 There are no order of compilation requirements: performing a
8155 compilation never obsoletes anything. The only way you can obsolete
8156 something and require recompilations is to modify one of the
8157 source files on which it depends.
8160 There is no library as such, apart from the ALI files
8161 (@pxref{The Ada Library Information Files}, for information on the format
8162 of these files). For now we find it convenient to create separate ALI files,
8163 but eventually the information therein may be incorporated into the object
8167 When you compile a unit, the source files for the specs of all units
8168 that it @code{with}'s, all its subunits, and the bodies of any generics it
8169 instantiates must be available (reachable by the search-paths mechanism
8170 described above), or you will receive a fatal error message.
8177 The following are some typical Ada compilation command line examples:
8180 @item $ gcc -c xyz.adb
8181 Compile body in file @file{xyz.adb} with all default options.
8184 @item $ gcc -c -O2 -gnata xyz-def.adb
8187 @item $ GNAT COMPILE /OPTIMIZE=ALL -gnata xyz-def.adb
8190 Compile the child unit package in file @file{xyz-def.adb} with extensive
8191 optimizations, and pragma @code{Assert}/@code{Debug} statements
8194 @item $ gcc -c -gnatc abc-def.adb
8195 Compile the subunit in file @file{abc-def.adb} in semantic-checking-only
8199 @node Binding with gnatbind
8200 @chapter Binding with @code{gnatbind}
8204 * Running gnatbind::
8205 * Switches for gnatbind::
8206 * Command-Line Access::
8207 * Search Paths for gnatbind::
8208 * Examples of gnatbind Usage::
8212 This chapter describes the GNAT binder, @code{gnatbind}, which is used
8213 to bind compiled GNAT objects.
8215 Note: to invoke @code{gnatbind} with a project file, use the @code{gnat}
8216 driver (see @ref{The GNAT Driver and Project Files}).
8218 The @code{gnatbind} program performs four separate functions:
8222 Checks that a program is consistent, in accordance with the rules in
8223 Chapter 10 of the Ada Reference Manual. In particular, error
8224 messages are generated if a program uses inconsistent versions of a
8228 Checks that an acceptable order of elaboration exists for the program
8229 and issues an error message if it cannot find an order of elaboration
8230 that satisfies the rules in Chapter 10 of the Ada Language Manual.
8233 Generates a main program incorporating the given elaboration order.
8234 This program is a small Ada package (body and spec) that
8235 must be subsequently compiled
8236 using the GNAT compiler. The necessary compilation step is usually
8237 performed automatically by @command{gnatlink}. The two most important
8238 functions of this program
8239 are to call the elaboration routines of units in an appropriate order
8240 and to call the main program.
8243 Determines the set of object files required by the given main program.
8244 This information is output in the forms of comments in the generated program,
8245 to be read by the @command{gnatlink} utility used to link the Ada application.
8248 @node Running gnatbind
8249 @section Running @code{gnatbind}
8252 The form of the @code{gnatbind} command is
8255 @c $ gnatbind @ovar{switches} @var{mainprog}@r{[}.ali@r{]} @ovar{switches}
8256 @c Expanding @ovar macro inline (explanation in macro def comments)
8257 $ gnatbind @r{[}@var{switches}@r{]} @var{mainprog}@r{[}.ali@r{]} @r{[}@var{switches}@r{]}
8261 where @file{@var{mainprog}.adb} is the Ada file containing the main program
8262 unit body. @code{gnatbind} constructs an Ada
8263 package in two files whose names are
8264 @file{b~@var{mainprog}.ads}, and @file{b~@var{mainprog}.adb}.
8265 For example, if given the
8266 parameter @file{hello.ali}, for a main program contained in file
8267 @file{hello.adb}, the binder output files would be @file{b~hello.ads}
8268 and @file{b~hello.adb}.
8270 When doing consistency checking, the binder takes into consideration
8271 any source files it can locate. For example, if the binder determines
8272 that the given main program requires the package @code{Pack}, whose
8274 file is @file{pack.ali} and whose corresponding source spec file is
8275 @file{pack.ads}, it attempts to locate the source file @file{pack.ads}
8276 (using the same search path conventions as previously described for the
8277 @command{gcc} command). If it can locate this source file, it checks that
8279 or source checksums of the source and its references to in @file{ALI} files
8280 match. In other words, any @file{ALI} files that mentions this spec must have
8281 resulted from compiling this version of the source file (or in the case
8282 where the source checksums match, a version close enough that the
8283 difference does not matter).
8285 @cindex Source files, use by binder
8286 The effect of this consistency checking, which includes source files, is
8287 that the binder ensures that the program is consistent with the latest
8288 version of the source files that can be located at bind time. Editing a
8289 source file without compiling files that depend on the source file cause
8290 error messages to be generated by the binder.
8292 For example, suppose you have a main program @file{hello.adb} and a
8293 package @code{P}, from file @file{p.ads} and you perform the following
8298 Enter @code{gcc -c hello.adb} to compile the main program.
8301 Enter @code{gcc -c p.ads} to compile package @code{P}.
8304 Edit file @file{p.ads}.
8307 Enter @code{gnatbind hello}.
8311 At this point, the file @file{p.ali} contains an out-of-date time stamp
8312 because the file @file{p.ads} has been edited. The attempt at binding
8313 fails, and the binder generates the following error messages:
8316 error: "hello.adb" must be recompiled ("p.ads" has been modified)
8317 error: "p.ads" has been modified and must be recompiled
8321 Now both files must be recompiled as indicated, and then the bind can
8322 succeed, generating a main program. You need not normally be concerned
8323 with the contents of this file, but for reference purposes a sample
8324 binder output file is given in @ref{Example of Binder Output File}.
8326 In most normal usage, the default mode of @command{gnatbind} which is to
8327 generate the main package in Ada, as described in the previous section.
8328 In particular, this means that any Ada programmer can read and understand
8329 the generated main program. It can also be debugged just like any other
8330 Ada code provided the @option{^-g^/DEBUG^} switch is used for
8331 @command{gnatbind} and @command{gnatlink}.
8333 @node Switches for gnatbind
8334 @section Switches for @command{gnatbind}
8337 The following switches are available with @code{gnatbind}; details will
8338 be presented in subsequent sections.
8341 * Consistency-Checking Modes::
8342 * Binder Error Message Control::
8343 * Elaboration Control::
8345 * Dynamic Allocation Control::
8346 * Binding with Non-Ada Main Programs::
8347 * Binding Programs with No Main Subprogram::
8354 @cindex @option{--version} @command{gnatbind}
8355 Display Copyright and version, then exit disregarding all other options.
8358 @cindex @option{--help} @command{gnatbind}
8359 If @option{--version} was not used, display usage, then exit disregarding
8363 @cindex @option{-a} @command{gnatbind}
8364 Indicates that, if supported by the platform, the adainit procedure should
8365 be treated as an initialisation routine by the linker (a constructor). This
8366 is intended to be used by the Project Manager to automatically initialize
8367 shared Stand-Alone Libraries.
8369 @item ^-aO^/OBJECT_SEARCH^
8370 @cindex @option{^-aO^/OBJECT_SEARCH^} (@command{gnatbind})
8371 Specify directory to be searched for ALI files.
8373 @item ^-aI^/SOURCE_SEARCH^
8374 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatbind})
8375 Specify directory to be searched for source file.
8377 @item ^-A^/ALI_LIST^@r{[=}@var{filename}@r{]}
8378 @cindex @option{^-A^/ALI_LIST^} (@command{gnatbind})
8379 Output ALI list (to standard output or to the named file).
8381 @item ^-b^/REPORT_ERRORS=BRIEF^
8382 @cindex @option{^-b^/REPORT_ERRORS=BRIEF^} (@command{gnatbind})
8383 Generate brief messages to @file{stderr} even if verbose mode set.
8385 @item ^-c^/NOOUTPUT^
8386 @cindex @option{^-c^/NOOUTPUT^} (@command{gnatbind})
8387 Check only, no generation of binder output file.
8389 @item ^-d^/DEFAULT_STACK_SIZE=^@var{nn}@r{[}k@r{|}m@r{]}
8390 @cindex @option{^-d^/DEFAULT_STACK_SIZE=^@var{nn}@r{[}k@r{|}m@r{]}} (@command{gnatbind})
8391 This switch can be used to change the default task stack size value
8392 to a specified size @var{nn}, which is expressed in bytes by default, or
8393 in kilobytes when suffixed with @var{k} or in megabytes when suffixed
8395 In the absence of a @samp{@r{[}k@r{|}m@r{]}} suffix, this switch is equivalent,
8396 in effect, to completing all task specs with
8397 @smallexample @c ada
8398 pragma Storage_Size (nn);
8400 When they do not already have such a pragma.
8402 @item ^-D^/DEFAULT_SECONDARY_STACK_SIZE=^@var{nn}@r{[}k@r{|}m@r{]}
8403 @cindex @option{^-D^/DEFAULT_SECONDARY_STACK_SIZE=nnnnn^} (@command{gnatbind})
8404 This switch can be used to change the default secondary stack size value
8405 to a specified size @var{nn}, which is expressed in bytes by default, or
8406 in kilobytes when suffixed with @var{k} or in megabytes when suffixed
8409 The secondary stack is used to deal with functions that return a variable
8410 sized result, for example a function returning an unconstrained
8411 String. There are two ways in which this secondary stack is allocated.
8413 For most targets, the secondary stack is growing on demand and is allocated
8414 as a chain of blocks in the heap. The -D option is not very
8415 relevant. It only give some control over the size of the allocated
8416 blocks (whose size is the minimum of the default secondary stack size value,
8417 and the actual size needed for the current allocation request).
8419 For certain targets, notably VxWorks 653,
8420 the secondary stack is allocated by carving off a fixed ratio chunk of the
8421 primary task stack. The -D option is used to define the
8422 size of the environment task's secondary stack.
8424 @item ^-e^/ELABORATION_DEPENDENCIES^
8425 @cindex @option{^-e^/ELABORATION_DEPENDENCIES^} (@command{gnatbind})
8426 Output complete list of elaboration-order dependencies.
8428 @item ^-E^/STORE_TRACEBACKS^
8429 @cindex @option{^-E^/STORE_TRACEBACKS^} (@command{gnatbind})
8430 Store tracebacks in exception occurrences when the target supports it.
8432 @c The following may get moved to an appendix
8433 This option is currently supported on the following targets:
8434 all x86 ports, Solaris, Windows, HP-UX, AIX, PowerPC VxWorks and Alpha VxWorks.
8436 See also the packages @code{GNAT.Traceback} and
8437 @code{GNAT.Traceback.Symbolic} for more information.
8439 Note that on x86 ports, you must not use @option{-fomit-frame-pointer}
8440 @command{gcc} option.
8443 @item ^-F^/FORCE_ELABS_FLAGS^
8444 @cindex @option{^-F^/FORCE_ELABS_FLAGS^} (@command{gnatbind})
8445 Force the checks of elaboration flags. @command{gnatbind} does not normally
8446 generate checks of elaboration flags for the main executable, except when
8447 a Stand-Alone Library is used. However, there are cases when this cannot be
8448 detected by gnatbind. An example is importing an interface of a Stand-Alone
8449 Library through a pragma Import and only specifying through a linker switch
8450 this Stand-Alone Library. This switch is used to guarantee that elaboration
8451 flag checks are generated.
8454 @cindex @option{^-h^/HELP^} (@command{gnatbind})
8455 Output usage (help) information
8457 @item ^-H32^/32_MALLOC^
8458 @cindex @option{^-H32^/32_MALLOC^} (@command{gnatbind})
8459 Use 32-bit allocations for @code{__gnat_malloc} (and thus for access types).
8460 For further details see @ref{Dynamic Allocation Control}.
8462 @item ^-H64^/64_MALLOC^
8463 @cindex @option{^-H64^/64_MALLOC^} (@command{gnatbind})
8464 Use 64-bit allocations for @code{__gnat_malloc} (and thus for access types).
8465 @cindex @code{__gnat_malloc}
8466 For further details see @ref{Dynamic Allocation Control}.
8469 @cindex @option{^-I^/SEARCH^} (@command{gnatbind})
8470 Specify directory to be searched for source and ALI files.
8472 @item ^-I-^/NOCURRENT_DIRECTORY^
8473 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gnatbind})
8474 Do not look for sources in the current directory where @code{gnatbind} was
8475 invoked, and do not look for ALI files in the directory containing the
8476 ALI file named in the @code{gnatbind} command line.
8478 @item ^-l^/ORDER_OF_ELABORATION^
8479 @cindex @option{^-l^/ORDER_OF_ELABORATION^} (@command{gnatbind})
8480 Output chosen elaboration order.
8482 @item ^-L@var{xxx}^/BUILD_LIBRARY=@var{xxx}^
8483 @cindex @option{^-L^/BUILD_LIBRARY^} (@command{gnatbind})
8484 Bind the units for library building. In this case the adainit and
8485 adafinal procedures (@pxref{Binding with Non-Ada Main Programs})
8486 are renamed to ^@var{xxx}init^@var{XXX}INIT^ and
8487 ^@var{xxx}final^@var{XXX}FINAL^.
8488 Implies ^-n^/NOCOMPILE^.
8490 (@xref{GNAT and Libraries}, for more details.)
8493 On OpenVMS, these init and final procedures are exported in uppercase
8494 letters. For example if /BUILD_LIBRARY=toto is used, the exported name of
8495 the init procedure will be "TOTOINIT" and the exported name of the final
8496 procedure will be "TOTOFINAL".
8499 @item ^-Mxyz^/RENAME_MAIN=xyz^
8500 @cindex @option{^-M^/RENAME_MAIN^} (@command{gnatbind})
8501 Rename generated main program from main to xyz. This option is
8502 supported on cross environments only.
8504 @item ^-m^/ERROR_LIMIT=^@var{n}
8505 @cindex @option{^-m^/ERROR_LIMIT^} (@command{gnatbind})
8506 Limit number of detected errors or warnings to @var{n}, where @var{n} is
8507 in the range 1..999999. The default value if no switch is
8508 given is 9999. If the number of warnings reaches this limit, then a
8509 message is output and further warnings are suppressed, the bind
8510 continues in this case. If the number of errors reaches this
8511 limit, then a message is output and the bind is abandoned.
8512 A value of zero means that no limit is enforced. The equal
8516 @cindex @option{^-n^/NOMAIN^} (@command{gnatbind})
8520 @cindex @option{-nostdinc} (@command{gnatbind})
8521 Do not look for sources in the system default directory.
8524 @cindex @option{-nostdlib} (@command{gnatbind})
8525 Do not look for library files in the system default directory.
8527 @item --RTS=@var{rts-path}
8528 @cindex @option{--RTS} (@code{gnatbind})
8529 Specifies the default location of the runtime library. Same meaning as the
8530 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
8532 @item ^-o ^/OUTPUT=^@var{file}
8533 @cindex @option{^-o ^/OUTPUT^} (@command{gnatbind})
8534 Name the output file @var{file} (default is @file{b~@var{xxx}.adb}).
8535 Note that if this option is used, then linking must be done manually,
8536 gnatlink cannot be used.
8538 @item ^-O^/OBJECT_LIST^@r{[=}@var{filename}@r{]}
8539 @cindex @option{^-O^/OBJECT_LIST^} (@command{gnatbind})
8540 Output object list (to standard output or to the named file).
8542 @item ^-p^/PESSIMISTIC_ELABORATION^
8543 @cindex @option{^-p^/PESSIMISTIC_ELABORATION^} (@command{gnatbind})
8544 Pessimistic (worst-case) elaboration order
8547 @cindex @option{^-P^/CODEPEER^} (@command{gnatbind})
8548 Generate binder file suitable for CodePeer.
8551 @cindex @option{^-R^-R^} (@command{gnatbind})
8552 Output closure source list, which includes all non-time-units that are
8553 included in the bind.
8556 @cindex @option{^-Ra^-Ra^} (@command{gnatbind})
8557 Like @option{-R} but the list includes run-time units.
8559 @item ^-s^/READ_SOURCES=ALL^
8560 @cindex @option{^-s^/READ_SOURCES=ALL^} (@command{gnatbind})
8561 Require all source files to be present.
8563 @item ^-S@var{xxx}^/INITIALIZE_SCALARS=@var{xxx}^
8564 @cindex @option{^-S^/INITIALIZE_SCALARS^} (@command{gnatbind})
8565 Specifies the value to be used when detecting uninitialized scalar
8566 objects with pragma Initialize_Scalars.
8567 The @var{xxx} ^string specified with the switch^option^ may be either
8569 @item ``@option{^in^INVALID^}'' requesting an invalid value where possible
8570 @item ``@option{^lo^LOW^}'' for the lowest possible value
8571 @item ``@option{^hi^HIGH^}'' for the highest possible value
8572 @item ``@option{@var{xx}}'' for a value consisting of repeated bytes with the
8573 value @code{16#@var{xx}#} (i.e., @var{xx} is a string of two hexadecimal digits).
8576 In addition, you can specify @option{-Sev} to indicate that the value is
8577 to be set at run time. In this case, the program will look for an environment
8578 @cindex GNAT_INIT_SCALARS
8579 variable of the form @env{GNAT_INIT_SCALARS=@var{xx}}, where @var{xx} is one
8580 of @option{in/lo/hi/@var{xx}} with the same meanings as above.
8581 If no environment variable is found, or if it does not have a valid value,
8582 then the default is @option{in} (invalid values).
8586 @cindex @option{-static} (@code{gnatbind})
8587 Link against a static GNAT run time.
8590 @cindex @option{-shared} (@code{gnatbind})
8591 Link against a shared GNAT run time when available.
8594 @item ^-t^/NOTIME_STAMP_CHECK^
8595 @cindex @option{^-t^/NOTIME_STAMP_CHECK^} (@code{gnatbind})
8596 Tolerate time stamp and other consistency errors
8598 @item ^-T@var{n}^/TIME_SLICE=@var{n}^
8599 @cindex @option{^-T^/TIME_SLICE^} (@code{gnatbind})
8600 Set the time slice value to @var{n} milliseconds. If the system supports
8601 the specification of a specific time slice value, then the indicated value
8602 is used. If the system does not support specific time slice values, but
8603 does support some general notion of round-robin scheduling, then any
8604 nonzero value will activate round-robin scheduling.
8606 A value of zero is treated specially. It turns off time
8607 slicing, and in addition, indicates to the tasking run time that the
8608 semantics should match as closely as possible the Annex D
8609 requirements of the Ada RM, and in particular sets the default
8610 scheduling policy to @code{FIFO_Within_Priorities}.
8612 @item ^-u@var{n}^/DYNAMIC_STACK_USAGE=@var{n}^
8613 @cindex @option{^-u^/DYNAMIC_STACK_USAGE^} (@code{gnatbind})
8614 Enable dynamic stack usage, with @var{n} results stored and displayed
8615 at program termination. A result is generated when a task
8616 terminates. Results that can't be stored are displayed on the fly, at
8617 task termination. This option is currently not supported on Itanium
8618 platforms. (See @ref{Dynamic Stack Usage Analysis} for details.)
8620 @item ^-v^/REPORT_ERRORS=VERBOSE^
8621 @cindex @option{^-v^/REPORT_ERRORS=VERBOSE^} (@code{gnatbind})
8622 Verbose mode. Write error messages, header, summary output to
8627 @cindex @option{-w} (@code{gnatbind})
8628 Warning mode (@var{x}=s/e for suppress/treat as error)
8632 @item /WARNINGS=NORMAL
8633 @cindex @option{/WARNINGS} (@code{gnatbind})
8634 Normal warnings mode. Warnings are issued but ignored
8636 @item /WARNINGS=SUPPRESS
8637 @cindex @option{/WARNINGS} (@code{gnatbind})
8638 All warning messages are suppressed
8640 @item /WARNINGS=ERROR
8641 @cindex @option{/WARNINGS} (@code{gnatbind})
8642 Warning messages are treated as fatal errors
8645 @item ^-Wx^/WIDE_CHARACTER_ENCODING=^@var{e}
8646 @cindex @option{^-Wx^/WIDE_CHARACTER_ENCODING^} (@code{gnatbind})
8647 Override default wide character encoding for standard Text_IO files.
8649 @item ^-x^/READ_SOURCES=NONE^
8650 @cindex @option{^-x^/READ_SOURCES^} (@code{gnatbind})
8651 Exclude source files (check object consistency only).
8654 @item /READ_SOURCES=AVAILABLE
8655 @cindex @option{/READ_SOURCES} (@code{gnatbind})
8656 Default mode, in which sources are checked for consistency only if
8660 @item ^-X@var{nnn}^/RETURN_CODES=POSIX^
8661 @cindex @option{^-X@var{nnn}^/RETURN_CODES=POSIX^} (@code{gnatbind})
8662 Set default exit status value, normally 0 for POSIX compliance.
8665 @item /RETURN_CODES=VMS
8666 @cindex @option{/RETURN_CODES=VMS} (@code{gnatbind})
8667 VMS default normal successful return value is 1.
8670 @item ^-y^/ENABLE_LEAP_SECONDS^
8671 @cindex @option{^-y^/ENABLE_LEAP_SECONDS^} (@code{gnatbind})
8672 Enable leap seconds support in @code{Ada.Calendar} and its children.
8674 @item ^-z^/ZERO_MAIN^
8675 @cindex @option{^-z^/ZERO_MAIN^} (@code{gnatbind})
8681 You may obtain this listing of switches by running @code{gnatbind} with
8685 @node Consistency-Checking Modes
8686 @subsection Consistency-Checking Modes
8689 As described earlier, by default @code{gnatbind} checks
8690 that object files are consistent with one another and are consistent
8691 with any source files it can locate. The following switches control binder
8696 @item ^-s^/READ_SOURCES=ALL^
8697 @cindex @option{^-s^/READ_SOURCES=ALL^} (@code{gnatbind})
8698 Require source files to be present. In this mode, the binder must be
8699 able to locate all source files that are referenced, in order to check
8700 their consistency. In normal mode, if a source file cannot be located it
8701 is simply ignored. If you specify this switch, a missing source
8704 @item ^-Wx^/WIDE_CHARACTER_ENCODING=^@var{e}
8705 @cindex @option{^-Wx^/WIDE_CHARACTER_ENCODING^} (@code{gnatbind})
8706 Override default wide character encoding for standard Text_IO files.
8707 Normally the default wide character encoding method used for standard
8708 [Wide_[Wide_]]Text_IO files is taken from the encoding specified for
8709 the main source input (see description of switch
8710 @option{^-gnatWx^/WIDE_CHARACTER_ENCODING^} for the compiler). The
8711 use of this switch for the binder (which has the same set of
8712 possible arguments) overrides this default as specified.
8714 @item ^-x^/READ_SOURCES=NONE^
8715 @cindex @option{^-x^/READ_SOURCES=NONE^} (@code{gnatbind})
8716 Exclude source files. In this mode, the binder only checks that ALI
8717 files are consistent with one another. Source files are not accessed.
8718 The binder runs faster in this mode, and there is still a guarantee that
8719 the resulting program is self-consistent.
8720 If a source file has been edited since it was last compiled, and you
8721 specify this switch, the binder will not detect that the object
8722 file is out of date with respect to the source file. Note that this is the
8723 mode that is automatically used by @command{gnatmake} because in this
8724 case the checking against sources has already been performed by
8725 @command{gnatmake} in the course of compilation (i.e.@: before binding).
8728 @item /READ_SOURCES=AVAILABLE
8729 @cindex @code{/READ_SOURCES=AVAILABLE} (@code{gnatbind})
8730 This is the default mode in which source files are checked if they are
8731 available, and ignored if they are not available.
8735 @node Binder Error Message Control
8736 @subsection Binder Error Message Control
8739 The following switches provide control over the generation of error
8740 messages from the binder:
8744 @item ^-v^/REPORT_ERRORS=VERBOSE^
8745 @cindex @option{^-v^/REPORT_ERRORS=VERBOSE^} (@code{gnatbind})
8746 Verbose mode. In the normal mode, brief error messages are generated to
8747 @file{stderr}. If this switch is present, a header is written
8748 to @file{stdout} and any error messages are directed to @file{stdout}.
8749 All that is written to @file{stderr} is a brief summary message.
8751 @item ^-b^/REPORT_ERRORS=BRIEF^
8752 @cindex @option{^-b^/REPORT_ERRORS=BRIEF^} (@code{gnatbind})
8753 Generate brief error messages to @file{stderr} even if verbose mode is
8754 specified. This is relevant only when used with the
8755 @option{^-v^/REPORT_ERRORS=VERBOSE^} switch.
8759 @cindex @option{-m} (@code{gnatbind})
8760 Limits the number of error messages to @var{n}, a decimal integer in the
8761 range 1-999. The binder terminates immediately if this limit is reached.
8764 @cindex @option{-M} (@code{gnatbind})
8765 Renames the generated main program from @code{main} to @code{xxx}.
8766 This is useful in the case of some cross-building environments, where
8767 the actual main program is separate from the one generated
8771 @item ^-ws^/WARNINGS=SUPPRESS^
8772 @cindex @option{^-ws^/WARNINGS=SUPPRESS^} (@code{gnatbind})
8774 Suppress all warning messages.
8776 @item ^-we^/WARNINGS=ERROR^
8777 @cindex @option{^-we^/WARNINGS=ERROR^} (@code{gnatbind})
8778 Treat any warning messages as fatal errors.
8781 @item /WARNINGS=NORMAL
8782 Standard mode with warnings generated, but warnings do not get treated
8786 @item ^-t^/NOTIME_STAMP_CHECK^
8787 @cindex @option{^-t^/NOTIME_STAMP_CHECK^} (@code{gnatbind})
8788 @cindex Time stamp checks, in binder
8789 @cindex Binder consistency checks
8790 @cindex Consistency checks, in binder
8791 The binder performs a number of consistency checks including:
8795 Check that time stamps of a given source unit are consistent
8797 Check that checksums of a given source unit are consistent
8799 Check that consistent versions of @code{GNAT} were used for compilation
8801 Check consistency of configuration pragmas as required
8805 Normally failure of such checks, in accordance with the consistency
8806 requirements of the Ada Reference Manual, causes error messages to be
8807 generated which abort the binder and prevent the output of a binder
8808 file and subsequent link to obtain an executable.
8810 The @option{^-t^/NOTIME_STAMP_CHECK^} switch converts these error messages
8811 into warnings, so that
8812 binding and linking can continue to completion even in the presence of such
8813 errors. The result may be a failed link (due to missing symbols), or a
8814 non-functional executable which has undefined semantics.
8815 @emph{This means that
8816 @option{^-t^/NOTIME_STAMP_CHECK^} should be used only in unusual situations,
8820 @node Elaboration Control
8821 @subsection Elaboration Control
8824 The following switches provide additional control over the elaboration
8825 order. For full details see @ref{Elaboration Order Handling in GNAT}.
8828 @item ^-p^/PESSIMISTIC_ELABORATION^
8829 @cindex @option{^-p^/PESSIMISTIC_ELABORATION^} (@code{gnatbind})
8830 Normally the binder attempts to choose an elaboration order that is
8831 likely to minimize the likelihood of an elaboration order error resulting
8832 in raising a @code{Program_Error} exception. This switch reverses the
8833 action of the binder, and requests that it deliberately choose an order
8834 that is likely to maximize the likelihood of an elaboration error.
8835 This is useful in ensuring portability and avoiding dependence on
8836 accidental fortuitous elaboration ordering.
8838 Normally it only makes sense to use the @option{^-p^/PESSIMISTIC_ELABORATION^}
8840 elaboration checking is used (@option{-gnatE} switch used for compilation).
8841 This is because in the default static elaboration mode, all necessary
8842 @code{Elaborate} and @code{Elaborate_All} pragmas are implicitly inserted.
8843 These implicit pragmas are still respected by the binder in
8844 @option{^-p^/PESSIMISTIC_ELABORATION^} mode, so a
8845 safe elaboration order is assured.
8847 Note that @option{^-p^/PESSIMISTIC_ELABORATION^} is not intended for
8848 production use; it is more for debugging/experimental use.
8851 @node Output Control
8852 @subsection Output Control
8855 The following switches allow additional control over the output
8856 generated by the binder.
8861 @item ^-c^/NOOUTPUT^
8862 @cindex @option{^-c^/NOOUTPUT^} (@code{gnatbind})
8863 Check only. Do not generate the binder output file. In this mode the
8864 binder performs all error checks but does not generate an output file.
8866 @item ^-e^/ELABORATION_DEPENDENCIES^
8867 @cindex @option{^-e^/ELABORATION_DEPENDENCIES^} (@code{gnatbind})
8868 Output complete list of elaboration-order dependencies, showing the
8869 reason for each dependency. This output can be rather extensive but may
8870 be useful in diagnosing problems with elaboration order. The output is
8871 written to @file{stdout}.
8874 @cindex @option{^-h^/HELP^} (@code{gnatbind})
8875 Output usage information. The output is written to @file{stdout}.
8877 @item ^-K^/LINKER_OPTION_LIST^
8878 @cindex @option{^-K^/LINKER_OPTION_LIST^} (@code{gnatbind})
8879 Output linker options to @file{stdout}. Includes library search paths,
8880 contents of pragmas Ident and Linker_Options, and libraries added
8883 @item ^-l^/ORDER_OF_ELABORATION^
8884 @cindex @option{^-l^/ORDER_OF_ELABORATION^} (@code{gnatbind})
8885 Output chosen elaboration order. The output is written to @file{stdout}.
8887 @item ^-O^/OBJECT_LIST^
8888 @cindex @option{^-O^/OBJECT_LIST^} (@code{gnatbind})
8889 Output full names of all the object files that must be linked to provide
8890 the Ada component of the program. The output is written to @file{stdout}.
8891 This list includes the files explicitly supplied and referenced by the user
8892 as well as implicitly referenced run-time unit files. The latter are
8893 omitted if the corresponding units reside in shared libraries. The
8894 directory names for the run-time units depend on the system configuration.
8896 @item ^-o ^/OUTPUT=^@var{file}
8897 @cindex @option{^-o^/OUTPUT^} (@code{gnatbind})
8898 Set name of output file to @var{file} instead of the normal
8899 @file{b~@var{mainprog}.adb} default. Note that @var{file} denote the Ada
8900 binder generated body filename.
8901 Note that if this option is used, then linking must be done manually.
8902 It is not possible to use gnatlink in this case, since it cannot locate
8905 @item ^-r^/RESTRICTION_LIST^
8906 @cindex @option{^-r^/RESTRICTION_LIST^} (@code{gnatbind})
8907 Generate list of @code{pragma Restrictions} that could be applied to
8908 the current unit. This is useful for code audit purposes, and also may
8909 be used to improve code generation in some cases.
8913 @node Dynamic Allocation Control
8914 @subsection Dynamic Allocation Control
8917 The heap control switches -- @option{-H32} and @option{-H64} --
8918 determine whether dynamic allocation uses 32-bit or 64-bit memory.
8919 They only affect compiler-generated allocations via @code{__gnat_malloc};
8920 explicit calls to @code{malloc} and related functions from the C
8921 run-time library are unaffected.
8925 Allocate memory on 32-bit heap
8928 Allocate memory on 64-bit heap. This is the default
8929 unless explicitly overridden by a @code{'Size} clause on the access type.
8934 See also @ref{Access types and 32/64-bit allocation}.
8938 These switches are only effective on VMS platforms.
8942 @node Binding with Non-Ada Main Programs
8943 @subsection Binding with Non-Ada Main Programs
8946 In our description so far we have assumed that the main
8947 program is in Ada, and that the task of the binder is to generate a
8948 corresponding function @code{main} that invokes this Ada main
8949 program. GNAT also supports the building of executable programs where
8950 the main program is not in Ada, but some of the called routines are
8951 written in Ada and compiled using GNAT (@pxref{Mixed Language Programming}).
8952 The following switch is used in this situation:
8956 @cindex @option{^-n^/NOMAIN^} (@code{gnatbind})
8957 No main program. The main program is not in Ada.
8961 In this case, most of the functions of the binder are still required,
8962 but instead of generating a main program, the binder generates a file
8963 containing the following callable routines:
8968 You must call this routine to initialize the Ada part of the program by
8969 calling the necessary elaboration routines. A call to @code{adainit} is
8970 required before the first call to an Ada subprogram.
8972 Note that it is assumed that the basic execution environment must be setup
8973 to be appropriate for Ada execution at the point where the first Ada
8974 subprogram is called. In particular, if the Ada code will do any
8975 floating-point operations, then the FPU must be setup in an appropriate
8976 manner. For the case of the x86, for example, full precision mode is
8977 required. The procedure GNAT.Float_Control.Reset may be used to ensure
8978 that the FPU is in the right state.
8982 You must call this routine to perform any library-level finalization
8983 required by the Ada subprograms. A call to @code{adafinal} is required
8984 after the last call to an Ada subprogram, and before the program
8989 If the @option{^-n^/NOMAIN^} switch
8990 @cindex @option{^-n^/NOMAIN^} (@command{gnatbind})
8991 @cindex Binder, multiple input files
8992 is given, more than one ALI file may appear on
8993 the command line for @code{gnatbind}. The normal @dfn{closure}
8994 calculation is performed for each of the specified units. Calculating
8995 the closure means finding out the set of units involved by tracing
8996 @code{with} references. The reason it is necessary to be able to
8997 specify more than one ALI file is that a given program may invoke two or
8998 more quite separate groups of Ada units.
9000 The binder takes the name of its output file from the last specified ALI
9001 file, unless overridden by the use of the @option{^-o file^/OUTPUT=file^}.
9002 @cindex @option{^-o^/OUTPUT^} (@command{gnatbind})
9003 The output is an Ada unit in source form that can be compiled with GNAT.
9004 This compilation occurs automatically as part of the @command{gnatlink}
9007 Currently the GNAT run time requires a FPU using 80 bits mode
9008 precision. Under targets where this is not the default it is required to
9009 call GNAT.Float_Control.Reset before using floating point numbers (this
9010 include float computation, float input and output) in the Ada code. A
9011 side effect is that this could be the wrong mode for the foreign code
9012 where floating point computation could be broken after this call.
9014 @node Binding Programs with No Main Subprogram
9015 @subsection Binding Programs with No Main Subprogram
9018 It is possible to have an Ada program which does not have a main
9019 subprogram. This program will call the elaboration routines of all the
9020 packages, then the finalization routines.
9022 The following switch is used to bind programs organized in this manner:
9025 @item ^-z^/ZERO_MAIN^
9026 @cindex @option{^-z^/ZERO_MAIN^} (@code{gnatbind})
9027 Normally the binder checks that the unit name given on the command line
9028 corresponds to a suitable main subprogram. When this switch is used,
9029 a list of ALI files can be given, and the execution of the program
9030 consists of elaboration of these units in an appropriate order. Note
9031 that the default wide character encoding method for standard Text_IO
9032 files is always set to Brackets if this switch is set (you can use
9034 @option{^-Wx^WIDE_CHARACTER_ENCODING^} to override this default).
9037 @node Command-Line Access
9038 @section Command-Line Access
9041 The package @code{Ada.Command_Line} provides access to the command-line
9042 arguments and program name. In order for this interface to operate
9043 correctly, the two variables
9055 are declared in one of the GNAT library routines. These variables must
9056 be set from the actual @code{argc} and @code{argv} values passed to the
9057 main program. With no @option{^n^/NOMAIN^} present, @code{gnatbind}
9058 generates the C main program to automatically set these variables.
9059 If the @option{^n^/NOMAIN^} switch is used, there is no automatic way to
9060 set these variables. If they are not set, the procedures in
9061 @code{Ada.Command_Line} will not be available, and any attempt to use
9062 them will raise @code{Constraint_Error}. If command line access is
9063 required, your main program must set @code{gnat_argc} and
9064 @code{gnat_argv} from the @code{argc} and @code{argv} values passed to
9067 @node Search Paths for gnatbind
9068 @section Search Paths for @code{gnatbind}
9071 The binder takes the name of an ALI file as its argument and needs to
9072 locate source files as well as other ALI files to verify object consistency.
9074 For source files, it follows exactly the same search rules as @command{gcc}
9075 (@pxref{Search Paths and the Run-Time Library (RTL)}). For ALI files the
9076 directories searched are:
9080 The directory containing the ALI file named in the command line, unless
9081 the switch @option{^-I-^/NOCURRENT_DIRECTORY^} is specified.
9084 All directories specified by @option{^-I^/SEARCH^}
9085 switches on the @code{gnatbind}
9086 command line, in the order given.
9089 @findex ADA_PRJ_OBJECTS_FILE
9090 Each of the directories listed in the text file whose name is given
9091 by the @env{ADA_PRJ_OBJECTS_FILE} ^environment variable^logical name^.
9094 @env{ADA_PRJ_OBJECTS_FILE} is normally set by gnatmake or by the ^gnat^GNAT^
9095 driver when project files are used. It should not normally be set
9099 @findex ADA_OBJECTS_PATH
9100 Each of the directories listed in the value of the
9101 @env{ADA_OBJECTS_PATH} ^environment variable^logical name^.
9103 Construct this value
9104 exactly as the @env{PATH} environment variable: a list of directory
9105 names separated by colons (semicolons when working with the NT version
9109 Normally, define this value as a logical name containing a comma separated
9110 list of directory names.
9112 This variable can also be defined by means of an environment string
9113 (an argument to the HP C exec* set of functions).
9117 DEFINE ANOTHER_PATH FOO:[BAG]
9118 DEFINE ADA_OBJECTS_PATH ANOTHER_PATH,FOO:[BAM],FOO:[BAR]
9121 By default, the path includes GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB]
9122 first, followed by the standard Ada
9123 libraries in GNU:[LIB.OPENVMS7_x.2_8_x.ADALIB].
9124 If this is not redefined, the user will obtain the HP Ada 83 IO packages
9125 (Text_IO, Sequential_IO, etc)
9126 instead of the standard Ada packages. Thus, in order to get the standard Ada
9127 packages by default, ADA_OBJECTS_PATH must be redefined.
9131 The content of the @file{ada_object_path} file which is part of the GNAT
9132 installation tree and is used to store standard libraries such as the
9133 GNAT Run Time Library (RTL) unless the switch @option{-nostdlib} is
9136 @ref{Installing a library}
9141 In the binder the switch @option{^-I^/SEARCH^}
9142 @cindex @option{^-I^/SEARCH^} (@command{gnatbind})
9143 is used to specify both source and
9144 library file paths. Use @option{^-aI^/SOURCE_SEARCH^}
9145 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatbind})
9146 instead if you want to specify
9147 source paths only, and @option{^-aO^/LIBRARY_SEARCH^}
9148 @cindex @option{^-aO^/LIBRARY_SEARCH^} (@command{gnatbind})
9149 if you want to specify library paths
9150 only. This means that for the binder
9151 @option{^-I^/SEARCH=^}@var{dir} is equivalent to
9152 @option{^-aI^/SOURCE_SEARCH=^}@var{dir}
9153 @option{^-aO^/OBJECT_SEARCH=^}@var{dir}.
9154 The binder generates the bind file (a C language source file) in the
9155 current working directory.
9161 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
9162 children make up the GNAT Run-Time Library, together with the package
9163 GNAT and its children, which contain a set of useful additional
9164 library functions provided by GNAT. The sources for these units are
9165 needed by the compiler and are kept together in one directory. The ALI
9166 files and object files generated by compiling the RTL are needed by the
9167 binder and the linker and are kept together in one directory, typically
9168 different from the directory containing the sources. In a normal
9169 installation, you need not specify these directory names when compiling
9170 or binding. Either the environment variables or the built-in defaults
9171 cause these files to be found.
9173 Besides simplifying access to the RTL, a major use of search paths is
9174 in compiling sources from multiple directories. This can make
9175 development environments much more flexible.
9177 @node Examples of gnatbind Usage
9178 @section Examples of @code{gnatbind} Usage
9181 This section contains a number of examples of using the GNAT binding
9182 utility @code{gnatbind}.
9185 @item gnatbind hello
9186 The main program @code{Hello} (source program in @file{hello.adb}) is
9187 bound using the standard switch settings. The generated main program is
9188 @file{b~hello.adb}. This is the normal, default use of the binder.
9191 @item gnatbind hello -o mainprog.adb
9194 @item gnatbind HELLO.ALI /OUTPUT=Mainprog.ADB
9196 The main program @code{Hello} (source program in @file{hello.adb}) is
9197 bound using the standard switch settings. The generated main program is
9198 @file{mainprog.adb} with the associated spec in
9199 @file{mainprog.ads}. Note that you must specify the body here not the
9200 spec. Note that if this option is used, then linking must be done manually,
9201 since gnatlink will not be able to find the generated file.
9204 @c ------------------------------------
9205 @node Linking with gnatlink
9206 @chapter Linking with @command{gnatlink}
9207 @c ------------------------------------
9211 This chapter discusses @command{gnatlink}, a tool that links
9212 an Ada program and builds an executable file. This utility
9213 invokes the system linker ^(via the @command{gcc} command)^^
9214 with a correct list of object files and library references.
9215 @command{gnatlink} automatically determines the list of files and
9216 references for the Ada part of a program. It uses the binder file
9217 generated by the @command{gnatbind} to determine this list.
9219 Note: to invoke @code{gnatlink} with a project file, use the @code{gnat}
9220 driver (see @ref{The GNAT Driver and Project Files}).
9223 * Running gnatlink::
9224 * Switches for gnatlink::
9227 @node Running gnatlink
9228 @section Running @command{gnatlink}
9231 The form of the @command{gnatlink} command is
9234 @c $ gnatlink @ovar{switches} @var{mainprog}@r{[}.ali@r{]}
9235 @c @ovar{non-Ada objects} @ovar{linker options}
9236 @c Expanding @ovar macro inline (explanation in macro def comments)
9237 $ gnatlink @r{[}@var{switches}@r{]} @var{mainprog}@r{[}.ali@r{]}
9238 @r{[}@var{non-Ada objects}@r{]} @r{[}@var{linker options}@r{]}
9243 The arguments of @command{gnatlink} (switches, main @file{ALI} file,
9245 or linker options) may be in any order, provided that no non-Ada object may
9246 be mistaken for a main @file{ALI} file.
9247 Any file name @file{F} without the @file{.ali}
9248 extension will be taken as the main @file{ALI} file if a file exists
9249 whose name is the concatenation of @file{F} and @file{.ali}.
9252 @file{@var{mainprog}.ali} references the ALI file of the main program.
9253 The @file{.ali} extension of this file can be omitted. From this
9254 reference, @command{gnatlink} locates the corresponding binder file
9255 @file{b~@var{mainprog}.adb} and, using the information in this file along
9256 with the list of non-Ada objects and linker options, constructs a
9257 linker command file to create the executable.
9259 The arguments other than the @command{gnatlink} switches and the main
9260 @file{ALI} file are passed to the linker uninterpreted.
9261 They typically include the names of
9262 object files for units written in other languages than Ada and any library
9263 references required to resolve references in any of these foreign language
9264 units, or in @code{Import} pragmas in any Ada units.
9266 @var{linker options} is an optional list of linker specific
9268 The default linker called by gnatlink is @command{gcc} which in
9269 turn calls the appropriate system linker.
9271 One useful option for the linker is @option{-s}: it reduces the size of the
9272 executable by removing all symbol table and relocation information from the
9275 Standard options for the linker such as @option{-lmy_lib} or
9276 @option{-Ldir} can be added as is.
9277 For options that are not recognized by
9278 @command{gcc} as linker options, use the @command{gcc} switches
9279 @option{-Xlinker} or @option{-Wl,}.
9281 Refer to the GCC documentation for
9284 Here is an example showing how to generate a linker map:
9287 $ ^gnatlink my_prog -Wl,-Map,MAPFILE^GNAT LINK my_prog.ali /MAP^
9290 Using @var{linker options} it is possible to set the program stack and
9293 See @ref{Setting Stack Size from gnatlink} and
9294 @ref{Setting Heap Size from gnatlink}.
9297 @command{gnatlink} determines the list of objects required by the Ada
9298 program and prepends them to the list of objects passed to the linker.
9299 @command{gnatlink} also gathers any arguments set by the use of
9300 @code{pragma Linker_Options} and adds them to the list of arguments
9301 presented to the linker.
9304 @command{gnatlink} accepts the following types of extra files on the command
9305 line: objects (@file{.OBJ}), libraries (@file{.OLB}), sharable images
9306 (@file{.EXE}), and options files (@file{.OPT}). These are recognized and
9307 handled according to their extension.
9310 @node Switches for gnatlink
9311 @section Switches for @command{gnatlink}
9314 The following switches are available with the @command{gnatlink} utility:
9320 @cindex @option{--version} @command{gnatlink}
9321 Display Copyright and version, then exit disregarding all other options.
9324 @cindex @option{--help} @command{gnatlink}
9325 If @option{--version} was not used, display usage, then exit disregarding
9328 @item ^-f^/FORCE_OBJECT_FILE_LIST^
9329 @cindex Command line length
9330 @cindex @option{^-f^/FORCE_OBJECT_FILE_LIST^} (@command{gnatlink})
9331 On some targets, the command line length is limited, and @command{gnatlink}
9332 will generate a separate file for the linker if the list of object files
9334 The @option{^-f^/FORCE_OBJECT_FILE_LIST^} switch forces this file
9335 to be generated even if
9336 the limit is not exceeded. This is useful in some cases to deal with
9337 special situations where the command line length is exceeded.
9340 @cindex Debugging information, including
9341 @cindex @option{^-g^/DEBUG^} (@command{gnatlink})
9342 The option to include debugging information causes the Ada bind file (in
9343 other words, @file{b~@var{mainprog}.adb}) to be compiled with
9344 @option{^-g^/DEBUG^}.
9345 In addition, the binder does not delete the @file{b~@var{mainprog}.adb},
9346 @file{b~@var{mainprog}.o} and @file{b~@var{mainprog}.ali} files.
9347 Without @option{^-g^/DEBUG^}, the binder removes these files by
9348 default. The same procedure apply if a C bind file was generated using
9349 @option{^-C^/BIND_FILE=C^} @code{gnatbind} option, in this case the filenames
9350 are @file{b_@var{mainprog}.c} and @file{b_@var{mainprog}.o}.
9352 @item ^-n^/NOCOMPILE^
9353 @cindex @option{^-n^/NOCOMPILE^} (@command{gnatlink})
9354 Do not compile the file generated by the binder. This may be used when
9355 a link is rerun with different options, but there is no need to recompile
9359 @cindex @option{^-v^/VERBOSE^} (@command{gnatlink})
9360 Causes additional information to be output, including a full list of the
9361 included object files. This switch option is most useful when you want
9362 to see what set of object files are being used in the link step.
9364 @item ^-v -v^/VERBOSE/VERBOSE^
9365 @cindex @option{^-v -v^/VERBOSE/VERBOSE^} (@command{gnatlink})
9366 Very verbose mode. Requests that the compiler operate in verbose mode when
9367 it compiles the binder file, and that the system linker run in verbose mode.
9369 @item ^-o ^/EXECUTABLE=^@var{exec-name}
9370 @cindex @option{^-o^/EXECUTABLE^} (@command{gnatlink})
9371 @var{exec-name} specifies an alternate name for the generated
9372 executable program. If this switch is omitted, the executable has the same
9373 name as the main unit. For example, @code{gnatlink try.ali} creates
9374 an executable called @file{^try^TRY.EXE^}.
9377 @item -b @var{target}
9378 @cindex @option{-b} (@command{gnatlink})
9379 Compile your program to run on @var{target}, which is the name of a
9380 system configuration. You must have a GNAT cross-compiler built if
9381 @var{target} is not the same as your host system.
9384 @cindex @option{-B} (@command{gnatlink})
9385 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
9386 from @var{dir} instead of the default location. Only use this switch
9387 when multiple versions of the GNAT compiler are available.
9388 @xref{Directory Options,,, gcc, The GNU Compiler Collection},
9389 for further details. You would normally use the @option{-b} or
9390 @option{-V} switch instead.
9393 When linking an executable, create a map file. The name of the map file
9394 has the same name as the executable with extension ".map".
9397 When linking an executable, create a map file. The name of the map file is
9400 @item --GCC=@var{compiler_name}
9401 @cindex @option{--GCC=compiler_name} (@command{gnatlink})
9402 Program used for compiling the binder file. The default is
9403 @command{gcc}. You need to use quotes around @var{compiler_name} if
9404 @code{compiler_name} contains spaces or other separator characters.
9405 As an example @option{--GCC="foo -x -y"} will instruct @command{gnatlink} to
9406 use @code{foo -x -y} as your compiler. Note that switch @option{-c} is always
9407 inserted after your command name. Thus in the above example the compiler
9408 command that will be used by @command{gnatlink} will be @code{foo -c -x -y}.
9409 A limitation of this syntax is that the name and path name of the executable
9410 itself must not include any embedded spaces. If the compiler executable is
9411 different from the default one (gcc or <prefix>-gcc), then the back-end
9412 switches in the ALI file are not used to compile the binder generated source.
9413 For example, this is the case with @option{--GCC="foo -x -y"}. But the back end
9414 switches will be used for @option{--GCC="gcc -gnatv"}. If several
9415 @option{--GCC=compiler_name} are used, only the last @var{compiler_name}
9416 is taken into account. However, all the additional switches are also taken
9418 @option{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
9419 @option{--GCC="bar -x -y -z -t"}.
9421 @item --LINK=@var{name}
9422 @cindex @option{--LINK=} (@command{gnatlink})
9423 @var{name} is the name of the linker to be invoked. This is especially
9424 useful in mixed language programs since languages such as C++ require
9425 their own linker to be used. When this switch is omitted, the default
9426 name for the linker is @command{gcc}. When this switch is used, the
9427 specified linker is called instead of @command{gcc} with exactly the same
9428 parameters that would have been passed to @command{gcc} so if the desired
9429 linker requires different parameters it is necessary to use a wrapper
9430 script that massages the parameters before invoking the real linker. It
9431 may be useful to control the exact invocation by using the verbose
9437 @item /DEBUG=TRACEBACK
9438 @cindex @code{/DEBUG=TRACEBACK} (@command{gnatlink})
9439 This qualifier causes sufficient information to be included in the
9440 executable file to allow a traceback, but does not include the full
9441 symbol information needed by the debugger.
9443 @item /IDENTIFICATION="<string>"
9444 @code{"<string>"} specifies the string to be stored in the image file
9445 identification field in the image header.
9446 It overrides any pragma @code{Ident} specified string.
9448 @item /NOINHIBIT-EXEC
9449 Generate the executable file even if there are linker warnings.
9451 @item /NOSTART_FILES
9452 Don't link in the object file containing the ``main'' transfer address.
9453 Used when linking with a foreign language main program compiled with an
9457 Prefer linking with object libraries over sharable images, even without
9463 @node The GNAT Make Program gnatmake
9464 @chapter The GNAT Make Program @command{gnatmake}
9468 * Running gnatmake::
9469 * Switches for gnatmake::
9470 * Mode Switches for gnatmake::
9471 * Notes on the Command Line::
9472 * How gnatmake Works::
9473 * Examples of gnatmake Usage::
9476 A typical development cycle when working on an Ada program consists of
9477 the following steps:
9481 Edit some sources to fix bugs.
9487 Compile all sources affected.
9497 The third step can be tricky, because not only do the modified files
9498 @cindex Dependency rules
9499 have to be compiled, but any files depending on these files must also be
9500 recompiled. The dependency rules in Ada can be quite complex, especially
9501 in the presence of overloading, @code{use} clauses, generics and inlined
9504 @command{gnatmake} automatically takes care of the third and fourth steps
9505 of this process. It determines which sources need to be compiled,
9506 compiles them, and binds and links the resulting object files.
9508 Unlike some other Ada make programs, the dependencies are always
9509 accurately recomputed from the new sources. The source based approach of
9510 the GNAT compilation model makes this possible. This means that if
9511 changes to the source program cause corresponding changes in
9512 dependencies, they will always be tracked exactly correctly by
9515 @node Running gnatmake
9516 @section Running @command{gnatmake}
9519 The usual form of the @command{gnatmake} command is
9522 @c $ gnatmake @ovar{switches} @var{file_name}
9523 @c @ovar{file_names} @ovar{mode_switches}
9524 @c Expanding @ovar macro inline (explanation in macro def comments)
9525 $ gnatmake @r{[}@var{switches}@r{]} @var{file_name}
9526 @r{[}@var{file_names}@r{]} @r{[}@var{mode_switches}@r{]}
9530 The only required argument is one @var{file_name}, which specifies
9531 a compilation unit that is a main program. Several @var{file_names} can be
9532 specified: this will result in several executables being built.
9533 If @code{switches} are present, they can be placed before the first
9534 @var{file_name}, between @var{file_names} or after the last @var{file_name}.
9535 If @var{mode_switches} are present, they must always be placed after
9536 the last @var{file_name} and all @code{switches}.
9538 If you are using standard file extensions (@file{.adb} and @file{.ads}), then the
9539 extension may be omitted from the @var{file_name} arguments. However, if
9540 you are using non-standard extensions, then it is required that the
9541 extension be given. A relative or absolute directory path can be
9542 specified in a @var{file_name}, in which case, the input source file will
9543 be searched for in the specified directory only. Otherwise, the input
9544 source file will first be searched in the directory where
9545 @command{gnatmake} was invoked and if it is not found, it will be search on
9546 the source path of the compiler as described in
9547 @ref{Search Paths and the Run-Time Library (RTL)}.
9549 All @command{gnatmake} output (except when you specify
9550 @option{^-M^/DEPENDENCIES_LIST^}) is to
9551 @file{stderr}. The output produced by the
9552 @option{^-M^/DEPENDENCIES_LIST^} switch is send to
9555 @node Switches for gnatmake
9556 @section Switches for @command{gnatmake}
9559 You may specify any of the following switches to @command{gnatmake}:
9565 @cindex @option{--version} @command{gnatmake}
9566 Display Copyright and version, then exit disregarding all other options.
9569 @cindex @option{--help} @command{gnatmake}
9570 If @option{--version} was not used, display usage, then exit disregarding
9574 @item --GCC=@var{compiler_name}
9575 @cindex @option{--GCC=compiler_name} (@command{gnatmake})
9576 Program used for compiling. The default is `@command{gcc}'. You need to use
9577 quotes around @var{compiler_name} if @code{compiler_name} contains
9578 spaces or other separator characters. As an example @option{--GCC="foo -x
9579 -y"} will instruct @command{gnatmake} to use @code{foo -x -y} as your
9580 compiler. A limitation of this syntax is that the name and path name of
9581 the executable itself must not include any embedded spaces. Note that
9582 switch @option{-c} is always inserted after your command name. Thus in the
9583 above example the compiler command that will be used by @command{gnatmake}
9584 will be @code{foo -c -x -y}. If several @option{--GCC=compiler_name} are
9585 used, only the last @var{compiler_name} is taken into account. However,
9586 all the additional switches are also taken into account. Thus,
9587 @option{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
9588 @option{--GCC="bar -x -y -z -t"}.
9590 @item --GNATBIND=@var{binder_name}
9591 @cindex @option{--GNATBIND=binder_name} (@command{gnatmake})
9592 Program used for binding. The default is `@code{gnatbind}'. You need to
9593 use quotes around @var{binder_name} if @var{binder_name} contains spaces
9594 or other separator characters. As an example @option{--GNATBIND="bar -x
9595 -y"} will instruct @command{gnatmake} to use @code{bar -x -y} as your
9596 binder. Binder switches that are normally appended by @command{gnatmake}
9597 to `@code{gnatbind}' are now appended to the end of @code{bar -x -y}.
9598 A limitation of this syntax is that the name and path name of the executable
9599 itself must not include any embedded spaces.
9601 @item --GNATLINK=@var{linker_name}
9602 @cindex @option{--GNATLINK=linker_name} (@command{gnatmake})
9603 Program used for linking. The default is `@command{gnatlink}'. You need to
9604 use quotes around @var{linker_name} if @var{linker_name} contains spaces
9605 or other separator characters. As an example @option{--GNATLINK="lan -x
9606 -y"} will instruct @command{gnatmake} to use @code{lan -x -y} as your
9607 linker. Linker switches that are normally appended by @command{gnatmake} to
9608 `@command{gnatlink}' are now appended to the end of @code{lan -x -y}.
9609 A limitation of this syntax is that the name and path name of the executable
9610 itself must not include any embedded spaces.
9614 @item ^--subdirs^/SUBDIRS^=subdir
9615 Actual object directory of each project file is the subdirectory subdir of the
9616 object directory specified or defaulted in the project file.
9618 @item ^--single-compile-per-obj-dir^/SINGLE_COMPILE_PER_OBJ_DIR^
9619 Disallow simultaneous compilations in the same object directory when
9620 project files are used.
9622 @item ^--unchecked-shared-lib-imports^/UNCHECKED_SHARED_LIB_IMPORTS^
9623 By default, shared library projects are not allowed to import static library
9624 projects. When this switch is used on the command line, this restriction is
9627 @item ^--source-info=<source info file>^/SRC_INFO=source-info-file^
9628 Specify a source info file. This switch is active only when project files
9629 are used. If the source info file is specified as a relative path, then it is
9630 relative to the object directory of the main project. If the source info file
9631 does not exist, then after the Project Manager has successfully parsed and
9632 processed the project files and found the sources, it creates the source info
9633 file. If the source info file already exists and can be read successfully,
9634 then the Project Manager will get all the needed information about the sources
9635 from the source info file and will not look for them. This reduces the time
9636 to process the project files, especially when looking for sources that take a
9637 long time. If the source info file exists but cannot be parsed successfully,
9638 the Project Manager will attempt to recreate it. If the Project Manager fails
9639 to create the source info file, a message is issued, but gnatmake does not
9640 fail. @command{gnatmake} "trusts" the source info file. This means that
9641 if the source files have changed (addition, deletion, moving to a different
9642 source directory), then the source info file need to be deleted and recreated.
9645 @item --create-map-file
9646 When linking an executable, create a map file. The name of the map file
9647 has the same name as the executable with extension ".map".
9649 @item --create-map-file=mapfile
9650 When linking an executable, create a map file. The name of the map file is
9655 @item ^-a^/ALL_FILES^
9656 @cindex @option{^-a^/ALL_FILES^} (@command{gnatmake})
9657 Consider all files in the make process, even the GNAT internal system
9658 files (for example, the predefined Ada library files), as well as any
9659 locked files. Locked files are files whose ALI file is write-protected.
9661 @command{gnatmake} does not check these files,
9662 because the assumption is that the GNAT internal files are properly up
9663 to date, and also that any write protected ALI files have been properly
9664 installed. Note that if there is an installation problem, such that one
9665 of these files is not up to date, it will be properly caught by the
9667 You may have to specify this switch if you are working on GNAT
9668 itself. The switch @option{^-a^/ALL_FILES^} is also useful
9669 in conjunction with @option{^-f^/FORCE_COMPILE^}
9670 if you need to recompile an entire application,
9671 including run-time files, using special configuration pragmas,
9672 such as a @code{Normalize_Scalars} pragma.
9675 @code{gnatmake ^-a^/ALL_FILES^} compiles all GNAT
9678 @code{gcc -c -gnatpg} rather than @code{gcc -c}.
9681 the @code{/CHECKS=SUPPRESS_ALL /STYLE_CHECKS=GNAT} switch.
9684 @item ^-b^/ACTIONS=BIND^
9685 @cindex @option{^-b^/ACTIONS=BIND^} (@command{gnatmake})
9686 Bind only. Can be combined with @option{^-c^/ACTIONS=COMPILE^} to do
9687 compilation and binding, but no link.
9688 Can be combined with @option{^-l^/ACTIONS=LINK^}
9689 to do binding and linking. When not combined with
9690 @option{^-c^/ACTIONS=COMPILE^}
9691 all the units in the closure of the main program must have been previously
9692 compiled and must be up to date. The root unit specified by @var{file_name}
9693 may be given without extension, with the source extension or, if no GNAT
9694 Project File is specified, with the ALI file extension.
9696 @item ^-c^/ACTIONS=COMPILE^
9697 @cindex @option{^-c^/ACTIONS=COMPILE^} (@command{gnatmake})
9698 Compile only. Do not perform binding, except when @option{^-b^/ACTIONS=BIND^}
9699 is also specified. Do not perform linking, except if both
9700 @option{^-b^/ACTIONS=BIND^} and
9701 @option{^-l^/ACTIONS=LINK^} are also specified.
9702 If the root unit specified by @var{file_name} is not a main unit, this is the
9703 default. Otherwise @command{gnatmake} will attempt binding and linking
9704 unless all objects are up to date and the executable is more recent than
9708 @cindex @option{^-C^/MAPPING^} (@command{gnatmake})
9709 Use a temporary mapping file. A mapping file is a way to communicate
9710 to the compiler two mappings: from unit names to file names (without
9711 any directory information) and from file names to path names (with
9712 full directory information). A mapping file can make the compiler's
9713 file searches faster, especially if there are many source directories,
9714 or the sources are read over a slow network connection. If
9715 @option{^-P^/PROJECT_FILE^} is used, a mapping file is always used, so
9716 @option{^-C^/MAPPING^} is unnecessary; in this case the mapping file
9717 is initially populated based on the project file. If
9718 @option{^-C^/MAPPING^} is used without
9719 @option{^-P^/PROJECT_FILE^},
9720 the mapping file is initially empty. Each invocation of the compiler
9721 will add any newly accessed sources to the mapping file.
9723 @item ^-C=^/USE_MAPPING_FILE=^@var{file}
9724 @cindex @option{^-C=^/USE_MAPPING^} (@command{gnatmake})
9725 Use a specific mapping file. The file, specified as a path name (absolute or
9726 relative) by this switch, should already exist, otherwise the switch is
9727 ineffective. The specified mapping file will be communicated to the compiler.
9728 This switch is not compatible with a project file
9729 (^-P^/PROJECT_FILE=^@var{file}) or with multiple compiling processes
9730 (^-j^/PROCESSES=^nnn, when nnn is greater than 1).
9732 @item ^-d^/DISPLAY_PROGRESS^
9733 @cindex @option{^-d^/DISPLAY_PROGRESS^} (@command{gnatmake})
9734 Display progress for each source, up to date or not, as a single line
9737 completed x out of y (zz%)
9740 If the file needs to be compiled this is displayed after the invocation of
9741 the compiler. These lines are displayed even in quiet output mode.
9743 @item ^-D ^/DIRECTORY_OBJECTS=^@var{dir}
9744 @cindex @option{^-D^/DIRECTORY_OBJECTS^} (@command{gnatmake})
9745 Put all object files and ALI file in directory @var{dir}.
9746 If the @option{^-D^/DIRECTORY_OBJECTS^} switch is not used, all object files
9747 and ALI files go in the current working directory.
9749 This switch cannot be used when using a project file.
9752 @cindex @option{-eI} (@command{gnatmake})
9753 Indicates that the main source is a multi-unit source and the rank of the unit
9754 in the source file is nnn. nnn needs to be a positive number and a valid
9755 index in the source. This switch cannot be used when @command{gnatmake} is
9756 invoked for several mains.
9760 @cindex @option{-eL} (@command{gnatmake})
9761 @cindex symbolic links
9762 Follow all symbolic links when processing project files.
9763 This should be used if your project uses symbolic links for files or
9764 directories, but is not needed in other cases.
9766 @cindex naming scheme
9767 This also assumes that no directory matches the naming scheme for files (for
9768 instance that you do not have a directory called "sources.ads" when using the
9769 default GNAT naming scheme).
9771 When you do not have to use this switch (i.e.@: by default), gnatmake is able to
9772 save a lot of system calls (several per source file and object file), which
9773 can result in a significant speed up to load and manipulate a project file,
9774 especially when using source files from a remote system.
9778 @item ^-eS^/STANDARD_OUTPUT_FOR_COMMANDS^
9779 @cindex @option{^-eS^/STANDARD_OUTPUT_FOR_COMMANDS^} (@command{gnatmake})
9780 Output the commands for the compiler, the binder and the linker
9781 on ^standard output^SYS$OUTPUT^,
9782 instead of ^standard error^SYS$ERROR^.
9784 @item ^-f^/FORCE_COMPILE^
9785 @cindex @option{^-f^/FORCE_COMPILE^} (@command{gnatmake})
9786 Force recompilations. Recompile all sources, even though some object
9787 files may be up to date, but don't recompile predefined or GNAT internal
9788 files or locked files (files with a write-protected ALI file),
9789 unless the @option{^-a^/ALL_FILES^} switch is also specified.
9791 @item ^-F^/FULL_PATH_IN_BRIEF_MESSAGES^
9792 @cindex @option{^-F^/FULL_PATH_IN_BRIEF_MESSAGES^} (@command{gnatmake})
9793 When using project files, if some errors or warnings are detected during
9794 parsing and verbose mode is not in effect (no use of switch
9795 ^-v^/VERBOSE^), then error lines start with the full path name of the project
9796 file, rather than its simple file name.
9799 @cindex @option{^-g^/DEBUG^} (@command{gnatmake})
9800 Enable debugging. This switch is simply passed to the compiler and to the
9803 @item ^-i^/IN_PLACE^
9804 @cindex @option{^-i^/IN_PLACE^} (@command{gnatmake})
9805 In normal mode, @command{gnatmake} compiles all object files and ALI files
9806 into the current directory. If the @option{^-i^/IN_PLACE^} switch is used,
9807 then instead object files and ALI files that already exist are overwritten
9808 in place. This means that once a large project is organized into separate
9809 directories in the desired manner, then @command{gnatmake} will automatically
9810 maintain and update this organization. If no ALI files are found on the
9811 Ada object path (@ref{Search Paths and the Run-Time Library (RTL)}),
9812 the new object and ALI files are created in the
9813 directory containing the source being compiled. If another organization
9814 is desired, where objects and sources are kept in different directories,
9815 a useful technique is to create dummy ALI files in the desired directories.
9816 When detecting such a dummy file, @command{gnatmake} will be forced to
9817 recompile the corresponding source file, and it will be put the resulting
9818 object and ALI files in the directory where it found the dummy file.
9820 @item ^-j^/PROCESSES=^@var{n}
9821 @cindex @option{^-j^/PROCESSES^} (@command{gnatmake})
9822 @cindex Parallel make
9823 Use @var{n} processes to carry out the (re)compilations. On a multiprocessor
9824 machine compilations will occur in parallel. If @var{n} is 0, then the
9825 maximum number of parallel compilations is the number of core processors
9826 on the platform. In the event of compilation errors, messages from various
9827 compilations might get interspersed (but @command{gnatmake} will give you the
9828 full ordered list of failing compiles at the end). If this is problematic,
9829 rerun the make process with n set to 1 to get a clean list of messages.
9831 @item ^-k^/CONTINUE_ON_ERROR^
9832 @cindex @option{^-k^/CONTINUE_ON_ERROR^} (@command{gnatmake})
9833 Keep going. Continue as much as possible after a compilation error. To
9834 ease the programmer's task in case of compilation errors, the list of
9835 sources for which the compile fails is given when @command{gnatmake}
9838 If @command{gnatmake} is invoked with several @file{file_names} and with this
9839 switch, if there are compilation errors when building an executable,
9840 @command{gnatmake} will not attempt to build the following executables.
9842 @item ^-l^/ACTIONS=LINK^
9843 @cindex @option{^-l^/ACTIONS=LINK^} (@command{gnatmake})
9844 Link only. Can be combined with @option{^-b^/ACTIONS=BIND^} to binding
9845 and linking. Linking will not be performed if combined with
9846 @option{^-c^/ACTIONS=COMPILE^}
9847 but not with @option{^-b^/ACTIONS=BIND^}.
9848 When not combined with @option{^-b^/ACTIONS=BIND^}
9849 all the units in the closure of the main program must have been previously
9850 compiled and must be up to date, and the main program needs to have been bound.
9851 The root unit specified by @var{file_name}
9852 may be given without extension, with the source extension or, if no GNAT
9853 Project File is specified, with the ALI file extension.
9855 @item ^-m^/MINIMAL_RECOMPILATION^
9856 @cindex @option{^-m^/MINIMAL_RECOMPILATION^} (@command{gnatmake})
9857 Specify that the minimum necessary amount of recompilations
9858 be performed. In this mode @command{gnatmake} ignores time
9859 stamp differences when the only
9860 modifications to a source file consist in adding/removing comments,
9861 empty lines, spaces or tabs. This means that if you have changed the
9862 comments in a source file or have simply reformatted it, using this
9863 switch will tell @command{gnatmake} not to recompile files that depend on it
9864 (provided other sources on which these files depend have undergone no
9865 semantic modifications). Note that the debugging information may be
9866 out of date with respect to the sources if the @option{-m} switch causes
9867 a compilation to be switched, so the use of this switch represents a
9868 trade-off between compilation time and accurate debugging information.
9870 @item ^-M^/DEPENDENCIES_LIST^
9871 @cindex Dependencies, producing list
9872 @cindex @option{^-M^/DEPENDENCIES_LIST^} (@command{gnatmake})
9873 Check if all objects are up to date. If they are, output the object
9874 dependences to @file{stdout} in a form that can be directly exploited in
9875 a @file{Makefile}. By default, each source file is prefixed with its
9876 (relative or absolute) directory name. This name is whatever you
9877 specified in the various @option{^-aI^/SOURCE_SEARCH^}
9878 and @option{^-I^/SEARCH^} switches. If you use
9879 @code{gnatmake ^-M^/DEPENDENCIES_LIST^}
9880 @option{^-q^/QUIET^}
9881 (see below), only the source file names,
9882 without relative paths, are output. If you just specify the
9883 @option{^-M^/DEPENDENCIES_LIST^}
9884 switch, dependencies of the GNAT internal system files are omitted. This
9885 is typically what you want. If you also specify
9886 the @option{^-a^/ALL_FILES^} switch,
9887 dependencies of the GNAT internal files are also listed. Note that
9888 dependencies of the objects in external Ada libraries (see switch
9889 @option{^-aL^/SKIP_MISSING=^}@var{dir} in the following list)
9892 @item ^-n^/DO_OBJECT_CHECK^
9893 @cindex @option{^-n^/DO_OBJECT_CHECK^} (@command{gnatmake})
9894 Don't compile, bind, or link. Checks if all objects are up to date.
9895 If they are not, the full name of the first file that needs to be
9896 recompiled is printed.
9897 Repeated use of this option, followed by compiling the indicated source
9898 file, will eventually result in recompiling all required units.
9900 @item ^-o ^/EXECUTABLE=^@var{exec_name}
9901 @cindex @option{^-o^/EXECUTABLE^} (@command{gnatmake})
9902 Output executable name. The name of the final executable program will be
9903 @var{exec_name}. If the @option{^-o^/EXECUTABLE^} switch is omitted the default
9904 name for the executable will be the name of the input file in appropriate form
9905 for an executable file on the host system.
9907 This switch cannot be used when invoking @command{gnatmake} with several
9910 @item ^-p or --create-missing-dirs^/CREATE_MISSING_DIRS^
9911 @cindex @option{^-p^/CREATE_MISSING_DIRS^} (@command{gnatmake})
9912 When using project files (^-P^/PROJECT_FILE=^@var{project}), create
9913 automatically missing object directories, library directories and exec
9916 @item ^-P^/PROJECT_FILE=^@var{project}
9917 @cindex @option{^-P^/PROJECT_FILE^} (@command{gnatmake})
9918 Use project file @var{project}. Only one such switch can be used.
9919 @xref{gnatmake and Project Files}.
9922 @cindex @option{^-q^/QUIET^} (@command{gnatmake})
9923 Quiet. When this flag is not set, the commands carried out by
9924 @command{gnatmake} are displayed.
9926 @item ^-s^/SWITCH_CHECK/^
9927 @cindex @option{^-s^/SWITCH_CHECK^} (@command{gnatmake})
9928 Recompile if compiler switches have changed since last compilation.
9929 All compiler switches but -I and -o are taken into account in the
9931 orders between different ``first letter'' switches are ignored, but
9932 orders between same switches are taken into account. For example,
9933 @option{-O -O2} is different than @option{-O2 -O}, but @option{-g -O}
9934 is equivalent to @option{-O -g}.
9936 This switch is recommended when Integrated Preprocessing is used.
9939 @cindex @option{^-u^/UNIQUE^} (@command{gnatmake})
9940 Unique. Recompile at most the main files. It implies -c. Combined with
9941 -f, it is equivalent to calling the compiler directly. Note that using
9942 ^-u^/UNIQUE^ with a project file and no main has a special meaning
9943 (@pxref{Project Files and Main Subprograms}).
9945 @item ^-U^/ALL_PROJECTS^
9946 @cindex @option{^-U^/ALL_PROJECTS^} (@command{gnatmake})
9947 When used without a project file or with one or several mains on the command
9948 line, is equivalent to ^-u^/UNIQUE^. When used with a project file and no main
9949 on the command line, all sources of all project files are checked and compiled
9950 if not up to date, and libraries are rebuilt, if necessary.
9953 @cindex @option{^-v^/REASONS^} (@command{gnatmake})
9954 Verbose. Display the reason for all recompilations @command{gnatmake}
9955 decides are necessary, with the highest verbosity level.
9957 @item ^-vl^/LOW_VERBOSITY^
9958 @cindex @option{^-vl^/LOW_VERBOSITY^} (@command{gnatmake})
9959 Verbosity level Low. Display fewer lines than in verbosity Medium.
9961 @item ^-vm^/MEDIUM_VERBOSITY^
9962 @cindex @option{^-vm^/MEDIUM_VERBOSITY^} (@command{gnatmake})
9963 Verbosity level Medium. Potentially display fewer lines than in verbosity High.
9965 @item ^-vh^/HIGH_VERBOSITY^
9966 @cindex @option{^-vm^/HIGH_VERBOSITY^} (@command{gnatmake})
9967 Verbosity level High. Equivalent to ^-v^/REASONS^.
9969 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
9970 Indicate the verbosity of the parsing of GNAT project files.
9971 @xref{Switches Related to Project Files}.
9973 @item ^-x^/NON_PROJECT_UNIT_COMPILATION^
9974 @cindex @option{^-x^/NON_PROJECT_UNIT_COMPILATION^} (@command{gnatmake})
9975 Indicate that sources that are not part of any Project File may be compiled.
9976 Normally, when using Project Files, only sources that are part of a Project
9977 File may be compile. When this switch is used, a source outside of all Project
9978 Files may be compiled. The ALI file and the object file will be put in the
9979 object directory of the main Project. The compilation switches used will only
9980 be those specified on the command line. Even when
9981 @option{^-x^/NON_PROJECT_UNIT_COMPILATION^} is used, mains specified on the
9982 command line need to be sources of a project file.
9984 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
9985 Indicate that external variable @var{name} has the value @var{value}.
9986 The Project Manager will use this value for occurrences of
9987 @code{external(name)} when parsing the project file.
9988 @xref{Switches Related to Project Files}.
9991 @cindex @option{^-z^/NOMAIN^} (@command{gnatmake})
9992 No main subprogram. Bind and link the program even if the unit name
9993 given on the command line is a package name. The resulting executable
9994 will execute the elaboration routines of the package and its closure,
9995 then the finalization routines.
10000 @item @command{gcc} @asis{switches}
10002 Any uppercase or multi-character switch that is not a @command{gnatmake} switch
10003 is passed to @command{gcc} (e.g.@: @option{-O}, @option{-gnato,} etc.)
10006 Any qualifier that cannot be recognized as a qualifier for @code{GNAT MAKE}
10007 but is recognizable as a valid qualifier for @code{GNAT COMPILE} is
10008 automatically treated as a compiler switch, and passed on to all
10009 compilations that are carried out.
10014 Source and library search path switches:
10018 @item ^-aI^/SOURCE_SEARCH=^@var{dir}
10019 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatmake})
10020 When looking for source files also look in directory @var{dir}.
10021 The order in which source files search is undertaken is
10022 described in @ref{Search Paths and the Run-Time Library (RTL)}.
10024 @item ^-aL^/SKIP_MISSING=^@var{dir}
10025 @cindex @option{^-aL^/SKIP_MISSING^} (@command{gnatmake})
10026 Consider @var{dir} as being an externally provided Ada library.
10027 Instructs @command{gnatmake} to skip compilation units whose @file{.ALI}
10028 files have been located in directory @var{dir}. This allows you to have
10029 missing bodies for the units in @var{dir} and to ignore out of date bodies
10030 for the same units. You still need to specify
10031 the location of the specs for these units by using the switches
10032 @option{^-aI^/SOURCE_SEARCH=^@var{dir}}
10033 or @option{^-I^/SEARCH=^@var{dir}}.
10034 Note: this switch is provided for compatibility with previous versions
10035 of @command{gnatmake}. The easier method of causing standard libraries
10036 to be excluded from consideration is to write-protect the corresponding
10039 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
10040 @cindex @option{^-aO^/OBJECT_SEARCH^} (@command{gnatmake})
10041 When searching for library and object files, look in directory
10042 @var{dir}. The order in which library files are searched is described in
10043 @ref{Search Paths for gnatbind}.
10045 @item ^-A^/CONDITIONAL_SOURCE_SEARCH=^@var{dir}
10046 @cindex Search paths, for @command{gnatmake}
10047 @cindex @option{^-A^/CONDITIONAL_SOURCE_SEARCH^} (@command{gnatmake})
10048 Equivalent to @option{^-aL^/SKIP_MISSING=^@var{dir}
10049 ^-aI^/SOURCE_SEARCH=^@var{dir}}.
10051 @item ^-I^/SEARCH=^@var{dir}
10052 @cindex @option{^-I^/SEARCH^} (@command{gnatmake})
10053 Equivalent to @option{^-aO^/OBJECT_SEARCH=^@var{dir}
10054 ^-aI^/SOURCE_SEARCH=^@var{dir}}.
10056 @item ^-I-^/NOCURRENT_DIRECTORY^
10057 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gnatmake})
10058 @cindex Source files, suppressing search
10059 Do not look for source files in the directory containing the source
10060 file named in the command line.
10061 Do not look for ALI or object files in the directory
10062 where @command{gnatmake} was invoked.
10064 @item ^-L^/LIBRARY_SEARCH=^@var{dir}
10065 @cindex @option{^-L^/LIBRARY_SEARCH^} (@command{gnatmake})
10066 @cindex Linker libraries
10067 Add directory @var{dir} to the list of directories in which the linker
10068 will search for libraries. This is equivalent to
10069 @option{-largs ^-L^/LIBRARY_SEARCH=^}@var{dir}.
10071 Furthermore, under Windows, the sources pointed to by the libraries path
10072 set in the registry are not searched for.
10076 @cindex @option{-nostdinc} (@command{gnatmake})
10077 Do not look for source files in the system default directory.
10080 @cindex @option{-nostdlib} (@command{gnatmake})
10081 Do not look for library files in the system default directory.
10083 @item --RTS=@var{rts-path}
10084 @cindex @option{--RTS} (@command{gnatmake})
10085 Specifies the default location of the runtime library. GNAT looks for the
10087 in the following directories, and stops as soon as a valid runtime is found
10088 (@file{adainclude} or @file{ada_source_path}, and @file{adalib} or
10089 @file{ada_object_path} present):
10092 @item <current directory>/$rts_path
10094 @item <default-search-dir>/$rts_path
10096 @item <default-search-dir>/rts-$rts_path
10100 The selected path is handled like a normal RTS path.
10104 @node Mode Switches for gnatmake
10105 @section Mode Switches for @command{gnatmake}
10108 The mode switches (referred to as @code{mode_switches}) allow the
10109 inclusion of switches that are to be passed to the compiler itself, the
10110 binder or the linker. The effect of a mode switch is to cause all
10111 subsequent switches up to the end of the switch list, or up to the next
10112 mode switch, to be interpreted as switches to be passed on to the
10113 designated component of GNAT.
10117 @item -cargs @var{switches}
10118 @cindex @option{-cargs} (@command{gnatmake})
10119 Compiler switches. Here @var{switches} is a list of switches
10120 that are valid switches for @command{gcc}. They will be passed on to
10121 all compile steps performed by @command{gnatmake}.
10123 @item -bargs @var{switches}
10124 @cindex @option{-bargs} (@command{gnatmake})
10125 Binder switches. Here @var{switches} is a list of switches
10126 that are valid switches for @code{gnatbind}. They will be passed on to
10127 all bind steps performed by @command{gnatmake}.
10129 @item -largs @var{switches}
10130 @cindex @option{-largs} (@command{gnatmake})
10131 Linker switches. Here @var{switches} is a list of switches
10132 that are valid switches for @command{gnatlink}. They will be passed on to
10133 all link steps performed by @command{gnatmake}.
10135 @item -margs @var{switches}
10136 @cindex @option{-margs} (@command{gnatmake})
10137 Make switches. The switches are directly interpreted by @command{gnatmake},
10138 regardless of any previous occurrence of @option{-cargs}, @option{-bargs}
10139 or @option{-largs}.
10142 @node Notes on the Command Line
10143 @section Notes on the Command Line
10146 This section contains some additional useful notes on the operation
10147 of the @command{gnatmake} command.
10151 @cindex Recompilation, by @command{gnatmake}
10152 If @command{gnatmake} finds no ALI files, it recompiles the main program
10153 and all other units required by the main program.
10154 This means that @command{gnatmake}
10155 can be used for the initial compile, as well as during subsequent steps of
10156 the development cycle.
10159 If you enter @code{gnatmake @var{file}.adb}, where @file{@var{file}.adb}
10160 is a subunit or body of a generic unit, @command{gnatmake} recompiles
10161 @file{@var{file}.adb} (because it finds no ALI) and stops, issuing a
10165 In @command{gnatmake} the switch @option{^-I^/SEARCH^}
10166 is used to specify both source and
10167 library file paths. Use @option{^-aI^/SOURCE_SEARCH^}
10168 instead if you just want to specify
10169 source paths only and @option{^-aO^/OBJECT_SEARCH^}
10170 if you want to specify library paths
10174 @command{gnatmake} will ignore any files whose ALI file is write-protected.
10175 This may conveniently be used to exclude standard libraries from
10176 consideration and in particular it means that the use of the
10177 @option{^-f^/FORCE_COMPILE^} switch will not recompile these files
10178 unless @option{^-a^/ALL_FILES^} is also specified.
10181 @command{gnatmake} has been designed to make the use of Ada libraries
10182 particularly convenient. Assume you have an Ada library organized
10183 as follows: @i{^obj-dir^[OBJ_DIR]^} contains the objects and ALI files for
10184 of your Ada compilation units,
10185 whereas @i{^include-dir^[INCLUDE_DIR]^} contains the
10186 specs of these units, but no bodies. Then to compile a unit
10187 stored in @code{main.adb}, which uses this Ada library you would just type
10191 $ gnatmake -aI@var{include-dir} -aL@var{obj-dir} main
10194 $ gnatmake /SOURCE_SEARCH=@i{[INCLUDE_DIR]}
10195 /SKIP_MISSING=@i{[OBJ_DIR]} main
10200 Using @command{gnatmake} along with the
10201 @option{^-m (minimal recompilation)^/MINIMAL_RECOMPILATION^}
10202 switch provides a mechanism for avoiding unnecessary recompilations. Using
10204 you can update the comments/format of your
10205 source files without having to recompile everything. Note, however, that
10206 adding or deleting lines in a source files may render its debugging
10207 info obsolete. If the file in question is a spec, the impact is rather
10208 limited, as that debugging info will only be useful during the
10209 elaboration phase of your program. For bodies the impact can be more
10210 significant. In all events, your debugger will warn you if a source file
10211 is more recent than the corresponding object, and alert you to the fact
10212 that the debugging information may be out of date.
10215 @node How gnatmake Works
10216 @section How @command{gnatmake} Works
10219 Generally @command{gnatmake} automatically performs all necessary
10220 recompilations and you don't need to worry about how it works. However,
10221 it may be useful to have some basic understanding of the @command{gnatmake}
10222 approach and in particular to understand how it uses the results of
10223 previous compilations without incorrectly depending on them.
10225 First a definition: an object file is considered @dfn{up to date} if the
10226 corresponding ALI file exists and if all the source files listed in the
10227 dependency section of this ALI file have time stamps matching those in
10228 the ALI file. This means that neither the source file itself nor any
10229 files that it depends on have been modified, and hence there is no need
10230 to recompile this file.
10232 @command{gnatmake} works by first checking if the specified main unit is up
10233 to date. If so, no compilations are required for the main unit. If not,
10234 @command{gnatmake} compiles the main program to build a new ALI file that
10235 reflects the latest sources. Then the ALI file of the main unit is
10236 examined to find all the source files on which the main program depends,
10237 and @command{gnatmake} recursively applies the above procedure on all these
10240 This process ensures that @command{gnatmake} only trusts the dependencies
10241 in an existing ALI file if they are known to be correct. Otherwise it
10242 always recompiles to determine a new, guaranteed accurate set of
10243 dependencies. As a result the program is compiled ``upside down'' from what may
10244 be more familiar as the required order of compilation in some other Ada
10245 systems. In particular, clients are compiled before the units on which
10246 they depend. The ability of GNAT to compile in any order is critical in
10247 allowing an order of compilation to be chosen that guarantees that
10248 @command{gnatmake} will recompute a correct set of new dependencies if
10251 When invoking @command{gnatmake} with several @var{file_names}, if a unit is
10252 imported by several of the executables, it will be recompiled at most once.
10254 Note: when using non-standard naming conventions
10255 (@pxref{Using Other File Names}), changing through a configuration pragmas
10256 file the version of a source and invoking @command{gnatmake} to recompile may
10257 have no effect, if the previous version of the source is still accessible
10258 by @command{gnatmake}. It may be necessary to use the switch
10259 ^-f^/FORCE_COMPILE^.
10261 @node Examples of gnatmake Usage
10262 @section Examples of @command{gnatmake} Usage
10265 @item gnatmake hello.adb
10266 Compile all files necessary to bind and link the main program
10267 @file{hello.adb} (containing unit @code{Hello}) and bind and link the
10268 resulting object files to generate an executable file @file{^hello^HELLO.EXE^}.
10270 @item gnatmake main1 main2 main3
10271 Compile all files necessary to bind and link the main programs
10272 @file{main1.adb} (containing unit @code{Main1}), @file{main2.adb}
10273 (containing unit @code{Main2}) and @file{main3.adb}
10274 (containing unit @code{Main3}) and bind and link the resulting object files
10275 to generate three executable files @file{^main1^MAIN1.EXE^},
10276 @file{^main2^MAIN2.EXE^}
10277 and @file{^main3^MAIN3.EXE^}.
10280 @item gnatmake -q Main_Unit -cargs -O2 -bargs -l
10284 @item gnatmake Main_Unit /QUIET
10285 /COMPILER_QUALIFIERS /OPTIMIZE=ALL
10286 /BINDER_QUALIFIERS /ORDER_OF_ELABORATION
10288 Compile all files necessary to bind and link the main program unit
10289 @code{Main_Unit} (from file @file{main_unit.adb}). All compilations will
10290 be done with optimization level 2 and the order of elaboration will be
10291 listed by the binder. @command{gnatmake} will operate in quiet mode, not
10292 displaying commands it is executing.
10295 @c *************************
10296 @node Improving Performance
10297 @chapter Improving Performance
10298 @cindex Improving performance
10301 This chapter presents several topics related to program performance.
10302 It first describes some of the tradeoffs that need to be considered
10303 and some of the techniques for making your program run faster.
10305 @ifclear FSFEDITION
10306 the @command{gnatelim} tool and
10308 unused subprogram/data
10309 elimination feature, which can reduce the size of program executables.
10313 * Performance Considerations::
10314 * Text_IO Suggestions::
10315 @ifclear FSFEDITION
10316 * Reducing Size of Ada Executables with gnatelim::
10318 * Reducing Size of Executables with unused subprogram/data elimination::
10322 @c *****************************
10323 @node Performance Considerations
10324 @section Performance Considerations
10327 The GNAT system provides a number of options that allow a trade-off
10332 performance of the generated code
10335 speed of compilation
10338 minimization of dependences and recompilation
10341 the degree of run-time checking.
10345 The defaults (if no options are selected) aim at improving the speed
10346 of compilation and minimizing dependences, at the expense of performance
10347 of the generated code:
10354 no inlining of subprogram calls
10357 all run-time checks enabled except overflow and elaboration checks
10361 These options are suitable for most program development purposes. This
10362 chapter describes how you can modify these choices, and also provides
10363 some guidelines on debugging optimized code.
10366 * Controlling Run-Time Checks::
10367 * Use of Restrictions::
10368 * Optimization Levels::
10369 * Debugging Optimized Code::
10370 * Inlining of Subprograms::
10371 * Vectorization of loops::
10372 * Other Optimization Switches::
10373 * Optimization and Strict Aliasing::
10374 * Aliased Variables and Optimization::
10375 * Atomic Variables and Optimization::
10376 * Passive Task Optimization::
10379 * Coverage Analysis::
10383 @node Controlling Run-Time Checks
10384 @subsection Controlling Run-Time Checks
10387 By default, GNAT generates all run-time checks, except integer overflow
10388 checks, stack overflow checks, and checks for access before elaboration on
10389 subprogram calls. The latter are not required in default mode, because all
10390 necessary checking is done at compile time.
10391 @cindex @option{-gnatp} (@command{gcc})
10392 @cindex @option{-gnato} (@command{gcc})
10393 Two gnat switches, @option{-gnatp} and @option{-gnato} allow this default to
10394 be modified. @xref{Run-Time Checks}.
10396 Our experience is that the default is suitable for most development
10399 We treat integer overflow specially because these
10400 are quite expensive and in our experience are not as important as other
10401 run-time checks in the development process. Note that division by zero
10402 is not considered an overflow check, and divide by zero checks are
10403 generated where required by default.
10405 Elaboration checks are off by default, and also not needed by default, since
10406 GNAT uses a static elaboration analysis approach that avoids the need for
10407 run-time checking. This manual contains a full chapter discussing the issue
10408 of elaboration checks, and if the default is not satisfactory for your use,
10409 you should read this chapter.
10411 For validity checks, the minimal checks required by the Ada Reference
10412 Manual (for case statements and assignments to array elements) are on
10413 by default. These can be suppressed by use of the @option{-gnatVn} switch.
10414 Note that in Ada 83, there were no validity checks, so if the Ada 83 mode
10415 is acceptable (or when comparing GNAT performance with an Ada 83 compiler),
10416 it may be reasonable to routinely use @option{-gnatVn}. Validity checks
10417 are also suppressed entirely if @option{-gnatp} is used.
10419 @cindex Overflow checks
10420 @cindex Checks, overflow
10423 @cindex pragma Suppress
10424 @cindex pragma Unsuppress
10425 Note that the setting of the switches controls the default setting of
10426 the checks. They may be modified using either @code{pragma Suppress} (to
10427 remove checks) or @code{pragma Unsuppress} (to add back suppressed
10428 checks) in the program source.
10430 @node Use of Restrictions
10431 @subsection Use of Restrictions
10434 The use of pragma Restrictions allows you to control which features are
10435 permitted in your program. Apart from the obvious point that if you avoid
10436 relatively expensive features like finalization (enforceable by the use
10437 of pragma Restrictions (No_Finalization), the use of this pragma does not
10438 affect the generated code in most cases.
10440 One notable exception to this rule is that the possibility of task abort
10441 results in some distributed overhead, particularly if finalization or
10442 exception handlers are used. The reason is that certain sections of code
10443 have to be marked as non-abortable.
10445 If you use neither the @code{abort} statement, nor asynchronous transfer
10446 of control (@code{select @dots{} then abort}), then this distributed overhead
10447 is removed, which may have a general positive effect in improving
10448 overall performance. Especially code involving frequent use of tasking
10449 constructs and controlled types will show much improved performance.
10450 The relevant restrictions pragmas are
10452 @smallexample @c ada
10453 pragma Restrictions (No_Abort_Statements);
10454 pragma Restrictions (Max_Asynchronous_Select_Nesting => 0);
10458 It is recommended that these restriction pragmas be used if possible. Note
10459 that this also means that you can write code without worrying about the
10460 possibility of an immediate abort at any point.
10462 @node Optimization Levels
10463 @subsection Optimization Levels
10464 @cindex @option{^-O^/OPTIMIZE^} (@command{gcc})
10467 Without any optimization ^option,^qualifier,^
10468 the compiler's goal is to reduce the cost of
10469 compilation and to make debugging produce the expected results.
10470 Statements are independent: if you stop the program with a breakpoint between
10471 statements, you can then assign a new value to any variable or change
10472 the program counter to any other statement in the subprogram and get exactly
10473 the results you would expect from the source code.
10475 Turning on optimization makes the compiler attempt to improve the
10476 performance and/or code size at the expense of compilation time and
10477 possibly the ability to debug the program.
10479 If you use multiple
10480 ^-O options, with or without level numbers,^/OPTIMIZE qualifiers,^
10481 the last such option is the one that is effective.
10484 The default is optimization off. This results in the fastest compile
10485 times, but GNAT makes absolutely no attempt to optimize, and the
10486 generated programs are considerably larger and slower than when
10487 optimization is enabled. You can use the
10489 @option{-O} switch (the permitted forms are @option{-O0}, @option{-O1}
10490 @option{-O2}, @option{-O3}, and @option{-Os})
10493 @code{OPTIMIZE} qualifier
10495 to @command{gcc} to control the optimization level:
10498 @item ^-O0^/OPTIMIZE=NONE^
10499 No optimization (the default);
10500 generates unoptimized code but has
10501 the fastest compilation time.
10503 Note that many other compilers do fairly extensive optimization
10504 even if ``no optimization'' is specified. With gcc, it is
10505 very unusual to use ^-O0^/OPTIMIZE=NONE^ for production if
10506 execution time is of any concern, since ^-O0^/OPTIMIZE=NONE^
10507 really does mean no optimization at all. This difference between
10508 gcc and other compilers should be kept in mind when doing
10509 performance comparisons.
10511 @item ^-O1^/OPTIMIZE=SOME^
10512 Moderate optimization;
10513 optimizes reasonably well but does not
10514 degrade compilation time significantly.
10516 @item ^-O2^/OPTIMIZE=ALL^
10518 @itemx /OPTIMIZE=DEVELOPMENT
10521 generates highly optimized code and has
10522 the slowest compilation time.
10524 @item ^-O3^/OPTIMIZE=INLINING^
10525 Full optimization as in @option{-O2};
10526 also uses more aggressive automatic inlining of subprograms within a unit
10527 (@pxref{Inlining of Subprograms}) and attempts to vectorize loops.
10529 @item ^-Os^/OPTIMIZE=SPACE^
10530 Optimize space usage (code and data) of resulting program.
10534 Higher optimization levels perform more global transformations on the
10535 program and apply more expensive analysis algorithms in order to generate
10536 faster and more compact code. The price in compilation time, and the
10537 resulting improvement in execution time,
10538 both depend on the particular application and the hardware environment.
10539 You should experiment to find the best level for your application.
10541 Since the precise set of optimizations done at each level will vary from
10542 release to release (and sometime from target to target), it is best to think
10543 of the optimization settings in general terms.
10544 @xref{Optimize Options,, Options That Control Optimization, gcc, Using
10545 the GNU Compiler Collection (GCC)}, for details about
10546 ^the @option{-O} settings and a number of @option{-f} options that^how to^
10547 individually enable or disable specific optimizations.
10549 Unlike some other compilation systems, ^@command{gcc}^GNAT^ has
10550 been tested extensively at all optimization levels. There are some bugs
10551 which appear only with optimization turned on, but there have also been
10552 bugs which show up only in @emph{unoptimized} code. Selecting a lower
10553 level of optimization does not improve the reliability of the code
10554 generator, which in practice is highly reliable at all optimization
10557 Note regarding the use of @option{-O3}: The use of this optimization level
10558 is generally discouraged with GNAT, since it often results in larger
10559 executables which may run more slowly. See further discussion of this point
10560 in @ref{Inlining of Subprograms}.
10562 @node Debugging Optimized Code
10563 @subsection Debugging Optimized Code
10564 @cindex Debugging optimized code
10565 @cindex Optimization and debugging
10568 Although it is possible to do a reasonable amount of debugging at
10570 nonzero optimization levels,
10571 the higher the level the more likely that
10574 @option{/OPTIMIZE} settings other than @code{NONE},
10575 such settings will make it more likely that
10577 source-level constructs will have been eliminated by optimization.
10578 For example, if a loop is strength-reduced, the loop
10579 control variable may be completely eliminated and thus cannot be
10580 displayed in the debugger.
10581 This can only happen at @option{-O2} or @option{-O3}.
10582 Explicit temporary variables that you code might be eliminated at
10583 ^level^setting^ @option{-O1} or higher.
10585 The use of the @option{^-g^/DEBUG^} switch,
10586 @cindex @option{^-g^/DEBUG^} (@command{gcc})
10587 which is needed for source-level debugging,
10588 affects the size of the program executable on disk,
10589 and indeed the debugging information can be quite large.
10590 However, it has no effect on the generated code (and thus does not
10591 degrade performance)
10593 Since the compiler generates debugging tables for a compilation unit before
10594 it performs optimizations, the optimizing transformations may invalidate some
10595 of the debugging data. You therefore need to anticipate certain
10596 anomalous situations that may arise while debugging optimized code.
10597 These are the most common cases:
10601 @i{The ``hopping Program Counter'':} Repeated @code{step} or @code{next}
10603 the PC bouncing back and forth in the code. This may result from any of
10604 the following optimizations:
10608 @i{Common subexpression elimination:} using a single instance of code for a
10609 quantity that the source computes several times. As a result you
10610 may not be able to stop on what looks like a statement.
10613 @i{Invariant code motion:} moving an expression that does not change within a
10614 loop, to the beginning of the loop.
10617 @i{Instruction scheduling:} moving instructions so as to
10618 overlap loads and stores (typically) with other code, or in
10619 general to move computations of values closer to their uses. Often
10620 this causes you to pass an assignment statement without the assignment
10621 happening and then later bounce back to the statement when the
10622 value is actually needed. Placing a breakpoint on a line of code
10623 and then stepping over it may, therefore, not always cause all the
10624 expected side-effects.
10628 @i{The ``big leap'':} More commonly known as @emph{cross-jumping}, in which
10629 two identical pieces of code are merged and the program counter suddenly
10630 jumps to a statement that is not supposed to be executed, simply because
10631 it (and the code following) translates to the same thing as the code
10632 that @emph{was} supposed to be executed. This effect is typically seen in
10633 sequences that end in a jump, such as a @code{goto}, a @code{return}, or
10634 a @code{break} in a C @code{^switch^switch^} statement.
10637 @i{The ``roving variable'':} The symptom is an unexpected value in a variable.
10638 There are various reasons for this effect:
10642 In a subprogram prologue, a parameter may not yet have been moved to its
10646 A variable may be dead, and its register re-used. This is
10647 probably the most common cause.
10650 As mentioned above, the assignment of a value to a variable may
10654 A variable may be eliminated entirely by value propagation or
10655 other means. In this case, GCC may incorrectly generate debugging
10656 information for the variable
10660 In general, when an unexpected value appears for a local variable or parameter
10661 you should first ascertain if that value was actually computed by
10662 your program, as opposed to being incorrectly reported by the debugger.
10664 array elements in an object designated by an access value
10665 are generally less of a problem, once you have ascertained that the access
10667 Typically, this means checking variables in the preceding code and in the
10668 calling subprogram to verify that the value observed is explainable from other
10669 values (one must apply the procedure recursively to those
10670 other values); or re-running the code and stopping a little earlier
10671 (perhaps before the call) and stepping to better see how the variable obtained
10672 the value in question; or continuing to step @emph{from} the point of the
10673 strange value to see if code motion had simply moved the variable's
10678 In light of such anomalies, a recommended technique is to use @option{-O0}
10679 early in the software development cycle, when extensive debugging capabilities
10680 are most needed, and then move to @option{-O1} and later @option{-O2} as
10681 the debugger becomes less critical.
10682 Whether to use the @option{^-g^/DEBUG^} switch in the release version is
10683 a release management issue.
10685 Note that if you use @option{-g} you can then use the @command{strip} program
10686 on the resulting executable,
10687 which removes both debugging information and global symbols.
10690 @node Inlining of Subprograms
10691 @subsection Inlining of Subprograms
10694 A call to a subprogram in the current unit is inlined if all the
10695 following conditions are met:
10699 The optimization level is at least @option{-O1}.
10702 The called subprogram is suitable for inlining: It must be small enough
10703 and not contain something that @command{gcc} cannot support in inlined
10707 @cindex pragma Inline
10709 Any one of the following applies: @code{pragma Inline} is applied to the
10710 subprogram and the @option{^-gnatn^/INLINE^} switch is specified; the
10711 subprogram is local to the unit and called once from within it; the
10712 subprogram is small and optimization level @option{-O2} is specified;
10713 optimization level @option{-O3} is specified.
10717 Calls to subprograms in @code{with}'ed units are normally not inlined.
10718 To achieve actual inlining (that is, replacement of the call by the code
10719 in the body of the subprogram), the following conditions must all be true:
10723 The optimization level is at least @option{-O1}.
10726 The called subprogram is suitable for inlining: It must be small enough
10727 and not contain something that @command{gcc} cannot support in inlined
10731 The call appears in a body (not in a package spec).
10734 There is a @code{pragma Inline} for the subprogram.
10737 The @option{^-gnatn^/INLINE^} switch is used on the command line.
10740 Even if all these conditions are met, it may not be possible for
10741 the compiler to inline the call, due to the length of the body,
10742 or features in the body that make it impossible for the compiler
10743 to do the inlining.
10745 Note that specifying the @option{-gnatn} switch causes additional
10746 compilation dependencies. Consider the following:
10748 @smallexample @c ada
10768 With the default behavior (no @option{-gnatn} switch specified), the
10769 compilation of the @code{Main} procedure depends only on its own source,
10770 @file{main.adb}, and the spec of the package in file @file{r.ads}. This
10771 means that editing the body of @code{R} does not require recompiling
10774 On the other hand, the call @code{R.Q} is not inlined under these
10775 circumstances. If the @option{-gnatn} switch is present when @code{Main}
10776 is compiled, the call will be inlined if the body of @code{Q} is small
10777 enough, but now @code{Main} depends on the body of @code{R} in
10778 @file{r.adb} as well as on the spec. This means that if this body is edited,
10779 the main program must be recompiled. Note that this extra dependency
10780 occurs whether or not the call is in fact inlined by @command{gcc}.
10782 The use of front end inlining with @option{-gnatN} generates similar
10783 additional dependencies.
10785 @cindex @option{^-fno-inline^/INLINE=SUPPRESS^} (@command{gcc})
10786 Note: The @option{^-fno-inline^/INLINE=SUPPRESS^} switch
10787 can be used to prevent
10788 all inlining. This switch overrides all other conditions and ensures
10789 that no inlining occurs. The extra dependences resulting from
10790 @option{-gnatn} will still be active, even if
10791 this switch is used to suppress the resulting inlining actions.
10793 @cindex @option{-fno-inline-functions} (@command{gcc})
10794 Note: The @option{-fno-inline-functions} switch can be used to prevent
10795 automatic inlining of subprograms if @option{-O3} is used.
10797 @cindex @option{-fno-inline-small-functions} (@command{gcc})
10798 Note: The @option{-fno-inline-small-functions} switch can be used to prevent
10799 automatic inlining of small subprograms if @option{-O2} is used.
10801 @cindex @option{-fno-inline-functions-called-once} (@command{gcc})
10802 Note: The @option{-fno-inline-functions-called-once} switch
10803 can be used to prevent inlining of subprograms local to the unit
10804 and called once from within it if @option{-O1} is used.
10806 Note regarding the use of @option{-O3}: @option{-gnatn} is made up of two
10807 sub-switches @option{-gnatn1} and @option{-gnatn2} that can be directly
10808 specified in lieu of it, @option{-gnatn} being translated into one of them
10809 based on the optimization level. With @option{-O2} or below, @option{-gnatn}
10810 is equivalent to @option{-gnatn1} which activates pragma @code{Inline} with
10811 moderate inlining across modules. With @option{-O3}, @option{-gnatn} is
10812 equivalent to @option{-gnatn2} which activates pragma @code{Inline} with
10813 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
10814 effect of inlining subprograms you did not think should be inlined. We have
10815 found that the use of @option{-O3} may slow down the compilation and increase
10816 the code size by performing excessive inlining, leading to increased
10817 instruction cache pressure from the increased code size and thus minor
10818 performance improvements. So the bottom line here is that you should not
10819 automatically assume that @option{-O3} is better than @option{-O2}, and
10820 indeed you should use @option{-O3} only if tests show that it actually
10821 improves performance for your program.
10823 @node Vectorization of loops
10824 @subsection Vectorization of loops
10825 @cindex Optimization Switches
10827 You can take advantage of the auto-vectorizer present in the @command{gcc}
10828 back end to vectorize loops with GNAT. The corresponding command line switch
10829 is @option{-ftree-vectorize} but, as it is enabled by default at @option{-O3}
10830 and other aggressive optimizations helpful for vectorization also are enabled
10831 by default at this level, using @option{-O3} directly is recommended.
10833 You also need to make sure that the target architecture features a supported
10834 SIMD instruction set. For example, for the x86 architecture, you should at
10835 least specify @option{-msse2} to get significant vectorization (but you don't
10836 need to specify it for x86-64 as it is part of the base 64-bit architecture).
10837 Similarly, for the PowerPC architecture, you should specify @option{-maltivec}.
10839 The preferred loop form for vectorization is the @code{for} iteration scheme.
10840 Loops with a @code{while} iteration scheme can also be vectorized if they are
10841 very simple, but the vectorizer will quickly give up otherwise. With either
10842 iteration scheme, the flow of control must be straight, in particular no
10843 @code{exit} statement may appear in the loop body. The loop may however
10844 contain a single nested loop, if it can be vectorized when considered alone:
10846 @smallexample @c ada
10848 A : array (1..4, 1..4) of Long_Float;
10849 S : array (1..4) of Long_Float;
10853 for I in A'Range(1) loop
10854 for J in A'Range(2) loop
10855 S (I) := S (I) + A (I, J);
10862 The vectorizable operations depend on the targeted SIMD instruction set, but
10863 the adding and some of the multiplying operators are generally supported, as
10864 well as the logical operators for modular types. Note that, in the former
10865 case, enabling overflow checks, for example with @option{-gnato}, totally
10866 disables vectorization. The other checks are not supposed to have the same
10867 definitive effect, although compiling with @option{-gnatp} might well reveal
10868 cases where some checks do thwart vectorization.
10870 Type conversions may also prevent vectorization if they involve semantics that
10871 are not directly supported by the code generator or the SIMD instruction set.
10872 A typical example is direct conversion from floating-point to integer types.
10873 The solution in this case is to use the following idiom:
10875 @smallexample @c ada
10876 Integer (S'Truncation (F))
10880 if @code{S} is the subtype of floating-point object @code{F}.
10882 In most cases, the vectorizable loops are loops that iterate over arrays.
10883 All kinds of array types are supported, i.e. constrained array types with
10886 @smallexample @c ada
10887 type Array_Type is array (1 .. 4) of Long_Float;
10891 constrained array types with dynamic bounds:
10893 @smallexample @c ada
10894 type Array_Type is array (1 .. Q.N) of Long_Float;
10896 type Array_Type is array (Q.K .. 4) of Long_Float;
10898 type Array_Type is array (Q.K .. Q.N) of Long_Float;
10902 or unconstrained array types:
10904 @smallexample @c ada
10905 type Array_Type is array (Positive range <>) of Long_Float;
10909 The quality of the generated code decreases when the dynamic aspect of the
10910 array type increases, the worst code being generated for unconstrained array
10911 types. This is so because, the less information the compiler has about the
10912 bounds of the array, the more fallback code it needs to generate in order to
10913 fix things up at run time.
10915 It is possible to specify that a given loop should be subject to vectorization
10916 preferably to other optimizations by means of pragma @code{Loop_Optimize}:
10918 @smallexample @c ada
10919 pragma Loop_Optimize (Vector);
10923 placed immediately within the loop will convey the appropriate hint to the
10924 compiler for this loop.
10926 It is also possible to help the compiler generate better vectorized code
10927 for a given loop by asserting that there are no loop-carried dependencies
10928 in the loop. Consider for example the procedure:
10930 @smallexample @c ada
10931 type Arr is array (1 .. 4) of Long_Float;
10933 procedure Add (X, Y : not null access Arr; R : not null access Arr) is
10935 for I in Arr'Range loop
10936 R(I) := X(I) + Y(I);
10942 By default, the compiler cannot unconditionally vectorize the loop because
10943 assigning to a component of the array designated by R in one iteration could
10944 change the value read from the components of the arrays designated by X or Y
10945 in a later iteration. As a result, the compiler will generate two versions
10946 of the loop in the object code, one vectorized and the other not vectorized,
10947 as well as a test to select the appropriate version at run time. This can
10948 be overcome by another hint:
10950 @smallexample @c ada
10951 pragma Loop_Optimize (Ivdep);
10955 placed immediately within the loop will tell the compiler that it can safely
10956 omit the non-vectorized version of the loop as well as the run-time test.
10958 @node Other Optimization Switches
10959 @subsection Other Optimization Switches
10960 @cindex Optimization Switches
10962 Since @code{GNAT} uses the @command{gcc} back end, all the specialized
10963 @command{gcc} optimization switches are potentially usable. These switches
10964 have not been extensively tested with GNAT but can generally be expected
10965 to work. Examples of switches in this category are @option{-funroll-loops}
10966 and the various target-specific @option{-m} options (in particular, it has
10967 been observed that @option{-march=xxx} can significantly improve performance
10968 on appropriate machines). For full details of these switches, see
10969 @ref{Submodel Options,, Hardware Models and Configurations, gcc, Using
10970 the GNU Compiler Collection (GCC)}.
10972 @node Optimization and Strict Aliasing
10973 @subsection Optimization and Strict Aliasing
10975 @cindex Strict Aliasing
10976 @cindex No_Strict_Aliasing
10979 The strong typing capabilities of Ada allow an optimizer to generate
10980 efficient code in situations where other languages would be forced to
10981 make worst case assumptions preventing such optimizations. Consider
10982 the following example:
10984 @smallexample @c ada
10987 type Int1 is new Integer;
10988 type Int2 is new Integer;
10989 type Int1A is access Int1;
10990 type Int2A is access Int2;
10997 for J in Data'Range loop
10998 if Data (J) = Int1V.all then
10999 Int2V.all := Int2V.all + 1;
11008 In this example, since the variable @code{Int1V} can only access objects
11009 of type @code{Int1}, and @code{Int2V} can only access objects of type
11010 @code{Int2}, there is no possibility that the assignment to
11011 @code{Int2V.all} affects the value of @code{Int1V.all}. This means that
11012 the compiler optimizer can "know" that the value @code{Int1V.all} is constant
11013 for all iterations of the loop and avoid the extra memory reference
11014 required to dereference it each time through the loop.
11016 This kind of optimization, called strict aliasing analysis, is
11017 triggered by specifying an optimization level of @option{-O2} or
11018 higher or @option{-Os} and allows @code{GNAT} to generate more efficient code
11019 when access values are involved.
11021 However, although this optimization is always correct in terms of
11022 the formal semantics of the Ada Reference Manual, difficulties can
11023 arise if features like @code{Unchecked_Conversion} are used to break
11024 the typing system. Consider the following complete program example:
11026 @smallexample @c ada
11029 type int1 is new integer;
11030 type int2 is new integer;
11031 type a1 is access int1;
11032 type a2 is access int2;
11037 function to_a2 (Input : a1) return a2;
11040 with Unchecked_Conversion;
11042 function to_a2 (Input : a1) return a2 is
11044 new Unchecked_Conversion (a1, a2);
11046 return to_a2u (Input);
11052 with Text_IO; use Text_IO;
11054 v1 : a1 := new int1;
11055 v2 : a2 := to_a2 (v1);
11059 put_line (int1'image (v1.all));
11065 This program prints out 0 in @option{-O0} or @option{-O1}
11066 mode, but it prints out 1 in @option{-O2} mode. That's
11067 because in strict aliasing mode, the compiler can and
11068 does assume that the assignment to @code{v2.all} could not
11069 affect the value of @code{v1.all}, since different types
11072 This behavior is not a case of non-conformance with the standard, since
11073 the Ada RM specifies that an unchecked conversion where the resulting
11074 bit pattern is not a correct value of the target type can result in an
11075 abnormal value and attempting to reference an abnormal value makes the
11076 execution of a program erroneous. That's the case here since the result
11077 does not point to an object of type @code{int2}. This means that the
11078 effect is entirely unpredictable.
11080 However, although that explanation may satisfy a language
11081 lawyer, in practice an applications programmer expects an
11082 unchecked conversion involving pointers to create true
11083 aliases and the behavior of printing 1 seems plain wrong.
11084 In this case, the strict aliasing optimization is unwelcome.
11086 Indeed the compiler recognizes this possibility, and the
11087 unchecked conversion generates a warning:
11090 p2.adb:5:07: warning: possible aliasing problem with type "a2"
11091 p2.adb:5:07: warning: use -fno-strict-aliasing switch for references
11092 p2.adb:5:07: warning: or use "pragma No_Strict_Aliasing (a2);"
11096 Unfortunately the problem is recognized when compiling the body of
11097 package @code{p2}, but the actual "bad" code is generated while
11098 compiling the body of @code{m} and this latter compilation does not see
11099 the suspicious @code{Unchecked_Conversion}.
11101 As implied by the warning message, there are approaches you can use to
11102 avoid the unwanted strict aliasing optimization in a case like this.
11104 One possibility is to simply avoid the use of @option{-O2}, but
11105 that is a bit drastic, since it throws away a number of useful
11106 optimizations that do not involve strict aliasing assumptions.
11108 A less drastic approach is to compile the program using the
11109 option @option{-fno-strict-aliasing}. Actually it is only the
11110 unit containing the dereferencing of the suspicious pointer
11111 that needs to be compiled. So in this case, if we compile
11112 unit @code{m} with this switch, then we get the expected
11113 value of zero printed. Analyzing which units might need
11114 the switch can be painful, so a more reasonable approach
11115 is to compile the entire program with options @option{-O2}
11116 and @option{-fno-strict-aliasing}. If the performance is
11117 satisfactory with this combination of options, then the
11118 advantage is that the entire issue of possible "wrong"
11119 optimization due to strict aliasing is avoided.
11121 To avoid the use of compiler switches, the configuration
11122 pragma @code{No_Strict_Aliasing} with no parameters may be
11123 used to specify that for all access types, the strict
11124 aliasing optimization should be suppressed.
11126 However, these approaches are still overkill, in that they causes
11127 all manipulations of all access values to be deoptimized. A more
11128 refined approach is to concentrate attention on the specific
11129 access type identified as problematic.
11131 First, if a careful analysis of uses of the pointer shows
11132 that there are no possible problematic references, then
11133 the warning can be suppressed by bracketing the
11134 instantiation of @code{Unchecked_Conversion} to turn
11137 @smallexample @c ada
11138 pragma Warnings (Off);
11140 new Unchecked_Conversion (a1, a2);
11141 pragma Warnings (On);
11145 Of course that approach is not appropriate for this particular
11146 example, since indeed there is a problematic reference. In this
11147 case we can take one of two other approaches.
11149 The first possibility is to move the instantiation of unchecked
11150 conversion to the unit in which the type is declared. In
11151 this example, we would move the instantiation of
11152 @code{Unchecked_Conversion} from the body of package
11153 @code{p2} to the spec of package @code{p1}. Now the
11154 warning disappears. That's because any use of the
11155 access type knows there is a suspicious unchecked
11156 conversion, and the strict aliasing optimization
11157 is automatically suppressed for the type.
11159 If it is not practical to move the unchecked conversion to the same unit
11160 in which the destination access type is declared (perhaps because the
11161 source type is not visible in that unit), you may use pragma
11162 @code{No_Strict_Aliasing} for the type. This pragma must occur in the
11163 same declarative sequence as the declaration of the access type:
11165 @smallexample @c ada
11166 type a2 is access int2;
11167 pragma No_Strict_Aliasing (a2);
11171 Here again, the compiler now knows that the strict aliasing optimization
11172 should be suppressed for any reference to type @code{a2} and the
11173 expected behavior is obtained.
11175 Finally, note that although the compiler can generate warnings for
11176 simple cases of unchecked conversions, there are tricker and more
11177 indirect ways of creating type incorrect aliases which the compiler
11178 cannot detect. Examples are the use of address overlays and unchecked
11179 conversions involving composite types containing access types as
11180 components. In such cases, no warnings are generated, but there can
11181 still be aliasing problems. One safe coding practice is to forbid the
11182 use of address clauses for type overlaying, and to allow unchecked
11183 conversion only for primitive types. This is not really a significant
11184 restriction since any possible desired effect can be achieved by
11185 unchecked conversion of access values.
11187 The aliasing analysis done in strict aliasing mode can certainly
11188 have significant benefits. We have seen cases of large scale
11189 application code where the time is increased by up to 5% by turning
11190 this optimization off. If you have code that includes significant
11191 usage of unchecked conversion, you might want to just stick with
11192 @option{-O1} and avoid the entire issue. If you get adequate
11193 performance at this level of optimization level, that's probably
11194 the safest approach. If tests show that you really need higher
11195 levels of optimization, then you can experiment with @option{-O2}
11196 and @option{-O2 -fno-strict-aliasing} to see how much effect this
11197 has on size and speed of the code. If you really need to use
11198 @option{-O2} with strict aliasing in effect, then you should
11199 review any uses of unchecked conversion of access types,
11200 particularly if you are getting the warnings described above.
11202 @node Aliased Variables and Optimization
11203 @subsection Aliased Variables and Optimization
11205 There are scenarios in which programs may
11206 use low level techniques to modify variables
11207 that otherwise might be considered to be unassigned. For example,
11208 a variable can be passed to a procedure by reference, which takes
11209 the address of the parameter and uses the address to modify the
11210 variable's value, even though it is passed as an IN parameter.
11211 Consider the following example:
11213 @smallexample @c ada
11215 Max_Length : constant Natural := 16;
11216 type Char_Ptr is access all Character;
11218 procedure Get_String(Buffer: Char_Ptr; Size : Integer);
11219 pragma Import (C, Get_String, "get_string");
11221 Name : aliased String (1 .. Max_Length) := (others => ' ');
11224 function Addr (S : String) return Char_Ptr is
11225 function To_Char_Ptr is
11226 new Ada.Unchecked_Conversion (System.Address, Char_Ptr);
11228 return To_Char_Ptr (S (S'First)'Address);
11232 Temp := Addr (Name);
11233 Get_String (Temp, Max_Length);
11238 where Get_String is a C function that uses the address in Temp to
11239 modify the variable @code{Name}. This code is dubious, and arguably
11240 erroneous, and the compiler would be entitled to assume that
11241 @code{Name} is never modified, and generate code accordingly.
11243 However, in practice, this would cause some existing code that
11244 seems to work with no optimization to start failing at high
11245 levels of optimzization.
11247 What the compiler does for such cases is to assume that marking
11248 a variable as aliased indicates that some "funny business" may
11249 be going on. The optimizer recognizes the aliased keyword and
11250 inhibits optimizations that assume the value cannot be assigned.
11251 This means that the above example will in fact "work" reliably,
11252 that is, it will produce the expected results.
11254 @node Atomic Variables and Optimization
11255 @subsection Atomic Variables and Optimization
11257 There are two considerations with regard to performance when
11258 atomic variables are used.
11260 First, the RM only guarantees that access to atomic variables
11261 be atomic, it has nothing to say about how this is achieved,
11262 though there is a strong implication that this should not be
11263 achieved by explicit locking code. Indeed GNAT will never
11264 generate any locking code for atomic variable access (it will
11265 simply reject any attempt to make a variable or type atomic
11266 if the atomic access cannot be achieved without such locking code).
11268 That being said, it is important to understand that you cannot
11269 assume that the entire variable will always be accessed. Consider
11272 @smallexample @c ada
11274 A,B,C,D : Character;
11277 for R'Alignment use 4;
11280 pragma Atomic (RV);
11287 You cannot assume that the reference to @code{RV.B}
11288 will read the entire 32-bit
11289 variable with a single load instruction. It is perfectly legitimate if
11290 the hardware allows it to do a byte read of just the B field. This read
11291 is still atomic, which is all the RM requires. GNAT can and does take
11292 advantage of this, depending on the architecture and optimization level.
11293 Any assumption to the contrary is non-portable and risky. Even if you
11294 examine the assembly language and see a full 32-bit load, this might
11295 change in a future version of the compiler.
11297 If your application requires that all accesses to @code{RV} in this
11298 example be full 32-bit loads, you need to make a copy for the access
11301 @smallexample @c ada
11303 RV_Copy : constant R := RV;
11311 Now the reference to RV must read the whole variable.
11312 Actually one can imagine some compiler which figures
11313 out that the whole copy is not required (because only
11314 the B field is actually accessed), but GNAT
11315 certainly won't do that, and we don't know of any
11316 compiler that would not handle this right, and the
11317 above code will in practice work portably across
11318 all architectures (that permit the Atomic declaration).
11320 The second issue with atomic variables has to do with
11321 the possible requirement of generating synchronization
11322 code. For more details on this, consult the sections on
11323 the pragmas Enable/Disable_Atomic_Synchronization in the
11324 GNAT Reference Manual. If performance is critical, and
11325 such synchronization code is not required, it may be
11326 useful to disable it.
11328 @node Passive Task Optimization
11329 @subsection Passive Task Optimization
11330 @cindex Passive Task
11332 A passive task is one which is sufficiently simple that
11333 in theory a compiler could recognize it an implement it
11334 efficiently without creating a new thread. The original design
11335 of Ada 83 had in mind this kind of passive task optimization, but
11336 only a few Ada 83 compilers attempted it. The problem was that
11337 it was difficult to determine the exact conditions under which
11338 the optimization was possible. The result is a very fragile
11339 optimization where a very minor change in the program can
11340 suddenly silently make a task non-optimizable.
11342 With the revisiting of this issue in Ada 95, there was general
11343 agreement that this approach was fundamentally flawed, and the
11344 notion of protected types was introduced. When using protected
11345 types, the restrictions are well defined, and you KNOW that the
11346 operations will be optimized, and furthermore this optimized
11347 performance is fully portable.
11349 Although it would theoretically be possible for GNAT to attempt to
11350 do this optimization, but it really doesn't make sense in the
11351 context of Ada 95, and none of the Ada 95 compilers implement
11352 this optimization as far as we know. In particular GNAT never
11353 attempts to perform this optimization.
11355 In any new Ada 95 code that is written, you should always
11356 use protected types in place of tasks that might be able to
11357 be optimized in this manner.
11358 Of course this does not help if you have legacy Ada 83 code
11359 that depends on this optimization, but it is unusual to encounter
11360 a case where the performance gains from this optimization
11363 Your program should work correctly without this optimization. If
11364 you have performance problems, then the most practical
11365 approach is to figure out exactly where these performance problems
11366 arise, and update those particular tasks to be protected types. Note
11367 that typically clients of the tasks who call entries, will not have
11368 to be modified, only the task definition itself.
11371 @node Coverage Analysis
11372 @subsection Coverage Analysis
11375 GNAT supports the HP Performance Coverage Analyzer (PCA), which allows
11376 the user to determine the distribution of execution time across a program,
11377 @pxref{Profiling} for details of usage.
11381 @node Text_IO Suggestions
11382 @section @code{Text_IO} Suggestions
11383 @cindex @code{Text_IO} and performance
11386 The @code{Ada.Text_IO} package has fairly high overheads due in part to
11387 the requirement of maintaining page and line counts. If performance
11388 is critical, a recommendation is to use @code{Stream_IO} instead of
11389 @code{Text_IO} for volume output, since this package has less overhead.
11391 If @code{Text_IO} must be used, note that by default output to the standard
11392 output and standard error files is unbuffered (this provides better
11393 behavior when output statements are used for debugging, or if the
11394 progress of a program is observed by tracking the output, e.g. by
11395 using the Unix @command{tail -f} command to watch redirected output.
11397 If you are generating large volumes of output with @code{Text_IO} and
11398 performance is an important factor, use a designated file instead
11399 of the standard output file, or change the standard output file to
11400 be buffered using @code{Interfaces.C_Streams.setvbuf}.
11403 @ifclear FSFEDITION
11404 @node Reducing Size of Ada Executables with gnatelim
11405 @section Reducing Size of Ada Executables with @code{gnatelim}
11409 This section describes @command{gnatelim}, a tool which detects unused
11410 subprograms and helps the compiler to create a smaller executable for your
11415 * Running gnatelim::
11416 * Processing Precompiled Libraries::
11417 * Correcting the List of Eliminate Pragmas::
11418 * Making Your Executables Smaller::
11419 * Summary of the gnatelim Usage Cycle::
11422 @node About gnatelim
11423 @subsection About @code{gnatelim}
11426 When a program shares a set of Ada
11427 packages with other programs, it may happen that this program uses
11428 only a fraction of the subprograms defined in these packages. The code
11429 created for these unused subprograms increases the size of the executable.
11431 @code{gnatelim} tracks unused subprograms in an Ada program and
11432 outputs a list of GNAT-specific pragmas @code{Eliminate} marking all the
11433 subprograms that are declared but never called. By placing the list of
11434 @code{Eliminate} pragmas in the GNAT configuration file @file{gnat.adc} and
11435 recompiling your program, you may decrease the size of its executable,
11436 because the compiler will not generate the code for 'eliminated' subprograms.
11437 @xref{Pragma Eliminate,,, gnat_rm, GNAT Reference Manual}, for more
11438 information about this pragma.
11440 @code{gnatelim} needs as its input data the name of the main subprogram.
11442 If a set of source files is specified as @code{gnatelim} arguments, it
11443 treats these files as a complete set of sources making up a program to
11444 analyse, and analyses only these sources.
11446 After a full successful build of the main subprogram @code{gnatelim} can be
11447 called without specifying sources to analyse, in this case it computes
11448 the source closure of the main unit from the @file{ALI} files.
11450 If the set of sources to be processed by @code{gnatelim} contains sources with
11451 preprocessing directives
11452 then the needed options should be provided to run preprocessor as a part of
11453 the @command{gnatelim} call, and the generated set of pragmas @code{Eliminate}
11454 will correspond to preprocessed sources.
11456 The following command will create the set of @file{ALI} files needed for
11460 $ gnatmake ^-c Main_Prog^/ACTIONS=COMPILE MAIN_PROG^
11463 Note that @code{gnatelim} does not need object files.
11465 @node Running gnatelim
11466 @subsection Running @code{gnatelim}
11469 @code{gnatelim} has the following command-line interface:
11472 $ gnatelim [@var{switches}] ^-main^?MAIN^=@var{main_unit_name} @{@var{filename}@} @r{[}-cargs @var{gcc_switches}@r{]}
11476 @var{main_unit_name} should be a name of a source file that contains the main
11477 subprogram of a program (partition).
11479 Each @var{filename} is the name (including the extension) of a source
11480 file to process. ``Wildcards'' are allowed, and
11481 the file name may contain path information.
11483 @samp{@var{gcc_switches}} is a list of switches for
11484 @command{gcc}. They will be passed on to all compiler invocations made by
11485 @command{gnatelim} to generate the ASIS trees. Here you can provide
11486 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
11487 use the @option{-gnatec} switch to set the configuration file,
11488 use the @option{-gnat05} switch if sources should be compiled in
11491 @code{gnatelim} has the following switches:
11496 @cindex @option{--version} @command{gnatelim}
11497 Display Copyright and version, then exit disregarding all other options.
11500 @cindex @option{--help} @command{gnatelim}
11501 Display usage, then exit disregarding all other options.
11503 @item -P @var{file}
11504 @cindex @option{-P} @command{gnatelim}
11505 Indicates the name of the project file that describes the set of sources
11508 @item -X@var{name}=@var{value}
11509 @cindex @option{-X} @command{gnatelim}
11510 Indicates that external variable @var{name} in the argument project
11511 has the value @var{value}. Has no effect if no project is specified as
11514 @item ^-files^/FILES^=@var{filename}
11515 @cindex @option{^-files^/FILES^} (@code{gnatelim})
11516 Take the argument source files from the specified file. This file should be an
11517 ordinary text file containing file names separated by spaces or
11518 line breaks. You can use this switch more than once in the same call to
11519 @command{gnatelim}. You also can combine this switch with
11520 an explicit list of files.
11523 @cindex @option{^-log^/LOG^} (@command{gnatelim})
11524 Duplicate all the output sent to @file{stderr} into a log file. The log file
11525 is named @file{gnatelim.log} and is located in the current directory.
11528 @item ^-log^/LOGFILE^=@var{filename}
11529 @cindex @option{^-log^/LOGFILE^} (@command{gnatelim})
11530 Duplicate all the output sent to @file{stderr} into a specified log file.
11533 @cindex @option{^--no-elim-dispatch^/NO_DISPATCH^} (@command{gnatelim})
11534 @item ^--no-elim-dispatch^/NO_DISPATCH^
11535 Do not generate pragmas for dispatching operations.
11537 @item ^--ignore^/IGNORE^=@var{filename}
11538 @cindex @option{^--ignore^/IGNORE^} (@command{gnatelim})
11539 Do not generate pragmas for subprograms declared in the sources
11540 listed in a specified file
11542 @cindex @option{^-o^/OUTPUT^} (@command{gnatelim})
11543 @item ^-o^/OUTPUT^=@var{report_file}
11544 Put @command{gnatelim} output into a specified file. If this file already exists,
11545 it is overridden. If this switch is not used, @command{gnatelim} outputs its results
11548 @item ^-j^/PROCESSES=^@var{n}
11549 @cindex @option{^-j^/PROCESSES^} (@command{gnatelim})
11550 Use @var{n} processes to carry out the tree creations (internal representations
11551 of the argument sources). On a multiprocessor machine this speeds up processing
11552 of big sets of argument sources. If @var{n} is 0, then the maximum number of
11553 parallel tree creations is the number of core processors on the platform.
11556 @cindex @option{^-q^/QUIET^} (@command{gnatelim})
11557 Quiet mode: by default @code{gnatelim} outputs to the standard error
11558 stream the number of program units left to be processed. This option turns
11561 @cindex @option{^-t^/TIME^} (@command{gnatelim})
11563 Print out execution time.
11565 @item ^-v^/VERBOSE^
11566 @cindex @option{^-v^/VERBOSE^} (@command{gnatelim})
11567 Verbose mode: @code{gnatelim} version information is printed as Ada
11568 comments to the standard output stream. Also, in addition to the number of
11569 program units left @code{gnatelim} will output the name of the current unit
11572 @item ^-wq^/WARNINGS=QUIET^
11573 @cindex @option{^-wq^/WARNINGS=QUIET^} (@command{gnatelim})
11574 Quiet warning mode - some warnings are suppressed. In particular warnings that
11575 indicate that the analysed set of sources is incomplete to make up a
11576 partition and that some subprogram bodies are missing are not generated.
11580 Note: to invoke @command{gnatelim} with a project file, use the @code{gnat}
11581 driver (see @ref{The GNAT Driver and Project Files}).
11583 @node Processing Precompiled Libraries
11584 @subsection Processing Precompiled Libraries
11587 If some program uses a precompiled Ada library, it can be processed by
11588 @code{gnatelim} in a usual way. @code{gnatelim} will newer generate an
11589 Eliminate pragma for a subprogram if the body of this subprogram has not
11590 been analysed, this is a typical case for subprograms from precompiled
11591 libraries. Switch @option{^-wq^/WARNINGS=QUIET^} may be used to suppress
11592 warnings about missing source files and non-analyzed subprogram bodies
11593 that can be generated when processing precompiled Ada libraries.
11595 @node Correcting the List of Eliminate Pragmas
11596 @subsection Correcting the List of Eliminate Pragmas
11599 In some rare cases @code{gnatelim} may try to eliminate
11600 subprograms that are actually called in the program. In this case, the
11601 compiler will generate an error message of the form:
11604 main.adb:4:08: cannot reference subprogram "P" eliminated at elim.out:5
11608 You will need to manually remove the wrong @code{Eliminate} pragmas from
11609 the configuration file indicated in the error message. You should recompile
11610 your program from scratch after that, because you need a consistent
11611 configuration file(s) during the entire compilation.
11613 @node Making Your Executables Smaller
11614 @subsection Making Your Executables Smaller
11617 In order to get a smaller executable for your program you now have to
11618 recompile the program completely with the configuration file containing
11619 pragmas Eliminate generated by gnatelim. If these pragmas are placed in
11620 @file{gnat.adc} file located in your current directory, just do:
11623 $ gnatmake ^-f main_prog^/FORCE_COMPILE MAIN_PROG^
11627 (Use the @option{^-f^/FORCE_COMPILE^} option for @command{gnatmake} to
11628 recompile everything
11629 with the set of pragmas @code{Eliminate} that you have obtained with
11630 @command{gnatelim}).
11632 Be aware that the set of @code{Eliminate} pragmas is specific to each
11633 program. It is not recommended to merge sets of @code{Eliminate}
11634 pragmas created for different programs in one configuration file.
11636 @node Summary of the gnatelim Usage Cycle
11637 @subsection Summary of the @code{gnatelim} Usage Cycle
11640 Here is a quick summary of the steps to be taken in order to reduce
11641 the size of your executables with @code{gnatelim}. You may use
11642 other GNAT options to control the optimization level,
11643 to produce the debugging information, to set search path, etc.
11647 Create a complete set of @file{ALI} files (if the program has not been
11651 $ gnatmake ^-c main_prog^/ACTIONS=COMPILE MAIN_PROG^
11655 Generate a list of @code{Eliminate} pragmas in default configuration file
11656 @file{gnat.adc} in the current directory
11659 $ PIPE GNAT ELIM MAIN_PROG > GNAT.ADC
11662 $ gnatelim main_prog >@r{[}>@r{]} gnat.adc
11667 Recompile the application
11670 $ gnatmake ^-f main_prog^/FORCE_COMPILE MAIN_PROG^
11676 @node Reducing Size of Executables with unused subprogram/data elimination
11677 @section Reducing Size of Executables with Unused Subprogram/Data Elimination
11678 @findex unused subprogram/data elimination
11681 This section describes how you can eliminate unused subprograms and data from
11682 your executable just by setting options at compilation time.
11685 * About unused subprogram/data elimination::
11686 * Compilation options::
11687 * Example of unused subprogram/data elimination::
11690 @node About unused subprogram/data elimination
11691 @subsection About unused subprogram/data elimination
11694 By default, an executable contains all code and data of its composing objects
11695 (directly linked or coming from statically linked libraries), even data or code
11696 never used by this executable.
11698 This feature will allow you to eliminate such unused code from your
11699 executable, making it smaller (in disk and in memory).
11701 This functionality is available on all Linux platforms except for the IA-64
11702 architecture and on all cross platforms using the ELF binary file format.
11703 In both cases GNU binutils version 2.16 or later are required to enable it.
11705 @node Compilation options
11706 @subsection Compilation options
11709 The operation of eliminating the unused code and data from the final executable
11710 is directly performed by the linker.
11712 In order to do this, it has to work with objects compiled with the
11714 @option{-ffunction-sections} @option{-fdata-sections}.
11715 @cindex @option{-ffunction-sections} (@command{gcc})
11716 @cindex @option{-fdata-sections} (@command{gcc})
11717 These options are usable with C and Ada files.
11718 They will place respectively each
11719 function or data in a separate section in the resulting object file.
11721 Once the objects and static libraries are created with these options, the
11722 linker can perform the dead code elimination. You can do this by setting
11723 the @option{-Wl,--gc-sections} option to gcc command or in the
11724 @option{-largs} section of @command{gnatmake}. This will perform a
11725 garbage collection of code and data never referenced.
11727 If the linker performs a partial link (@option{-r} linker option), then you
11728 will need to provide the entry point using the @option{-e} / @option{--entry}
11731 Note that objects compiled without the @option{-ffunction-sections} and
11732 @option{-fdata-sections} options can still be linked with the executable.
11733 However, no dead code elimination will be performed on those objects (they will
11736 The GNAT static library is now compiled with -ffunction-sections and
11737 -fdata-sections on some platforms. This allows you to eliminate the unused code
11738 and data of the GNAT library from your executable.
11740 @node Example of unused subprogram/data elimination
11741 @subsection Example of unused subprogram/data elimination
11744 Here is a simple example:
11746 @smallexample @c ada
11755 Used_Data : Integer;
11756 Unused_Data : Integer;
11758 procedure Used (Data : Integer);
11759 procedure Unused (Data : Integer);
11762 package body Aux is
11763 procedure Used (Data : Integer) is
11768 procedure Unused (Data : Integer) is
11770 Unused_Data := Data;
11776 @code{Unused} and @code{Unused_Data} are never referenced in this code
11777 excerpt, and hence they may be safely removed from the final executable.
11782 $ nm test | grep used
11783 020015f0 T aux__unused
11784 02005d88 B aux__unused_data
11785 020015cc T aux__used
11786 02005d84 B aux__used_data
11788 $ gnatmake test -cargs -fdata-sections -ffunction-sections \
11789 -largs -Wl,--gc-sections
11791 $ nm test | grep used
11792 02005350 T aux__used
11793 0201ffe0 B aux__used_data
11797 It can be observed that the procedure @code{Unused} and the object
11798 @code{Unused_Data} are removed by the linker when using the
11799 appropriate options.
11801 @c ********************************
11802 @node Renaming Files with gnatchop
11803 @chapter Renaming Files with @code{gnatchop}
11807 This chapter discusses how to handle files with multiple units by using
11808 the @code{gnatchop} utility. This utility is also useful in renaming
11809 files to meet the standard GNAT default file naming conventions.
11812 * Handling Files with Multiple Units::
11813 * Operating gnatchop in Compilation Mode::
11814 * Command Line for gnatchop::
11815 * Switches for gnatchop::
11816 * Examples of gnatchop Usage::
11819 @node Handling Files with Multiple Units
11820 @section Handling Files with Multiple Units
11823 The basic compilation model of GNAT requires that a file submitted to the
11824 compiler have only one unit and there be a strict correspondence
11825 between the file name and the unit name.
11827 The @code{gnatchop} utility allows both of these rules to be relaxed,
11828 allowing GNAT to process files which contain multiple compilation units
11829 and files with arbitrary file names. @code{gnatchop}
11830 reads the specified file and generates one or more output files,
11831 containing one unit per file. The unit and the file name correspond,
11832 as required by GNAT.
11834 If you want to permanently restructure a set of ``foreign'' files so that
11835 they match the GNAT rules, and do the remaining development using the
11836 GNAT structure, you can simply use @command{gnatchop} once, generate the
11837 new set of files and work with them from that point on.
11839 Alternatively, if you want to keep your files in the ``foreign'' format,
11840 perhaps to maintain compatibility with some other Ada compilation
11841 system, you can set up a procedure where you use @command{gnatchop} each
11842 time you compile, regarding the source files that it writes as temporary
11843 files that you throw away.
11845 Note that if your file containing multiple units starts with a byte order
11846 mark (BOM) specifying UTF-8 encoding, then the files generated by gnatchop
11847 will each start with a copy of this BOM, meaning that they can be compiled
11848 automatically in UTF-8 mode without needing to specify an explicit encoding.
11850 @node Operating gnatchop in Compilation Mode
11851 @section Operating gnatchop in Compilation Mode
11854 The basic function of @code{gnatchop} is to take a file with multiple units
11855 and split it into separate files. The boundary between files is reasonably
11856 clear, except for the issue of comments and pragmas. In default mode, the
11857 rule is that any pragmas between units belong to the previous unit, except
11858 that configuration pragmas always belong to the following unit. Any comments
11859 belong to the following unit. These rules
11860 almost always result in the right choice of
11861 the split point without needing to mark it explicitly and most users will
11862 find this default to be what they want. In this default mode it is incorrect to
11863 submit a file containing only configuration pragmas, or one that ends in
11864 configuration pragmas, to @code{gnatchop}.
11866 However, using a special option to activate ``compilation mode'',
11868 can perform another function, which is to provide exactly the semantics
11869 required by the RM for handling of configuration pragmas in a compilation.
11870 In the absence of configuration pragmas (at the main file level), this
11871 option has no effect, but it causes such configuration pragmas to be handled
11872 in a quite different manner.
11874 First, in compilation mode, if @code{gnatchop} is given a file that consists of
11875 only configuration pragmas, then this file is appended to the
11876 @file{gnat.adc} file in the current directory. This behavior provides
11877 the required behavior described in the RM for the actions to be taken
11878 on submitting such a file to the compiler, namely that these pragmas
11879 should apply to all subsequent compilations in the same compilation
11880 environment. Using GNAT, the current directory, possibly containing a
11881 @file{gnat.adc} file is the representation
11882 of a compilation environment. For more information on the
11883 @file{gnat.adc} file, see @ref{Handling of Configuration Pragmas}.
11885 Second, in compilation mode, if @code{gnatchop}
11886 is given a file that starts with
11887 configuration pragmas, and contains one or more units, then these
11888 configuration pragmas are prepended to each of the chopped files. This
11889 behavior provides the required behavior described in the RM for the
11890 actions to be taken on compiling such a file, namely that the pragmas
11891 apply to all units in the compilation, but not to subsequently compiled
11894 Finally, if configuration pragmas appear between units, they are appended
11895 to the previous unit. This results in the previous unit being illegal,
11896 since the compiler does not accept configuration pragmas that follow
11897 a unit. This provides the required RM behavior that forbids configuration
11898 pragmas other than those preceding the first compilation unit of a
11901 For most purposes, @code{gnatchop} will be used in default mode. The
11902 compilation mode described above is used only if you need exactly
11903 accurate behavior with respect to compilations, and you have files
11904 that contain multiple units and configuration pragmas. In this
11905 circumstance the use of @code{gnatchop} with the compilation mode
11906 switch provides the required behavior, and is for example the mode
11907 in which GNAT processes the ACVC tests.
11909 @node Command Line for gnatchop
11910 @section Command Line for @code{gnatchop}
11913 The @code{gnatchop} command has the form:
11916 @c $ gnatchop switches @var{file name} @r{[}@var{file name} @dots{}@r{]}
11917 @c @ovar{directory}
11918 @c Expanding @ovar macro inline (explanation in macro def comments)
11919 $ gnatchop switches @var{file name} @r{[}@var{file name} @dots{}@r{]}
11920 @r{[}@var{directory}@r{]}
11924 The only required argument is the file name of the file to be chopped.
11925 There are no restrictions on the form of this file name. The file itself
11926 contains one or more Ada units, in normal GNAT format, concatenated
11927 together. As shown, more than one file may be presented to be chopped.
11929 When run in default mode, @code{gnatchop} generates one output file in
11930 the current directory for each unit in each of the files.
11932 @var{directory}, if specified, gives the name of the directory to which
11933 the output files will be written. If it is not specified, all files are
11934 written to the current directory.
11936 For example, given a
11937 file called @file{hellofiles} containing
11939 @smallexample @c ada
11944 with Text_IO; use Text_IO;
11947 Put_Line ("Hello");
11957 $ gnatchop ^hellofiles^HELLOFILES.^
11961 generates two files in the current directory, one called
11962 @file{hello.ads} containing the single line that is the procedure spec,
11963 and the other called @file{hello.adb} containing the remaining text. The
11964 original file is not affected. The generated files can be compiled in
11968 When gnatchop is invoked on a file that is empty or that contains only empty
11969 lines and/or comments, gnatchop will not fail, but will not produce any
11972 For example, given a
11973 file called @file{toto.txt} containing
11975 @smallexample @c ada
11987 $ gnatchop ^toto.txt^TOT.TXT^
11991 will not produce any new file and will result in the following warnings:
11994 toto.txt:1:01: warning: empty file, contains no compilation units
11995 no compilation units found
11996 no source files written
11999 @node Switches for gnatchop
12000 @section Switches for @code{gnatchop}
12003 @command{gnatchop} recognizes the following switches:
12009 @cindex @option{--version} @command{gnatchop}
12010 Display Copyright and version, then exit disregarding all other options.
12013 @cindex @option{--help} @command{gnatchop}
12014 If @option{--version} was not used, display usage, then exit disregarding
12017 @item ^-c^/COMPILATION^
12018 @cindex @option{^-c^/COMPILATION^} (@code{gnatchop})
12019 Causes @code{gnatchop} to operate in compilation mode, in which
12020 configuration pragmas are handled according to strict RM rules. See
12021 previous section for a full description of this mode.
12024 @item -gnat@var{xxx}
12025 This passes the given @option{-gnat@var{xxx}} switch to @code{gnat} which is
12026 used to parse the given file. Not all @var{xxx} options make sense,
12027 but for example, the use of @option{-gnati2} allows @code{gnatchop} to
12028 process a source file that uses Latin-2 coding for identifiers.
12032 Causes @code{gnatchop} to generate a brief help summary to the standard
12033 output file showing usage information.
12035 @item ^-k@var{mm}^/FILE_NAME_MAX_LENGTH=@var{mm}^
12036 @cindex @option{^-k^/FILE_NAME_MAX_LENGTH^} (@code{gnatchop})
12037 Limit generated file names to the specified number @code{mm}
12039 This is useful if the
12040 resulting set of files is required to be interoperable with systems
12041 which limit the length of file names.
12043 If no value is given, or
12044 if no @code{/FILE_NAME_MAX_LENGTH} qualifier is given,
12045 a default of 39, suitable for OpenVMS Alpha
12046 Systems, is assumed
12049 No space is allowed between the @option{-k} and the numeric value. The numeric
12050 value may be omitted in which case a default of @option{-k8},
12052 with DOS-like file systems, is used. If no @option{-k} switch
12054 there is no limit on the length of file names.
12057 @item ^-p^/PRESERVE^
12058 @cindex @option{^-p^/PRESERVE^} (@code{gnatchop})
12059 Causes the file ^modification^creation^ time stamp of the input file to be
12060 preserved and used for the time stamp of the output file(s). This may be
12061 useful for preserving coherency of time stamps in an environment where
12062 @code{gnatchop} is used as part of a standard build process.
12065 @cindex @option{^-q^/QUIET^} (@code{gnatchop})
12066 Causes output of informational messages indicating the set of generated
12067 files to be suppressed. Warnings and error messages are unaffected.
12069 @item ^-r^/REFERENCE^
12070 @cindex @option{^-r^/REFERENCE^} (@code{gnatchop})
12071 @findex Source_Reference
12072 Generate @code{Source_Reference} pragmas. Use this switch if the output
12073 files are regarded as temporary and development is to be done in terms
12074 of the original unchopped file. This switch causes
12075 @code{Source_Reference} pragmas to be inserted into each of the
12076 generated files to refers back to the original file name and line number.
12077 The result is that all error messages refer back to the original
12079 In addition, the debugging information placed into the object file (when
12080 the @option{^-g^/DEBUG^} switch of @command{gcc} or @command{gnatmake} is
12082 also refers back to this original file so that tools like profilers and
12083 debuggers will give information in terms of the original unchopped file.
12085 If the original file to be chopped itself contains
12086 a @code{Source_Reference}
12087 pragma referencing a third file, then gnatchop respects
12088 this pragma, and the generated @code{Source_Reference} pragmas
12089 in the chopped file refer to the original file, with appropriate
12090 line numbers. This is particularly useful when @code{gnatchop}
12091 is used in conjunction with @code{gnatprep} to compile files that
12092 contain preprocessing statements and multiple units.
12094 @item ^-v^/VERBOSE^
12095 @cindex @option{^-v^/VERBOSE^} (@code{gnatchop})
12096 Causes @code{gnatchop} to operate in verbose mode. The version
12097 number and copyright notice are output, as well as exact copies of
12098 the gnat1 commands spawned to obtain the chop control information.
12100 @item ^-w^/OVERWRITE^
12101 @cindex @option{^-w^/OVERWRITE^} (@code{gnatchop})
12102 Overwrite existing file names. Normally @code{gnatchop} regards it as a
12103 fatal error if there is already a file with the same name as a
12104 file it would otherwise output, in other words if the files to be
12105 chopped contain duplicated units. This switch bypasses this
12106 check, and causes all but the last instance of such duplicated
12107 units to be skipped.
12110 @item --GCC=@var{xxxx}
12111 @cindex @option{--GCC=} (@code{gnatchop})
12112 Specify the path of the GNAT parser to be used. When this switch is used,
12113 no attempt is made to add the prefix to the GNAT parser executable.
12117 @node Examples of gnatchop Usage
12118 @section Examples of @code{gnatchop} Usage
12122 @item gnatchop /OVERWRITE HELLO_S.ADA [PRERELEASE.FILES]
12125 @item gnatchop -w hello_s.ada prerelease/files
12128 Chops the source file @file{hello_s.ada}. The output files will be
12129 placed in the directory @file{^prerelease/files^[PRERELEASE.FILES]^},
12131 files with matching names in that directory (no files in the current
12132 directory are modified).
12134 @item gnatchop ^archive^ARCHIVE.^
12135 Chops the source file @file{^archive^ARCHIVE.^}
12136 into the current directory. One
12137 useful application of @code{gnatchop} is in sending sets of sources
12138 around, for example in email messages. The required sources are simply
12139 concatenated (for example, using a ^Unix @code{cat}^VMS @code{APPEND/NEW}^
12141 @command{gnatchop} is used at the other end to reconstitute the original
12144 @item gnatchop file1 file2 file3 direc
12145 Chops all units in files @file{file1}, @file{file2}, @file{file3}, placing
12146 the resulting files in the directory @file{direc}. Note that if any units
12147 occur more than once anywhere within this set of files, an error message
12148 is generated, and no files are written. To override this check, use the
12149 @option{^-w^/OVERWRITE^} switch,
12150 in which case the last occurrence in the last file will
12151 be the one that is output, and earlier duplicate occurrences for a given
12152 unit will be skipped.
12155 @node Configuration Pragmas
12156 @chapter Configuration Pragmas
12157 @cindex Configuration pragmas
12158 @cindex Pragmas, configuration
12161 * Handling of Configuration Pragmas::
12162 * The Configuration Pragmas Files::
12166 Configuration pragmas include those pragmas described as
12167 such in the Ada Reference Manual, as well as
12168 implementation-dependent pragmas that are configuration pragmas.
12169 @xref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference Manual},
12170 for details on these additional GNAT-specific configuration pragmas.
12171 Most notably, the pragma @code{Source_File_Name}, which allows
12172 specifying non-default names for source files, is a configuration
12173 pragma. The following is a complete list of configuration pragmas
12174 recognized by GNAT:
12183 Allow_Integer_Address
12186 Assume_No_Invalid_Values
12191 Compile_Time_Warning
12193 Component_Alignment
12194 Convention_Identifier
12197 Default_Storage_Pool
12203 External_Name_Casing
12206 Float_Representation
12219 Priority_Specific_Dispatching
12222 Propagate_Exceptions
12225 Restricted_Run_Time
12227 Restrictions_Warnings
12229 Short_Circuit_And_Or
12231 Source_File_Name_Project
12235 Suppress_Exception_Locations
12236 Task_Dispatching_Policy
12242 Wide_Character_Encoding
12245 @node Handling of Configuration Pragmas
12246 @section Handling of Configuration Pragmas
12248 Configuration pragmas may either appear at the start of a compilation
12249 unit, or they can appear in a configuration pragma file to apply to
12250 all compilations performed in a given compilation environment.
12252 GNAT also provides the @code{gnatchop} utility to provide an automatic
12253 way to handle configuration pragmas following the semantics for
12254 compilations (that is, files with multiple units), described in the RM.
12255 See @ref{Operating gnatchop in Compilation Mode} for details.
12256 However, for most purposes, it will be more convenient to edit the
12257 @file{gnat.adc} file that contains configuration pragmas directly,
12258 as described in the following section.
12260 In the case of @code{Restrictions} pragmas appearing as configuration
12261 pragmas in individual compilation units, the exact handling depends on
12262 the type of restriction.
12264 Restrictions that require partition-wide consistency (like
12265 @code{No_Tasking}) are
12266 recognized wherever they appear
12267 and can be freely inherited, e.g. from a with'ed unit to the with'ing
12268 unit. This makes sense since the binder will in any case insist on seeing
12269 consistent use, so any unit not conforming to any restrictions that are
12270 anywhere in the partition will be rejected, and you might as well find
12271 that out at compile time rather than at bind time.
12273 For restrictions that do not require partition-wide consistency, e.g.
12274 SPARK or No_Implementation_Attributes, in general the restriction applies
12275 only to the unit in which the pragma appears, and not to any other units.
12277 The exception is No_Elaboration_Code which always applies to the entire
12278 object file from a compilation, i.e. to the body, spec, and all subunits.
12279 This restriction can be specified in a configuration pragma file, or it
12280 can be on the body and/or the spec (in eithe case it applies to all the
12281 relevant units). It can appear on a subunit only if it has previously
12282 appeared in the body of spec.
12284 @node The Configuration Pragmas Files
12285 @section The Configuration Pragmas Files
12286 @cindex @file{gnat.adc}
12289 In GNAT a compilation environment is defined by the current
12290 directory at the time that a compile command is given. This current
12291 directory is searched for a file whose name is @file{gnat.adc}. If
12292 this file is present, it is expected to contain one or more
12293 configuration pragmas that will be applied to the current compilation.
12294 However, if the switch @option{-gnatA} is used, @file{gnat.adc} is not
12297 Configuration pragmas may be entered into the @file{gnat.adc} file
12298 either by running @code{gnatchop} on a source file that consists only of
12299 configuration pragmas, or more conveniently by
12300 direct editing of the @file{gnat.adc} file, which is a standard format
12303 In addition to @file{gnat.adc}, additional files containing configuration
12304 pragmas may be applied to the current compilation using the switch
12305 @option{-gnatec}@var{path}. @var{path} must designate an existing file that
12306 contains only configuration pragmas. These configuration pragmas are
12307 in addition to those found in @file{gnat.adc} (provided @file{gnat.adc}
12308 is present and switch @option{-gnatA} is not used).
12310 It is allowed to specify several switches @option{-gnatec}, all of which
12311 will be taken into account.
12313 If you are using project file, a separate mechanism is provided using
12314 project attributes, see @ref{Specifying Configuration Pragmas} for more
12318 Of special interest to GNAT OpenVMS Alpha is the following
12319 configuration pragma:
12321 @smallexample @c ada
12323 pragma Extend_System (Aux_DEC);
12328 In the presence of this pragma, GNAT adds to the definition of the
12329 predefined package SYSTEM all the additional types and subprograms that are
12330 defined in HP Ada. See @ref{Compatibility with HP Ada} for details.
12333 @node Handling Arbitrary File Naming Conventions with gnatname
12334 @chapter Handling Arbitrary File Naming Conventions with @code{gnatname}
12335 @cindex Arbitrary File Naming Conventions
12338 * Arbitrary File Naming Conventions::
12339 * Running gnatname::
12340 * Switches for gnatname::
12341 * Examples of gnatname Usage::
12344 @node Arbitrary File Naming Conventions
12345 @section Arbitrary File Naming Conventions
12348 The GNAT compiler must be able to know the source file name of a compilation
12349 unit. When using the standard GNAT default file naming conventions
12350 (@code{.ads} for specs, @code{.adb} for bodies), the GNAT compiler
12351 does not need additional information.
12354 When the source file names do not follow the standard GNAT default file naming
12355 conventions, the GNAT compiler must be given additional information through
12356 a configuration pragmas file (@pxref{Configuration Pragmas})
12358 When the non-standard file naming conventions are well-defined,
12359 a small number of pragmas @code{Source_File_Name} specifying a naming pattern
12360 (@pxref{Alternative File Naming Schemes}) may be sufficient. However,
12361 if the file naming conventions are irregular or arbitrary, a number
12362 of pragma @code{Source_File_Name} for individual compilation units
12364 To help maintain the correspondence between compilation unit names and
12365 source file names within the compiler,
12366 GNAT provides a tool @code{gnatname} to generate the required pragmas for a
12369 @node Running gnatname
12370 @section Running @code{gnatname}
12373 The usual form of the @code{gnatname} command is
12376 @c $ gnatname @ovar{switches} @var{naming_pattern} @ovar{naming_patterns}
12377 @c @r{[}--and @ovar{switches} @var{naming_pattern} @ovar{naming_patterns}@r{]}
12378 @c Expanding @ovar macro inline (explanation in macro def comments)
12379 $ gnatname @r{[}@var{switches}@r{]} @var{naming_pattern} @r{[}@var{naming_patterns}@r{]}
12380 @r{[}--and @r{[}@var{switches}@r{]} @var{naming_pattern} @r{[}@var{naming_patterns}@r{]}@r{]}
12384 All of the arguments are optional. If invoked without any argument,
12385 @code{gnatname} will display its usage.
12388 When used with at least one naming pattern, @code{gnatname} will attempt to
12389 find all the compilation units in files that follow at least one of the
12390 naming patterns. To find these compilation units,
12391 @code{gnatname} will use the GNAT compiler in syntax-check-only mode on all
12395 One or several Naming Patterns may be given as arguments to @code{gnatname}.
12396 Each Naming Pattern is enclosed between double quotes (or single
12397 quotes on Windows).
12398 A Naming Pattern is a regular expression similar to the wildcard patterns
12399 used in file names by the Unix shells or the DOS prompt.
12402 @code{gnatname} may be called with several sections of directories/patterns.
12403 Sections are separated by switch @code{--and}. In each section, there must be
12404 at least one pattern. If no directory is specified in a section, the current
12405 directory (or the project directory is @code{-P} is used) is implied.
12406 The options other that the directory switches and the patterns apply globally
12407 even if they are in different sections.
12410 Examples of Naming Patterns are
12419 For a more complete description of the syntax of Naming Patterns,
12420 see the second kind of regular expressions described in @file{g-regexp.ads}
12421 (the ``Glob'' regular expressions).
12424 When invoked with no switch @code{-P}, @code{gnatname} will create a
12425 configuration pragmas file @file{gnat.adc} in the current working directory,
12426 with pragmas @code{Source_File_Name} for each file that contains a valid Ada
12429 @node Switches for gnatname
12430 @section Switches for @code{gnatname}
12433 Switches for @code{gnatname} must precede any specified Naming Pattern.
12436 You may specify any of the following switches to @code{gnatname}:
12442 @cindex @option{--version} @command{gnatname}
12443 Display Copyright and version, then exit disregarding all other options.
12446 @cindex @option{--help} @command{gnatname}
12447 If @option{--version} was not used, display usage, then exit disregarding
12450 @item --subdirs=<dir>
12451 Real object, library or exec directories are subdirectories <dir> of the
12455 Do not create a backup copy of an existing project file.
12458 Start another section of directories/patterns.
12460 @item ^-c^/CONFIG_FILE=^@file{file}
12461 @cindex @option{^-c^/CONFIG_FILE^} (@code{gnatname})
12462 Create a configuration pragmas file @file{file} (instead of the default
12465 There may be zero, one or more space between @option{-c} and
12468 @file{file} may include directory information. @file{file} must be
12469 writable. There may be only one switch @option{^-c^/CONFIG_FILE^}.
12470 When a switch @option{^-c^/CONFIG_FILE^} is
12471 specified, no switch @option{^-P^/PROJECT_FILE^} may be specified (see below).
12473 @item ^-d^/SOURCE_DIRS=^@file{dir}
12474 @cindex @option{^-d^/SOURCE_DIRS^} (@code{gnatname})
12475 Look for source files in directory @file{dir}. There may be zero, one or more
12476 spaces between @option{^-d^/SOURCE_DIRS=^} and @file{dir}.
12477 @file{dir} may end with @code{/**}, that is it may be of the form
12478 @code{root_dir/**}. In this case, the directory @code{root_dir} and all of its
12479 subdirectories, recursively, have to be searched for sources.
12480 When a switch @option{^-d^/SOURCE_DIRS^}
12481 is specified, the current working directory will not be searched for source
12482 files, unless it is explicitly specified with a @option{^-d^/SOURCE_DIRS^}
12483 or @option{^-D^/DIR_FILES^} switch.
12484 Several switches @option{^-d^/SOURCE_DIRS^} may be specified.
12485 If @file{dir} is a relative path, it is relative to the directory of
12486 the configuration pragmas file specified with switch
12487 @option{^-c^/CONFIG_FILE^},
12488 or to the directory of the project file specified with switch
12489 @option{^-P^/PROJECT_FILE^} or,
12490 if neither switch @option{^-c^/CONFIG_FILE^}
12491 nor switch @option{^-P^/PROJECT_FILE^} are specified, it is relative to the
12492 current working directory. The directory
12493 specified with switch @option{^-d^/SOURCE_DIRS^} must exist and be readable.
12495 @item ^-D^/DIRS_FILE=^@file{file}
12496 @cindex @option{^-D^/DIRS_FILE^} (@code{gnatname})
12497 Look for source files in all directories listed in text file @file{file}.
12498 There may be zero, one or more spaces between @option{^-D^/DIRS_FILE=^}
12500 @file{file} must be an existing, readable text file.
12501 Each nonempty line in @file{file} must be a directory.
12502 Specifying switch @option{^-D^/DIRS_FILE^} is equivalent to specifying as many
12503 switches @option{^-d^/SOURCE_DIRS^} as there are nonempty lines in
12507 Follow symbolic links when processing project files.
12509 @item ^-f^/FOREIGN_PATTERN=^@file{pattern}
12510 @cindex @option{^-f^/FOREIGN_PATTERN^} (@code{gnatname})
12511 Foreign patterns. Using this switch, it is possible to add sources of languages
12512 other than Ada to the list of sources of a project file.
12513 It is only useful if a ^-P^/PROJECT_FILE^ switch is used.
12516 gnatname ^-Pprj -f"*.c"^/PROJECT_FILE=PRJ /FOREIGN_PATTERN=*.C^ "*.ada"
12519 will look for Ada units in all files with the @file{.ada} extension,
12520 and will add to the list of file for project @file{prj.gpr} the C files
12521 with extension @file{.^c^C^}.
12524 @cindex @option{^-h^/HELP^} (@code{gnatname})
12525 Output usage (help) information. The output is written to @file{stdout}.
12527 @item ^-P^/PROJECT_FILE=^@file{proj}
12528 @cindex @option{^-P^/PROJECT_FILE^} (@code{gnatname})
12529 Create or update project file @file{proj}. There may be zero, one or more space
12530 between @option{-P} and @file{proj}. @file{proj} may include directory
12531 information. @file{proj} must be writable.
12532 There may be only one switch @option{^-P^/PROJECT_FILE^}.
12533 When a switch @option{^-P^/PROJECT_FILE^} is specified,
12534 no switch @option{^-c^/CONFIG_FILE^} may be specified.
12535 On all platforms, except on VMS, when @code{gnatname} is invoked for an
12536 existing project file <proj>.gpr, a backup copy of the project file is created
12537 in the project directory with file name <proj>.gpr.saved_x. 'x' is the first
12538 non negative number that makes this backup copy a new file.
12540 @item ^-v^/VERBOSE^
12541 @cindex @option{^-v^/VERBOSE^} (@code{gnatname})
12542 Verbose mode. Output detailed explanation of behavior to @file{stdout}.
12543 This includes name of the file written, the name of the directories to search
12544 and, for each file in those directories whose name matches at least one of
12545 the Naming Patterns, an indication of whether the file contains a unit,
12546 and if so the name of the unit.
12548 @item ^-v -v^/VERBOSE /VERBOSE^
12549 @cindex @option{^-v -v^/VERBOSE /VERBOSE^} (@code{gnatname})
12550 Very Verbose mode. In addition to the output produced in verbose mode,
12551 for each file in the searched directories whose name matches none of
12552 the Naming Patterns, an indication is given that there is no match.
12554 @item ^-x^/EXCLUDED_PATTERN=^@file{pattern}
12555 @cindex @option{^-x^/EXCLUDED_PATTERN^} (@code{gnatname})
12556 Excluded patterns. Using this switch, it is possible to exclude some files
12557 that would match the name patterns. For example,
12559 gnatname ^-x "*_nt.ada"^/EXCLUDED_PATTERN=*_nt.ada^ "*.ada"
12562 will look for Ada units in all files with the @file{.ada} extension,
12563 except those whose names end with @file{_nt.ada}.
12567 @node Examples of gnatname Usage
12568 @section Examples of @code{gnatname} Usage
12572 $ gnatname /CONFIG_FILE=[HOME.ME]NAMES.ADC /SOURCE_DIRS=SOURCES "[a-z]*.ada*"
12578 $ gnatname -c /home/me/names.adc -d sources "[a-z]*.ada*"
12583 In this example, the directory @file{^/home/me^[HOME.ME]^} must already exist
12584 and be writable. In addition, the directory
12585 @file{^/home/me/sources^[HOME.ME.SOURCES]^} (specified by
12586 @option{^-d sources^/SOURCE_DIRS=SOURCES^}) must exist and be readable.
12589 Note the optional spaces after @option{-c} and @option{-d}.
12594 $ gnatname -P/home/me/proj -x "*_nt_body.ada"
12595 -dsources -dsources/plus -Dcommon_dirs.txt "body_*" "spec_*"
12598 $ gnatname /PROJECT_FILE=[HOME.ME]PROJ
12599 /EXCLUDED_PATTERN=*_nt_body.ada
12600 /SOURCE_DIRS=(SOURCES,[SOURCES.PLUS])
12601 /DIRS_FILE=COMMON_DIRS.TXT "body_*" "spec_*"
12605 Note that several switches @option{^-d^/SOURCE_DIRS^} may be used,
12606 even in conjunction with one or several switches
12607 @option{^-D^/DIRS_FILE^}. Several Naming Patterns and one excluded pattern
12608 are used in this example.
12610 @c *****************************************
12611 @c * G N A T P r o j e c t M a n a g e r *
12612 @c *****************************************
12614 @c ------ macros for projects.texi
12615 @c These macros are needed when building the gprbuild documentation, but
12616 @c should have no effect in the gnat user's guide
12618 @macro CODESAMPLE{TXT}
12626 @macro PROJECTFILE{TXT}
12630 @c simulates a newline when in a @CODESAMPLE
12641 @macro TIPHTML{TXT}
12645 @macro IMPORTANT{TXT}
12660 @include projects.texi
12662 @c ---------------------------------------------
12663 @c Tools Supporting Project Files
12664 @c ---------------------------------------------
12666 @node Tools Supporting Project Files
12667 @chapter Tools Supporting Project Files
12672 * gnatmake and Project Files::
12673 * The GNAT Driver and Project Files::
12676 @c ---------------------------------------------
12677 @node gnatmake and Project Files
12678 @section gnatmake and Project Files
12679 @c ---------------------------------------------
12682 This section covers several topics related to @command{gnatmake} and
12683 project files: defining ^switches^switches^ for @command{gnatmake}
12684 and for the tools that it invokes; specifying configuration pragmas;
12685 the use of the @code{Main} attribute; building and rebuilding library project
12689 * Switches Related to Project Files::
12690 * Switches and Project Files::
12691 * Specifying Configuration Pragmas::
12692 * Project Files and Main Subprograms::
12693 * Library Project Files::
12696 @c ---------------------------------------------
12697 @node Switches Related to Project Files
12698 @subsection Switches Related to Project Files
12699 @c ---------------------------------------------
12702 The following switches are used by GNAT tools that support project files:
12706 @item ^-P^/PROJECT_FILE=^@var{project}
12707 @cindex @option{^-P^/PROJECT_FILE^} (any project-aware tool)
12708 Indicates the name of a project file. This project file will be parsed with
12709 the verbosity indicated by @option{^-vP^MESSAGE_PROJECT_FILES=^@emph{x}},
12710 if any, and using the external references indicated
12711 by @option{^-X^/EXTERNAL_REFERENCE^} switches, if any.
12713 There may zero, one or more spaces between @option{-P} and @var{project}.
12716 There must be only one @option{^-P^/PROJECT_FILE^} switch on the command line.
12718 Since the Project Manager parses the project file only after all the switches
12719 on the command line are checked, the order of the switches
12720 @option{^-P^/PROJECT_FILE^},
12721 @option{^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}}
12722 or @option{^-X^/EXTERNAL_REFERENCE^} is not significant.
12724 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
12725 @cindex @option{^-X^/EXTERNAL_REFERENCE^} (any project-aware tool)
12726 Indicates that external variable @var{name} has the value @var{value}.
12727 The Project Manager will use this value for occurrences of
12728 @code{external(name)} when parsing the project file.
12731 If @var{name} or @var{value} includes a space, then @var{name=value} should be
12732 put between quotes.
12739 Several @option{^-X^/EXTERNAL_REFERENCE^} switches can be used simultaneously.
12740 If several @option{^-X^/EXTERNAL_REFERENCE^} switches specify the same
12741 @var{name}, only the last one is used.
12743 An external variable specified with a @option{^-X^/EXTERNAL_REFERENCE^} switch
12744 takes precedence over the value of the same name in the environment.
12746 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
12747 @cindex @option{^-vP^/MESSAGES_PROJECT_FILE^} (any project-aware tool)
12748 Indicates the verbosity of the parsing of GNAT project files.
12751 @option{-vP0} means Default;
12752 @option{-vP1} means Medium;
12753 @option{-vP2} means High.
12757 There are three possible options for this qualifier: DEFAULT, MEDIUM and
12761 The default is ^Default^DEFAULT^: no output for syntactically correct
12763 If several @option{^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}} switches are present,
12764 only the last one is used.
12766 @item ^-aP^/ADD_PROJECT_SEARCH_DIR=^<dir>
12767 @cindex @option{^-aP^/ADD_PROJECT_SEARCH_DIR=^} (any project-aware tool)
12768 Add directory <dir> at the beginning of the project search path, in order,
12769 after the current working directory.
12773 @cindex @option{-eL} (any project-aware tool)
12774 Follow all symbolic links when processing project files.
12777 @item ^--subdirs^/SUBDIRS^=<subdir>
12778 @cindex @option{^--subdirs^/SUBDIRS^=} (gnatmake and gnatclean)
12779 This switch is recognized by @command{gnatmake} and @command{gnatclean}. It
12780 indicate that the real directories (except the source directories) are the
12781 subdirectories <subdir> of the directories specified in the project files.
12782 This applies in particular to object directories, library directories and
12783 exec directories. If the subdirectories do not exist, they are created
12788 @c ---------------------------------------------
12789 @node Switches and Project Files
12790 @subsection Switches and Project Files
12791 @c ---------------------------------------------
12795 It is not currently possible to specify VMS style qualifiers in the project
12796 files; only Unix style ^switches^switches^ may be specified.
12799 For each of the packages @code{Builder}, @code{Compiler}, @code{Binder}, and
12800 @code{Linker}, you can specify a @code{^Default_Switches^Default_Switches^}
12801 attribute, a @code{Switches} attribute, or both;
12802 as their names imply, these ^switch^switch^-related
12803 attributes affect the ^switches^switches^ that are used for each of these GNAT
12805 @command{gnatmake} is invoked. As will be explained below, these
12806 component-specific ^switches^switches^ precede
12807 the ^switches^switches^ provided on the @command{gnatmake} command line.
12809 The @code{^Default_Switches^Default_Switches^} attribute is an attribute
12810 indexed by language name (case insensitive) whose value is a string list.
12813 @smallexample @c projectfile
12815 package Compiler is
12816 for ^Default_Switches^Default_Switches^ ("Ada")
12817 use ("^-gnaty^-gnaty^",
12824 The @code{Switches} attribute is indexed on a file name (which may or may
12825 not be case sensitive, depending
12826 on the operating system) whose value is a string list. For example:
12828 @smallexample @c projectfile
12831 for Switches ("main1.adb")
12833 for Switches ("main2.adb")
12840 For the @code{Builder} package, the file names must designate source files
12841 for main subprograms. For the @code{Binder} and @code{Linker} packages, the
12842 file names must designate @file{ALI} or source files for main subprograms.
12843 In each case just the file name without an explicit extension is acceptable.
12845 For each tool used in a program build (@command{gnatmake}, the compiler, the
12846 binder, and the linker), the corresponding package @dfn{contributes} a set of
12847 ^switches^switches^ for each file on which the tool is invoked, based on the
12848 ^switch^switch^-related attributes defined in the package.
12849 In particular, the ^switches^switches^
12850 that each of these packages contributes for a given file @var{f} comprise:
12853 @item the value of attribute @code{Switches (@var{f})},
12854 if it is specified in the package for the given file,
12855 @item otherwise, the value of @code{^Default_Switches^Default_Switches^ ("Ada")},
12856 if it is specified in the package.
12861 If neither of these attributes is defined in the package, then the package does
12862 not contribute any ^switches^switches^ for the given file.
12864 When @command{gnatmake} is invoked on a file, the ^switches^switches^ comprise
12865 two sets, in the following order: those contributed for the file
12866 by the @code{Builder} package;
12867 and the switches passed on the command line.
12869 When @command{gnatmake} invokes a tool (compiler, binder, linker) on a file,
12870 the ^switches^switches^ passed to the tool comprise three sets,
12871 in the following order:
12875 the applicable ^switches^switches^ contributed for the file
12876 by the @code{Builder} package in the project file supplied on the command line;
12879 those contributed for the file by the package (in the relevant project file --
12880 see below) corresponding to the tool; and
12883 the applicable switches passed on the command line.
12886 The term @emph{applicable ^switches^switches^} reflects the fact that
12887 @command{gnatmake} ^switches^switches^ may or may not be passed to individual
12888 tools, depending on the individual ^switch^switch^.
12890 @command{gnatmake} may invoke the compiler on source files from different
12891 projects. The Project Manager will use the appropriate project file to
12892 determine the @code{Compiler} package for each source file being compiled.
12893 Likewise for the @code{Binder} and @code{Linker} packages.
12895 As an example, consider the following package in a project file:
12897 @smallexample @c projectfile
12900 package Compiler is
12901 for ^Default_Switches^Default_Switches^ ("Ada")
12903 for Switches ("a.adb")
12905 for Switches ("b.adb")
12907 "^-gnaty^-gnaty^");
12914 If @command{gnatmake} is invoked with this project file, and it needs to
12915 compile, say, the files @file{a.adb}, @file{b.adb}, and @file{c.adb}, then
12916 @file{a.adb} will be compiled with the ^switch^switch^
12917 @option{^-O1^-O1^},
12918 @file{b.adb} with ^switches^switches^
12920 and @option{^-gnaty^-gnaty^},
12921 and @file{c.adb} with @option{^-g^-g^}.
12923 The following example illustrates the ordering of the ^switches^switches^
12924 contributed by different packages:
12926 @smallexample @c projectfile
12930 for Switches ("main.adb")
12938 package Compiler is
12939 for Switches ("main.adb")
12947 If you issue the command:
12950 gnatmake ^-Pproj2^/PROJECT_FILE=PROJ2^ -O0 main
12954 then the compiler will be invoked on @file{main.adb} with the following
12955 sequence of ^switches^switches^
12958 ^-g -O1 -O2 -O0^-g -O1 -O2 -O0^
12962 with the last @option{^-O^-O^}
12963 ^switch^switch^ having precedence over the earlier ones;
12964 several other ^switches^switches^
12965 (such as @option{^-c^-c^}) are added implicitly.
12967 The ^switches^switches^
12969 and @option{^-O1^-O1^} are contributed by package
12970 @code{Builder}, @option{^-O2^-O2^} is contributed
12971 by the package @code{Compiler}
12972 and @option{^-O0^-O0^} comes from the command line.
12974 The @option{^-g^-g^}
12975 ^switch^switch^ will also be passed in the invocation of
12976 @command{Gnatlink.}
12978 A final example illustrates switch contributions from packages in different
12981 @smallexample @c projectfile
12984 for Source_Files use ("pack.ads", "pack.adb");
12985 package Compiler is
12986 for ^Default_Switches^Default_Switches^ ("Ada")
12987 use ("^-gnata^-gnata^");
12995 for Source_Files use ("foo_main.adb", "bar_main.adb");
12997 for Switches ("foo_main.adb")
13005 -- Ada source file:
13007 procedure Foo_Main is
13016 gnatmake ^-PProj4^/PROJECT_FILE=PROJ4^ foo_main.adb -cargs -gnato
13020 then the ^switches^switches^ passed to the compiler for @file{foo_main.adb} are
13021 @option{^-g^-g^} (contributed by the package @code{Proj4.Builder}) and
13022 @option{^-gnato^-gnato^} (passed on the command line).
13023 When the imported package @code{Pack} is compiled, the ^switches^switches^ used
13024 are @option{^-g^-g^} from @code{Proj4.Builder},
13025 @option{^-gnata^-gnata^} (contributed from package @code{Proj3.Compiler},
13026 and @option{^-gnato^-gnato^} from the command line.
13028 When using @command{gnatmake} with project files, some ^switches^switches^ or
13029 arguments may be expressed as relative paths. As the working directory where
13030 compilation occurs may change, these relative paths are converted to absolute
13031 paths. For the ^switches^switches^ found in a project file, the relative paths
13032 are relative to the project file directory, for the switches on the command
13033 line, they are relative to the directory where @command{gnatmake} is invoked.
13034 The ^switches^switches^ for which this occurs are:
13040 ^-aI^-aI^, as well as all arguments that are not switches (arguments to
13042 ^-o^-o^, object files specified in package @code{Linker} or after
13043 -largs on the command line). The exception to this rule is the ^switch^switch^
13044 ^--RTS=^--RTS=^ for which a relative path argument is never converted.
13046 @c ---------------------------------------------
13047 @node Specifying Configuration Pragmas
13048 @subsection Specifying Configuration Pragmas
13049 @c ---------------------------------------------
13052 When using @command{gnatmake} with project files, if there exists a file
13053 @file{gnat.adc} that contains configuration pragmas, this file will be
13056 Configuration pragmas can be defined by means of the following attributes in
13057 project files: @code{Global_Configuration_Pragmas} in package @code{Builder}
13058 and @code{Local_Configuration_Pragmas} in package @code{Compiler}.
13060 Both these attributes are single string attributes. Their values is the path
13061 name of a file containing configuration pragmas. If a path name is relative,
13062 then it is relative to the project directory of the project file where the
13063 attribute is defined.
13065 When compiling a source, the configuration pragmas used are, in order,
13066 those listed in the file designated by attribute
13067 @code{Global_Configuration_Pragmas} in package @code{Builder} of the main
13068 project file, if it is specified, and those listed in the file designated by
13069 attribute @code{Local_Configuration_Pragmas} in package @code{Compiler} of
13070 the project file of the source, if it exists.
13072 @c ---------------------------------------------
13073 @node Project Files and Main Subprograms
13074 @subsection Project Files and Main Subprograms
13075 @c ---------------------------------------------
13078 When using a project file, you can invoke @command{gnatmake}
13079 with one or several main subprograms, by specifying their source files on the
13083 gnatmake ^-P^/PROJECT_FILE=^prj main1.adb main2.adb main3.adb
13087 Each of these needs to be a source file of the same project, except
13088 when the switch ^-u^/UNIQUE^ is used.
13090 When ^-u^/UNIQUE^ is not used, all the mains need to be sources of the
13091 same project, one of the project in the tree rooted at the project specified
13092 on the command line. The package @code{Builder} of this common project, the
13093 "main project" is the one that is considered by @command{gnatmake}.
13095 When ^-u^/UNIQUE^ is used, the specified source files may be in projects
13096 imported directly or indirectly by the project specified on the command line.
13097 Note that if such a source file is not part of the project specified on the
13098 command line, the ^switches^switches^ found in package @code{Builder} of the
13099 project specified on the command line, if any, that are transmitted
13100 to the compiler will still be used, not those found in the project file of
13103 When using a project file, you can also invoke @command{gnatmake} without
13104 explicitly specifying any main, and the effect depends on whether you have
13105 defined the @code{Main} attribute. This attribute has a string list value,
13106 where each element in the list is the name of a source file (the file
13107 extension is optional) that contains a unit that can be a main subprogram.
13109 If the @code{Main} attribute is defined in a project file as a non-empty
13110 string list and the switch @option{^-u^/UNIQUE^} is not used on the command
13111 line, then invoking @command{gnatmake} with this project file but without any
13112 main on the command line is equivalent to invoking @command{gnatmake} with all
13113 the file names in the @code{Main} attribute on the command line.
13116 @smallexample @c projectfile
13119 for Main use ("main1.adb", "main2.adb", "main3.adb");
13125 With this project file, @code{"gnatmake ^-Pprj^/PROJECT_FILE=PRJ^"}
13127 @code{"gnatmake ^-Pprj^/PROJECT_FILE=PRJ^ main1.adb main2.adb main3.adb"}.
13129 When the project attribute @code{Main} is not specified, or is specified
13130 as an empty string list, or when the switch @option{-u} is used on the command
13131 line, then invoking @command{gnatmake} with no main on the command line will
13132 result in all immediate sources of the project file being checked, and
13133 potentially recompiled. Depending on the presence of the switch @option{-u},
13134 sources from other project files on which the immediate sources of the main
13135 project file depend are also checked and potentially recompiled. In other
13136 words, the @option{-u} switch is applied to all of the immediate sources of the
13139 When no main is specified on the command line and attribute @code{Main} exists
13140 and includes several mains, or when several mains are specified on the
13141 command line, the default ^switches^switches^ in package @code{Builder} will
13142 be used for all mains, even if there are specific ^switches^switches^
13143 specified for one or several mains.
13145 But the ^switches^switches^ from package @code{Binder} or @code{Linker} will be
13146 the specific ^switches^switches^ for each main, if they are specified.
13148 @c ---------------------------------------------
13149 @node Library Project Files
13150 @subsection Library Project Files
13151 @c ---------------------------------------------
13154 When @command{gnatmake} is invoked with a main project file that is a library
13155 project file, it is not allowed to specify one or more mains on the command
13158 When a library project file is specified, switches ^-b^/ACTION=BIND^ and
13159 ^-l^/ACTION=LINK^ have special meanings.
13162 @item ^-b^/ACTION=BIND^ is only allowed for stand-alone libraries. It indicates
13163 to @command{gnatmake} that @command{gnatbind} should be invoked for the
13166 @item ^-l^/ACTION=LINK^ may be used for all library projects. It indicates
13167 to @command{gnatmake} that the binder generated file should be compiled
13168 (in the case of a stand-alone library) and that the library should be built.
13171 @c ---------------------------------------------
13172 @node The GNAT Driver and Project Files
13173 @section The GNAT Driver and Project Files
13174 @c ---------------------------------------------
13177 A number of GNAT tools, other than @command{^gnatmake^gnatmake^}
13178 can benefit from project files:
13179 (@command{^gnatbind^gnatbind^},
13180 @ifclear FSFEDITION
13181 @command{^gnatcheck^gnatcheck^},
13183 @command{^gnatclean^gnatclean^},
13184 @ifclear FSFEDITION
13185 @command{^gnatelim^gnatelim^},
13187 @command{^gnatfind^gnatfind^},
13188 @command{^gnatlink^gnatlink^},
13189 @command{^gnatls^gnatls^},
13190 @ifclear FSFEDITION
13191 @command{^gnatmetric^gnatmetric^},
13192 @command{^gnatpp^gnatpp^},
13193 @command{^gnatstub^gnatstub^},
13195 and @command{^gnatxref^gnatxref^}). However, none of these tools can be invoked
13196 directly with a project file switch (@option{^-P^/PROJECT_FILE=^}).
13197 They must be invoked through the @command{gnat} driver.
13199 The @command{gnat} driver is a wrapper that accepts a number of commands and
13200 calls the corresponding tool. It was designed initially for VMS platforms (to
13201 convert VMS qualifiers to Unix-style switches), but it is now available on all
13204 On non-VMS platforms, the @command{gnat} driver accepts the following commands
13205 (case insensitive):
13208 @item BIND to invoke @command{^gnatbind^gnatbind^}
13209 @item CHOP to invoke @command{^gnatchop^gnatchop^}
13210 @item CLEAN to invoke @command{^gnatclean^gnatclean^}
13211 @item COMP or COMPILE to invoke the compiler
13212 @ifclear FSFEDITION
13213 @item ELIM to invoke @command{^gnatelim^gnatelim^}
13215 @item FIND to invoke @command{^gnatfind^gnatfind^}
13216 @item KR or KRUNCH to invoke @command{^gnatkr^gnatkr^}
13217 @item LINK to invoke @command{^gnatlink^gnatlink^}
13218 @item LS or LIST to invoke @command{^gnatls^gnatls^}
13219 @item MAKE to invoke @command{^gnatmake^gnatmake^}
13220 @item NAME to invoke @command{^gnatname^gnatname^}
13221 @item PREP or PREPROCESS to invoke @command{^gnatprep^gnatprep^}
13222 @ifclear FSFEDITION
13223 @item PP or PRETTY to invoke @command{^gnatpp^gnatpp^}
13224 @item METRIC to invoke @command{^gnatmetric^gnatmetric^}
13225 @item STUB to invoke @command{^gnatstub^gnatstub^}
13227 @item XREF to invoke @command{^gnatxref^gnatxref^}
13232 (note that the compiler is invoked using the command
13233 @command{^gnatmake -f -u -c^gnatmake -f -u -c^}).
13235 On non-VMS platforms, between @command{gnat} and the command, two
13236 special switches may be used:
13239 @item @command{-v} to display the invocation of the tool.
13240 @item @command{-dn} to prevent the @command{gnat} driver from removing
13241 the temporary files it has created. These temporary files are
13242 configuration files and temporary file list files.
13247 The command may be followed by switches and arguments for the invoked
13251 gnat bind -C main.ali
13257 Switches may also be put in text files, one switch per line, and the text
13258 files may be specified with their path name preceded by '@@'.
13261 gnat bind @@args.txt main.ali
13265 In addition, for commands BIND, COMP or COMPILE, FIND,
13266 @ifclear FSFEDITION
13270 @ifclear FSFEDITION
13275 and XREF, the project file related switches
13276 (@option{^-P^/PROJECT_FILE^},
13277 @option{^-X^/EXTERNAL_REFERENCE^} and
13278 @option{^-vP^/MESSAGES_PROJECT_FILE=^x}) may be used in addition to
13279 the switches of the invoking tool.
13281 @ifclear FSFEDITION
13282 When GNAT PP or GNAT PRETTY is used with a project file, but with no source
13283 specified on the command line, it invokes @command{^gnatpp^gnatpp^} with all
13284 the immediate sources of the specified project file.
13287 @ifclear FSFEDITION
13288 When GNAT METRIC is used with a project file, but with no source
13289 specified on the command line, it invokes @command{^gnatmetric^gnatmetric^}
13290 with all the immediate sources of the specified project file and with
13291 @option{^-d^/DIRECTORY^} with the parameter pointing to the object directory
13295 @ifclear FSFEDITION
13296 In addition, when GNAT PP, GNAT PRETTY or GNAT METRIC is used with
13297 a project file, no source is specified on the command line and
13298 switch ^-U^/ALL_PROJECTS^ is specified on the command line, then
13299 the underlying tool (^gnatpp^gnatpp^ or
13300 ^gnatmetric^gnatmetric^) is invoked for all sources of all projects,
13301 not only for the immediate sources of the main project.
13303 (-U stands for Universal or Union of the project files of the project tree)
13307 For each of the following commands, there is optionally a corresponding
13308 package in the main project.
13311 @item package @code{Binder} for command BIND (invoking @code{^gnatbind^gnatbind^})
13313 @ifclear FSFEDITION
13314 @item package @code{Check} for command CHECK (invoking
13315 @code{^gnatcheck^gnatcheck^})
13318 @item package @code{Compiler} for command COMP or COMPILE (invoking the compiler)
13320 @item package @code{Cross_Reference} for command XREF (invoking
13321 @code{^gnatxref^gnatxref^})
13323 @ifclear FSFEDITION
13324 @item package @code{Eliminate} for command ELIM (invoking
13325 @code{^gnatelim^gnatelim^})
13328 @item package @code{Finder} for command FIND (invoking @code{^gnatfind^gnatfind^})
13330 @item package @code{Gnatls} for command LS or LIST (invoking @code{^gnatls^gnatls^})
13332 @ifclear FSFEDITION
13333 @item package @code{Gnatstub} for command STUB
13334 (invoking @code{^gnatstub^gnatstub^})
13337 @item package @code{Linker} for command LINK (invoking @code{^gnatlink^gnatlink^})
13339 @ifclear FSFEDITION
13340 @item package @code{Check} for command CHECK
13341 (invoking @code{^gnatcheck^gnatcheck^})
13344 @ifclear FSFEDITION
13345 @item package @code{Metrics} for command METRIC
13346 (invoking @code{^gnatmetric^gnatmetric^})
13349 @ifclear FSFEDITION
13350 @item package @code{Pretty_Printer} for command PP or PRETTY
13351 (invoking @code{^gnatpp^gnatpp^})
13357 Package @code{Gnatls} has a unique attribute @code{Switches},
13358 a simple variable with a string list value. It contains ^switches^switches^
13359 for the invocation of @code{^gnatls^gnatls^}.
13361 @smallexample @c projectfile
13374 All other packages have two attribute @code{Switches} and
13375 @code{^Default_Switches^Default_Switches^}.
13377 @code{Switches} is an indexed attribute, indexed by the
13378 source file name, that has a string list value: the ^switches^switches^ to be
13379 used when the tool corresponding to the package is invoked for the specific
13382 @code{^Default_Switches^Default_Switches^} is an attribute,
13383 indexed by the programming language that has a string list value.
13384 @code{^Default_Switches^Default_Switches^ ("Ada")} contains the
13385 ^switches^switches^ for the invocation of the tool corresponding
13386 to the package, except if a specific @code{Switches} attribute
13387 is specified for the source file.
13389 @smallexample @c projectfile
13393 for Source_Dirs use ("**");
13403 package Compiler is
13404 for ^Default_Switches^Default_Switches^ ("Ada")
13405 use ("^-gnatv^-gnatv^",
13406 "^-gnatwa^-gnatwa^");
13412 for ^Default_Switches^Default_Switches^ ("Ada")
13420 for ^Default_Switches^Default_Switches^ ("Ada")
13422 for Switches ("main.adb")
13431 for ^Default_Switches^Default_Switches^ ("Ada")
13438 package Cross_Reference is
13439 for ^Default_Switches^Default_Switches^ ("Ada")
13444 end Cross_Reference;
13450 With the above project file, commands such as
13453 ^gnat comp -Pproj main^GNAT COMP /PROJECT_FILE=PROJ MAIN^
13454 ^gnat ls -Pproj main^GNAT LIST /PROJECT_FILE=PROJ MAIN^
13455 ^gnat xref -Pproj main^GNAT XREF /PROJECT_FILE=PROJ MAIN^
13456 ^gnat bind -Pproj main.ali^GNAT BIND /PROJECT_FILE=PROJ MAIN.ALI^
13457 ^gnat link -Pproj main.ali^GNAT LINK /PROJECT_FILE=PROJ MAIN.ALI^
13461 will set up the environment properly and invoke the tool with the switches
13462 found in the package corresponding to the tool:
13463 @code{^Default_Switches^Default_Switches^ ("Ada")} for all tools,
13464 except @code{Switches ("main.adb")}
13465 for @code{^gnatlink^gnatlink^}.
13466 @ifclear FSFEDITION
13467 It is also possible to invoke some of the tools,
13468 (@code{^gnatcheck^gnatcheck^},
13469 @code{^gnatmetric^gnatmetric^},
13470 and @code{^gnatpp^gnatpp^})
13471 on a set of project units thanks to the combination of the switches
13472 @option{-P}, @option{-U} and possibly the main unit when one is interested
13473 in its closure. For instance,
13479 will compute the metrics for all the immediate units of project
13482 gnat metric -Pproj -U
13486 will compute the metrics for all the units of the closure of projects
13487 rooted at @code{proj}.
13489 gnat metric -Pproj -U main_unit
13493 will compute the metrics for the closure of units rooted at
13494 @code{main_unit}. This last possibility relies implicitly
13495 on @command{gnatbind}'s option @option{-R}. But if the argument files for the
13496 tool invoked by the @command{gnat} driver are explicitly specified
13497 either directly or through the tool @option{-files} option, then the tool
13498 is called only for these explicitly specified files.
13501 @c *****************************************
13502 @c * Cross-referencing tools
13503 @c *****************************************
13505 @node The Cross-Referencing Tools gnatxref and gnatfind
13506 @chapter The Cross-Referencing Tools @code{gnatxref} and @code{gnatfind}
13511 The compiler generates cross-referencing information (unless
13512 you set the @samp{-gnatx} switch), which are saved in the @file{.ali} files.
13513 This information indicates where in the source each entity is declared and
13514 referenced. Note that entities in package Standard are not included, but
13515 entities in all other predefined units are included in the output.
13517 Before using any of these two tools, you need to compile successfully your
13518 application, so that GNAT gets a chance to generate the cross-referencing
13521 The two tools @code{gnatxref} and @code{gnatfind} take advantage of this
13522 information to provide the user with the capability to easily locate the
13523 declaration and references to an entity. These tools are quite similar,
13524 the difference being that @code{gnatfind} is intended for locating
13525 definitions and/or references to a specified entity or entities, whereas
13526 @code{gnatxref} is oriented to generating a full report of all
13529 To use these tools, you must not compile your application using the
13530 @option{-gnatx} switch on the @command{gnatmake} command line
13531 (@pxref{The GNAT Make Program gnatmake}). Otherwise, cross-referencing
13532 information will not be generated.
13534 Note: to invoke @code{gnatxref} or @code{gnatfind} with a project file,
13535 use the @code{gnat} driver (see @ref{The GNAT Driver and Project Files}).
13538 * Switches for gnatxref::
13539 * Switches for gnatfind::
13540 * Project Files for gnatxref and gnatfind::
13541 * Regular Expressions in gnatfind and gnatxref::
13542 * Examples of gnatxref Usage::
13543 * Examples of gnatfind Usage::
13546 @node Switches for gnatxref
13547 @section @code{gnatxref} Switches
13550 The command invocation for @code{gnatxref} is:
13552 @c $ gnatxref @ovar{switches} @var{sourcefile1} @r{[}@var{sourcefile2} @dots{}@r{]}
13553 @c Expanding @ovar macro inline (explanation in macro def comments)
13554 $ gnatxref @r{[}@var{switches}@r{]} @var{sourcefile1} @r{[}@var{sourcefile2} @dots{}@r{]}
13563 identifies the source files for which a report is to be generated. The
13564 ``with''ed units will be processed too. You must provide at least one file.
13566 These file names are considered to be regular expressions, so for instance
13567 specifying @file{source*.adb} is the same as giving every file in the current
13568 directory whose name starts with @file{source} and whose extension is
13571 You shouldn't specify any directory name, just base names. @command{gnatxref}
13572 and @command{gnatfind} will be able to locate these files by themselves using
13573 the source path. If you specify directories, no result is produced.
13578 The switches can be:
13582 @cindex @option{--version} @command{gnatxref}
13583 Display Copyright and version, then exit disregarding all other options.
13586 @cindex @option{--help} @command{gnatxref}
13587 If @option{--version} was not used, display usage, then exit disregarding
13590 @item ^-a^/ALL_FILES^
13591 @cindex @option{^-a^/ALL_FILES^} (@command{gnatxref})
13592 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
13593 the read-only files found in the library search path. Otherwise, these files
13594 will be ignored. This option can be used to protect Gnat sources or your own
13595 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
13596 much faster, and their output much smaller. Read-only here refers to access
13597 or permissions status in the file system for the current user.
13600 @cindex @option{-aIDIR} (@command{gnatxref})
13601 When looking for source files also look in directory DIR. The order in which
13602 source file search is undertaken is the same as for @command{gnatmake}.
13605 @cindex @option{-aODIR} (@command{gnatxref})
13606 When searching for library and object files, look in directory
13607 DIR. The order in which library files are searched is the same as for
13608 @command{gnatmake}.
13611 @cindex @option{-nostdinc} (@command{gnatxref})
13612 Do not look for sources in the system default directory.
13615 @cindex @option{-nostdlib} (@command{gnatxref})
13616 Do not look for library files in the system default directory.
13618 @item --ext=@var{extension}
13619 @cindex @option{--ext} (@command{gnatxref})
13620 Specify an alternate ali file extension. The default is @code{ali} and other
13621 extensions (e.g. @code{gli} for C/C++ sources when using @option{-fdump-xref})
13622 may be specified via this switch. Note that if this switch overrides the
13623 default, which means that only the new extension will be considered.
13625 @item --RTS=@var{rts-path}
13626 @cindex @option{--RTS} (@command{gnatxref})
13627 Specifies the default location of the runtime library. Same meaning as the
13628 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
13630 @item ^-d^/DERIVED_TYPES^
13631 @cindex @option{^-d^/DERIVED_TYPES^} (@command{gnatxref})
13632 If this switch is set @code{gnatxref} will output the parent type
13633 reference for each matching derived types.
13635 @item ^-f^/FULL_PATHNAME^
13636 @cindex @option{^-f^/FULL_PATHNAME^} (@command{gnatxref})
13637 If this switch is set, the output file names will be preceded by their
13638 directory (if the file was found in the search path). If this switch is
13639 not set, the directory will not be printed.
13641 @item ^-g^/IGNORE_LOCALS^
13642 @cindex @option{^-g^/IGNORE_LOCALS^} (@command{gnatxref})
13643 If this switch is set, information is output only for library-level
13644 entities, ignoring local entities. The use of this switch may accelerate
13645 @code{gnatfind} and @code{gnatxref}.
13648 @cindex @option{-IDIR} (@command{gnatxref})
13649 Equivalent to @samp{-aODIR -aIDIR}.
13652 @cindex @option{-pFILE} (@command{gnatxref})
13653 Specify a project file to use @xref{GNAT Project Manager}.
13654 If you need to use the @file{.gpr}
13655 project files, you should use gnatxref through the GNAT driver
13656 (@command{gnat xref -Pproject}).
13658 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
13659 project file in the current directory.
13661 If a project file is either specified or found by the tools, then the content
13662 of the source directory and object directory lines are added as if they
13663 had been specified respectively by @samp{^-aI^/SOURCE_SEARCH^}
13664 and @samp{^-aO^OBJECT_SEARCH^}.
13666 Output only unused symbols. This may be really useful if you give your
13667 main compilation unit on the command line, as @code{gnatxref} will then
13668 display every unused entity and 'with'ed package.
13672 Instead of producing the default output, @code{gnatxref} will generate a
13673 @file{tags} file that can be used by vi. For examples how to use this
13674 feature, see @ref{Examples of gnatxref Usage}. The tags file is output
13675 to the standard output, thus you will have to redirect it to a file.
13681 All these switches may be in any order on the command line, and may even
13682 appear after the file names. They need not be separated by spaces, thus
13683 you can say @samp{gnatxref ^-ag^/ALL_FILES/IGNORE_LOCALS^} instead of
13684 @samp{gnatxref ^-a -g^/ALL_FILES /IGNORE_LOCALS^}.
13686 @node Switches for gnatfind
13687 @section @code{gnatfind} Switches
13690 The command line for @code{gnatfind} is:
13693 @c $ gnatfind @ovar{switches} @var{pattern}@r{[}:@var{sourcefile}@r{[}:@var{line}@r{[}:@var{column}@r{]]]}
13694 @c @r{[}@var{file1} @var{file2} @dots{}]
13695 @c Expanding @ovar macro inline (explanation in macro def comments)
13696 $ gnatfind @r{[}@var{switches}@r{]} @var{pattern}@r{[}:@var{sourcefile}@r{[}:@var{line}@r{[}:@var{column}@r{]]]}
13697 @r{[}@var{file1} @var{file2} @dots{}@r{]}
13705 An entity will be output only if it matches the regular expression found
13706 in @var{pattern}, see @ref{Regular Expressions in gnatfind and gnatxref}.
13708 Omitting the pattern is equivalent to specifying @samp{*}, which
13709 will match any entity. Note that if you do not provide a pattern, you
13710 have to provide both a sourcefile and a line.
13712 Entity names are given in Latin-1, with uppercase/lowercase equivalence
13713 for matching purposes. At the current time there is no support for
13714 8-bit codes other than Latin-1, or for wide characters in identifiers.
13717 @code{gnatfind} will look for references, bodies or declarations
13718 of symbols referenced in @file{@var{sourcefile}}, at line @var{line}
13719 and column @var{column}. See @ref{Examples of gnatfind Usage}
13720 for syntax examples.
13723 is a decimal integer identifying the line number containing
13724 the reference to the entity (or entities) to be located.
13727 is a decimal integer identifying the exact location on the
13728 line of the first character of the identifier for the
13729 entity reference. Columns are numbered from 1.
13731 @item file1 file2 @dots{}
13732 The search will be restricted to these source files. If none are given, then
13733 the search will be done for every library file in the search path.
13734 These file must appear only after the pattern or sourcefile.
13736 These file names are considered to be regular expressions, so for instance
13737 specifying @file{source*.adb} is the same as giving every file in the current
13738 directory whose name starts with @file{source} and whose extension is
13741 The location of the spec of the entity will always be displayed, even if it
13742 isn't in one of @file{@var{file1}}, @file{@var{file2}},@enddots{} The
13743 occurrences of the entity in the separate units of the ones given on the
13744 command line will also be displayed.
13746 Note that if you specify at least one file in this part, @code{gnatfind} may
13747 sometimes not be able to find the body of the subprograms.
13752 At least one of 'sourcefile' or 'pattern' has to be present on
13755 The following switches are available:
13759 @cindex @option{--version} @command{gnatfind}
13760 Display Copyright and version, then exit disregarding all other options.
13763 @cindex @option{--help} @command{gnatfind}
13764 If @option{--version} was not used, display usage, then exit disregarding
13767 @item ^-a^/ALL_FILES^
13768 @cindex @option{^-a^/ALL_FILES^} (@command{gnatfind})
13769 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
13770 the read-only files found in the library search path. Otherwise, these files
13771 will be ignored. This option can be used to protect Gnat sources or your own
13772 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
13773 much faster, and their output much smaller. Read-only here refers to access
13774 or permission status in the file system for the current user.
13777 @cindex @option{-aIDIR} (@command{gnatfind})
13778 When looking for source files also look in directory DIR. The order in which
13779 source file search is undertaken is the same as for @command{gnatmake}.
13782 @cindex @option{-aODIR} (@command{gnatfind})
13783 When searching for library and object files, look in directory
13784 DIR. The order in which library files are searched is the same as for
13785 @command{gnatmake}.
13788 @cindex @option{-nostdinc} (@command{gnatfind})
13789 Do not look for sources in the system default directory.
13792 @cindex @option{-nostdlib} (@command{gnatfind})
13793 Do not look for library files in the system default directory.
13795 @item --ext=@var{extension}
13796 @cindex @option{--ext} (@command{gnatfind})
13797 Specify an alternate ali file extension. The default is @code{ali} and other
13798 extensions (e.g. @code{gli} for C/C++ sources when using @option{-fdump-xref})
13799 may be specified via this switch. Note that if this switch overrides the
13800 default, which means that only the new extension will be considered.
13802 @item --RTS=@var{rts-path}
13803 @cindex @option{--RTS} (@command{gnatfind})
13804 Specifies the default location of the runtime library. Same meaning as the
13805 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
13807 @item ^-d^/DERIVED_TYPE_INFORMATION^
13808 @cindex @option{^-d^/DERIVED_TYPE_INFORMATION^} (@code{gnatfind})
13809 If this switch is set, then @code{gnatfind} will output the parent type
13810 reference for each matching derived types.
13812 @item ^-e^/EXPRESSIONS^
13813 @cindex @option{^-e^/EXPRESSIONS^} (@command{gnatfind})
13814 By default, @code{gnatfind} accept the simple regular expression set for
13815 @samp{pattern}. If this switch is set, then the pattern will be
13816 considered as full Unix-style regular expression.
13818 @item ^-f^/FULL_PATHNAME^
13819 @cindex @option{^-f^/FULL_PATHNAME^} (@command{gnatfind})
13820 If this switch is set, the output file names will be preceded by their
13821 directory (if the file was found in the search path). If this switch is
13822 not set, the directory will not be printed.
13824 @item ^-g^/IGNORE_LOCALS^
13825 @cindex @option{^-g^/IGNORE_LOCALS^} (@command{gnatfind})
13826 If this switch is set, information is output only for library-level
13827 entities, ignoring local entities. The use of this switch may accelerate
13828 @code{gnatfind} and @code{gnatxref}.
13831 @cindex @option{-IDIR} (@command{gnatfind})
13832 Equivalent to @samp{-aODIR -aIDIR}.
13835 @cindex @option{-pFILE} (@command{gnatfind})
13836 Specify a project file (@pxref{GNAT Project Manager}) to use.
13837 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
13838 project file in the current directory.
13840 If a project file is either specified or found by the tools, then the content
13841 of the source directory and object directory lines are added as if they
13842 had been specified respectively by @samp{^-aI^/SOURCE_SEARCH^} and
13843 @samp{^-aO^/OBJECT_SEARCH^}.
13845 @item ^-r^/REFERENCES^
13846 @cindex @option{^-r^/REFERENCES^} (@command{gnatfind})
13847 By default, @code{gnatfind} will output only the information about the
13848 declaration, body or type completion of the entities. If this switch is
13849 set, the @code{gnatfind} will locate every reference to the entities in
13850 the files specified on the command line (or in every file in the search
13851 path if no file is given on the command line).
13853 @item ^-s^/PRINT_LINES^
13854 @cindex @option{^-s^/PRINT_LINES^} (@command{gnatfind})
13855 If this switch is set, then @code{gnatfind} will output the content
13856 of the Ada source file lines were the entity was found.
13858 @item ^-t^/TYPE_HIERARCHY^
13859 @cindex @option{^-t^/TYPE_HIERARCHY^} (@command{gnatfind})
13860 If this switch is set, then @code{gnatfind} will output the type hierarchy for
13861 the specified type. It act like -d option but recursively from parent
13862 type to parent type. When this switch is set it is not possible to
13863 specify more than one file.
13868 All these switches may be in any order on the command line, and may even
13869 appear after the file names. They need not be separated by spaces, thus
13870 you can say @samp{gnatxref ^-ag^/ALL_FILES/IGNORE_LOCALS^} instead of
13871 @samp{gnatxref ^-a -g^/ALL_FILES /IGNORE_LOCALS^}.
13873 As stated previously, gnatfind will search in every directory in the
13874 search path. You can force it to look only in the current directory if
13875 you specify @code{*} at the end of the command line.
13877 @node Project Files for gnatxref and gnatfind
13878 @section Project Files for @command{gnatxref} and @command{gnatfind}
13881 Project files allow a programmer to specify how to compile its
13882 application, where to find sources, etc. These files are used
13884 primarily by GPS, but they can also be used
13887 @code{gnatxref} and @code{gnatfind}.
13889 A project file name must end with @file{.gpr}. If a single one is
13890 present in the current directory, then @code{gnatxref} and @code{gnatfind} will
13891 extract the information from it. If multiple project files are found, none of
13892 them is read, and you have to use the @samp{-p} switch to specify the one
13895 The following lines can be included, even though most of them have default
13896 values which can be used in most cases.
13897 The lines can be entered in any order in the file.
13898 Except for @file{src_dir} and @file{obj_dir}, you can only have one instance of
13899 each line. If you have multiple instances, only the last one is taken into
13904 [default: @code{"^./^[]^"}]
13905 specifies a directory where to look for source files. Multiple @code{src_dir}
13906 lines can be specified and they will be searched in the order they
13910 [default: @code{"^./^[]^"}]
13911 specifies a directory where to look for object and library files. Multiple
13912 @code{obj_dir} lines can be specified, and they will be searched in the order
13915 @item comp_opt=SWITCHES
13916 [default: @code{""}]
13917 creates a variable which can be referred to subsequently by using
13918 the @code{$@{comp_opt@}} notation. This is intended to store the default
13919 switches given to @command{gnatmake} and @command{gcc}.
13921 @item bind_opt=SWITCHES
13922 [default: @code{""}]
13923 creates a variable which can be referred to subsequently by using
13924 the @samp{$@{bind_opt@}} notation. This is intended to store the default
13925 switches given to @command{gnatbind}.
13927 @item link_opt=SWITCHES
13928 [default: @code{""}]
13929 creates a variable which can be referred to subsequently by using
13930 the @samp{$@{link_opt@}} notation. This is intended to store the default
13931 switches given to @command{gnatlink}.
13933 @item main=EXECUTABLE
13934 [default: @code{""}]
13935 specifies the name of the executable for the application. This variable can
13936 be referred to in the following lines by using the @samp{$@{main@}} notation.
13939 @item comp_cmd=COMMAND
13940 [default: @code{"GNAT COMPILE /SEARCH=$@{src_dir@} /DEBUG /TRY_SEMANTICS"}]
13943 @item comp_cmd=COMMAND
13944 [default: @code{"gcc -c -I$@{src_dir@} -g -gnatq"}]
13946 specifies the command used to compile a single file in the application.
13949 @item make_cmd=COMMAND
13950 [default: @code{"GNAT MAKE $@{main@}
13951 /SOURCE_SEARCH=$@{src_dir@} /OBJECT_SEARCH=$@{obj_dir@}
13952 /DEBUG /TRY_SEMANTICS /COMPILER_QUALIFIERS $@{comp_opt@}
13953 /BINDER_QUALIFIERS $@{bind_opt@} /LINKER_QUALIFIERS $@{link_opt@}"}]
13956 @item make_cmd=COMMAND
13957 [default: @code{"gnatmake $@{main@} -aI$@{src_dir@}
13958 -aO$@{obj_dir@} -g -gnatq -cargs $@{comp_opt@}
13959 -bargs $@{bind_opt@} -largs $@{link_opt@}"}]
13961 specifies the command used to recompile the whole application.
13963 @item run_cmd=COMMAND
13964 [default: @code{"$@{main@}"}]
13965 specifies the command used to run the application.
13967 @item debug_cmd=COMMAND
13968 [default: @code{"gdb $@{main@}"}]
13969 specifies the command used to debug the application
13974 @command{gnatxref} and @command{gnatfind} only take into account the
13975 @code{src_dir} and @code{obj_dir} lines, and ignore the others.
13977 @node Regular Expressions in gnatfind and gnatxref
13978 @section Regular Expressions in @code{gnatfind} and @code{gnatxref}
13981 As specified in the section about @command{gnatfind}, the pattern can be a
13982 regular expression. Actually, there are to set of regular expressions
13983 which are recognized by the program:
13986 @item globbing patterns
13987 These are the most usual regular expression. They are the same that you
13988 generally used in a Unix shell command line, or in a DOS session.
13990 Here is a more formal grammar:
13997 term ::= elmt -- matches elmt
13998 term ::= elmt elmt -- concatenation (elmt then elmt)
13999 term ::= * -- any string of 0 or more characters
14000 term ::= ? -- matches any character
14001 term ::= [char @{char@}] -- matches any character listed
14002 term ::= [char - char] -- matches any character in range
14006 @item full regular expression
14007 The second set of regular expressions is much more powerful. This is the
14008 type of regular expressions recognized by utilities such a @file{grep}.
14010 The following is the form of a regular expression, expressed in Ada
14011 reference manual style BNF is as follows
14018 regexp ::= term @{| term@} -- alternation (term or term @dots{})
14020 term ::= item @{item@} -- concatenation (item then item)
14022 item ::= elmt -- match elmt
14023 item ::= elmt * -- zero or more elmt's
14024 item ::= elmt + -- one or more elmt's
14025 item ::= elmt ? -- matches elmt or nothing
14028 elmt ::= nschar -- matches given character
14029 elmt ::= [nschar @{nschar@}] -- matches any character listed
14030 elmt ::= [^^^ nschar @{nschar@}] -- matches any character not listed
14031 elmt ::= [char - char] -- matches chars in given range
14032 elmt ::= \ char -- matches given character
14033 elmt ::= . -- matches any single character
14034 elmt ::= ( regexp ) -- parens used for grouping
14036 char ::= any character, including special characters
14037 nschar ::= any character except ()[].*+?^^^
14041 Following are a few examples:
14045 will match any of the two strings @samp{abcde} and @samp{fghi},
14048 will match any string like @samp{abd}, @samp{abcd}, @samp{abccd},
14049 @samp{abcccd}, and so on,
14052 will match any string which has only lowercase characters in it (and at
14053 least one character.
14058 @node Examples of gnatxref Usage
14059 @section Examples of @code{gnatxref} Usage
14061 @subsection General Usage
14064 For the following examples, we will consider the following units:
14066 @smallexample @c ada
14072 3: procedure Foo (B : in Integer);
14079 1: package body Main is
14080 2: procedure Foo (B : in Integer) is
14091 2: procedure Print (B : Integer);
14100 The first thing to do is to recompile your application (for instance, in
14101 that case just by doing a @samp{gnatmake main}, so that GNAT generates
14102 the cross-referencing information.
14103 You can then issue any of the following commands:
14105 @item gnatxref main.adb
14106 @code{gnatxref} generates cross-reference information for main.adb
14107 and every unit 'with'ed by main.adb.
14109 The output would be:
14117 Decl: main.ads 3:20
14118 Body: main.adb 2:20
14119 Ref: main.adb 4:13 5:13 6:19
14122 Ref: main.adb 6:8 7:8
14132 Decl: main.ads 3:15
14133 Body: main.adb 2:15
14136 Body: main.adb 1:14
14139 Ref: main.adb 6:12 7:12
14143 that is the entity @code{Main} is declared in main.ads, line 2, column 9,
14144 its body is in main.adb, line 1, column 14 and is not referenced any where.
14146 The entity @code{Print} is declared in bar.ads, line 2, column 15 and it
14147 is referenced in main.adb, line 6 column 12 and line 7 column 12.
14149 @item gnatxref package1.adb package2.ads
14150 @code{gnatxref} will generates cross-reference information for
14151 package1.adb, package2.ads and any other package 'with'ed by any
14157 @subsection Using gnatxref with vi
14159 @code{gnatxref} can generate a tags file output, which can be used
14160 directly from @command{vi}. Note that the standard version of @command{vi}
14161 will not work properly with overloaded symbols. Consider using another
14162 free implementation of @command{vi}, such as @command{vim}.
14165 $ gnatxref -v gnatfind.adb > tags
14169 will generate the tags file for @code{gnatfind} itself (if the sources
14170 are in the search path!).
14172 From @command{vi}, you can then use the command @samp{:tag @var{entity}}
14173 (replacing @var{entity} by whatever you are looking for), and vi will
14174 display a new file with the corresponding declaration of entity.
14177 @node Examples of gnatfind Usage
14178 @section Examples of @code{gnatfind} Usage
14182 @item gnatfind ^-f^/FULL_PATHNAME^ xyz:main.adb
14183 Find declarations for all entities xyz referenced at least once in
14184 main.adb. The references are search in every library file in the search
14187 The directories will be printed as well (as the @samp{^-f^/FULL_PATHNAME^}
14190 The output will look like:
14192 ^directory/^[directory]^main.ads:106:14: xyz <= declaration
14193 ^directory/^[directory]^main.adb:24:10: xyz <= body
14194 ^directory/^[directory]^foo.ads:45:23: xyz <= declaration
14198 that is to say, one of the entities xyz found in main.adb is declared at
14199 line 12 of main.ads (and its body is in main.adb), and another one is
14200 declared at line 45 of foo.ads
14202 @item gnatfind ^-fs^/FULL_PATHNAME/SOURCE_LINE^ xyz:main.adb
14203 This is the same command as the previous one, instead @code{gnatfind} will
14204 display the content of the Ada source file lines.
14206 The output will look like:
14209 ^directory/^[directory]^main.ads:106:14: xyz <= declaration
14211 ^directory/^[directory]^main.adb:24:10: xyz <= body
14213 ^directory/^[directory]^foo.ads:45:23: xyz <= declaration
14218 This can make it easier to find exactly the location your are looking
14221 @item gnatfind ^-r^/REFERENCES^ "*x*":main.ads:123 foo.adb
14222 Find references to all entities containing an x that are
14223 referenced on line 123 of main.ads.
14224 The references will be searched only in main.ads and foo.adb.
14226 @item gnatfind main.ads:123
14227 Find declarations and bodies for all entities that are referenced on
14228 line 123 of main.ads.
14230 This is the same as @code{gnatfind "*":main.adb:123}.
14232 @item gnatfind ^mydir/^[mydir]^main.adb:123:45
14233 Find the declaration for the entity referenced at column 45 in
14234 line 123 of file main.adb in directory mydir. Note that it
14235 is usual to omit the identifier name when the column is given,
14236 since the column position identifies a unique reference.
14238 The column has to be the beginning of the identifier, and should not
14239 point to any character in the middle of the identifier.
14243 @ifclear FSFEDITION
14244 @c *********************************
14245 @node The GNAT Pretty-Printer gnatpp
14246 @chapter The GNAT Pretty-Printer @command{gnatpp}
14248 @cindex Pretty-Printer
14251 * Switches for gnatpp::
14252 * Formatting Rules::
14256 ^The @command{gnatpp} tool^GNAT PRETTY^ is an ASIS-based utility
14257 for source reformatting / pretty-printing.
14258 It takes an Ada source file as input and generates a reformatted
14260 You can specify various style directives via switches; e.g.,
14261 identifier case conventions, rules of indentation, and comment layout.
14263 Note: A newly-redesigned set of formatting algorithms used by gnatpp
14265 To invoke the old formatting algorithms, use the @option{--pp-old} switch.
14266 Support for @option{--pp-old} will be removed in some future version.
14268 To produce a reformatted file, @command{gnatpp} invokes the Ada
14269 compiler and generates and uses the ASIS tree for the input source;
14270 thus the input must be legal Ada code, and the tool should have all the
14271 information needed to compile the input source. To provide this information,
14272 you may specify as a tool parameter the project file the input source belongs to
14273 (or you may call @command{gnatpp}
14274 through the @command{gnat} driver (see @ref{The GNAT Driver and
14275 Project Files}). Another possibility is to specify the source search
14276 path and needed configuration files in @option{-cargs} section of @command{gnatpp}
14277 call, see the description of the @command{gnatpp} switches below.
14279 @command{gnatpp} cannot process sources that contain
14280 preprocessing directives.
14282 The @command{gnatpp} command has the form
14285 @c $ gnatpp @ovar{switches} @var{filename}
14286 @c Expanding @ovar macro inline (explanation in macro def comments)
14287 $ gnatpp @r{[}@var{switches}@r{]} @var{filename} @r{[}-cargs @var{gcc_switches}@r{]}
14294 @var{switches} is an optional sequence of switches defining such properties as
14295 the formatting rules, the source search path, and the destination for the
14299 @var{filename} is the name (including the extension) of the source file to
14300 reformat; wildcards or several file names on the same gnatpp command are
14301 allowed. The file name may contain path information; it does not have to
14302 follow the GNAT file naming rules
14305 @samp{@var{gcc_switches}} is a list of switches for
14306 @command{gcc}. They will be passed on to all compiler invocations made by
14307 @command{gnatpp} to generate the ASIS trees. Here you can provide
14308 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
14309 use the @option{-gnatec} switch to set the configuration file, etc.
14312 @node Switches for gnatpp
14313 @section Switches for @command{gnatpp}
14316 The following subsections describe the various switches accepted by
14317 @command{gnatpp}, organized by category.
14320 You specify a switch by supplying a name and generally also a value.
14321 In many cases the values for a switch with a given name are incompatible with
14323 (for example the switch that controls the casing of a reserved word may have
14324 exactly one value: upper case, lower case, or
14325 mixed case) and thus exactly one such switch can be in effect for an
14326 invocation of @command{gnatpp}.
14327 If more than one is supplied, the last one is used.
14328 However, some values for the same switch are mutually compatible.
14329 You may supply several such switches to @command{gnatpp}, but then
14330 each must be specified in full, with both the name and the value.
14331 Abbreviated forms (the name appearing once, followed by each value) are
14336 In many cases the set of options for a given qualifier are incompatible with
14337 each other (for example the qualifier that controls the casing of a reserved
14338 word may have exactly one option, which specifies either upper case, lower
14339 case, or mixed case), and thus exactly one such option can be in effect for
14340 an invocation of @command{gnatpp}.
14341 If more than one is supplied, the last one is used.
14345 * Alignment Control::
14347 * General Text Layout Control::
14348 * Other Formatting Options::
14349 * Setting the Source Search Path::
14350 * Output File Control::
14351 * Other gnatpp Switches::
14354 @node Alignment Control
14355 @subsection Alignment Control
14356 @cindex Alignment control in @command{gnatpp}
14359 Programs can be easier to read if certain constructs are vertically aligned.
14360 By default alignment of the following constructs is set ON:
14361 @code{:} in declarations, @code{:=} in initializations in declarations
14362 @code{:=} in assignment statements, @code{=>} in associations, and
14363 @code{at} keywords in the component clauses in record
14364 representation clauses.
14367 @cindex @option{^-A@var{n}^/ALIGN^} (@command{gnatpp})
14369 @item ^-A0^/ALIGN=OFF^
14370 Set alignment to OFF
14372 @item ^-A1^/ALIGN=ON^
14373 Set alignment to ON
14376 @node Casing Control
14377 @subsection Casing Control
14378 @cindex Casing control in @command{gnatpp}
14381 @command{gnatpp} allows you to specify the casing for reserved words,
14382 pragma names, attribute designators and identifiers.
14383 For identifiers you may define a
14384 general rule for name casing but also override this rule
14385 via a set of dictionary files.
14387 Three types of casing are supported: lower case, upper case, and mixed case.
14388 ``Mixed case'' means that the first letter, and also each letter immediately
14389 following an underscore, are converted to their uppercase forms;
14390 all the other letters are converted to their lowercase forms.
14393 @cindex @option{^-a@var{x}^/ATTRIBUTE^} (@command{gnatpp})
14394 @item ^-aL^/ATTRIBUTE_CASING=LOWER_CASE^
14395 Attribute designators are lower case
14397 @item ^-aU^/ATTRIBUTE_CASING=UPPER_CASE^
14398 Attribute designators are upper case
14400 @item ^-aM^/ATTRIBUTE_CASING=MIXED_CASE^
14401 Attribute designators are mixed case (this is the default)
14403 @cindex @option{^-k@var{x}^/KEYWORD_CASING^} (@command{gnatpp})
14404 @item ^-kL^/KEYWORD_CASING=LOWER_CASE^
14405 Keywords (technically, these are known in Ada as @emph{reserved words}) are
14406 lower case (this is the default)
14408 @item ^-kU^/KEYWORD_CASING=UPPER_CASE^
14409 Keywords are upper case
14411 @cindex @option{^-n@var{x}^/NAME_CASING^} (@command{gnatpp})
14412 @item ^-nD^/NAME_CASING=AS_DECLARED^
14413 Name casing for defining occurrences are as they appear in the source file
14414 (this is the default)
14416 @item ^-nU^/NAME_CASING=UPPER_CASE^
14417 Names are in upper case
14419 @item ^-nL^/NAME_CASING=LOWER_CASE^
14420 Names are in lower case
14422 @item ^-nM^/NAME_CASING=MIXED_CASE^
14423 Names are in mixed case
14425 @cindex @option{^-ne@var{x}^/ENUM_CASING^} (@command{gnatpp})
14426 @item ^-neD^/ENUM_CASING=AS_DECLARED^
14427 Enumeration literal casing for defining occurrences are as they appear in the
14428 source file. Overrides ^-n^/NAME_CASING^ casing setting.
14430 @item ^-neU^/ENUM_CASING=UPPER_CASE^
14431 Enumeration literals are in upper case. Overrides ^-n^/NAME_CASING^ casing
14434 @item ^-neL^/ENUM_CASING=LOWER_CASE^
14435 Enumeration literals are in lower case. Overrides ^-n^/NAME_CASING^ casing
14438 @item ^-neM^/ENUM_CASING=MIXED_CASE^
14439 Enumeration literals are in mixed case. Overrides ^-n^/NAME_CASING^ casing
14442 @cindex @option{^-nt@var{x}^/TYPE_CASING^} (@command{gnatpp})
14443 @item ^-neD^/TYPE_CASING=AS_DECLARED^
14444 Names introduced by type and subtype declarations are always
14445 cased as they appear in the declaration in the source file.
14446 Overrides ^-n^/NAME_CASING^ casing setting.
14448 @item ^-ntU^/TYPE_CASING=UPPER_CASE^
14449 Names introduced by type and subtype declarations are always in
14450 upper case. Overrides ^-n^/NAME_CASING^ casing setting.
14452 @item ^-ntL^/TYPE_CASING=LOWER_CASE^
14453 Names introduced by type and subtype declarations are always in
14454 lower case. Overrides ^-n^/NAME_CASING^ casing setting.
14456 @item ^-ntM^/TYPE_CASING=MIXED_CASE^
14457 Names introduced by type and subtype declarations are always in
14458 mixed case. Overrides ^-n^/NAME_CASING^ casing setting.
14460 @item ^-nnU^/NUMBER_CASING=UPPER_CASE^
14461 Names introduced by number declarations are always in
14462 upper case. Overrides ^-n^/NAME_CASING^ casing setting.
14464 @item ^-nnL^/NUMBER_CASING=LOWER_CASE^
14465 Names introduced by number declarations are always in
14466 lower case. Overrides ^-n^/NAME_CASING^ casing setting.
14468 @item ^-nnM^/NUMBER_CASING=MIXED_CASE^
14469 Names introduced by number declarations are always in
14470 mixed case. Overrides ^-n^/NAME_CASING^ casing setting.
14472 @cindex @option{^-p@var{x}^/PRAGMA_CASING^} (@command{gnatpp})
14473 @item ^-pL^/PRAGMA_CASING=LOWER_CASE^
14474 Pragma names are lower case
14476 @item ^-pU^/PRAGMA_CASING=UPPER_CASE^
14477 Pragma names are upper case
14479 @item ^-pM^/PRAGMA_CASING=MIXED_CASE^
14480 Pragma names are mixed case (this is the default)
14482 @item ^-D@var{file}^/DICTIONARY=@var{file}^
14483 @cindex @option{^-D^/DICTIONARY^} (@command{gnatpp})
14484 Use @var{file} as a @emph{dictionary file} that defines
14485 the casing for a set of specified names,
14486 thereby overriding the effect on these names by
14487 any explicit or implicit
14488 ^-n^/NAME_CASING^ switch.
14489 To supply more than one dictionary file,
14490 use ^several @option{-D} switches^a list of files as options^.
14493 @option{gnatpp} implicitly uses a @emph{default dictionary file}
14494 to define the casing for the Ada predefined names and
14495 the names declared in the GNAT libraries.
14497 @item ^-D-^/SPECIFIC_CASING^
14498 @cindex @option{^-D-^/SPECIFIC_CASING^} (@command{gnatpp})
14499 Do not use the default dictionary file;
14500 instead, use the casing
14501 defined by a @option{^-n^/NAME_CASING^} switch and any explicit
14506 The structure of a dictionary file, and details on the conventions
14507 used in the default dictionary file, are defined in @ref{Name Casing}.
14509 The @option{^-D-^/SPECIFIC_CASING^} and
14510 @option{^-D@var{file}^/DICTIONARY=@var{file}^} switches are mutually
14514 This group of @command{gnatpp} switches controls the layout of comments and
14515 complex syntactic constructs. See @ref{Formatting Comments} for details
14519 @cindex @option{^-c@var{n}^/COMMENTS_LAYOUT^} (@command{gnatpp})
14520 @item ^-c0^/COMMENTS_LAYOUT=UNTOUCHED^
14521 All comments remain unchanged.
14523 @item ^-c1^/COMMENTS_LAYOUT=DEFAULT^
14524 GNAT-style comment line indentation.
14525 This is the default.
14527 @item ^-c3^/COMMENTS_LAYOUT=GNAT_BEGINNING^
14528 GNAT-style comment beginning.
14530 @item ^-c4^/COMMENTS_LAYOUT=REFORMAT^
14531 Fill comment blocks.
14533 @item ^-c5^/COMMENTS_LAYOUT=KEEP_SPECIAL^
14534 Keep unchanged special form comments.
14535 This is the default.
14537 @item --comments-only
14538 @cindex @option{--comments-only} @command{gnatpp}
14539 Format just the comments.
14541 @cindex @option{^--no-separate-is^/NO_SEPARATE_IS^} (@command{gnatpp})
14542 @item ^--no-separate-is^/NO_SEPARATE_IS^
14543 Do not place the keyword @code{is} on a separate line in a subprogram body in
14544 case if the spec occupies more than one line.
14546 @cindex @option{^--separate-loop-then^/SEPARATE_LOOP_THEN^} (@command{gnatpp})
14547 @item ^--separate-loop-then^/SEPARATE_LOOP_THEN^
14548 Place the keyword @code{loop} in FOR and WHILE loop statements and the
14549 keyword @code{then} in IF statements on a separate line.
14551 @cindex @option{^--no-separate-loop-then^/NO_SEPARATE_LOOP_THEN^} (@command{gnatpp})
14552 @item ^--no-separate-loop-then^/NO_SEPARATE_LOOP_THEN^
14553 Do not place the keyword @code{loop} in FOR and WHILE loop statements and the
14554 keyword @code{then} in IF statements on a separate line. This option is
14555 incompatible with @option{^--separate-loop-then^/SEPARATE_LOOP_THEN^} option.
14557 @cindex @option{^--use-on-new-line^/USE_ON_NEW_LINE^} (@command{gnatpp})
14558 @item ^--use-on-new-line^/USE_ON_NEW_LINE^
14559 Start each USE clause in a context clause from a separate line.
14561 @cindex @option{^--insert-blank-lines^/INSERT_BLANK_LINES^} (@command{gnatpp})
14562 @item ^--insert-blank-lines^/INSERT_BLANK_LINES^
14563 Insert blank lines where appropriate (between bodies and other large
14566 @cindex @option{^--preserve-blank-lines^/PRESERVE_BLANK_LINES^} (@command{gnatpp})
14567 @item ^--preserve-blank-lines^/PRESERVE_BLANK_LINES^
14568 Preserve blank lines in the input. By default, gnatpp will squeeze
14569 multiple blank lines down to one.
14575 The @option{-c} switches are compatible with one another, except that
14576 the @option{-c0} switch disables all other comment formatting
14582 For the @option{/COMMENTS_LAYOUT} qualifier,
14583 The @option{GNAT_BEGINNING}, @option{REFORMAT}, and @option{DEFAULT}
14584 options are compatible with one another.
14587 @node General Text Layout Control
14588 @subsection General Text Layout Control
14591 These switches allow control over line length and indentation.
14594 @item ^-M@var{nnn}^/LINE_LENGTH_MAX=@var{nnn}^
14595 @cindex @option{^-M^/LINE_LENGTH^} (@command{gnatpp})
14596 Maximum line length, @var{nnn} from 32@dots{}256, the default value is 79
14598 @item ^-i@var{nnn}^/INDENTATION_LEVEL=@var{nnn}^
14599 @cindex @option{^-i^/INDENTATION_LEVEL^} (@command{gnatpp})
14600 Indentation level, @var{nnn} from 1@dots{}9, the default value is 3
14602 @item ^-cl@var{nnn}^/CONTINUATION_INDENT=@var{nnn}^
14603 @cindex @option{^-cl^/CONTINUATION_INDENT^} (@command{gnatpp})
14604 Indentation level for continuation lines (relative to the line being
14605 continued), @var{nnn} from 1@dots{}9.
14607 value is one less than the (normal) indentation level, unless the
14608 indentation is set to 1 (in which case the default value for continuation
14609 line indentation is also 1)
14612 @node Other Formatting Options
14613 @subsection Other Formatting Options
14616 These switches control other formatting not listed above.
14619 @item --decimal-grouping=@var{n}
14620 @cindex @option{--decimal-grouping} @command{gnatpp}
14621 Put underscores in decimal literals (numeric literals without a base)
14622 every @var{n} characters. If a literal already has one or more
14623 underscores, it is not modified. For example, with
14624 @code{--decimal-grouping=3}, @code{1000000} will be changed to
14627 @item --based-grouping=@var{n}
14628 @cindex @option{--based-grouping} @command{gnatpp}
14629 Same as @code{--decimal-grouping}, but for based literals. For
14630 example, with @code{--based-grouping=4}, @code{16#0001FFFE#} will be
14631 changed to @code{16#0001_FFFE#}.
14633 @item ^--RM-style-spacing^/RM_STYLE_SPACING^
14634 @cindex @option{^--RM-style-spacing^/RM_STYLE_SPACING^} (@command{gnatpp})
14635 Do not insert an extra blank before various occurrences of
14636 `(' and `:'. This also turns off alignment.
14638 @item ^-ff^/FORM_FEED_AFTER_PRAGMA_PAGE^
14639 @cindex @option{^-ff^/FORM_FEED_AFTER_PRAGMA_PAGE^} (@command{gnatpp})
14640 Insert a Form Feed character after a pragma Page.
14642 @item ^--call_threshold=@var{nnn}^/MAX_ACT=@var{nnn}^
14643 @cindex @option{^--call_threshold^/MAX_ACT^} (@command{gnatpp})
14644 If the number of parameter associations is greater than @var{nnn} and if at
14645 least one association uses named notation, start each association from
14646 a new line. If @var{nnn} is 0, no check for the number of associations
14647 is made; this is the default.
14649 @item ^--par_threshold=@var{nnn}^/MAX_PAR=@var{nnn}^
14650 @cindex @option{^--par_threshold^/MAX_PAR^} (@command{gnatpp})
14651 If the number of parameter specifications is greater than @var{nnn}
14652 (or equal to @var{nnn} in case of a function), start each specification from
14653 a new line. This feature is disabled by default.
14656 @node Setting the Source Search Path
14657 @subsection Setting the Source Search Path
14660 To define the search path for the input source file, @command{gnatpp}
14661 uses the same switches as the GNAT compiler, with the same effects:
14664 @item ^-I^/SEARCH=^@var{dir}
14665 @cindex @option{^-I^/SEARCH^} (@command{gnatpp})
14667 @item ^-I-^/NOCURRENT_DIRECTORY^
14668 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gnatpp})
14670 @item ^-gnatec^/CONFIGURATION_PRAGMAS_FILE^=@var{path}
14671 @cindex @option{^-gnatec^/CONFIGURATION_PRAGMAS_FILE^} (@command{gnatpp})
14673 @item ^--RTS^/RUNTIME_SYSTEM^=@var{path}
14674 @cindex @option{^--RTS^/RUNTIME_SYSTEM^} (@command{gnatpp})
14678 @node Output File Control
14679 @subsection Output File Control
14682 By default the output is sent to a file whose name is obtained by appending
14683 the ^@file{.pp}^@file{$PP}^ suffix to the name of the input file.
14684 If the file with this name already exists, it is overwritten.
14685 Thus if the input file is @file{^my_ada_proc.adb^MY_ADA_PROC.ADB^} then
14686 @command{gnatpp} will produce @file{^my_ada_proc.adb.pp^MY_ADA_PROC.ADB$PP^}
14688 The output may be redirected by the following switches:
14691 @item ^--output-dir=@var{dir}^/OUTPUT_DIR=@var{dir}^
14692 @cindex @option{^--output-dir^/OUTPUT_DIR^} (@command{gnatpp})
14693 Generate output file in directory @file{dir} with the same name as the input
14694 file. If @file{dir} is the same as the directory containing the input file,
14695 the input file is not processed; use @option{^-rnb^/REPLACE_NO_BACKUP^}
14696 if you want to update the input file in place.
14698 @item ^-pipe^/STANDARD_OUTPUT^
14699 @cindex @option{^-pipe^/STANDARD_OUTPUT^} (@command{gnatpp})
14700 Send the output to @code{Standard_Output}
14702 @item ^-o @var{output_file}^/OUTPUT=@var{output_file}^
14703 @cindex @option{^-o^/OUTPUT^} (@code{gnatpp})
14704 Write the output into @var{output_file}.
14705 If @var{output_file} already exists, @command{gnatpp} terminates without
14706 reading or processing the input file.
14708 @item ^-of ^/FORCED_OUTPUT=^@var{output_file}
14709 @cindex @option{^-of^/FORCED_OUTPUT^} (@command{gnatpp})
14710 Write the output into @var{output_file}, overwriting the existing file
14711 (if one is present).
14713 @item ^-r^/REPLACE^
14714 @cindex @option{^-r^/REPLACE^} (@command{gnatpp})
14715 Replace the input source file with the reformatted output, and copy the
14716 original input source into the file whose name is obtained by appending the
14717 ^@file{.npp}^@file{$NPP}^ suffix to the name of the input file.
14718 If a file with this name already exists, @command{gnatpp} terminates without
14719 reading or processing the input file.
14721 @item ^-rf^/OVERRIDING_REPLACE^
14722 @cindex @option{^-rf^/OVERRIDING_REPLACE^} (@code{gnatpp})
14723 Like @option{^-r^/REPLACE^} except that if the file with the specified name
14724 already exists, it is overwritten.
14726 @item ^-rnb^/REPLACE_NO_BACKUP^
14727 @cindex @option{^-rnb^/REPLACE_NO_BACKUP^} (@command{gnatpp})
14728 Replace the input source file with the reformatted output without
14729 creating any backup copy of the input source.
14731 @item ^--eol=@var{xxx}^/END_OF_LINE=@var{xxx}^
14732 @cindex @option{^--eol^/END_OF_LINE^} (@code{gnatpp})
14733 Specifies the line-ending style of the reformatted output file. The @var{xxx}
14734 ^string specified with the switch^option^ may be:
14736 @item ``@option{^dos^DOS^}'' MS DOS style, lines end with CR LF characters
14737 @item ``@option{^crlf^CRLF^}''
14738 the same as @option{^dos^DOS^}
14739 @item ``@option{^unix^UNIX^}'' UNIX style, lines end with LF character
14740 @item ``@option{^lf^LF^}''
14741 the same as @option{^unix^UNIX^}
14744 @item ^-W^/RESULT_ENCODING=^@var{e}
14745 @cindex @option{^-W^/RESULT_ENCODING=^} (@command{gnatpp})
14746 Specify the wide character encoding method for the input and output files.
14747 @var{e} is one of the following:
14755 Upper half encoding
14757 @item ^s^SHIFT_JIS^
14767 Brackets encoding (default value)
14773 Options @option{^-o^/OUTPUT^} and
14774 @option{^-of^/FORCED_OUTPUT^} are allowed only if the call to gnatpp
14775 contains only one file to reformat.
14777 @option{^--eol^/END_OF_LINE^}
14779 @option{^-W^/RESULT_ENCODING^}
14780 cannot be used together
14781 with @option{^-pipe^/STANDARD_OUTPUT^} option.
14783 @node Other gnatpp Switches
14784 @subsection Other @code{gnatpp} Switches
14787 The additional @command{gnatpp} switches are defined in this subsection.
14791 @cindex @option{--version} @command{gnatpp}
14792 Display copyright and version, then exit disregarding all other options.
14795 @cindex @option{--help} @command{gnatpp}
14796 Display usage, then exit disregarding all other options.
14798 @item -P @var{file}
14799 @cindex @option{-P} @command{gnatpp}
14800 Indicates the name of the project file that describes the set of sources
14801 to be processed. The exact set of argument sources depends on other options
14802 specified; see below.
14805 @cindex @option{-U} @command{gnatpp}
14806 If a project file is specified and no argument source is explicitly
14807 specified (either directly or by means of @option{-files} option), process
14808 all the units of the closure of the argument project. Otherwise this option
14811 @item -U @var{main_unit}
14812 If a project file is specified and no argument source is explicitly
14813 specified (either directly or by means of @option{-files} option), process
14814 the closure of units rooted at @var{main_unit}. Otherwise this option
14817 @item -X@var{name}=@var{value}
14818 @cindex @option{-X} @command{gnatpp}
14819 Indicates that external variable @var{name} in the argument project
14820 has the value @var{value}. Has no effect if no project is specified as
14823 @item --incremental
14824 @cindex @option{--incremental} @command{gnatpp}
14825 Incremental processing on a per-file basis. Source files are only
14826 processed if they have been modified, or if files they depend on have
14827 been modified. This is similar to the way gnatmake/gprbuild only
14828 compiles files that need to be recompiled.
14830 @item --pp-off=@var{xxx}
14831 @cindex @option{--pp-off} @command{gnatpp}
14832 Use @code{--xxx} as the command to turn off pretty printing, instead
14833 of the default @code{--!pp off}.
14835 @item --pp-on=@var{xxx}
14836 @cindex @option{--pp-on} @command{gnatpp}
14837 Use @code{--xxx} as the command to turn pretty printing back on, instead
14838 of the default @code{--!pp on}.
14841 @cindex @option{--pp-old} @command{gnatpp}
14842 Use the old formatting algorithms.
14844 @item ^-files @var{filename}^/FILES=@var{filename}^
14845 @cindex @option{^-files^/FILES^} (@code{gnatpp})
14846 Take the argument source files from the specified file. This file should be an
14847 ordinary text file containing file names separated by spaces or
14848 line breaks. You can use this switch more than once in the same call to
14849 @command{gnatpp}. You also can combine this switch with an explicit list of
14852 @item ^-j^/PROCESSES=^@var{n}
14853 @cindex @option{^-j^/PROCESSES^} (@command{gnatpp})
14854 Without @option{--incremental}, use @var{n} processes to carry out the
14855 tree creations (internal representations of the argument sources). On
14856 a multiprocessor machine this speeds up processing of big sets of
14857 argument sources. If @var{n} is 0, then the maximum number of parallel
14858 tree creations is the number of core processors on the platform. This
14859 option cannot be used together with @option{^-r^/REPLACE^},
14860 @option{^-rf^/OVERRIDING_REPLACE^} or
14861 @option{^-rnb^/REPLACE_NO_BACKUP^} option.
14863 With @option{--incremental}, use @var{n} @command{gnatpp} processes to
14864 perform pretty-printing in parallel. @var{n} = 0 means the same as
14865 above. In this case, @option{^-r^/REPLACE^},
14866 @option{^-rf^/OVERRIDING_REPLACE^} or
14867 @option{^-rnb^/REPLACE_NO_BACKUP^} options are allowed.
14869 @cindex @option{^-t^/TIME^} (@command{gnatpp})
14871 Print out execution time.
14873 @item ^-v^/VERBOSE^
14874 @cindex @option{^-v^/VERBOSE^} (@command{gnatpp})
14878 @cindex @option{^-q^/QUIET^} (@command{gnatpp})
14883 If a project file is specified and no argument source is explicitly
14884 specified (either directly or by means of @option{-files} option), and no
14885 @option{-U} is specified, then the set of processed sources is
14886 all the immediate units of the argument project.
14889 @node Formatting Rules
14890 @section Formatting Rules
14893 The following subsections show how @command{gnatpp} treats white space,
14894 comments, program layout, and name casing.
14895 They provide detailed descriptions of the switches shown above.
14898 * Disabling Pretty Printing::
14899 * White Space and Empty Lines::
14900 * Formatting Comments::
14904 @node Disabling Pretty Printing
14905 @subsection Disabling Pretty Printing
14908 Pretty printing is highly heuristic in nature, and sometimes doesn't
14909 do exactly what you want. If you wish to format a certain region of
14910 code by hand, you can turn off pretty printing in that region by
14911 surrounding it with special comments that start with @code{--!pp off}
14912 and @code{--!pp on}. The text in that region will then be reproduced
14913 verbatim in the output with no formatting.
14915 To disable pretty printing for the whole file, put @code{--!pp off} at
14916 the top, with no following @code{--!pp on}.
14918 The comments must appear on a line by themselves, with nothing
14919 preceding except spaces. The initial text of the comment must be
14920 exactly @code{--!pp off} or @code{--!pp on} (case sensitive), but may
14921 be followed by arbitrary additional text. For example:
14923 @smallexample @c ada
14925 package Interrupts is
14926 --!pp off -- turn off pretty printing so "Interrupt_Kind" lines up
14927 type Interrupt_Kind is
14928 (Asynchronous_Interrupt_Kind,
14929 Synchronous_Interrupt_Kind,
14930 Green_Interrupt_Kind);
14931 --!pp on -- reenable pretty printing
14937 You can specify different comment strings using the @code{--pp-off}
14938 and @code{--pp-on} switches. For example, if you say @code{gnatpp
14939 --pp-off=' pp-' *.ad?} then gnatpp will recognize comments of the form
14940 @code{-- pp-} instead of @code{--!pp off} for disabling pretty
14941 printing. Note that the leading @code{--} of the comment is not
14942 included in the argument to these switches.
14944 @node White Space and Empty Lines
14945 @subsection White Space and Empty Lines
14948 @command{gnatpp} does not have an option to control space characters.
14949 It will add or remove spaces according to the style illustrated by the
14950 examples in the @cite{Ada Reference Manual}.
14951 The output file will contain no lines with trailing white space.
14953 By default, a sequence of one or more blank lines in the input is
14954 converted to a single blank line in the output; multiple blank lines
14955 are squeezed down to one.
14956 The @option{^--preserve-blank-lines^/PRESERVE_BLANK_LINES^} option
14957 turns off the squeezing; each blank line in the input is copied
14959 The @option{^--insert-blank-lines^/INSERT_BLANK_LINES^} option
14960 causes additional blank lines to be inserted if not already
14961 present in the input (e.g. between bodies).
14963 @node Formatting Comments
14964 @subsection Formatting Comments
14967 Comments in Ada code are of two kinds:
14970 a @emph{whole-line comment}, which appears by itself (possibly preceded by
14971 white space) on a line
14974 an @emph{end-of-line comment}, which follows some other Ada code on
14979 A whole-line comment is indented according to the surrounding code,
14980 with some exceptions.
14981 Comments that start in column 1 are kept there.
14982 If possible, comments are not moved so far to the right that the maximum
14983 line length is exceeded.
14984 The @option{^-c0^/COMMENTS_LAYOUT=UNTOUCHED^} option
14985 turns off comment formatting.
14986 Special-form comments such as SPARK-style @code{--#...} are left alone.
14988 For an end-of-line comment, @command{gnatpp} tries to leave the same
14989 number of spaces between the end of the preceding Ada code and the
14990 beginning of the comment as appear in the original source.
14993 The @option{^-c3^/COMMENTS_LAYOUT=GNAT_BEGINNING^} switch
14994 (GNAT style comment beginning) has the following
14999 For each whole-line comment that does not end with two hyphens,
15000 @command{gnatpp} inserts spaces if necessary after the starting two hyphens
15001 to ensure that there are at least two spaces between these hyphens and the
15002 first non-blank character of the comment.
15006 The @option{^-c4^/COMMENTS_LAYOUT=REFORMAT^} switch specifies that
15007 whole-line comments that form a paragraph will be filled in typical
15008 word processor style (that is, moving words between lines to make the
15009 lines other than the last similar in length ).
15012 The @option{--comments-only} switch specifies that only the comments
15013 are formatted; the rest of the program text is left alone. The
15014 comments are formatted according to the -c3 and -c4 switches; other
15015 formatting switches are ignored. For example, @option{--comments-only
15016 -c4} means to fill comment paragraphs, and do nothing else. Likewise,
15017 @option{--comments-only -c3} ensures comments start with at least two
15018 spaces after @code{--}, and @option{--comments-only -c3 -c4} does
15019 both. If @option{--comments-only} is given without @option{-c3} or
15020 @option{-c4}, then gnatpp doesn't format anything.
15023 @subsection Name Casing
15026 @command{gnatpp} always converts the usage occurrence of a (simple) name to
15027 the same casing as the corresponding defining identifier.
15029 You control the casing for defining occurrences via the
15030 @option{^-n^/NAME_CASING^} switch.
15032 With @option{-nD} (``as declared'', which is the default),
15035 With @option{/NAME_CASING=AS_DECLARED}, which is the default,
15037 defining occurrences appear exactly as in the source file
15038 where they are declared.
15039 The other ^values for this switch^options for this qualifier^ ---
15040 @option{^-nU^UPPER_CASE^},
15041 @option{^-nL^LOWER_CASE^},
15042 @option{^-nM^MIXED_CASE^} ---
15044 ^upper, lower, or mixed case, respectively^the corresponding casing^.
15045 If @command{gnatpp} changes the casing of a defining
15046 occurrence, it analogously changes the casing of all the
15047 usage occurrences of this name.
15049 If the defining occurrence of a name is not in the source compilation unit
15050 currently being processed by @command{gnatpp}, the casing of each reference to
15051 this name is changed according to the value of the @option{^-n^/NAME_CASING^}
15052 switch (subject to the dictionary file mechanism described below).
15053 Thus @command{gnatpp} acts as though the @option{^-n^/NAME_CASING^} switch
15055 casing for the defining occurrence of the name.
15058 @option{^-a@var{x}^/ATTRIBUTE^},
15059 @option{^-k@var{x}^/KEYWORD_CASING^},
15060 @option{^-ne@var{x}^/ENUM_CASING^},
15061 @option{^-nt@var{x}^/TYPE_CASING^},
15062 @option{^-nn@var{x}^/NUMBER_CASING^}, and
15063 @option{^-p@var{x}^/PRAGMA_CASING^}
15064 allow finer-grained control over casing for
15065 attributes, keywords, enumeration literals,
15066 types, named numbers and pragmas, respectively.
15067 @option{^-nt@var{x}^/TYPE_CASING^} covers subtypes and
15068 task and protected bodies as well.
15070 Some names may need to be spelled with casing conventions that are not
15071 covered by the upper-, lower-, and mixed-case transformations.
15072 You can arrange correct casing by placing such names in a
15073 @emph{dictionary file},
15074 and then supplying a @option{^-D^/DICTIONARY^} switch.
15075 The casing of names from dictionary files overrides
15076 any @option{^-n^/NAME_CASING^} switch.
15078 To handle the casing of Ada predefined names and the names from GNAT libraries,
15079 @command{gnatpp} assumes a default dictionary file.
15080 The name of each predefined entity is spelled with the same casing as is used
15081 for the entity in the @cite{Ada Reference Manual} (usually mixed case).
15082 The name of each entity in the GNAT libraries is spelled with the same casing
15083 as is used in the declaration of that entity.
15085 The @w{@option{^-D-^/SPECIFIC_CASING^}} switch suppresses the use of
15086 the default dictionary file. Instead, the casing for predefined and
15087 GNAT-defined names will be established by the
15088 @option{^-n^/NAME_CASING^} switch or explicit dictionary files. For
15089 example, by default the names @code{Ada.Text_IO} and
15090 @code{GNAT.OS_Lib} will appear as just shown, even in the presence of
15091 a @option{^-nU^/NAME_CASING=UPPER_CASE^} switch. To ensure that even
15092 such names are rendered in uppercase, additionally supply the
15093 @w{@option{^-D-^/SPECIFIC_CASING^}} switch (or else place these names
15094 in upper case in a dictionary file).
15096 A dictionary file is a plain text file; each line in this file can be
15097 either a blank line (containing only space characters), an Ada comment
15098 line, or the specification of exactly one @emph{casing schema}.
15100 A casing schema is a string that has the following syntax:
15104 @var{casing_schema} ::= @var{identifier} | *@var{simple_identifier}*
15106 @var{simple_identifier} ::= @var{letter}@{@var{letter_or_digit}@}
15111 (See @cite{Ada Reference Manual}, Section 2.3) for the definition of the
15112 @var{identifier} lexical element and the @var{letter_or_digit} category.)
15114 The casing schema string can be followed by white space and/or an Ada-style
15115 comment; any amount of white space is allowed before the string.
15117 If a dictionary file is passed as
15119 the value of a @option{-D@var{file}} switch
15122 an option to the @option{/DICTIONARY} qualifier
15125 simple name and every identifier, @command{gnatpp} checks if the dictionary
15126 defines the casing for the name or for some of its parts (the term ``subword''
15127 is used below to denote the part of a name which is delimited by ``_'' or by
15128 the beginning or end of the word and which does not contain any ``_'' inside):
15132 if the whole name is in the dictionary, @command{gnatpp} uses for this name
15133 the casing defined by the dictionary; no subwords are checked for this word
15136 for every subword @command{gnatpp} checks if the dictionary contains the
15137 corresponding string of the form @code{*@var{simple_identifier}*},
15138 and if it does, the casing of this @var{simple_identifier} is used
15142 if the whole name does not contain any ``_'' inside, and if for this name
15143 the dictionary contains two entries - one of the form @var{identifier},
15144 and another - of the form *@var{simple_identifier}*, then the first one
15145 is applied to define the casing of this name
15148 if more than one dictionary file is passed as @command{gnatpp} switches, each
15149 dictionary adds new casing exceptions and overrides all the existing casing
15150 exceptions set by the previous dictionaries
15153 when @command{gnatpp} checks if the word or subword is in the dictionary,
15154 this check is not case sensitive
15158 For example, suppose we have the following source to reformat:
15160 @smallexample @c ada
15163 name1 : integer := 1;
15164 name4_name3_name2 : integer := 2;
15165 name2_name3_name4 : Boolean;
15168 name2_name3_name4 := name4_name3_name2 > name1;
15174 And suppose we have two dictionaries:
15191 If @command{gnatpp} is called with the following switches:
15195 @command{gnatpp -nM -D dict1 -D dict2 test.adb}
15198 @command{gnatpp test.adb /NAME_CASING=MIXED_CASE /DICTIONARY=(dict1, dict2)}
15203 then we will get the following name casing in the @command{gnatpp} output:
15205 @smallexample @c ada
15208 NAME1 : Integer := 1;
15209 Name4_NAME3_Name2 : Integer := 2;
15210 Name2_NAME3_Name4 : Boolean;
15213 Name2_NAME3_Name4 := Name4_NAME3_Name2 > NAME1;
15219 @ifclear FSFEDITION
15221 @c *********************************
15222 @node The Ada-to-XML converter gnat2xml
15223 @chapter The Ada-to-XML converter @command{gnat2xml}
15225 @cindex XML generation
15228 The @command{gnat2xml} tool is an ASIS-based utility that converts
15229 Ada source code into XML.
15232 * Switches for gnat2xml::
15234 * Structure of the XML::
15237 @node Switches for gnat2xml
15238 @section Switches for @command{gnat2xml}
15241 @command{gnat2xml} takes Ada source code as input, and produces XML
15242 that conforms to the schema.
15247 gnat2xml [options] filenames [-files filename] [-cargs gcc_switches]
15254 --help -- generate usage information and quit, ignoring all other options
15255 --version -- print version and quit, ignoring all other options
15257 -P @file{file} -- indicates the name of the project file that describes
15258 the set of sources to be processed. The exact set of argument
15259 sources depends on other options specified, see below.
15261 -U -- if a project file is specified and no argument source is explicitly
15262 specified, process all the units of the closure of the argument project.
15263 Otherwise this option has no effect.
15265 -U @var{main_unit} -- if a project file is specified and no argument source
15266 is explicitly specified (either directly or by means of @option{-files}
15267 option), process the closure of units rooted at @var{main_unit}.
15268 Otherwise this option has no effect.
15270 -X@var{name}=@var{value} -- indicates that external variable @var{name} in
15271 the argument project has the value @var{value}. Has no effect if no
15272 project is specified as tool argument.
15274 --incremental -- incremental processing on a per-file basis. Source files are
15275 only processed if they have been modified, or if files they depend
15276 on have been modified. This is similar to the way gnatmake/gprbuild
15277 only compiles files that need to be recompiled.
15279 -j@var{n} -- In @option{--incremental} mode, use @var{n} @command{gnat2xml}
15280 processes to perform XML generation in parallel. If @var{n} is 0, then
15281 the maximum number of parallel tree creations is the number of core
15282 processors on the platform.
15284 --output-dir=@var{dir} -- generate one .xml file for each Ada source file, in
15285 directory @file{dir}. (Default is to generate the XML to standard
15289 directories to search for dependencies
15290 You can also set the ADA_INCLUDE_PATH environment variable for this.
15292 --compact -- debugging version, with interspersed source, and a more
15293 compact representation of "sloc". This version does not conform
15296 -files=filename - the name of a text file containing a list
15297 of Ada source files to process
15302 -cargs ... -- options to pass to gcc
15306 If a project file is specified and no argument source is explicitly
15307 specified, and no @option{-U} is specified, then the set of processed
15308 sources is all the immediate units of the argument project.
15313 gnat2xml -v -output-dir=xml-files *.ad[sb]
15317 The above will create *.xml files in the @file{xml-files} subdirectory.
15318 For example, if there is an Ada package Mumble.Dumble, whose spec and
15319 body source code lives in mumble-dumble.ads and mumble-dumble.adb,
15320 the above will produce xml-files/mumble-dumble.ads.xml and
15321 xml-files/mumble-dumble.adb.xml.
15323 @node Other Programs
15324 @section Other Programs
15327 The distribution includes two other programs that are related to
15328 @command{gnat2xml}:
15330 @command{gnat2xsd} is the schema generator, which generates the schema
15331 to standard output, based on the structure of Ada as encoded by
15332 ASIS. You don't need to run @command{gnat2xsd} in order to use
15333 @command{gnat2xml}. To generate the schema, type:
15336 gnat2xsd > ada-schema.xsd
15340 @command{gnat2xml} generates XML files that will validate against
15341 @file{ada-schema.xsd}.
15343 @command{xml2gnat} is a back-translator that translates the XML back
15344 into Ada source code. The Ada generated by @command{xml2gnat} has
15345 identical semantics to the original Ada code passed to
15346 @command{gnat2xml}. It is not textually identical, however --- for
15347 example, no attempt is made to preserve the original indentation.
15349 @node Structure of the XML
15350 @section Structure of the XML
15353 The primary documentation for the structure of the XML generated by
15354 @command{gnat2xml} is the schema (see @command{gnat2xsd} above). The
15355 following documentation gives additional details needed to understand
15356 the schema and therefore the XML.
15358 The elements listed under Defining Occurrences, Usage Occurrences, and
15359 Other Elements represent the syntactic structure of the Ada program.
15360 Element names are given in lower case, with the corresponding element
15361 type Capitalized_Like_This. The element and element type names are
15362 derived directly from the ASIS enumeration type Flat_Element_Kinds,
15363 declared in Asis.Extensions.Flat_Kinds, with the leading ``An_'' or ``A_''
15364 removed. For example, the ASIS enumeration literal
15365 An_Assignment_Statement corresponds to the XML element
15366 assignment_statement of XML type Assignment_Statement.
15368 To understand the details of the schema and the corresponding XML, it is
15369 necessary to understand the ASIS standard, as well as the GNAT-specific
15372 A defining occurrence is an identifier (or character literal or operator
15373 symbol) declared by a declaration. A usage occurrence is an identifier
15374 (or ...) that references such a declared entity. For example, in:
15377 type T is range 1..10;
15378 X, Y : constant T := 1;
15382 The first ``T'' is the defining occurrence of a type. The ``X'' is the
15383 defining occurrence of a constant, as is the ``Y'', and the second ``T'' is
15384 a usage occurrence referring to the defining occurrence of T.
15386 Each element has a 'sloc' (source location), and subelements for each
15387 syntactic subtree, reflecting the Ada grammar as implemented by ASIS.
15388 The types of subelements are as defined in the ASIS standard. For
15389 example, for the right-hand side of an assignment_statement we have
15390 the following comment in asis-statements.ads:
15393 ------------------------------------------------------------------------------
15394 -- 18.3 function Assignment_Expression
15395 ------------------------------------------------------------------------------
15397 function Assignment_Expression
15398 (Statement : Asis.Statement)
15399 return Asis.Expression;
15401 ------------------------------------------------------------------------------
15403 -- Returns the expression from the right hand side of the assignment.
15405 -- Returns Element_Kinds:
15410 The corresponding sub-element of type Assignment_Statement is:
15413 <xsd:element name="assignment_expression_q" type="Expression_Class"/>
15417 where Expression_Class is defined by an xsd:choice of all the
15418 various kinds of expression.
15420 The 'sloc' of each element indicates the starting and ending line and
15421 column numbers. Column numbers are character counts; that is, a tab
15422 counts as 1, not as however many spaces it might expand to.
15424 Subelements of type Element have names ending in ``_q'' (for ASIS
15425 ``Query''), and those of type Element_List end in ``_ql'' (``Query returning
15428 Some subelements are ``Boolean''. For example, Private_Type_Definition
15429 has has_abstract_q and has_limited_q, to indicate whether those
15430 keywords are present, as in @code{type T is abstract limited
15431 private;}. False is represented by a Nil_Element. True is represented
15432 by an element type specific to that query (for example, Abstract and
15435 The root of the tree is a Compilation_Unit, with attributes:
15439 unit_kind, unit_class, and unit_origin. These are strings that match the
15440 enumeration literals of types Unit_Kinds, Unit_Classes, and Unit_Origins
15444 unit_full_name is the full expanded name of the unit, starting from a
15445 root library unit. So for @code{package P.Q.R is ...},
15446 @code{unit_full_name="P.Q.R"}. Same for @code{separate (P.Q) package R is ...}.
15449 def_name is the same as unit_full_name for library units; for subunits,
15450 it is just the simple name.
15453 source_file is the name of the Ada source file. For example, for
15454 the spec of @code{P.Q.R}, @code{source_file="p-q-r.ads"}. This allows one to
15455 interpret the source locations --- the ``sloc'' of all elements
15456 within this Compilation_Unit refers to line and column numbers
15457 within the named file.
15461 Defining occurrences have these attributes:
15465 def_name is the simple name of the declared entity, as written in the Ada
15469 def is a unique URI of the form:
15471 ada://kind/fully/qualified/name
15475 kind indicates the kind of Ada entity being declared (see below), and
15477 fully/qualified/name, is the fully qualified name of the Ada
15478 entity, with each of ``fully'', ``qualified'', and ``name'' being
15479 mangled for uniqueness. We do not document the mangling
15480 algorithm, which is subject to change; we just guarantee that the
15481 names are unique in the face of overloading.
15484 type is the type of the declared object, or @code{null} for
15485 declarations of things other than objects.
15489 Usage occurrences have these attributes:
15493 ref_name is the same as the def_name of the corresponding defining
15494 occurrence. This attribute is not of much use, because of
15495 overloading; use ref for lookups, instead.
15498 ref is the same as the def of the corresponding defining
15503 In summary, @code{def_name} and @code{ref_name} are as in the source
15504 code of the declaration, possibly overloaded, whereas @code{def} and
15505 @code{ref} are unique-ified.
15507 Literal elements have this attribute:
15511 lit_val is the value of the literal as written in the source text,
15512 appropriately escaped (e.g. @code{"} ---> @code{"}). This applies
15513 only to numeric and string literals. Enumeration literals in Ada are
15514 not really "literals" in the usual sense; they are usage occurrences,
15515 and have ref_name and ref as described above. Note also that string
15516 literals used as operator symbols are treated as defining or usage
15517 occurrences, not as literals.
15521 Elements that can syntactically represent names and expressions (which
15522 includes usage occurrences, plus function calls and so forth) have this
15527 type. If the element represents an expression or the name of an object,
15528 'type' is the 'def' for the defining occurrence of the type of that
15529 expression or name. Names of other kinds of entities, such as package
15530 names and type names, do not have a type in Ada; these have type="null"
15535 Pragma elements have this attribute:
15539 pragma_name is the name of the pragma. For language-defined pragmas, the
15540 pragma name is redundant with the element kind (for example, an
15541 assert_pragma element necessarily has pragma_name="Assert"). However, all
15542 implementation-defined pragmas are lumped together in ASIS as a single
15543 element kind (for example, the GNAT-specific pragma Unreferenced is
15544 represented by an implementation_defined_pragma element with
15545 pragma_name="Unreferenced").
15549 Defining occurrences of formal parameters and generic formal objects have this
15554 mode indicates that the parameter is of mode 'in', 'in out', or 'out'.
15558 All elements other than Not_An_Element have this attribute:
15562 checks is a comma-separated list of run-time checks that are needed
15563 for that element. The possible checks are: do_accessibility_check,
15564 do_discriminant_check,do_division_check,do_length_check,
15565 do_overflow_check,do_range_check,do_storage_check,do_tag_check.
15569 The "kind" part of the "def" and "ref" attributes is taken from the ASIS
15570 enumeration type Flat_Declaration_Kinds, declared in
15571 Asis.Extensions.Flat_Kinds, with the leading "An_" or "A_" removed, and
15572 any trailing "_Declaration" or "_Specification" removed. Thus, the
15573 possible kinds are as follows:
15580 tagged_incomplete_type
15591 enumeration_literal
15595 generalized_iterator
15605 expression_function
15613 generic_package_renaming
15614 generic_procedure_renaming
15615 generic_function_renaming
15621 procedure_body_stub
15625 protected_body_stub
15631 package_instantiation
15632 procedure_instantiation
15633 function_instantiation
15636 formal_incomplete_type
15640 formal_package_declaration_with_box
15646 @ifclear FSFEDITION
15647 @c *********************************
15648 @node The GNAT Metrics Tool gnatmetric
15649 @chapter The GNAT Metrics Tool @command{gnatmetric}
15651 @cindex Metric tool
15654 ^The @command{gnatmetric} tool^@command{GNAT METRIC}^ is an ASIS-based utility
15655 for computing various program metrics.
15656 It takes an Ada source file as input and generates a file containing the
15657 metrics data as output. Various switches control which
15658 metrics are computed and output.
15661 * Switches for gnatmetric::
15664 To compute program metrics, @command{gnatmetric} invokes the Ada
15665 compiler and generates and uses the ASIS tree for the input source;
15666 thus the input must be legal Ada code, and the tool should have all the
15667 information needed to compile the input source. To provide this information,
15668 you may specify as a tool parameter the project file the input source belongs to
15669 (or you may call @command{gnatmetric}
15670 through the @command{gnat} driver (see @ref{The GNAT Driver and
15671 Project Files}). Another possibility is to specify the source search
15672 path and needed configuration files in @option{-cargs} section of @command{gnatmetric}
15673 call, see the description of the @command{gnatmetric} switches below.
15675 If the set of sources to be processed by @code{gnatmetric} contains sources with
15676 preprocessing directives
15677 then the needed options should be provided to run preprocessor as a part of
15678 the @command{gnatmetric} call, and the computed metrics
15679 will correspond to preprocessed sources.
15682 The @command{gnatmetric} command has the form
15685 @c $ gnatmetric @ovar{switches} @{@var{filename}@} @r{[}-cargs @var{gcc_switches}@r{]}
15686 @c Expanding @ovar macro inline (explanation in macro def comments)
15687 $ gnatmetric @r{[}@var{switches}@r{]} @{@var{filename}@} @r{[}-cargs @var{gcc_switches}@r{]}
15694 @var{switches} specify the metrics to compute and define the destination for
15698 Each @var{filename} is the name (including the extension) of a source
15699 file to process. ``Wildcards'' are allowed, and
15700 the file name may contain path information.
15701 If no @var{filename} is supplied, then the @var{switches} list must contain
15703 @option{-files} switch (@pxref{Other gnatmetric Switches}).
15704 Including both a @option{-files} switch and one or more
15705 @var{filename} arguments is permitted.
15708 @samp{@var{gcc_switches}} is a list of switches for
15709 @command{gcc}. They will be passed on to all compiler invocations made by
15710 @command{gnatmetric} to generate the ASIS trees. Here you can provide
15711 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
15712 and use the @option{-gnatec} switch to set the configuration file,
15713 use the @option{-gnat05} switch if sources should be compiled in
15717 @node Switches for gnatmetric
15718 @section Switches for @command{gnatmetric}
15721 The following subsections describe the various switches accepted by
15722 @command{gnatmetric}, organized by category.
15725 * Output Files Control::
15726 * Disable Metrics For Local Units::
15727 * Specifying a set of metrics to compute::
15728 * Other gnatmetric Switches::
15730 * Generate project-wide metrics::
15734 @node Output Files Control
15735 @subsection Output File Control
15736 @cindex Output file control in @command{gnatmetric}
15739 @command{gnatmetric} has two output formats. It can generate a
15740 textual (human-readable) form, and also XML. By default only textual
15741 output is generated.
15743 When generating the output in textual form, @command{gnatmetric} creates
15744 for each Ada source file a corresponding text file
15745 containing the computed metrics, except for the case when the set of metrics
15746 specified by gnatmetric parameters consists only of metrics that are computed
15747 for the whole set of analyzed sources, but not for each Ada source.
15748 By default, the name of the file containing metric information for a source
15749 is obtained by appending the ^@file{.metrix}^@file{$METRIX}^ suffix to the
15750 name of the input source file. If not otherwise specified and no project file
15751 is specified as @command{gnatmetric} option this file is placed in the same
15752 directory as where the source file is located. If @command{gnatmetric} has a
15753 project file as its parameter, it places all the generated files in the
15754 object directory of the project (or in the project source directory if the
15755 project does not define an objects directory), if @option{--subdirs} option
15756 is specified, the files are placed in the subrirectory of this directory
15757 specified by this option.
15759 All the output information generated in XML format is placed in a single
15760 file. By default the name of this file is ^@file{metrix.xml}^@file{METRIX$XML}^.
15761 If not otherwise specified and if no project file is specified
15762 as @command{gnatmetric} option this file is placed in the
15765 Some of the computed metrics are summed over the units passed to
15766 @command{gnatmetric}; for example, the total number of lines of code.
15767 By default this information is sent to @file{stdout}, but a file
15768 can be specified with the @option{-og} switch.
15770 The following switches control the @command{gnatmetric} output:
15773 @cindex @option{^-x^/XML^} (@command{gnatmetric})
15775 Generate the XML output
15777 @cindex @option{^-xs^/XSD^} (@command{gnatmetric})
15779 Generate the XML output and the XML schema file that describes the structure
15780 of the XML metric report, this schema is assigned to the XML file. The schema
15781 file has the same name as the XML output file with @file{.xml} suffix replaced
15784 @cindex @option{^-nt^/NO_TEXT^} (@command{gnatmetric})
15785 @item ^-nt^/NO_TEXT^
15786 Do not generate the output in text form (implies @option{^-x^/XML^})
15788 @cindex @option{^-d^/DIRECTORY^} (@command{gnatmetric})
15789 @item ^-d @var{output_dir}^/DIRECTORY=@var{output_dir}^
15790 Put text files with detailed metrics into @var{output_dir}
15792 @cindex @option{^-o^/SUFFIX_DETAILS^} (@command{gnatmetric})
15793 @item ^-o @var{file_suffix}^/SUFFIX_DETAILS=@var{file_suffix}^
15794 Use @var{file_suffix}, instead of ^@file{.metrix}^@file{$METRIX}^
15795 in the name of the output file.
15797 @cindex @option{^-og^/GLOBAL_OUTPUT^} (@command{gnatmetric})
15798 @item ^-og @var{file_name}^/GLOBAL_OUTPUT=@var{file_name}^
15799 Put global metrics into @var{file_name}
15801 @cindex @option{^-ox^/XML_OUTPUT^} (@command{gnatmetric})
15802 @item ^-ox @var{file_name}^/XML_OUTPUT=@var{file_name}^
15803 Put the XML output into @var{file_name} (also implies @option{^-x^/XML^})
15805 @cindex @option{^-sfn^/SHORT_SOURCE_FILE_NAME^} (@command{gnatmetric})
15806 @item ^-sfn^/SHORT_SOURCE_FILE_NAME^
15807 Use ``short'' source file names in the output. (The @command{gnatmetric}
15808 output includes the name(s) of the Ada source file(s) from which the metrics
15809 are computed. By default each name includes the absolute path. The
15810 @option{^-sfn^/SHORT_SOURCE_FILE_NAME^} switch causes @command{gnatmetric}
15811 to exclude all directory information from the file names that are output.)
15815 @node Disable Metrics For Local Units
15816 @subsection Disable Metrics For Local Units
15817 @cindex Disable Metrics For Local Units in @command{gnatmetric}
15820 @command{gnatmetric} relies on the GNAT compilation model @minus{}
15822 unit per one source file. It computes line metrics for the whole source
15823 file, and it also computes syntax
15824 and complexity metrics for the file's outermost unit.
15826 By default, @command{gnatmetric} will also compute all metrics for certain
15827 kinds of locally declared program units:
15831 subprogram (and generic subprogram) bodies;
15834 package (and generic package) specs and bodies;
15837 task object and type specifications and bodies;
15840 protected object and type specifications and bodies.
15844 These kinds of entities will be referred to as
15845 @emph{eligible local program units}, or simply @emph{eligible local units},
15846 @cindex Eligible local unit (for @command{gnatmetric})
15847 in the discussion below.
15849 Note that a subprogram declaration, generic instantiation,
15850 or renaming declaration only receives metrics
15851 computation when it appear as the outermost entity
15854 Suppression of metrics computation for eligible local units can be
15855 obtained via the following switch:
15858 @cindex @option{^-nolocal^/SUPPRESS^} (@command{gnatmetric})
15859 @item ^-nolocal^/SUPPRESS=LOCAL_DETAILS^
15860 Do not compute detailed metrics for eligible local program units
15864 @node Specifying a set of metrics to compute
15865 @subsection Specifying a set of metrics to compute
15868 By default all the metrics are computed and reported. The switches
15869 described in this subsection allow you to control, on an individual
15870 basis, whether metrics are computed and
15871 reported. If at least one positive metric
15872 switch is specified (that is, a switch that defines that a given
15873 metric or set of metrics is to be computed), then only
15874 explicitly specified metrics are reported.
15877 * Line Metrics Control::
15878 * Syntax Metrics Control::
15879 * Complexity Metrics Control::
15880 * Coupling Metrics Control::
15883 @node Line Metrics Control
15884 @subsubsection Line Metrics Control
15885 @cindex Line metrics control in @command{gnatmetric}
15888 For any (legal) source file, and for each of its
15889 eligible local program units, @command{gnatmetric} computes the following
15894 the total number of lines;
15897 the total number of code lines (i.e., non-blank lines that are not comments)
15900 the number of comment lines
15903 the number of code lines containing end-of-line comments;
15906 the comment percentage: the ratio between the number of lines that contain
15907 comments and the number of all non-blank lines, expressed as a percentage;
15910 the number of empty lines and lines containing only space characters and/or
15911 format effectors (blank lines)
15914 the average number of code lines in subprogram bodies, task bodies, entry
15915 bodies and statement sequences in package bodies (this metric is only computed
15916 across the whole set of the analyzed units)
15921 @command{gnatmetric} sums the values of the line metrics for all the
15922 files being processed and then generates the cumulative results. The tool
15923 also computes for all the files being processed the average number of code
15926 You can use the following switches to select the specific line metrics
15927 to be computed and reported.
15930 @cindex @option{^--lines@var{x}^/LINE_COUNT_METRICS^} (@command{gnatmetric})
15933 @cindex @option{--no-lines@var{x}}
15936 @item ^--lines-all^/LINE_COUNT_METRICS=ALL^
15937 Report all the line metrics
15939 @item ^--no-lines-all^/LINE_COUNT_METRICS=NONE^
15940 Do not report any of line metrics
15942 @item ^--lines^/LINE_COUNT_METRICS=ALL_LINES^
15943 Report the number of all lines
15945 @item ^--no-lines^/LINE_COUNT_METRICS=NOALL_LINES^
15946 Do not report the number of all lines
15948 @item ^--lines-code^/LINE_COUNT_METRICS=CODE_LINES^
15949 Report the number of code lines
15951 @item ^--no-lines-code^/LINE_COUNT_METRICS=NOCODE_LINES^
15952 Do not report the number of code lines
15954 @item ^--lines-comment^/LINE_COUNT_METRICS=COMMENT_LINES^
15955 Report the number of comment lines
15957 @item ^--no-lines-comment^/LINE_COUNT_METRICS=NOCOMMENT_LINES^
15958 Do not report the number of comment lines
15960 @item ^--lines-eol-comment^/LINE_COUNT_METRICS=CODE_COMMENT_LINES^
15961 Report the number of code lines containing
15962 end-of-line comments
15964 @item ^--no-lines-eol-comment^/LINE_COUNT_METRICS=NOCODE_COMMENT_LINES^
15965 Do not report the number of code lines containing
15966 end-of-line comments
15968 @item ^--lines-ratio^/LINE_COUNT_METRICS=COMMENT_PERCENTAGE^
15969 Report the comment percentage in the program text
15971 @item ^--no-lines-ratio^/LINE_COUNT_METRICS=NOCOMMENT_PERCENTAGE^
15972 Do not report the comment percentage in the program text
15974 @item ^--lines-blank^/LINE_COUNT_METRICS=BLANK_LINES^
15975 Report the number of blank lines
15977 @item ^--no-lines-blank^/LINE_COUNT_METRICS=NOBLANK_LINES^
15978 Do not report the number of blank lines
15980 @item ^--lines-average^/LINE_COUNT_METRICS=AVERAGE_BODY_LINES^
15981 Report the average number of code lines in subprogram bodies, task bodies,
15982 entry bodies and statement sequences in package bodies. The metric is computed
15983 and reported for the whole set of processed Ada sources only.
15985 @item ^--no-lines-average^/LINE_COUNT_METRICS=NOAVERAGE_BODY_LINES^
15986 Do not report the average number of code lines in subprogram bodies,
15987 task bodies, entry bodies and statement sequences in package bodies.
15991 @node Syntax Metrics Control
15992 @subsubsection Syntax Metrics Control
15993 @cindex Syntax metrics control in @command{gnatmetric}
15996 @command{gnatmetric} computes various syntactic metrics for the
15997 outermost unit and for each eligible local unit:
16000 @item LSLOC (``Logical Source Lines Of Code'')
16001 The total number of declarations and the total number of statements. Note
16002 that the definition of declarations is the one given in the reference
16006 ``Each of the following is defined to be a declaration: any basic_declaration;
16007 an enumeration_literal_specification; a discriminant_specification;
16008 a component_declaration; a loop_parameter_specification; a
16009 parameter_specification; a subprogram_body; an entry_declaration;
16010 an entry_index_specification; a choice_parameter_specification;
16011 a generic_formal_parameter_declaration.''
16013 This means for example that each enumeration literal adds one to the count,
16014 as well as each subprogram parameter.
16016 Thus the results from this metric will be significantly greater than might
16017 be expected from a naive view of counting semicolons.
16019 @item Maximal static nesting level of inner program units
16021 @cite{Ada Reference Manual}, 10.1(1), ``A program unit is either a
16022 package, a task unit, a protected unit, a
16023 protected entry, a generic unit, or an explicitly declared subprogram other
16024 than an enumeration literal.''
16026 @item Maximal nesting level of composite syntactic constructs
16027 This corresponds to the notion of the
16028 maximum nesting level in the GNAT built-in style checks
16029 (@pxref{Style Checking})
16033 For the outermost unit in the file, @command{gnatmetric} additionally computes
16034 the following metrics:
16037 @item Public subprograms
16038 This metric is computed for package specs. It is the
16039 number of subprograms and generic subprograms declared in the visible
16040 part (including the visible part of nested packages, protected objects, and
16043 @item All subprograms
16044 This metric is computed for bodies and subunits. The
16045 metric is equal to a total number of subprogram bodies in the compilation
16047 Neither generic instantiations nor renamings-as-a-body nor body stubs
16048 are counted. Any subprogram body is counted, independently of its nesting
16049 level and enclosing constructs. Generic bodies and bodies of protected
16050 subprograms are counted in the same way as ``usual'' subprogram bodies.
16053 This metric is computed for package specs and
16054 generic package declarations. It is the total number of types
16055 that can be referenced from outside this compilation unit, plus the
16056 number of types from all the visible parts of all the visible generic
16057 packages. Generic formal types are not counted. Only types, not subtypes,
16061 Along with the total number of public types, the following
16062 types are counted and reported separately:
16069 Root tagged types (abstract, non-abstract, private, non-private). Type
16070 extensions are @emph{not} counted
16073 Private types (including private extensions)
16084 This metric is computed for any compilation unit. It is equal to the total
16085 number of the declarations of different types given in the compilation unit.
16086 The private and the corresponding full type declaration are counted as one
16087 type declaration. Incomplete type declarations and generic formal types
16089 No distinction is made among different kinds of types (abstract,
16090 private etc.); the total number of types is computed and reported.
16095 By default, all the syntax metrics are computed and reported. You can use the
16096 following switches to select specific syntax metrics.
16100 @cindex @option{^--syntax@var{x}^/SYNTAX_METRICS^} (@command{gnatmetric})
16103 @cindex @option{--no-syntax@var{x}} (@command{gnatmetric})
16106 @item ^--syntax-all^/SYNTAX_METRICS=ALL^
16107 Report all the syntax metrics
16109 @item ^--no-syntax-all^/SYNTAX_METRICS=NONE^
16110 Do not report any of syntax metrics
16112 @item ^--declarations^/SYNTAX_METRICS=DECLARATIONS^
16113 Report the total number of declarations
16115 @item ^--no-declarations^/SYNTAX_METRICS=NODECLARATIONS^
16116 Do not report the total number of declarations
16118 @item ^--statements^/SYNTAX_METRICS=STATEMENTS^
16119 Report the total number of statements
16121 @item ^--no-statements^/SYNTAX_METRICS=NOSTATEMENTS^
16122 Do not report the total number of statements
16124 @item ^--public-subprograms^/SYNTAX_METRICS=PUBLIC_SUBPROGRAMS^
16125 Report the number of public subprograms in a compilation unit
16127 @item ^--no-public-subprograms^/SYNTAX_METRICS=NOPUBLIC_SUBPROGRAMS^
16128 Do not report the number of public subprograms in a compilation unit
16130 @item ^--all-subprograms^/SYNTAX_METRICS=ALL_SUBPROGRAMS^
16131 Report the number of all the subprograms in a compilation unit
16133 @item ^--no-all-subprograms^/SYNTAX_METRICS=NOALL_SUBPROGRAMS^
16134 Do not report the number of all the subprograms in a compilation unit
16136 @item ^--public-types^/SYNTAX_METRICS=PUBLIC_TYPES^
16137 Report the number of public types in a compilation unit
16139 @item ^--no-public-types^/SYNTAX_METRICS=NOPUBLIC_TYPES^
16140 Do not report the number of public types in a compilation unit
16142 @item ^--all-types^/SYNTAX_METRICS=ALL_TYPES^
16143 Report the number of all the types in a compilation unit
16145 @item ^--no-all-types^/SYNTAX_METRICS=NOALL_TYPES^
16146 Do not report the number of all the types in a compilation unit
16148 @item ^--unit-nesting^/SYNTAX_METRICS=UNIT_NESTING^
16149 Report the maximal program unit nesting level
16151 @item ^--no-unit-nesting^/SYNTAX_METRICS=UNIT_NESTING_OFF^
16152 Do not report the maximal program unit nesting level
16154 @item ^--construct-nesting^/SYNTAX_METRICS=CONSTRUCT_NESTING^
16155 Report the maximal construct nesting level
16157 @item ^--no-construct-nesting^/SYNTAX_METRICS=NOCONSTRUCT_NESTING^
16158 Do not report the maximal construct nesting level
16162 @node Complexity Metrics Control
16163 @subsubsection Complexity Metrics Control
16164 @cindex Complexity metrics control in @command{gnatmetric}
16167 For a program unit that is an executable body (a subprogram body (including
16168 generic bodies), task body, entry body or a package body containing
16169 its own statement sequence) @command{gnatmetric} computes the following
16170 complexity metrics:
16174 McCabe cyclomatic complexity;
16177 McCabe essential complexity;
16180 maximal loop nesting level;
16183 extra exit points (for subprograms);
16187 The McCabe cyclomatic complexity metric is defined
16188 in @url{http://www.mccabe.com/pdf/mccabe-nist235r.pdf}
16190 According to McCabe, both control statements and short-circuit control forms
16191 should be taken into account when computing cyclomatic complexity.
16192 For Ada 2012 we have also take into account conditional expressions
16193 and quantified expressions. For each body, we compute three metric values:
16197 the complexity introduced by control
16198 statements only, without taking into account short-circuit forms,
16201 the complexity introduced by short-circuit control forms only, and
16205 cyclomatic complexity, which is the sum of these two values.
16210 The cyclomatic complexity is also computed for Ada 2012 expression functions.
16211 An expression function cannot have statements as its components, so only one
16212 metric value is computed as a cyclomatic complexity of an expression function.
16214 The origin of cyclomatic complexity metric is the need to estimate the number
16215 of independent paths in the control flow graph that in turn gives the number
16216 of tests needed to satisfy paths coverage testing completeness criterion.
16217 Considered from the testing point of view, a static Ada @code{loop} (that is,
16218 the @code{loop} statement having static subtype in loop parameter
16219 specification) does not add to cyclomatic complexity. By providing
16220 @option{^--no-static-loop^NO_STATIC_LOOP^} option a user
16221 may specify that such loops should not be counted when computing the
16222 cyclomatic complexity metric
16224 The Ada essential complexity metric is a McCabe cyclomatic complexity metric
16225 counted for the code that is reduced by excluding all the pure structural Ada
16226 control statements. An compound statement is considered as a non-structural
16227 if it contains a @code{raise} or @code{return} statement as it subcomponent,
16228 or if it contains a @code{goto} statement that transfers the control outside
16229 the operator. A selective accept statement with @code{terminate} alternative
16230 is considered as non-structural statement. When computing this metric,
16231 @code{exit} statements are treated in the same way as @code{goto}
16232 statements unless @option{^-ne^NO_EXITS_AS_GOTOS^} option is specified.
16234 The Ada essential complexity metric defined here is intended to quantify
16235 the extent to which the software is unstructured. It is adapted from
16236 the McCabe essential complexity metric defined in
16237 @url{http://www.mccabe.com/pdf/mccabe-nist235r.pdf} but is modified to be more
16238 suitable for typical Ada usage. For example, short circuit forms
16239 are not penalized as unstructured in the Ada essential complexity metric.
16241 When computing cyclomatic and essential complexity, @command{gnatmetric} skips
16242 the code in the exception handlers and in all the nested program units. The
16243 code of assertions and predicates (that is, subprogram preconditions and
16244 postconditions, subtype predicates and type invariants) is also skipped.
16246 By default, all the complexity metrics are computed and reported.
16247 For more fine-grained control you can use
16248 the following switches:
16251 @cindex @option{^-complexity@var{x}^/COMPLEXITY_METRICS^} (@command{gnatmetric})
16254 @cindex @option{--no-complexity@var{x}}
16257 @item ^--complexity-all^/COMPLEXITY_METRICS=ALL^
16258 Report all the complexity metrics
16260 @item ^--no-complexity-all^/COMPLEXITY_METRICS=NONE^
16261 Do not report any of complexity metrics
16263 @item ^--complexity-cyclomatic^/COMPLEXITY_METRICS=CYCLOMATIC^
16264 Report the McCabe Cyclomatic Complexity
16266 @item ^--no-complexity-cyclomatic^/COMPLEXITY_METRICS=NOCYCLOMATIC^
16267 Do not report the McCabe Cyclomatic Complexity
16269 @item ^--complexity-essential^/COMPLEXITY_METRICS=ESSENTIAL^
16270 Report the Essential Complexity
16272 @item ^--no-complexity-essential^/COMPLEXITY_METRICS=NOESSENTIAL^
16273 Do not report the Essential Complexity
16275 @item ^--loop-nesting^/COMPLEXITY_METRICS=LOOP_NESTING_ON^
16276 Report maximal loop nesting level
16278 @item ^--no-loop-nesting^/COMPLEXITY_METRICS=NOLOOP_NESTING^
16279 Do not report maximal loop nesting level
16281 @item ^--complexity-average^/COMPLEXITY_METRICS=AVERAGE_COMPLEXITY^
16282 Report the average McCabe Cyclomatic Complexity for all the subprogram bodies,
16283 task bodies, entry bodies and statement sequences in package bodies.
16284 The metric is computed and reported for whole set of processed Ada sources
16287 @item ^--no-complexity-average^/COMPLEXITY_METRICS=NOAVERAGE_COMPLEXITY^
16288 Do not report the average McCabe Cyclomatic Complexity for all the subprogram
16289 bodies, task bodies, entry bodies and statement sequences in package bodies
16291 @cindex @option{^-ne^/NO_EXITS_AS_GOTOS^} (@command{gnatmetric})
16292 @item ^-ne^/NO_EXITS_AS_GOTOS^
16293 Do not consider @code{exit} statements as @code{goto}s when
16294 computing Essential Complexity
16296 @cindex @option{^--no-static-loop^/NO_STATIC_LOOP^} (@command{gnatmetric})
16297 @item ^--no-static-loop^/NO_STATIC_LOOP^
16298 Do not consider static loops when computing cyclomatic complexity
16300 @item ^--extra-exit-points^/EXTRA_EXIT_POINTS^
16301 Report the extra exit points for subprogram bodies. As an exit point, this
16302 metric counts @code{return} statements and raise statements in case when the
16303 raised exception is not handled in the same body. In case of a function this
16304 metric subtracts 1 from the number of exit points, because a function body
16305 must contain at least one @code{return} statement.
16307 @item ^--no-extra-exit-points^/NOEXTRA_EXIT_POINTS^
16308 Do not report the extra exit points for subprogram bodies
16312 @node Coupling Metrics Control
16313 @subsubsection Coupling Metrics Control
16314 @cindex Coupling metrics control in @command{gnatmetric}
16317 @cindex Coupling metrics (in @command{gnatmetric})
16318 Coupling metrics measure the dependencies between a given entity and other
16319 entities in the program. This information is useful since high coupling
16320 may signal potential issues with maintainability as the program evolves.
16322 @command{gnatmetric} computes the following coupling metrics:
16327 @emph{object-oriented coupling}, for classes in traditional object-oriented
16331 @emph{unit coupling}, for all the program units making up a program;
16334 @emph{control coupling}, reflecting dependencies between a unit and
16335 other units that contain subprograms.
16339 Two kinds of coupling metrics are computed:
16342 @item fan-out coupling (``efferent coupling''):
16343 @cindex fan-out coupling
16344 @cindex efferent coupling
16345 the number of entities the given entity depends upon. This metric
16346 reflects how the given entity depends on the changes in the
16347 ``external world''.
16349 @item fan-in coupling (``afferent'' coupling):
16350 @cindex fan-in coupling
16351 @cindex afferent coupling
16352 the number of entities that depend on a given entity.
16353 This metric reflects how the ``external world'' depends on the changes in a
16358 Object-oriented coupling metrics measure the dependencies
16359 between a given class (or a group of classes) and the other classes in the
16360 program. In this subsection the term ``class'' is used in its traditional
16361 object-oriented programming sense (an instantiable module that contains data
16362 and/or method members). A @emph{category} (of classes) is a group of closely
16363 related classes that are reused and/or modified together.
16365 A class @code{K}'s fan-out coupling is the number of classes
16366 that @code{K} depends upon.
16367 A category's fan-out coupling is the number of classes outside the
16368 category that the classes inside the category depend upon.
16370 A class @code{K}'s fan-in coupling is the number of classes
16371 that depend upon @code{K}.
16372 A category's fan-in coupling is the number of classes outside the
16373 category that depend on classes belonging to the category.
16375 Ada's object-oriented paradigm separates the instantiable entity
16376 (type) from the module (package), so the definition of the coupling
16377 metrics for Ada maps the class and class category notions
16378 onto Ada constructs.
16380 For the coupling metrics, several kinds of modules that define a tagged type
16381 or an interface type -- library packages, library generic packages, and
16382 library generic package instantiations -- are considered to be classes.
16383 A category consists of a library package (or
16384 a library generic package) that defines a tagged or an interface type,
16385 together with all its descendant (generic) packages that define tagged
16386 or interface types. Thus a
16387 category is an Ada hierarchy of library-level program units. Class
16388 coupling in Ada is referred to as ``tagged coupling'', and category coupling
16389 is referred to as ``hierarchy coupling''.
16391 For any package serving as a class, its body and subunits (if any) are
16392 considered together with its spec when computing dependencies, and coupling
16393 metrics are reported for spec units only. Dependencies between classes
16394 mean Ada semantic dependencies. For object-oriented coupling
16395 metrics, only dependencies on units treated as classes are
16398 Similarly, for unit and control coupling an entity is considered to be the
16399 conceptual construct consisting of the entity's specification, body, and
16400 any subunits (transitively).
16401 @command{gnatmetric} computes
16402 the dependencies of all these units as a whole, but
16403 metrics are only reported for spec
16404 units (or for a subprogram body unit in case if there is no
16405 separate spec for the given subprogram).
16407 For unit coupling, dependencies are computed between all kinds of program
16408 units. For control coupling, the dependencies of a given unit are limited to
16409 those units that define subprograms. Thus control fan-out coupling is reported
16410 for all units, but control fan-in coupling is only reported for units
16411 that define subprograms.
16413 The following simple example illustrates the difference between unit coupling
16414 and control coupling metrics:
16416 @smallexample @c ada
16419 function F_1 (I : Integer) return Integer;
16425 type T_2 is new Integer;
16430 package body Lib_1 is
16431 function F_1 (I : Integer) return Integer is
16439 with Lib_2; use Lib_2;
16442 function Fun (I : Integer) return Integer;
16447 with Lib_1; use Lib_1;
16448 package body Pack is
16449 function Fun (I : Integer) return Integer is
16458 If we apply @command{gnatmetric} with the @option{--coupling-all} option to
16459 these units, the result will be:
16465 Unit Lib_1 (C:\customers\662\L406-007\lib_1.ads)
16466 control fan-out coupling : 0
16467 control fan-in coupling : 1
16468 unit fan-out coupling : 0
16469 unit fan-in coupling : 1
16473 Unit Pack (C:\customers\662\L406-007\pack.ads)
16474 control fan-out coupling : 1
16475 control fan-in coupling : 0
16476 unit fan-out coupling : 2
16477 unit fan-in coupling : 0
16481 Unit Lib_2 (C:\customers\662\L406-007\lib_2.ads)
16482 control fan-out coupling : 0
16483 unit fan-out coupling : 0
16484 unit fan-in coupling : 1
16489 The result does not contain values for object-oriented
16490 coupling because none of the argument units contains a tagged type and
16491 therefore none of these units can be treated as a class.
16493 The @code{Pack} package (spec and body) depends on two
16494 units -- @code{Lib_1} @code{and Lib_2} -- and so its unit fan-out coupling
16495 is 2. Since nothing depends on it, its unit fan-in coupling is 0, as
16496 is its control fan-in coupling. Only one of the units @code{Pack} depends
16497 upon defines a subprogram, so its control fan-out coupling is 1.
16499 @code{Lib_2} depends on nothing, so its fan-out metrics are 0. It does
16500 not define any subprograms, so it has no control fan-in metric.
16501 One unit (@code{Pack}) depends on it , so its unit fan-in coupling is 1.
16503 @code{Lib_1} is similar to @code{Lib_2}, but it does define a subprogram.
16504 Its control fan-in coupling is 1 (because there is one unit
16507 When computing coupling metrics, @command{gnatmetric} counts only
16508 dependencies between units that are arguments of the @command{gnatmetric}
16509 invocation. Coupling metrics are program-wide (or project-wide) metrics, so
16510 you should invoke @command{gnatmetric} for
16511 the complete set of sources comprising your program. This can be done
16512 by invoking @command{gnatmetric} with the corresponding project file
16513 and with the @option{-U} option.
16515 By default, all the coupling metrics are disabled. You can use the following
16516 switches to specify the coupling metrics to be computed and reported:
16521 @cindex @option{--tagged-coupling@var{x}} (@command{gnatmetric})
16522 @cindex @option{--hierarchy-coupling@var{x}} (@command{gnatmetric})
16523 @cindex @option{--unit-coupling@var{x}} (@command{gnatmetric})
16524 @cindex @option{--control-coupling@var{x}} (@command{gnatmetric})
16528 @cindex @option{/COUPLING_METRICS} (@command{gnatmetric})
16531 @item ^--coupling-all^/COUPLING_METRICS=ALL^
16532 Report all the coupling metrics
16534 @item ^--tagged-coupling-out^/COUPLING_METRICS=TAGGED_OUT^
16535 Report tagged (class) fan-out coupling
16537 @item ^--tagged-coupling-in^/COUPLING_METRICS=TAGGED_IN^
16538 Report tagged (class) fan-in coupling
16540 @item ^--hierarchy-coupling-out^/COUPLING_METRICS=HIERARCHY_OUT^
16541 Report hierarchy (category) fan-out coupling
16543 @item ^--hierarchy-coupling-in^/COUPLING_METRICS=HIERARCHY_IN^
16544 Report hierarchy (category) fan-in coupling
16546 @item ^--unit-coupling-out^/COUPLING_METRICS=UNIT_OUT^
16547 Report unit fan-out coupling
16549 @item ^--unit-coupling-in^/COUPLING_METRICS=UNIT_IN^
16550 Report unit fan-in coupling
16552 @item ^--control-coupling-out^/COUPLING_METRICS=CONTROL_OUT^
16553 Report control fan-out coupling
16555 @item ^--control-coupling-in^/COUPLING_METRICS=CONTROL_IN^
16556 Report control fan-in coupling
16559 @node Other gnatmetric Switches
16560 @subsection Other @code{gnatmetric} Switches
16563 Additional @command{gnatmetric} switches are as follows:
16567 @cindex @option{--version} @command{gnatmetric}
16568 Display Copyright and version, then exit disregarding all other options.
16571 @cindex @option{--help} @command{gnatmetric}
16572 Display usage, then exit disregarding all other options.
16574 @item -P @var{file}
16575 @cindex @option{-P} @command{gnatmetric}
16576 Indicates the name of the project file that describes the set of sources
16577 to be processed. The exact set of argument sources depends on other options
16578 specified, see below.
16581 @cindex @option{-U} @command{gnatmetric}
16582 If a project file is specified and no argument source is explicitly
16583 specified (either directly or by means of @option{-files} option), process
16584 all the units of the closure of the argument project. Otherwise this option
16587 @item -U @var{main_unit}
16588 If a project file is specified and no argument source is explicitly
16589 specified (either directly or by means of @option{-files} option), process
16590 the closure of units rooted at @var{main_unit}. Otherwise this option
16593 @item -X@var{name}=@var{value}
16594 @cindex @option{-X} @command{gnatmetric}
16595 Indicates that external variable @var{name} in the argument project
16596 has the value @var{value}. Has no effect if no project is specified as
16599 @item --subdirs=@var{dir}
16600 @cindex @option{--subdirs=@var{dir}} @command{gnatmetric}
16601 Use the specified subdirectory of the project objects file (or of the
16602 project file directory if the project does not specify an object directory)
16603 for tool output files. Has no effect if no project is specified as
16604 tool argument r if @option{--no_objects_dir} is specified.
16606 @item --no_objects_dir
16607 @cindex @option{--no_objects_dir} @command{gnatmetric}
16608 Place all the result files into the current directory instead of
16609 project objects directory. This corresponds to the @command{gnatcheck}
16610 behavior when it is called with the project file from the
16611 GNAT driver. Has no effect if no project is specified.
16613 @item ^-files @var{filename}^/FILES=@var{filename}^
16614 @cindex @option{^-files^/FILES^} (@code{gnatmetric})
16615 Take the argument source files from the specified file. This file should be an
16616 ordinary text file containing file names separated by spaces or
16617 line breaks. You can use this switch more than once in the same call to
16618 @command{gnatmetric}. You also can combine this switch with
16619 an explicit list of files.
16621 @item ^-j^/PROCESSES=^@var{n}
16622 @cindex @option{^-j^/PROCESSES^} (@command{gnatmetric})
16623 Use @var{n} processes to carry out the tree creations (internal representations
16624 of the argument sources). On a multiprocessor machine this speeds up processing
16625 of big sets of argument sources. If @var{n} is 0, then the maximum number of
16626 parallel tree creations is the number of core processors on the platform.
16628 @cindex @option{^-t^/TIME^} (@command{gnatmetric})
16630 Print out execution time.
16632 @item ^-v^/VERBOSE^
16633 @cindex @option{^-v^/VERBOSE^} (@command{gnatmetric})
16635 @command{gnatmetric} generates version information and then
16636 a trace of sources being processed.
16639 @cindex @option{^-q^/QUIET^} (@command{gnatmetric})
16644 If a project file is specified and no argument source is explicitly
16645 specified (either directly or by means of @option{-files} option), and no
16646 @option{-U} is specified, then the set of processed sources is
16647 all the immediate units of the argument project.
16651 @node Generate project-wide metrics
16652 @subsection Generate project-wide metrics
16654 In order to compute metrics on all units of a given project, you can use
16655 the @command{gnat} driver along with the @option{-P} option:
16661 If the project @code{proj} depends upon other projects, you can compute
16662 the metrics on the project closure using the @option{-U} option:
16664 gnat metric -Pproj -U
16668 Finally, if not all the units are relevant to a particular main
16669 program in the project closure, you can generate metrics for the set
16670 of units needed to create a given main program (unit closure) using
16671 the @option{-U} option followed by the name of the main unit:
16673 gnat metric -Pproj -U main
16679 @c ***********************************
16680 @node File Name Krunching with gnatkr
16681 @chapter File Name Krunching with @code{gnatkr}
16685 This chapter discusses the method used by the compiler to shorten
16686 the default file names chosen for Ada units so that they do not
16687 exceed the maximum length permitted. It also describes the
16688 @code{gnatkr} utility that can be used to determine the result of
16689 applying this shortening.
16693 * Krunching Method::
16694 * Examples of gnatkr Usage::
16698 @section About @code{gnatkr}
16701 The default file naming rule in GNAT
16702 is that the file name must be derived from
16703 the unit name. The exact default rule is as follows:
16706 Take the unit name and replace all dots by hyphens.
16708 If such a replacement occurs in the
16709 second character position of a name, and the first character is
16710 ^@samp{a}, @samp{g}, @samp{s}, or @samp{i}, ^@samp{A}, @samp{G}, @samp{S}, or @samp{I},^
16711 then replace the dot by the character
16712 ^@samp{~} (tilde)^@samp{$} (dollar sign)^
16713 instead of a minus.
16715 The reason for this exception is to avoid clashes
16716 with the standard names for children of System, Ada, Interfaces,
16717 and GNAT, which use the prefixes
16718 ^@samp{s-}, @samp{a-}, @samp{i-}, and @samp{g-},^@samp{S-}, @samp{A-}, @samp{I-}, and @samp{G-},^
16721 The @option{^-gnatk^/FILE_NAME_MAX_LENGTH=^@var{nn}}
16722 switch of the compiler activates a ``krunching''
16723 circuit that limits file names to nn characters (where nn is a decimal
16724 integer). For example, using OpenVMS,
16725 where the maximum file name length is
16726 39, the value of nn is usually set to 39, but if you want to generate
16727 a set of files that would be usable if ported to a system with some
16728 different maximum file length, then a different value can be specified.
16729 The default value of 39 for OpenVMS need not be specified.
16731 The @code{gnatkr} utility can be used to determine the krunched name for
16732 a given file, when krunched to a specified maximum length.
16735 @section Using @code{gnatkr}
16738 The @code{gnatkr} command has the form
16742 @c $ gnatkr @var{name} @ovar{length}
16743 @c Expanding @ovar macro inline (explanation in macro def comments)
16744 $ gnatkr @var{name} @r{[}@var{length}@r{]}
16750 $ gnatkr @var{name} /COUNT=nn
16755 @var{name} is the uncrunched file name, derived from the name of the unit
16756 in the standard manner described in the previous section (i.e., in particular
16757 all dots are replaced by hyphens). The file name may or may not have an
16758 extension (defined as a suffix of the form period followed by arbitrary
16759 characters other than period). If an extension is present then it will
16760 be preserved in the output. For example, when krunching @file{hellofile.ads}
16761 to eight characters, the result will be hellofil.ads.
16763 Note: for compatibility with previous versions of @code{gnatkr} dots may
16764 appear in the name instead of hyphens, but the last dot will always be
16765 taken as the start of an extension. So if @code{gnatkr} is given an argument
16766 such as @file{Hello.World.adb} it will be treated exactly as if the first
16767 period had been a hyphen, and for example krunching to eight characters
16768 gives the result @file{hellworl.adb}.
16770 Note that the result is always all lower case (except on OpenVMS where it is
16771 all upper case). Characters of the other case are folded as required.
16773 @var{length} represents the length of the krunched name. The default
16774 when no argument is given is ^8^39^ characters. A length of zero stands for
16775 unlimited, in other words do not chop except for system files where the
16776 implied crunching length is always eight characters.
16779 The output is the krunched name. The output has an extension only if the
16780 original argument was a file name with an extension.
16782 @node Krunching Method
16783 @section Krunching Method
16786 The initial file name is determined by the name of the unit that the file
16787 contains. The name is formed by taking the full expanded name of the
16788 unit and replacing the separating dots with hyphens and
16789 using ^lowercase^uppercase^
16790 for all letters, except that a hyphen in the second character position is
16791 replaced by a ^tilde^dollar sign^ if the first character is
16792 ^@samp{a}, @samp{i}, @samp{g}, or @samp{s}^@samp{A}, @samp{I}, @samp{G}, or @samp{S}^.
16793 The extension is @code{.ads} for a
16794 spec and @code{.adb} for a body.
16795 Krunching does not affect the extension, but the file name is shortened to
16796 the specified length by following these rules:
16800 The name is divided into segments separated by hyphens, tildes or
16801 underscores and all hyphens, tildes, and underscores are
16802 eliminated. If this leaves the name short enough, we are done.
16805 If the name is too long, the longest segment is located (left-most
16806 if there are two of equal length), and shortened by dropping
16807 its last character. This is repeated until the name is short enough.
16809 As an example, consider the krunching of @*@file{our-strings-wide_fixed.adb}
16810 to fit the name into 8 characters as required by some operating systems.
16813 our-strings-wide_fixed 22
16814 our strings wide fixed 19
16815 our string wide fixed 18
16816 our strin wide fixed 17
16817 our stri wide fixed 16
16818 our stri wide fixe 15
16819 our str wide fixe 14
16820 our str wid fixe 13
16826 Final file name: oustwifi.adb
16830 The file names for all predefined units are always krunched to eight
16831 characters. The krunching of these predefined units uses the following
16832 special prefix replacements:
16836 replaced by @file{^a^A^-}
16839 replaced by @file{^g^G^-}
16842 replaced by @file{^i^I^-}
16845 replaced by @file{^s^S^-}
16848 These system files have a hyphen in the second character position. That
16849 is why normal user files replace such a character with a
16850 ^tilde^dollar sign^, to
16851 avoid confusion with system file names.
16853 As an example of this special rule, consider
16854 @*@file{ada-strings-wide_fixed.adb}, which gets krunched as follows:
16857 ada-strings-wide_fixed 22
16858 a- strings wide fixed 18
16859 a- string wide fixed 17
16860 a- strin wide fixed 16
16861 a- stri wide fixed 15
16862 a- stri wide fixe 14
16863 a- str wide fixe 13
16869 Final file name: a-stwifi.adb
16873 Of course no file shortening algorithm can guarantee uniqueness over all
16874 possible unit names, and if file name krunching is used then it is your
16875 responsibility to ensure that no name clashes occur. The utility
16876 program @code{gnatkr} is supplied for conveniently determining the
16877 krunched name of a file.
16879 @node Examples of gnatkr Usage
16880 @section Examples of @code{gnatkr} Usage
16887 $ gnatkr very_long_unit_name.ads --> velounna.ads
16888 $ gnatkr grandparent-parent-child.ads --> grparchi.ads
16889 $ gnatkr Grandparent.Parent.Child.ads --> grparchi.ads
16890 $ gnatkr grandparent-parent-child --> grparchi
16892 $ gnatkr very_long_unit_name.ads/count=6 --> vlunna.ads
16893 $ gnatkr very_long_unit_name.ads/count=0 --> very_long_unit_name.ads
16896 @node Preprocessing with gnatprep
16897 @chapter Preprocessing with @code{gnatprep}
16901 This chapter discusses how to use GNAT's @code{gnatprep} utility for simple
16903 Although designed for use with GNAT, @code{gnatprep} does not depend on any
16904 special GNAT features.
16905 For further discussion of conditional compilation in general, see
16906 @ref{Conditional Compilation}.
16909 * Preprocessing Symbols::
16911 * Switches for gnatprep::
16912 * Form of Definitions File::
16913 * Form of Input Text for gnatprep::
16916 @node Preprocessing Symbols
16917 @section Preprocessing Symbols
16920 Preprocessing symbols are defined in definition files and referred to in
16921 sources to be preprocessed. A Preprocessing symbol is an identifier, following
16922 normal Ada (case-insensitive) rules for its syntax, with the restriction that
16923 all characters need to be in the ASCII set (no accented letters).
16925 @node Using gnatprep
16926 @section Using @code{gnatprep}
16929 To call @code{gnatprep} use
16932 @c $ gnatprep @ovar{switches} @var{infile} @var{outfile} @ovar{deffile}
16933 @c Expanding @ovar macro inline (explanation in macro def comments)
16934 $ gnatprep @r{[}@var{switches}@r{]} @var{infile} @var{outfile} @r{[}@var{deffile}@r{]}
16941 is an optional sequence of switches as described in the next section.
16944 is the full name of the input file, which is an Ada source
16945 file containing preprocessor directives.
16948 is the full name of the output file, which is an Ada source
16949 in standard Ada form. When used with GNAT, this file name will
16950 normally have an ads or adb suffix.
16953 is the full name of a text file containing definitions of
16954 preprocessing symbols to be referenced by the preprocessor. This argument is
16955 optional, and can be replaced by the use of the @option{-D} switch.
16959 @node Switches for gnatprep
16960 @section Switches for @code{gnatprep}
16965 @item ^-b^/BLANK_LINES^
16966 @cindex @option{^-b^/BLANK_LINES^} (@command{gnatprep})
16967 Causes both preprocessor lines and the lines deleted by
16968 preprocessing to be replaced by blank lines in the output source file,
16969 preserving line numbers in the output file.
16971 @item ^-c^/COMMENTS^
16972 @cindex @option{^-c^/COMMENTS^} (@command{gnatprep})
16973 Causes both preprocessor lines and the lines deleted
16974 by preprocessing to be retained in the output source as comments marked
16975 with the special string @code{"--! "}. This option will result in line numbers
16976 being preserved in the output file.
16978 @item ^-C^/REPLACE_IN_COMMENTS^
16979 @cindex @option{^-C^/REPLACE_IN_COMMENTS^} (@command{gnatprep})
16980 Causes comments to be scanned. Normally comments are ignored by gnatprep.
16981 If this option is specified, then comments are scanned and any $symbol
16982 substitutions performed as in program text. This is particularly useful
16983 when structured comments are used (e.g., when writing programs in the
16984 SPARK dialect of Ada). Note that this switch is not available when
16985 doing integrated preprocessing (it would be useless in this context
16986 since comments are ignored by the compiler in any case).
16988 @item ^-Dsymbol=value^/ASSOCIATE="symbol=value"^
16989 @cindex @option{^-D^/ASSOCIATE^} (@command{gnatprep})
16990 Defines a new preprocessing symbol, associated with value. If no value is given
16991 on the command line, then symbol is considered to be @code{True}. This switch
16992 can be used in place of a definition file.
16996 @cindex @option{/REMOVE} (@command{gnatprep})
16997 This is the default setting which causes lines deleted by preprocessing
16998 to be entirely removed from the output file.
17001 @item ^-r^/REFERENCE^
17002 @cindex @option{^-r^/REFERENCE^} (@command{gnatprep})
17003 Causes a @code{Source_Reference} pragma to be generated that
17004 references the original input file, so that error messages will use
17005 the file name of this original file. The use of this switch implies
17006 that preprocessor lines are not to be removed from the file, so its
17007 use will force @option{^-b^/BLANK_LINES^} mode if
17008 @option{^-c^/COMMENTS^}
17009 has not been specified explicitly.
17011 Note that if the file to be preprocessed contains multiple units, then
17012 it will be necessary to @code{gnatchop} the output file from
17013 @code{gnatprep}. If a @code{Source_Reference} pragma is present
17014 in the preprocessed file, it will be respected by
17015 @code{gnatchop ^-r^/REFERENCE^}
17016 so that the final chopped files will correctly refer to the original
17017 input source file for @code{gnatprep}.
17019 @item ^-s^/SYMBOLS^
17020 @cindex @option{^-s^/SYMBOLS^} (@command{gnatprep})
17021 Causes a sorted list of symbol names and values to be
17022 listed on the standard output file.
17024 @item ^-u^/UNDEFINED^
17025 @cindex @option{^-u^/UNDEFINED^} (@command{gnatprep})
17026 Causes undefined symbols to be treated as having the value FALSE in the context
17027 of a preprocessor test. In the absence of this option, an undefined symbol in
17028 a @code{#if} or @code{#elsif} test will be treated as an error.
17034 Note: if neither @option{-b} nor @option{-c} is present,
17035 then preprocessor lines and
17036 deleted lines are completely removed from the output, unless -r is
17037 specified, in which case -b is assumed.
17040 @node Form of Definitions File
17041 @section Form of Definitions File
17044 The definitions file contains lines of the form
17051 where symbol is a preprocessing symbol, and value is one of the following:
17055 Empty, corresponding to a null substitution
17057 A string literal using normal Ada syntax
17059 Any sequence of characters from the set
17060 (letters, digits, period, underline).
17064 Comment lines may also appear in the definitions file, starting with
17065 the usual @code{--},
17066 and comments may be added to the definitions lines.
17068 @node Form of Input Text for gnatprep
17069 @section Form of Input Text for @code{gnatprep}
17072 The input text may contain preprocessor conditional inclusion lines,
17073 as well as general symbol substitution sequences.
17075 The preprocessor conditional inclusion commands have the form
17080 #if @i{expression} @r{[}then@r{]}
17082 #elsif @i{expression} @r{[}then@r{]}
17084 #elsif @i{expression} @r{[}then@r{]}
17095 In this example, @i{expression} is defined by the following grammar:
17097 @i{expression} ::= <symbol>
17098 @i{expression} ::= <symbol> = "<value>"
17099 @i{expression} ::= <symbol> = <symbol>
17100 @i{expression} ::= <symbol> = <integer>
17101 @i{expression} ::= <symbol> > <integer>
17102 @i{expression} ::= <symbol> >= <integer>
17103 @i{expression} ::= <symbol> < <integer>
17104 @i{expression} ::= <symbol> <= <integer>
17105 @i{expression} ::= <symbol> 'Defined
17106 @i{expression} ::= not @i{expression}
17107 @i{expression} ::= @i{expression} and @i{expression}
17108 @i{expression} ::= @i{expression} or @i{expression}
17109 @i{expression} ::= @i{expression} and then @i{expression}
17110 @i{expression} ::= @i{expression} or else @i{expression}
17111 @i{expression} ::= ( @i{expression} )
17114 The following restriction exists: it is not allowed to have "and" or "or"
17115 following "not" in the same expression without parentheses. For example, this
17122 This should be one of the following:
17130 For the first test (@i{expression} ::= <symbol>) the symbol must have
17131 either the value true or false, that is to say the right-hand of the
17132 symbol definition must be one of the (case-insensitive) literals
17133 @code{True} or @code{False}. If the value is true, then the
17134 corresponding lines are included, and if the value is false, they are
17137 When comparing a symbol to an integer, the integer is any non negative
17138 literal integer as defined in the Ada Reference Manual, such as 3, 16#FF# or
17139 2#11#. The symbol value must also be a non negative integer. Integer values
17140 in the range 0 .. 2**31-1 are supported.
17142 The test (@i{expression} ::= <symbol> @code{'Defined}) is true only if
17143 the symbol has been defined in the definition file or by a @option{-D}
17144 switch on the command line. Otherwise, the test is false.
17146 The equality tests are case insensitive, as are all the preprocessor lines.
17148 If the symbol referenced is not defined in the symbol definitions file,
17149 then the effect depends on whether or not switch @option{-u}
17150 is specified. If so, then the symbol is treated as if it had the value
17151 false and the test fails. If this switch is not specified, then
17152 it is an error to reference an undefined symbol. It is also an error to
17153 reference a symbol that is defined with a value other than @code{True}
17156 The use of the @code{not} operator inverts the sense of this logical test.
17157 The @code{not} operator cannot be combined with the @code{or} or @code{and}
17158 operators, without parentheses. For example, "if not X or Y then" is not
17159 allowed, but "if (not X) or Y then" and "if not (X or Y) then" are.
17161 The @code{then} keyword is optional as shown
17163 The @code{#} must be the first non-blank character on a line, but
17164 otherwise the format is free form. Spaces or tabs may appear between
17165 the @code{#} and the keyword. The keywords and the symbols are case
17166 insensitive as in normal Ada code. Comments may be used on a
17167 preprocessor line, but other than that, no other tokens may appear on a
17168 preprocessor line. Any number of @code{elsif} clauses can be present,
17169 including none at all. The @code{else} is optional, as in Ada.
17171 The @code{#} marking the start of a preprocessor line must be the first
17172 non-blank character on the line, i.e., it must be preceded only by
17173 spaces or horizontal tabs.
17175 Symbol substitution outside of preprocessor lines is obtained by using
17183 anywhere within a source line, except in a comment or within a
17184 string literal. The identifier
17185 following the @code{$} must match one of the symbols defined in the symbol
17186 definition file, and the result is to substitute the value of the
17187 symbol in place of @code{$symbol} in the output file.
17189 Note that although the substitution of strings within a string literal
17190 is not possible, it is possible to have a symbol whose defined value is
17191 a string literal. So instead of setting XYZ to @code{hello} and writing:
17194 Header : String := "$XYZ";
17198 you should set XYZ to @code{"hello"} and write:
17201 Header : String := $XYZ;
17205 and then the substitution will occur as desired.
17207 @node The GNAT Library Browser gnatls
17208 @chapter The GNAT Library Browser @code{gnatls}
17210 @cindex Library browser
17213 @code{gnatls} is a tool that outputs information about compiled
17214 units. It gives the relationship between objects, unit names and source
17215 files. It can also be used to check the source dependencies of a unit
17216 as well as various characteristics.
17218 Note: to invoke @code{gnatls} with a project file, use the @code{gnat}
17219 driver (see @ref{The GNAT Driver and Project Files}).
17223 * Switches for gnatls::
17224 * Examples of gnatls Usage::
17227 @node Running gnatls
17228 @section Running @code{gnatls}
17231 The @code{gnatls} command has the form
17234 $ gnatls switches @var{object_or_ali_file}
17238 The main argument is the list of object or @file{ali} files
17239 (@pxref{The Ada Library Information Files})
17240 for which information is requested.
17242 In normal mode, without additional option, @code{gnatls} produces a
17243 four-column listing. Each line represents information for a specific
17244 object. The first column gives the full path of the object, the second
17245 column gives the name of the principal unit in this object, the third
17246 column gives the status of the source and the fourth column gives the
17247 full path of the source representing this unit.
17248 Here is a simple example of use:
17252 ^./^[]^demo1.o demo1 DIF demo1.adb
17253 ^./^[]^demo2.o demo2 OK demo2.adb
17254 ^./^[]^hello.o h1 OK hello.adb
17255 ^./^[]^instr-child.o instr.child MOK instr-child.adb
17256 ^./^[]^instr.o instr OK instr.adb
17257 ^./^[]^tef.o tef DIF tef.adb
17258 ^./^[]^text_io_example.o text_io_example OK text_io_example.adb
17259 ^./^[]^tgef.o tgef DIF tgef.adb
17263 The first line can be interpreted as follows: the main unit which is
17265 object file @file{demo1.o} is demo1, whose main source is in
17266 @file{demo1.adb}. Furthermore, the version of the source used for the
17267 compilation of demo1 has been modified (DIF). Each source file has a status
17268 qualifier which can be:
17271 @item OK (unchanged)
17272 The version of the source file used for the compilation of the
17273 specified unit corresponds exactly to the actual source file.
17275 @item MOK (slightly modified)
17276 The version of the source file used for the compilation of the
17277 specified unit differs from the actual source file but not enough to
17278 require recompilation. If you use gnatmake with the qualifier
17279 @option{^-m (minimal recompilation)^/MINIMAL_RECOMPILATION^}, a file marked
17280 MOK will not be recompiled.
17282 @item DIF (modified)
17283 No version of the source found on the path corresponds to the source
17284 used to build this object.
17286 @item ??? (file not found)
17287 No source file was found for this unit.
17289 @item HID (hidden, unchanged version not first on PATH)
17290 The version of the source that corresponds exactly to the source used
17291 for compilation has been found on the path but it is hidden by another
17292 version of the same source that has been modified.
17296 @node Switches for gnatls
17297 @section Switches for @code{gnatls}
17300 @code{gnatls} recognizes the following switches:
17304 @cindex @option{--version} @command{gnatls}
17305 Display Copyright and version, then exit disregarding all other options.
17308 @cindex @option{--help} @command{gnatls}
17309 If @option{--version} was not used, display usage, then exit disregarding
17312 @item ^-a^/ALL_UNITS^
17313 @cindex @option{^-a^/ALL_UNITS^} (@code{gnatls})
17314 Consider all units, including those of the predefined Ada library.
17315 Especially useful with @option{^-d^/DEPENDENCIES^}.
17317 @item ^-d^/DEPENDENCIES^
17318 @cindex @option{^-d^/DEPENDENCIES^} (@code{gnatls})
17319 List sources from which specified units depend on.
17321 @item ^-h^/OUTPUT=OPTIONS^
17322 @cindex @option{^-h^/OUTPUT=OPTIONS^} (@code{gnatls})
17323 Output the list of options.
17325 @item ^-o^/OUTPUT=OBJECTS^
17326 @cindex @option{^-o^/OUTPUT=OBJECTS^} (@code{gnatls})
17327 Only output information about object files.
17329 @item ^-s^/OUTPUT=SOURCES^
17330 @cindex @option{^-s^/OUTPUT=SOURCES^} (@code{gnatls})
17331 Only output information about source files.
17333 @item ^-u^/OUTPUT=UNITS^
17334 @cindex @option{^-u^/OUTPUT=UNITS^} (@code{gnatls})
17335 Only output information about compilation units.
17337 @item ^-files^/FILES^=@var{file}
17338 @cindex @option{^-files^/FILES^} (@code{gnatls})
17339 Take as arguments the files listed in text file @var{file}.
17340 Text file @var{file} may contain empty lines that are ignored.
17341 Each nonempty line should contain the name of an existing file.
17342 Several such switches may be specified simultaneously.
17344 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
17345 @itemx ^-aI^/SOURCE_SEARCH=^@var{dir}
17346 @itemx ^-I^/SEARCH=^@var{dir}
17347 @itemx ^-I-^/NOCURRENT_DIRECTORY^
17349 @cindex @option{^-aO^/OBJECT_SEARCH^} (@code{gnatls})
17350 @cindex @option{^-aI^/SOURCE_SEARCH^} (@code{gnatls})
17351 @cindex @option{^-I^/SEARCH^} (@code{gnatls})
17352 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatls})
17353 Source path manipulation. Same meaning as the equivalent @command{gnatmake}
17354 flags (@pxref{Switches for gnatmake}).
17356 @item ^-aP^/ADD_PROJECT_SEARCH_DIR=^@var{dir}
17357 @cindex @option{^-aP^/ADD_PROJECT_SEARCH_DIR=^} (@code{gnatls})
17358 Add @var{dir} at the beginning of the project search dir.
17360 @item --RTS=@var{rts-path}
17361 @cindex @option{--RTS} (@code{gnatls})
17362 Specifies the default location of the runtime library. Same meaning as the
17363 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
17365 @item ^-v^/OUTPUT=VERBOSE^
17366 @cindex @option{^-v^/OUTPUT=VERBOSE^} (@code{gnatls})
17367 Verbose mode. Output the complete source, object and project paths. Do not use
17368 the default column layout but instead use long format giving as much as
17369 information possible on each requested units, including special
17370 characteristics such as:
17373 @item Preelaborable
17374 The unit is preelaborable in the Ada sense.
17377 No elaboration code has been produced by the compiler for this unit.
17380 The unit is pure in the Ada sense.
17382 @item Elaborate_Body
17383 The unit contains a pragma Elaborate_Body.
17386 The unit contains a pragma Remote_Types.
17388 @item Shared_Passive
17389 The unit contains a pragma Shared_Passive.
17392 This unit is part of the predefined environment and cannot be modified
17395 @item Remote_Call_Interface
17396 The unit contains a pragma Remote_Call_Interface.
17402 @node Examples of gnatls Usage
17403 @section Example of @code{gnatls} Usage
17407 Example of using the verbose switch. Note how the source and
17408 object paths are affected by the -I switch.
17411 $ gnatls -v -I.. demo1.o
17413 GNATLS 5.03w (20041123-34)
17414 Copyright 1997-2004 Free Software Foundation, Inc.
17416 Source Search Path:
17417 <Current_Directory>
17419 /home/comar/local/adainclude/
17421 Object Search Path:
17422 <Current_Directory>
17424 /home/comar/local/lib/gcc-lib/x86-linux/3.4.3/adalib/
17426 Project Search Path:
17427 <Current_Directory>
17428 /home/comar/local/lib/gnat/
17433 Kind => subprogram body
17434 Flags => No_Elab_Code
17435 Source => demo1.adb modified
17439 The following is an example of use of the dependency list.
17440 Note the use of the -s switch
17441 which gives a straight list of source files. This can be useful for
17442 building specialized scripts.
17445 $ gnatls -d demo2.o
17446 ./demo2.o demo2 OK demo2.adb
17452 $ gnatls -d -s -a demo1.o
17454 /home/comar/local/adainclude/ada.ads
17455 /home/comar/local/adainclude/a-finali.ads
17456 /home/comar/local/adainclude/a-filico.ads
17457 /home/comar/local/adainclude/a-stream.ads
17458 /home/comar/local/adainclude/a-tags.ads
17461 /home/comar/local/adainclude/gnat.ads
17462 /home/comar/local/adainclude/g-io.ads
17464 /home/comar/local/adainclude/system.ads
17465 /home/comar/local/adainclude/s-exctab.ads
17466 /home/comar/local/adainclude/s-finimp.ads
17467 /home/comar/local/adainclude/s-finroo.ads
17468 /home/comar/local/adainclude/s-secsta.ads
17469 /home/comar/local/adainclude/s-stalib.ads
17470 /home/comar/local/adainclude/s-stoele.ads
17471 /home/comar/local/adainclude/s-stratt.ads
17472 /home/comar/local/adainclude/s-tasoli.ads
17473 /home/comar/local/adainclude/s-unstyp.ads
17474 /home/comar/local/adainclude/unchconv.ads
17480 GNAT LIST /DEPENDENCIES /OUTPUT=SOURCES /ALL_UNITS DEMO1.ADB
17482 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]ada.ads
17483 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-finali.ads
17484 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-filico.ads
17485 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-stream.ads
17486 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-tags.ads
17490 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]gnat.ads
17491 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]g-io.ads
17493 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]system.ads
17494 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-exctab.ads
17495 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-finimp.ads
17496 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-finroo.ads
17497 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-secsta.ads
17498 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stalib.ads
17499 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stoele.ads
17500 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stratt.ads
17501 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-tasoli.ads
17502 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-unstyp.ads
17503 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]unchconv.ads
17507 @node Cleaning Up with gnatclean
17508 @chapter Cleaning Up with @code{gnatclean}
17510 @cindex Cleaning tool
17513 @code{gnatclean} is a tool that allows the deletion of files produced by the
17514 compiler, binder and linker, including ALI files, object files, tree files,
17515 expanded source files, library files, interface copy source files, binder
17516 generated files and executable files.
17519 * Running gnatclean::
17520 * Switches for gnatclean::
17521 @c * Examples of gnatclean Usage::
17524 @node Running gnatclean
17525 @section Running @code{gnatclean}
17528 The @code{gnatclean} command has the form:
17531 $ gnatclean switches @var{names}
17535 @var{names} is a list of source file names. Suffixes @code{.^ads^ADS^} and
17536 @code{^adb^ADB^} may be omitted. If a project file is specified using switch
17537 @code{^-P^/PROJECT_FILE=^}, then @var{names} may be completely omitted.
17540 In normal mode, @code{gnatclean} delete the files produced by the compiler and,
17541 if switch @code{^-c^/COMPILER_FILES_ONLY^} is not specified, by the binder and
17542 the linker. In informative-only mode, specified by switch
17543 @code{^-n^/NODELETE^}, the list of files that would have been deleted in
17544 normal mode is listed, but no file is actually deleted.
17546 @node Switches for gnatclean
17547 @section Switches for @code{gnatclean}
17550 @code{gnatclean} recognizes the following switches:
17554 @cindex @option{--version} @command{gnatclean}
17555 Display Copyright and version, then exit disregarding all other options.
17558 @cindex @option{--help} @command{gnatclean}
17559 If @option{--version} was not used, display usage, then exit disregarding
17562 @item ^--subdirs^/SUBDIRS^=subdir
17563 Actual object directory of each project file is the subdirectory subdir of the
17564 object directory specified or defaulted in the project file.
17566 @item ^--unchecked-shared-lib-imports^/UNCHECKED_SHARED_LIB_IMPORTS^
17567 By default, shared library projects are not allowed to import static library
17568 projects. When this switch is used on the command line, this restriction is
17571 @item ^-c^/COMPILER_FILES_ONLY^
17572 @cindex @option{^-c^/COMPILER_FILES_ONLY^} (@code{gnatclean})
17573 Only attempt to delete the files produced by the compiler, not those produced
17574 by the binder or the linker. The files that are not to be deleted are library
17575 files, interface copy files, binder generated files and executable files.
17577 @item ^-D ^/DIRECTORY_OBJECTS=^@var{dir}
17578 @cindex @option{^-D^/DIRECTORY_OBJECTS^} (@code{gnatclean})
17579 Indicate that ALI and object files should normally be found in directory
17582 @item ^-F^/FULL_PATH_IN_BRIEF_MESSAGES^
17583 @cindex @option{^-F^/FULL_PATH_IN_BRIEF_MESSAGES^} (@code{gnatclean})
17584 When using project files, if some errors or warnings are detected during
17585 parsing and verbose mode is not in effect (no use of switch
17586 ^-v^/VERBOSE^), then error lines start with the full path name of the project
17587 file, rather than its simple file name.
17590 @cindex @option{^-h^/HELP^} (@code{gnatclean})
17591 Output a message explaining the usage of @code{^gnatclean^gnatclean^}.
17593 @item ^-n^/NODELETE^
17594 @cindex @option{^-n^/NODELETE^} (@code{gnatclean})
17595 Informative-only mode. Do not delete any files. Output the list of the files
17596 that would have been deleted if this switch was not specified.
17598 @item ^-P^/PROJECT_FILE=^@var{project}
17599 @cindex @option{^-P^/PROJECT_FILE^} (@code{gnatclean})
17600 Use project file @var{project}. Only one such switch can be used.
17601 When cleaning a project file, the files produced by the compilation of the
17602 immediate sources or inherited sources of the project files are to be
17603 deleted. This is not depending on the presence or not of executable names
17604 on the command line.
17607 @cindex @option{^-q^/QUIET^} (@code{gnatclean})
17608 Quiet output. If there are no errors, do not output anything, except in
17609 verbose mode (switch ^-v^/VERBOSE^) or in informative-only mode
17610 (switch ^-n^/NODELETE^).
17612 @item ^-r^/RECURSIVE^
17613 @cindex @option{^-r^/RECURSIVE^} (@code{gnatclean})
17614 When a project file is specified (using switch ^-P^/PROJECT_FILE=^),
17615 clean all imported and extended project files, recursively. If this switch
17616 is not specified, only the files related to the main project file are to be
17617 deleted. This switch has no effect if no project file is specified.
17619 @item ^-v^/VERBOSE^
17620 @cindex @option{^-v^/VERBOSE^} (@code{gnatclean})
17623 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
17624 @cindex @option{^-vP^/MESSAGES_PROJECT_FILE^} (@code{gnatclean})
17625 Indicates the verbosity of the parsing of GNAT project files.
17626 @xref{Switches Related to Project Files}.
17628 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
17629 @cindex @option{^-X^/EXTERNAL_REFERENCE^} (@code{gnatclean})
17630 Indicates that external variable @var{name} has the value @var{value}.
17631 The Project Manager will use this value for occurrences of
17632 @code{external(name)} when parsing the project file.
17633 @xref{Switches Related to Project Files}.
17635 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
17636 @cindex @option{^-aO^/OBJECT_SEARCH^} (@code{gnatclean})
17637 When searching for ALI and object files, look in directory
17640 @item ^-I^/SEARCH=^@var{dir}
17641 @cindex @option{^-I^/SEARCH^} (@code{gnatclean})
17642 Equivalent to @option{^-aO^/OBJECT_SEARCH=^@var{dir}}.
17644 @item ^-I-^/NOCURRENT_DIRECTORY^
17645 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatclean})
17646 @cindex Source files, suppressing search
17647 Do not look for ALI or object files in the directory
17648 where @code{gnatclean} was invoked.
17652 @c @node Examples of gnatclean Usage
17653 @c @section Examples of @code{gnatclean} Usage
17656 @node GNAT and Libraries
17657 @chapter GNAT and Libraries
17658 @cindex Library, building, installing, using
17661 This chapter describes how to build and use libraries with GNAT, and also shows
17662 how to recompile the GNAT run-time library. You should be familiar with the
17663 Project Manager facility (@pxref{GNAT Project Manager}) before reading this
17667 * Introduction to Libraries in GNAT::
17668 * General Ada Libraries::
17669 * Stand-alone Ada Libraries::
17670 * Rebuilding the GNAT Run-Time Library::
17673 @node Introduction to Libraries in GNAT
17674 @section Introduction to Libraries in GNAT
17677 A library is, conceptually, a collection of objects which does not have its
17678 own main thread of execution, but rather provides certain services to the
17679 applications that use it. A library can be either statically linked with the
17680 application, in which case its code is directly included in the application,
17681 or, on platforms that support it, be dynamically linked, in which case
17682 its code is shared by all applications making use of this library.
17684 GNAT supports both types of libraries.
17685 In the static case, the compiled code can be provided in different ways. The
17686 simplest approach is to provide directly the set of objects resulting from
17687 compilation of the library source files. Alternatively, you can group the
17688 objects into an archive using whatever commands are provided by the operating
17689 system. For the latter case, the objects are grouped into a shared library.
17691 In the GNAT environment, a library has three types of components:
17697 @xref{The Ada Library Information Files}.
17699 Object files, an archive or a shared library.
17703 A GNAT library may expose all its source files, which is useful for
17704 documentation purposes. Alternatively, it may expose only the units needed by
17705 an external user to make use of the library. That is to say, the specs
17706 reflecting the library services along with all the units needed to compile
17707 those specs, which can include generic bodies or any body implementing an
17708 inlined routine. In the case of @emph{stand-alone libraries} those exposed
17709 units are called @emph{interface units} (@pxref{Stand-alone Ada Libraries}).
17711 All compilation units comprising an application, including those in a library,
17712 need to be elaborated in an order partially defined by Ada's semantics. GNAT
17713 computes the elaboration order from the @file{ALI} files and this is why they
17714 constitute a mandatory part of GNAT libraries.
17715 @emph{Stand-alone libraries} are the exception to this rule because a specific
17716 library elaboration routine is produced independently of the application(s)
17719 @node General Ada Libraries
17720 @section General Ada Libraries
17723 * Building a library::
17724 * Installing a library::
17725 * Using a library::
17728 @node Building a library
17729 @subsection Building a library
17732 The easiest way to build a library is to use the Project Manager,
17733 which supports a special type of project called a @emph{Library Project}
17734 (@pxref{Library Projects}).
17736 A project is considered a library project, when two project-level attributes
17737 are defined in it: @code{Library_Name} and @code{Library_Dir}. In order to
17738 control different aspects of library configuration, additional optional
17739 project-level attributes can be specified:
17742 This attribute controls whether the library is to be static or dynamic
17744 @item Library_Version
17745 This attribute specifies the library version; this value is used
17746 during dynamic linking of shared libraries to determine if the currently
17747 installed versions of the binaries are compatible.
17749 @item Library_Options
17751 These attributes specify additional low-level options to be used during
17752 library generation, and redefine the actual application used to generate
17757 The GNAT Project Manager takes full care of the library maintenance task,
17758 including recompilation of the source files for which objects do not exist
17759 or are not up to date, assembly of the library archive, and installation of
17760 the library (i.e., copying associated source, object and @file{ALI} files
17761 to the specified location).
17763 Here is a simple library project file:
17764 @smallexample @c ada
17766 for Source_Dirs use ("src1", "src2");
17767 for Object_Dir use "obj";
17768 for Library_Name use "mylib";
17769 for Library_Dir use "lib";
17770 for Library_Kind use "dynamic";
17775 and the compilation command to build and install the library:
17777 @smallexample @c ada
17778 $ gnatmake -Pmy_lib
17782 It is not entirely trivial to perform manually all the steps required to
17783 produce a library. We recommend that you use the GNAT Project Manager
17784 for this task. In special cases where this is not desired, the necessary
17785 steps are discussed below.
17787 There are various possibilities for compiling the units that make up the
17788 library: for example with a Makefile (@pxref{Using the GNU make Utility}) or
17789 with a conventional script. For simple libraries, it is also possible to create
17790 a dummy main program which depends upon all the packages that comprise the
17791 interface of the library. This dummy main program can then be given to
17792 @command{gnatmake}, which will ensure that all necessary objects are built.
17794 After this task is accomplished, you should follow the standard procedure
17795 of the underlying operating system to produce the static or shared library.
17797 Here is an example of such a dummy program:
17798 @smallexample @c ada
17800 with My_Lib.Service1;
17801 with My_Lib.Service2;
17802 with My_Lib.Service3;
17803 procedure My_Lib_Dummy is
17811 Here are the generic commands that will build an archive or a shared library.
17814 # compiling the library
17815 $ gnatmake -c my_lib_dummy.adb
17817 # we don't need the dummy object itself
17818 $ rm my_lib_dummy.o my_lib_dummy.ali
17820 # create an archive with the remaining objects
17821 $ ar rc libmy_lib.a *.o
17822 # some systems may require "ranlib" to be run as well
17824 # or create a shared library
17825 $ gcc -shared -o libmy_lib.so *.o
17826 # some systems may require the code to have been compiled with -fPIC
17828 # remove the object files that are now in the library
17831 # Make the ALI files read-only so that gnatmake will not try to
17832 # regenerate the objects that are in the library
17837 Please note that the library must have a name of the form @file{lib@var{xxx}.a}
17838 or @file{lib@var{xxx}.so} (or @file{lib@var{xxx}.dll} on Windows) in order to
17839 be accessed by the directive @option{-l@var{xxx}} at link time.
17841 @node Installing a library
17842 @subsection Installing a library
17843 @cindex @code{ADA_PROJECT_PATH}
17844 @cindex @code{GPR_PROJECT_PATH}
17847 If you use project files, library installation is part of the library build
17848 process (@pxref{Installing a library with project files}).
17850 When project files are not an option, it is also possible, but not recommended,
17851 to install the library so that the sources needed to use the library are on the
17852 Ada source path and the ALI files & libraries be on the Ada Object path (see
17853 @ref{Search Paths and the Run-Time Library (RTL)}. Alternatively, the system
17854 administrator can place general-purpose libraries in the default compiler
17855 paths, by specifying the libraries' location in the configuration files
17856 @file{ada_source_path} and @file{ada_object_path}. These configuration files
17857 must be located in the GNAT installation tree at the same place as the gcc spec
17858 file. The location of the gcc spec file can be determined as follows:
17864 The configuration files mentioned above have a simple format: each line
17865 must contain one unique directory name.
17866 Those names are added to the corresponding path
17867 in their order of appearance in the file. The names can be either absolute
17868 or relative; in the latter case, they are relative to where theses files
17871 The files @file{ada_source_path} and @file{ada_object_path} might not be
17873 GNAT installation, in which case, GNAT will look for its run-time library in
17874 the directories @file{adainclude} (for the sources) and @file{adalib} (for the
17875 objects and @file{ALI} files). When the files exist, the compiler does not
17876 look in @file{adainclude} and @file{adalib}, and thus the
17877 @file{ada_source_path} file
17878 must contain the location for the GNAT run-time sources (which can simply
17879 be @file{adainclude}). In the same way, the @file{ada_object_path} file must
17880 contain the location for the GNAT run-time objects (which can simply
17883 You can also specify a new default path to the run-time library at compilation
17884 time with the switch @option{--RTS=rts-path}. You can thus choose / change
17885 the run-time library you want your program to be compiled with. This switch is
17886 recognized by @command{gcc}, @command{gnatmake}, @command{gnatbind},
17887 @command{gnatls}, @command{gnatfind} and @command{gnatxref}.
17889 It is possible to install a library before or after the standard GNAT
17890 library, by reordering the lines in the configuration files. In general, a
17891 library must be installed before the GNAT library if it redefines
17894 @node Using a library
17895 @subsection Using a library
17897 @noindent Once again, the project facility greatly simplifies the use of
17898 libraries. In this context, using a library is just a matter of adding a
17899 @code{with} clause in the user project. For instance, to make use of the
17900 library @code{My_Lib} shown in examples in earlier sections, you can
17903 @smallexample @c projectfile
17910 Even if you have a third-party, non-Ada library, you can still use GNAT's
17911 Project Manager facility to provide a wrapper for it. For example, the
17912 following project, when @code{with}ed by your main project, will link with the
17913 third-party library @file{liba.a}:
17915 @smallexample @c projectfile
17918 for Externally_Built use "true";
17919 for Source_Files use ();
17920 for Library_Dir use "lib";
17921 for Library_Name use "a";
17922 for Library_Kind use "static";
17926 This is an alternative to the use of @code{pragma Linker_Options}. It is
17927 especially interesting in the context of systems with several interdependent
17928 static libraries where finding a proper linker order is not easy and best be
17929 left to the tools having visibility over project dependence information.
17932 In order to use an Ada library manually, you need to make sure that this
17933 library is on both your source and object path
17934 (see @ref{Search Paths and the Run-Time Library (RTL)}
17935 and @ref{Search Paths for gnatbind}). Furthermore, when the objects are grouped
17936 in an archive or a shared library, you need to specify the desired
17937 library at link time.
17939 For example, you can use the library @file{mylib} installed in
17940 @file{/dir/my_lib_src} and @file{/dir/my_lib_obj} with the following commands:
17943 $ gnatmake -aI/dir/my_lib_src -aO/dir/my_lib_obj my_appl \
17948 This can be expressed more simply:
17953 when the following conditions are met:
17956 @file{/dir/my_lib_src} has been added by the user to the environment
17957 variable @env{ADA_INCLUDE_PATH}, or by the administrator to the file
17958 @file{ada_source_path}
17960 @file{/dir/my_lib_obj} has been added by the user to the environment
17961 variable @env{ADA_OBJECTS_PATH}, or by the administrator to the file
17962 @file{ada_object_path}
17964 a pragma @code{Linker_Options} has been added to one of the sources.
17967 @smallexample @c ada
17968 pragma Linker_Options ("-lmy_lib");
17972 @node Stand-alone Ada Libraries
17973 @section Stand-alone Ada Libraries
17974 @cindex Stand-alone library, building, using
17977 * Introduction to Stand-alone Libraries::
17978 * Building a Stand-alone Library::
17979 * Creating a Stand-alone Library to be used in a non-Ada context::
17980 * Restrictions in Stand-alone Libraries::
17983 @node Introduction to Stand-alone Libraries
17984 @subsection Introduction to Stand-alone Libraries
17987 A Stand-alone Library (abbreviated ``SAL'') is a library that contains the
17989 elaborate the Ada units that are included in the library. In contrast with
17990 an ordinary library, which consists of all sources, objects and @file{ALI}
17992 library, a SAL may specify a restricted subset of compilation units
17993 to serve as a library interface. In this case, the fully
17994 self-sufficient set of files will normally consist of an objects
17995 archive, the sources of interface units' specs, and the @file{ALI}
17996 files of interface units.
17997 If an interface spec contains a generic unit or an inlined subprogram,
17999 source must also be provided; if the units that must be provided in the source
18000 form depend on other units, the source and @file{ALI} files of those must
18003 The main purpose of a SAL is to minimize the recompilation overhead of client
18004 applications when a new version of the library is installed. Specifically,
18005 if the interface sources have not changed, client applications do not need to
18006 be recompiled. If, furthermore, a SAL is provided in the shared form and its
18007 version, controlled by @code{Library_Version} attribute, is not changed,
18008 then the clients do not need to be relinked.
18010 SALs also allow the library providers to minimize the amount of library source
18011 text exposed to the clients. Such ``information hiding'' might be useful or
18012 necessary for various reasons.
18014 Stand-alone libraries are also well suited to be used in an executable whose
18015 main routine is not written in Ada.
18017 @node Building a Stand-alone Library
18018 @subsection Building a Stand-alone Library
18021 GNAT's Project facility provides a simple way of building and installing
18022 stand-alone libraries; see @ref{Stand-alone Library Projects}.
18023 To be a Stand-alone Library Project, in addition to the two attributes
18024 that make a project a Library Project (@code{Library_Name} and
18025 @code{Library_Dir}; see @ref{Library Projects}), the attribute
18026 @code{Library_Interface} must be defined. For example:
18028 @smallexample @c projectfile
18030 for Library_Dir use "lib_dir";
18031 for Library_Name use "dummy";
18032 for Library_Interface use ("int1", "int1.child");
18037 Attribute @code{Library_Interface} has a non-empty string list value,
18038 each string in the list designating a unit contained in an immediate source
18039 of the project file.
18041 When a Stand-alone Library is built, first the binder is invoked to build
18042 a package whose name depends on the library name
18043 (@file{^b~dummy.ads/b^B$DUMMY.ADS/B^} in the example above).
18044 This binder-generated package includes initialization and
18045 finalization procedures whose
18046 names depend on the library name (@code{dummyinit} and @code{dummyfinal}
18048 above). The object corresponding to this package is included in the library.
18050 You must ensure timely (e.g., prior to any use of interfaces in the SAL)
18051 calling of these procedures if a static SAL is built, or if a shared SAL
18053 with the project-level attribute @code{Library_Auto_Init} set to
18056 For a Stand-Alone Library, only the @file{ALI} files of the Interface Units
18057 (those that are listed in attribute @code{Library_Interface}) are copied to
18058 the Library Directory. As a consequence, only the Interface Units may be
18059 imported from Ada units outside of the library. If other units are imported,
18060 the binding phase will fail.
18063 It is also possible to build an encapsulated library where not only
18064 the code to elaborate and finalize the library is embedded but also
18065 ensuring that the library is linked only against static
18066 libraries. So an encapsulated library only depends on system
18067 libraries, all other code, including the GNAT runtime, is embedded. To
18068 build an encapsulated library the attribute
18069 @code{Library_Standalone} must be set to @code{encapsulated}:
18071 @smallexample @c projectfile
18073 for Library_Dir use "lib_dir";
18074 for Library_Name use "dummy";
18075 for Library_Kind use "dynamic";
18076 for Library_Interface use ("int1", "int1.child");
18077 for Library_Standalone use "encapsulated";
18082 The default value for this attribute is @code{standard} in which case
18083 a stand-alone library is built.
18085 The attribute @code{Library_Src_Dir} may be specified for a
18086 Stand-Alone Library. @code{Library_Src_Dir} is a simple attribute that has a
18087 single string value. Its value must be the path (absolute or relative to the
18088 project directory) of an existing directory. This directory cannot be the
18089 object directory or one of the source directories, but it can be the same as
18090 the library directory. The sources of the Interface
18091 Units of the library that are needed by an Ada client of the library will be
18092 copied to the designated directory, called the Interface Copy directory.
18093 These sources include the specs of the Interface Units, but they may also
18094 include bodies and subunits, when pragmas @code{Inline} or @code{Inline_Always}
18095 are used, or when there is a generic unit in the spec. Before the sources
18096 are copied to the Interface Copy directory, an attempt is made to delete all
18097 files in the Interface Copy directory.
18099 Building stand-alone libraries by hand is somewhat tedious, but for those
18100 occasions when it is necessary here are the steps that you need to perform:
18103 Compile all library sources.
18106 Invoke the binder with the switch @option{-n} (No Ada main program),
18107 with all the @file{ALI} files of the interfaces, and
18108 with the switch @option{-L} to give specific names to the @code{init}
18109 and @code{final} procedures. For example:
18111 gnatbind -n int1.ali int2.ali -Lsal1
18115 Compile the binder generated file:
18121 Link the dynamic library with all the necessary object files,
18122 indicating to the linker the names of the @code{init} (and possibly
18123 @code{final}) procedures for automatic initialization (and finalization).
18124 The built library should be placed in a directory different from
18125 the object directory.
18128 Copy the @code{ALI} files of the interface to the library directory,
18129 add in this copy an indication that it is an interface to a SAL
18130 (i.e., add a word @option{SL} on the line in the @file{ALI} file that starts
18131 with letter ``P'') and make the modified copy of the @file{ALI} file
18136 Using SALs is not different from using other libraries
18137 (see @ref{Using a library}).
18139 @node Creating a Stand-alone Library to be used in a non-Ada context
18140 @subsection Creating a Stand-alone Library to be used in a non-Ada context
18143 It is easy to adapt the SAL build procedure discussed above for use of a SAL in
18146 The only extra step required is to ensure that library interface subprograms
18147 are compatible with the main program, by means of @code{pragma Export}
18148 or @code{pragma Convention}.
18150 Here is an example of simple library interface for use with C main program:
18152 @smallexample @c ada
18153 package My_Package is
18155 procedure Do_Something;
18156 pragma Export (C, Do_Something, "do_something");
18158 procedure Do_Something_Else;
18159 pragma Export (C, Do_Something_Else, "do_something_else");
18165 On the foreign language side, you must provide a ``foreign'' view of the
18166 library interface; remember that it should contain elaboration routines in
18167 addition to interface subprograms.
18169 The example below shows the content of @code{mylib_interface.h} (note
18170 that there is no rule for the naming of this file, any name can be used)
18172 /* the library elaboration procedure */
18173 extern void mylibinit (void);
18175 /* the library finalization procedure */
18176 extern void mylibfinal (void);
18178 /* the interface exported by the library */
18179 extern void do_something (void);
18180 extern void do_something_else (void);
18184 Libraries built as explained above can be used from any program, provided
18185 that the elaboration procedures (named @code{mylibinit} in the previous
18186 example) are called before the library services are used. Any number of
18187 libraries can be used simultaneously, as long as the elaboration
18188 procedure of each library is called.
18190 Below is an example of a C program that uses the @code{mylib} library.
18193 #include "mylib_interface.h"
18198 /* First, elaborate the library before using it */
18201 /* Main program, using the library exported entities */
18203 do_something_else ();
18205 /* Library finalization at the end of the program */
18212 Note that invoking any library finalization procedure generated by
18213 @code{gnatbind} shuts down the Ada run-time environment.
18215 finalization of all Ada libraries must be performed at the end of the program.
18216 No call to these libraries or to the Ada run-time library should be made
18217 after the finalization phase.
18219 @node Restrictions in Stand-alone Libraries
18220 @subsection Restrictions in Stand-alone Libraries
18223 The pragmas listed below should be used with caution inside libraries,
18224 as they can create incompatibilities with other Ada libraries:
18226 @item pragma @code{Locking_Policy}
18227 @item pragma @code{Partition_Elaboration_Policy}
18228 @item pragma @code{Queuing_Policy}
18229 @item pragma @code{Task_Dispatching_Policy}
18230 @item pragma @code{Unreserve_All_Interrupts}
18234 When using a library that contains such pragmas, the user must make sure
18235 that all libraries use the same pragmas with the same values. Otherwise,
18236 @code{Program_Error} will
18237 be raised during the elaboration of the conflicting
18238 libraries. The usage of these pragmas and its consequences for the user
18239 should therefore be well documented.
18241 Similarly, the traceback in the exception occurrence mechanism should be
18242 enabled or disabled in a consistent manner across all libraries.
18243 Otherwise, Program_Error will be raised during the elaboration of the
18244 conflicting libraries.
18246 If the @code{Version} or @code{Body_Version}
18247 attributes are used inside a library, then you need to
18248 perform a @code{gnatbind} step that specifies all @file{ALI} files in all
18249 libraries, so that version identifiers can be properly computed.
18250 In practice these attributes are rarely used, so this is unlikely
18251 to be a consideration.
18253 @node Rebuilding the GNAT Run-Time Library
18254 @section Rebuilding the GNAT Run-Time Library
18255 @cindex GNAT Run-Time Library, rebuilding
18256 @cindex Building the GNAT Run-Time Library
18257 @cindex Rebuilding the GNAT Run-Time Library
18258 @cindex Run-Time Library, rebuilding
18261 It may be useful to recompile the GNAT library in various contexts, the
18262 most important one being the use of partition-wide configuration pragmas
18263 such as @code{Normalize_Scalars}. A special Makefile called
18264 @code{Makefile.adalib} is provided to that effect and can be found in
18265 the directory containing the GNAT library. The location of this
18266 directory depends on the way the GNAT environment has been installed and can
18267 be determined by means of the command:
18274 The last entry in the object search path usually contains the
18275 gnat library. This Makefile contains its own documentation and in
18276 particular the set of instructions needed to rebuild a new library and
18279 @node Using the GNU make Utility
18280 @chapter Using the GNU @code{make} Utility
18284 This chapter offers some examples of makefiles that solve specific
18285 problems. It does not explain how to write a makefile (@pxref{Top,, GNU
18286 make, make, GNU @code{make}}), nor does it try to replace the
18287 @command{gnatmake} utility (@pxref{The GNAT Make Program gnatmake}).
18289 All the examples in this section are specific to the GNU version of
18290 make. Although @command{make} is a standard utility, and the basic language
18291 is the same, these examples use some advanced features found only in
18295 * Using gnatmake in a Makefile::
18296 * Automatically Creating a List of Directories::
18297 * Generating the Command Line Switches::
18298 * Overcoming Command Line Length Limits::
18301 @node Using gnatmake in a Makefile
18302 @section Using gnatmake in a Makefile
18307 Complex project organizations can be handled in a very powerful way by
18308 using GNU make combined with gnatmake. For instance, here is a Makefile
18309 which allows you to build each subsystem of a big project into a separate
18310 shared library. Such a makefile allows you to significantly reduce the link
18311 time of very big applications while maintaining full coherence at
18312 each step of the build process.
18314 The list of dependencies are handled automatically by
18315 @command{gnatmake}. The Makefile is simply used to call gnatmake in each of
18316 the appropriate directories.
18318 Note that you should also read the example on how to automatically
18319 create the list of directories
18320 (@pxref{Automatically Creating a List of Directories})
18321 which might help you in case your project has a lot of subdirectories.
18326 @font@heightrm=cmr8
18329 ## This Makefile is intended to be used with the following directory
18331 ## - The sources are split into a series of csc (computer software components)
18332 ## Each of these csc is put in its own directory.
18333 ## Their name are referenced by the directory names.
18334 ## They will be compiled into shared library (although this would also work
18335 ## with static libraries
18336 ## - The main program (and possibly other packages that do not belong to any
18337 ## csc is put in the top level directory (where the Makefile is).
18338 ## toplevel_dir __ first_csc (sources) __ lib (will contain the library)
18339 ## \_ second_csc (sources) __ lib (will contain the library)
18341 ## Although this Makefile is build for shared library, it is easy to modify
18342 ## to build partial link objects instead (modify the lines with -shared and
18345 ## With this makefile, you can change any file in the system or add any new
18346 ## file, and everything will be recompiled correctly (only the relevant shared
18347 ## objects will be recompiled, and the main program will be re-linked).
18349 # The list of computer software component for your project. This might be
18350 # generated automatically.
18353 # Name of the main program (no extension)
18356 # If we need to build objects with -fPIC, uncomment the following line
18359 # The following variable should give the directory containing libgnat.so
18360 # You can get this directory through 'gnatls -v'. This is usually the last
18361 # directory in the Object_Path.
18364 # The directories for the libraries
18365 # (This macro expands the list of CSC to the list of shared libraries, you
18366 # could simply use the expanded form:
18367 # LIB_DIR=aa/lib/libaa.so bb/lib/libbb.so cc/lib/libcc.so
18368 LIB_DIR=$@{foreach dir,$@{CSC_LIST@},$@{dir@}/lib/lib$@{dir@}.so@}
18370 $@{MAIN@}: objects $@{LIB_DIR@}
18371 gnatbind $@{MAIN@} $@{CSC_LIST:%=-aO%/lib@} -shared
18372 gnatlink $@{MAIN@} $@{CSC_LIST:%=-l%@}
18375 # recompile the sources
18376 gnatmake -c -i $@{MAIN@}.adb $@{NEED_FPIC@} $@{CSC_LIST:%=-I%@}
18378 # Note: In a future version of GNAT, the following commands will be simplified
18379 # by a new tool, gnatmlib
18381 mkdir -p $@{dir $@@ @}
18382 cd $@{dir $@@ @} && gcc -shared -o $@{notdir $@@ @} ../*.o -L$@{GLIB@} -lgnat
18383 cd $@{dir $@@ @} && cp -f ../*.ali .
18385 # The dependencies for the modules
18386 # Note that we have to force the expansion of *.o, since in some cases
18387 # make won't be able to do it itself.
18388 aa/lib/libaa.so: $@{wildcard aa/*.o@}
18389 bb/lib/libbb.so: $@{wildcard bb/*.o@}
18390 cc/lib/libcc.so: $@{wildcard cc/*.o@}
18392 # Make sure all of the shared libraries are in the path before starting the
18395 LD_LIBRARY_PATH=`pwd`/aa/lib:`pwd`/bb/lib:`pwd`/cc/lib ./$@{MAIN@}
18398 $@{RM@} -rf $@{CSC_LIST:%=%/lib@}
18399 $@{RM@} $@{CSC_LIST:%=%/*.ali@}
18400 $@{RM@} $@{CSC_LIST:%=%/*.o@}
18401 $@{RM@} *.o *.ali $@{MAIN@}
18404 @node Automatically Creating a List of Directories
18405 @section Automatically Creating a List of Directories
18408 In most makefiles, you will have to specify a list of directories, and
18409 store it in a variable. For small projects, it is often easier to
18410 specify each of them by hand, since you then have full control over what
18411 is the proper order for these directories, which ones should be
18414 However, in larger projects, which might involve hundreds of
18415 subdirectories, it might be more convenient to generate this list
18418 The example below presents two methods. The first one, although less
18419 general, gives you more control over the list. It involves wildcard
18420 characters, that are automatically expanded by @command{make}. Its
18421 shortcoming is that you need to explicitly specify some of the
18422 organization of your project, such as for instance the directory tree
18423 depth, whether some directories are found in a separate tree, @enddots{}
18425 The second method is the most general one. It requires an external
18426 program, called @command{find}, which is standard on all Unix systems. All
18427 the directories found under a given root directory will be added to the
18433 @font@heightrm=cmr8
18436 # The examples below are based on the following directory hierarchy:
18437 # All the directories can contain any number of files
18438 # ROOT_DIRECTORY -> a -> aa -> aaa
18441 # -> b -> ba -> baa
18444 # This Makefile creates a variable called DIRS, that can be reused any time
18445 # you need this list (see the other examples in this section)
18447 # The root of your project's directory hierarchy
18451 # First method: specify explicitly the list of directories
18452 # This allows you to specify any subset of all the directories you need.
18455 DIRS := a/aa/ a/ab/ b/ba/
18458 # Second method: use wildcards
18459 # Note that the argument(s) to wildcard below should end with a '/'.
18460 # Since wildcards also return file names, we have to filter them out
18461 # to avoid duplicate directory names.
18462 # We thus use make's @code{dir} and @code{sort} functions.
18463 # It sets DIRs to the following value (note that the directories aaa and baa
18464 # are not given, unless you change the arguments to wildcard).
18465 # DIRS= ./a/a/ ./b/ ./a/aa/ ./a/ab/ ./a/ac/ ./b/ba/ ./b/bb/ ./b/bc/
18468 DIRS := $@{sort $@{dir $@{wildcard $@{ROOT_DIRECTORY@}/*/
18469 $@{ROOT_DIRECTORY@}/*/*/@}@}@}
18472 # Third method: use an external program
18473 # This command is much faster if run on local disks, avoiding NFS slowdowns.
18474 # This is the most complete command: it sets DIRs to the following value:
18475 # DIRS= ./a ./a/aa ./a/aa/aaa ./a/ab ./a/ac ./b ./b/ba ./b/ba/baa ./b/bb ./b/bc
18478 DIRS := $@{shell find $@{ROOT_DIRECTORY@} -type d -print@}
18482 @node Generating the Command Line Switches
18483 @section Generating the Command Line Switches
18486 Once you have created the list of directories as explained in the
18487 previous section (@pxref{Automatically Creating a List of Directories}),
18488 you can easily generate the command line arguments to pass to gnatmake.
18490 For the sake of completeness, this example assumes that the source path
18491 is not the same as the object path, and that you have two separate lists
18495 # see "Automatically creating a list of directories" to create
18500 GNATMAKE_SWITCHES := $@{patsubst %,-aI%,$@{SOURCE_DIRS@}@}
18501 GNATMAKE_SWITCHES += $@{patsubst %,-aO%,$@{OBJECT_DIRS@}@}
18504 gnatmake $@{GNATMAKE_SWITCHES@} main_unit
18507 @node Overcoming Command Line Length Limits
18508 @section Overcoming Command Line Length Limits
18511 One problem that might be encountered on big projects is that many
18512 operating systems limit the length of the command line. It is thus hard to give
18513 gnatmake the list of source and object directories.
18515 This example shows how you can set up environment variables, which will
18516 make @command{gnatmake} behave exactly as if the directories had been
18517 specified on the command line, but have a much higher length limit (or
18518 even none on most systems).
18520 It assumes that you have created a list of directories in your Makefile,
18521 using one of the methods presented in
18522 @ref{Automatically Creating a List of Directories}.
18523 For the sake of completeness, we assume that the object
18524 path (where the ALI files are found) is different from the sources patch.
18526 Note a small trick in the Makefile below: for efficiency reasons, we
18527 create two temporary variables (SOURCE_LIST and OBJECT_LIST), that are
18528 expanded immediately by @code{make}. This way we overcome the standard
18529 make behavior which is to expand the variables only when they are
18532 On Windows, if you are using the standard Windows command shell, you must
18533 replace colons with semicolons in the assignments to these variables.
18538 @font@heightrm=cmr8
18541 # In this example, we create both ADA_INCLUDE_PATH and ADA_OBJECTS_PATH.
18542 # This is the same thing as putting the -I arguments on the command line.
18543 # (the equivalent of using -aI on the command line would be to define
18544 # only ADA_INCLUDE_PATH, the equivalent of -aO is ADA_OBJECTS_PATH).
18545 # You can of course have different values for these variables.
18547 # Note also that we need to keep the previous values of these variables, since
18548 # they might have been set before running 'make' to specify where the GNAT
18549 # library is installed.
18551 # see "Automatically creating a list of directories" to create these
18557 space:=$@{empty@} $@{empty@}
18558 SOURCE_LIST := $@{subst $@{space@},:,$@{SOURCE_DIRS@}@}
18559 OBJECT_LIST := $@{subst $@{space@},:,$@{OBJECT_DIRS@}@}
18560 ADA_INCLUDE_PATH += $@{SOURCE_LIST@}
18561 ADA_OBJECTS_PATH += $@{OBJECT_LIST@}
18562 export ADA_INCLUDE_PATH
18563 export ADA_OBJECTS_PATH
18570 @node Memory Management Issues
18571 @chapter Memory Management Issues
18574 This chapter describes some useful memory pools provided in the GNAT library
18575 and in particular the GNAT Debug Pool facility, which can be used to detect
18576 incorrect uses of access values (including ``dangling references'').
18578 @ifclear FSFEDITION
18579 It also describes the @command{gnatmem} tool, which can be used to track down
18585 * Some Useful Memory Pools::
18586 * The GNAT Debug Pool Facility::
18588 @ifclear FSFEDITION
18589 * The gnatmem Tool::
18594 @node Some Useful Memory Pools
18595 @section Some Useful Memory Pools
18596 @findex Memory Pool
18597 @cindex storage, pool
18600 The @code{System.Pool_Global} package offers the Unbounded_No_Reclaim_Pool
18601 storage pool. Allocations use the standard system call @code{malloc} while
18602 deallocations use the standard system call @code{free}. No reclamation is
18603 performed when the pool goes out of scope. For performance reasons, the
18604 standard default Ada allocators/deallocators do not use any explicit storage
18605 pools but if they did, they could use this storage pool without any change in
18606 behavior. That is why this storage pool is used when the user
18607 manages to make the default implicit allocator explicit as in this example:
18608 @smallexample @c ada
18609 type T1 is access Something;
18610 -- no Storage pool is defined for T2
18611 type T2 is access Something_Else;
18612 for T2'Storage_Pool use T1'Storage_Pool;
18613 -- the above is equivalent to
18614 for T2'Storage_Pool use System.Pool_Global.Global_Pool_Object;
18618 The @code{System.Pool_Local} package offers the Unbounded_Reclaim_Pool storage
18619 pool. The allocation strategy is similar to @code{Pool_Local}'s
18620 except that the all
18621 storage allocated with this pool is reclaimed when the pool object goes out of
18622 scope. This pool provides a explicit mechanism similar to the implicit one
18623 provided by several Ada 83 compilers for allocations performed through a local
18624 access type and whose purpose was to reclaim memory when exiting the
18625 scope of a given local access. As an example, the following program does not
18626 leak memory even though it does not perform explicit deallocation:
18628 @smallexample @c ada
18629 with System.Pool_Local;
18630 procedure Pooloc1 is
18631 procedure Internal is
18632 type A is access Integer;
18633 X : System.Pool_Local.Unbounded_Reclaim_Pool;
18634 for A'Storage_Pool use X;
18637 for I in 1 .. 50 loop
18642 for I in 1 .. 100 loop
18649 The @code{System.Pool_Size} package implements the Stack_Bounded_Pool used when
18650 @code{Storage_Size} is specified for an access type.
18651 The whole storage for the pool is
18652 allocated at once, usually on the stack at the point where the access type is
18653 elaborated. It is automatically reclaimed when exiting the scope where the
18654 access type is defined. This package is not intended to be used directly by the
18655 user and it is implicitly used for each such declaration:
18657 @smallexample @c ada
18658 type T1 is access Something;
18659 for T1'Storage_Size use 10_000;
18662 @node The GNAT Debug Pool Facility
18663 @section The GNAT Debug Pool Facility
18665 @cindex storage, pool, memory corruption
18668 The use of unchecked deallocation and unchecked conversion can easily
18669 lead to incorrect memory references. The problems generated by such
18670 references are usually difficult to tackle because the symptoms can be
18671 very remote from the origin of the problem. In such cases, it is
18672 very helpful to detect the problem as early as possible. This is the
18673 purpose of the Storage Pool provided by @code{GNAT.Debug_Pools}.
18675 In order to use the GNAT specific debugging pool, the user must
18676 associate a debug pool object with each of the access types that may be
18677 related to suspected memory problems. See Ada Reference Manual 13.11.
18678 @smallexample @c ada
18679 type Ptr is access Some_Type;
18680 Pool : GNAT.Debug_Pools.Debug_Pool;
18681 for Ptr'Storage_Pool use Pool;
18685 @code{GNAT.Debug_Pools} is derived from a GNAT-specific kind of
18686 pool: the @code{Checked_Pool}. Such pools, like standard Ada storage pools,
18687 allow the user to redefine allocation and deallocation strategies. They
18688 also provide a checkpoint for each dereference, through the use of
18689 the primitive operation @code{Dereference} which is implicitly called at
18690 each dereference of an access value.
18692 Once an access type has been associated with a debug pool, operations on
18693 values of the type may raise four distinct exceptions,
18694 which correspond to four potential kinds of memory corruption:
18697 @code{GNAT.Debug_Pools.Accessing_Not_Allocated_Storage}
18699 @code{GNAT.Debug_Pools.Accessing_Deallocated_Storage}
18701 @code{GNAT.Debug_Pools.Freeing_Not_Allocated_Storage}
18703 @code{GNAT.Debug_Pools.Freeing_Deallocated_Storage }
18707 For types associated with a Debug_Pool, dynamic allocation is performed using
18708 the standard GNAT allocation routine. References to all allocated chunks of
18709 memory are kept in an internal dictionary. Several deallocation strategies are
18710 provided, whereupon the user can choose to release the memory to the system,
18711 keep it allocated for further invalid access checks, or fill it with an easily
18712 recognizable pattern for debug sessions. The memory pattern is the old IBM
18713 hexadecimal convention: @code{16#DEADBEEF#}.
18715 See the documentation in the file g-debpoo.ads for more information on the
18716 various strategies.
18718 Upon each dereference, a check is made that the access value denotes a
18719 properly allocated memory location. Here is a complete example of use of
18720 @code{Debug_Pools}, that includes typical instances of memory corruption:
18721 @smallexample @c ada
18725 with Gnat.Io; use Gnat.Io;
18726 with Unchecked_Deallocation;
18727 with Unchecked_Conversion;
18728 with GNAT.Debug_Pools;
18729 with System.Storage_Elements;
18730 with Ada.Exceptions; use Ada.Exceptions;
18731 procedure Debug_Pool_Test is
18733 type T is access Integer;
18734 type U is access all T;
18736 P : GNAT.Debug_Pools.Debug_Pool;
18737 for T'Storage_Pool use P;
18739 procedure Free is new Unchecked_Deallocation (Integer, T);
18740 function UC is new Unchecked_Conversion (U, T);
18743 procedure Info is new GNAT.Debug_Pools.Print_Info(Put_Line);
18753 Put_Line (Integer'Image(B.all));
18755 when E : others => Put_Line ("raised: " & Exception_Name (E));
18760 when E : others => Put_Line ("raised: " & Exception_Name (E));
18764 Put_Line (Integer'Image(B.all));
18766 when E : others => Put_Line ("raised: " & Exception_Name (E));
18771 when E : others => Put_Line ("raised: " & Exception_Name (E));
18774 end Debug_Pool_Test;
18778 The debug pool mechanism provides the following precise diagnostics on the
18779 execution of this erroneous program:
18782 Total allocated bytes : 0
18783 Total deallocated bytes : 0
18784 Current Water Mark: 0
18788 Total allocated bytes : 8
18789 Total deallocated bytes : 0
18790 Current Water Mark: 8
18793 raised: GNAT.DEBUG_POOLS.ACCESSING_DEALLOCATED_STORAGE
18794 raised: GNAT.DEBUG_POOLS.FREEING_DEALLOCATED_STORAGE
18795 raised: GNAT.DEBUG_POOLS.ACCESSING_NOT_ALLOCATED_STORAGE
18796 raised: GNAT.DEBUG_POOLS.FREEING_NOT_ALLOCATED_STORAGE
18798 Total allocated bytes : 8
18799 Total deallocated bytes : 4
18800 Current Water Mark: 4
18805 @ifclear FSFEDITION
18806 @node The gnatmem Tool
18807 @section The @command{gnatmem} Tool
18811 The @code{gnatmem} utility monitors dynamic allocation and
18812 deallocation activity in a program, and displays information about
18813 incorrect deallocations and possible sources of memory leaks.
18814 It is designed to work in association with a static runtime library
18815 only and in this context provides three types of information:
18818 General information concerning memory management, such as the total
18819 number of allocations and deallocations, the amount of allocated
18820 memory and the high water mark, i.e.@: the largest amount of allocated
18821 memory in the course of program execution.
18824 Backtraces for all incorrect deallocations, that is to say deallocations
18825 which do not correspond to a valid allocation.
18828 Information on each allocation that is potentially the origin of a memory
18833 * Running gnatmem::
18834 * Switches for gnatmem::
18835 * Example of gnatmem Usage::
18838 @node Running gnatmem
18839 @subsection Running @code{gnatmem}
18842 @code{gnatmem} makes use of the output created by the special version of
18843 allocation and deallocation routines that record call information. This allows
18844 it to obtain accurate dynamic memory usage history at a minimal cost to the
18845 execution speed. Note however, that @code{gnatmem} is not supported on all
18846 platforms (currently, it is supported on AIX, HP-UX, GNU/Linux, Solaris and
18847 Windows NT/2000/XP (x86).
18850 The @code{gnatmem} command has the form
18853 @c $ gnatmem @ovar{switches} user_program
18854 @c Expanding @ovar macro inline (explanation in macro def comments)
18855 $ gnatmem @r{[}@var{switches}@r{]} @var{user_program}
18859 The program must have been linked with the instrumented version of the
18860 allocation and deallocation routines. This is done by linking with the
18861 @file{libgmem.a} library. For correct symbolic backtrace information,
18862 the user program should be compiled with debugging options
18863 (see @ref{Switches for gcc}). For example to build @file{my_program}:
18866 $ gnatmake -g my_program -largs -lgmem
18870 As library @file{libgmem.a} contains an alternate body for package
18871 @code{System.Memory}, @file{s-memory.adb} should not be compiled and linked
18872 when an executable is linked with library @file{libgmem.a}. It is then not
18873 recommended to use @command{gnatmake} with switch @option{^-a^/ALL_FILES^}.
18876 When @file{my_program} is executed, the file @file{gmem.out} is produced.
18877 This file contains information about all allocations and deallocations
18878 performed by the program. It is produced by the instrumented allocations and
18879 deallocations routines and will be used by @code{gnatmem}.
18881 In order to produce symbolic backtrace information for allocations and
18882 deallocations performed by the GNAT run-time library, you need to use a
18883 version of that library that has been compiled with the @option{-g} switch
18884 (see @ref{Rebuilding the GNAT Run-Time Library}).
18886 Gnatmem must be supplied with the @file{gmem.out} file and the executable to
18887 examine. If the location of @file{gmem.out} file was not explicitly supplied by
18888 @option{-i} switch, gnatmem will assume that this file can be found in the
18889 current directory. For example, after you have executed @file{my_program},
18890 @file{gmem.out} can be analyzed by @code{gnatmem} using the command:
18893 $ gnatmem my_program
18897 This will produce the output with the following format:
18899 *************** debut cc
18901 $ gnatmem my_program
18905 Total number of allocations : 45
18906 Total number of deallocations : 6
18907 Final Water Mark (non freed mem) : 11.29 Kilobytes
18908 High Water Mark : 11.40 Kilobytes
18913 Allocation Root # 2
18914 -------------------
18915 Number of non freed allocations : 11
18916 Final Water Mark (non freed mem) : 1.16 Kilobytes
18917 High Water Mark : 1.27 Kilobytes
18919 my_program.adb:23 my_program.alloc
18925 The first block of output gives general information. In this case, the
18926 Ada construct ``@code{@b{new}}'' was executed 45 times, and only 6 calls to an
18927 Unchecked_Deallocation routine occurred.
18930 Subsequent paragraphs display information on all allocation roots.
18931 An allocation root is a specific point in the execution of the program
18932 that generates some dynamic allocation, such as a ``@code{@b{new}}''
18933 construct. This root is represented by an execution backtrace (or subprogram
18934 call stack). By default the backtrace depth for allocations roots is 1, so
18935 that a root corresponds exactly to a source location. The backtrace can
18936 be made deeper, to make the root more specific.
18938 @node Switches for gnatmem
18939 @subsection Switches for @code{gnatmem}
18942 @code{gnatmem} recognizes the following switches:
18947 @cindex @option{-q} (@code{gnatmem})
18948 Quiet. Gives the minimum output needed to identify the origin of the
18949 memory leaks. Omits statistical information.
18952 @cindex @var{N} (@code{gnatmem})
18953 N is an integer literal (usually between 1 and 10) which controls the
18954 depth of the backtraces defining allocation root. The default value for
18955 N is 1. The deeper the backtrace, the more precise the localization of
18956 the root. Note that the total number of roots can depend on this
18957 parameter. This parameter must be specified @emph{before} the name of the
18958 executable to be analyzed, to avoid ambiguity.
18961 @cindex @option{-b} (@code{gnatmem})
18962 This switch has the same effect as just depth parameter.
18964 @item -i @var{file}
18965 @cindex @option{-i} (@code{gnatmem})
18966 Do the @code{gnatmem} processing starting from @file{file}, rather than
18967 @file{gmem.out} in the current directory.
18970 @cindex @option{-m} (@code{gnatmem})
18971 This switch causes @code{gnatmem} to mask the allocation roots that have less
18972 than n leaks. The default value is 1. Specifying the value of 0 will allow
18973 examination of even the roots that did not result in leaks.
18976 @cindex @option{-s} (@code{gnatmem})
18977 This switch causes @code{gnatmem} to sort the allocation roots according to the
18978 specified order of sort criteria, each identified by a single letter. The
18979 currently supported criteria are @code{n, h, w} standing respectively for
18980 number of unfreed allocations, high watermark, and final watermark
18981 corresponding to a specific root. The default order is @code{nwh}.
18984 @cindex @option{-t} (@code{gnatmem})
18985 This switch causes memory allocated size to be always output in bytes.
18986 Default @code{gnatmem} behavior is to show memory sizes less then 1 kilobyte
18987 in bytes, from 1 kilobyte till 1 megabyte in kilobytes and the rest in
18992 @node Example of gnatmem Usage
18993 @subsection Example of @code{gnatmem} Usage
18996 The following example shows the use of @code{gnatmem}
18997 on a simple memory-leaking program.
18998 Suppose that we have the following Ada program:
19000 @smallexample @c ada
19003 with Unchecked_Deallocation;
19004 procedure Test_Gm is
19006 type T is array (1..1000) of Integer;
19007 type Ptr is access T;
19008 procedure Free is new Unchecked_Deallocation (T, Ptr);
19011 procedure My_Alloc is
19016 procedure My_DeAlloc is
19024 for I in 1 .. 5 loop
19025 for J in I .. 5 loop
19036 The program needs to be compiled with debugging option and linked with
19037 @code{gmem} library:
19040 $ gnatmake -g test_gm -largs -lgmem
19044 Then we execute the program as usual:
19051 Then @code{gnatmem} is invoked simply with
19057 which produces the following output (result may vary on different platforms):
19062 Total number of allocations : 18
19063 Total number of deallocations : 5
19064 Final Water Mark (non freed mem) : 53.00 Kilobytes
19065 High Water Mark : 56.90 Kilobytes
19067 Allocation Root # 1
19068 -------------------
19069 Number of non freed allocations : 11
19070 Final Water Mark (non freed mem) : 42.97 Kilobytes
19071 High Water Mark : 46.88 Kilobytes
19073 test_gm.adb:11 test_gm.my_alloc
19075 Allocation Root # 2
19076 -------------------
19077 Number of non freed allocations : 1
19078 Final Water Mark (non freed mem) : 10.02 Kilobytes
19079 High Water Mark : 10.02 Kilobytes
19081 s-secsta.adb:81 system.secondary_stack.ss_init
19083 Allocation Root # 3
19084 -------------------
19085 Number of non freed allocations : 1
19086 Final Water Mark (non freed mem) : 12 Bytes
19087 High Water Mark : 12 Bytes
19089 s-secsta.adb:181 system.secondary_stack.ss_init
19093 Note that the GNAT run time contains itself a certain number of
19094 allocations that have no corresponding deallocation,
19095 as shown here for root #2 and root
19096 #3. This is a normal behavior when the number of non-freed allocations
19097 is one, it allocates dynamic data structures that the run time needs for
19098 the complete lifetime of the program. Note also that there is only one
19099 allocation root in the user program with a single line back trace:
19100 test_gm.adb:11 test_gm.my_alloc, whereas a careful analysis of the
19101 program shows that 'My_Alloc' is called at 2 different points in the
19102 source (line 21 and line 24). If those two allocation roots need to be
19103 distinguished, the backtrace depth parameter can be used:
19106 $ gnatmem 3 test_gm
19110 which will give the following output:
19115 Total number of allocations : 18
19116 Total number of deallocations : 5
19117 Final Water Mark (non freed mem) : 53.00 Kilobytes
19118 High Water Mark : 56.90 Kilobytes
19120 Allocation Root # 1
19121 -------------------
19122 Number of non freed allocations : 10
19123 Final Water Mark (non freed mem) : 39.06 Kilobytes
19124 High Water Mark : 42.97 Kilobytes
19126 test_gm.adb:11 test_gm.my_alloc
19127 test_gm.adb:24 test_gm
19128 b_test_gm.c:52 main
19130 Allocation Root # 2
19131 -------------------
19132 Number of non freed allocations : 1
19133 Final Water Mark (non freed mem) : 10.02 Kilobytes
19134 High Water Mark : 10.02 Kilobytes
19136 s-secsta.adb:81 system.secondary_stack.ss_init
19137 s-secsta.adb:283 <system__secondary_stack___elabb>
19138 b_test_gm.c:33 adainit
19140 Allocation Root # 3
19141 -------------------
19142 Number of non freed allocations : 1
19143 Final Water Mark (non freed mem) : 3.91 Kilobytes
19144 High Water Mark : 3.91 Kilobytes
19146 test_gm.adb:11 test_gm.my_alloc
19147 test_gm.adb:21 test_gm
19148 b_test_gm.c:52 main
19150 Allocation Root # 4
19151 -------------------
19152 Number of non freed allocations : 1
19153 Final Water Mark (non freed mem) : 12 Bytes
19154 High Water Mark : 12 Bytes
19156 s-secsta.adb:181 system.secondary_stack.ss_init
19157 s-secsta.adb:283 <system__secondary_stack___elabb>
19158 b_test_gm.c:33 adainit
19162 The allocation root #1 of the first example has been split in 2 roots #1
19163 and #3 thanks to the more precise associated backtrace.
19167 @node Stack Related Facilities
19168 @chapter Stack Related Facilities
19171 This chapter describes some useful tools associated with stack
19172 checking and analysis. In
19173 particular, it deals with dynamic and static stack usage measurements.
19176 * Stack Overflow Checking::
19177 * Static Stack Usage Analysis::
19178 * Dynamic Stack Usage Analysis::
19181 @node Stack Overflow Checking
19182 @section Stack Overflow Checking
19183 @cindex Stack Overflow Checking
19184 @cindex -fstack-check
19187 For most operating systems, @command{gcc} does not perform stack overflow
19188 checking by default. This means that if the main environment task or
19189 some other task exceeds the available stack space, then unpredictable
19190 behavior will occur. Most native systems offer some level of protection by
19191 adding a guard page at the end of each task stack. This mechanism is usually
19192 not enough for dealing properly with stack overflow situations because
19193 a large local variable could ``jump'' above the guard page.
19194 Furthermore, when the
19195 guard page is hit, there may not be any space left on the stack for executing
19196 the exception propagation code. Enabling stack checking avoids
19199 To activate stack checking, compile all units with the gcc option
19200 @option{-fstack-check}. For example:
19203 gcc -c -fstack-check package1.adb
19207 Units compiled with this option will generate extra instructions to check
19208 that any use of the stack (for procedure calls or for declaring local
19209 variables in declare blocks) does not exceed the available stack space.
19210 If the space is exceeded, then a @code{Storage_Error} exception is raised.
19212 For declared tasks, the stack size is controlled by the size
19213 given in an applicable @code{Storage_Size} pragma or by the value specified
19214 at bind time with @option{-d} (@pxref{Switches for gnatbind}) or is set to
19215 the default size as defined in the GNAT runtime otherwise.
19217 For the environment task, the stack size depends on
19218 system defaults and is unknown to the compiler. Stack checking
19219 may still work correctly if a fixed
19220 size stack is allocated, but this cannot be guaranteed.
19222 To ensure that a clean exception is signalled for stack
19223 overflow, set the environment variable
19224 @env{GNAT_STACK_LIMIT} to indicate the maximum
19225 stack area that can be used, as in:
19226 @cindex GNAT_STACK_LIMIT
19229 SET GNAT_STACK_LIMIT 1600
19233 The limit is given in kilobytes, so the above declaration would
19234 set the stack limit of the environment task to 1.6 megabytes.
19235 Note that the only purpose of this usage is to limit the amount
19236 of stack used by the environment task. If it is necessary to
19237 increase the amount of stack for the environment task, then this
19238 is an operating systems issue, and must be addressed with the
19239 appropriate operating systems commands.
19242 To have a fixed size stack in the environment task, the stack must be put
19243 in the P0 address space and its size specified. Use these switches to
19247 gnatmake my_progs -largs "-Wl,--opt=STACK=4000,/p0image"
19251 The quotes are required to keep case. The number after @samp{STACK=} is the
19252 size of the environmental task stack in pagelets (512 bytes). In this example
19253 the stack size is about 2 megabytes.
19256 A consequence of the @option{/p0image} qualifier is also to makes RMS buffers
19257 be placed in P0 space. Refer to @cite{HP OpenVMS Linker Utility Manual} for
19258 more details about the @option{/p0image} qualifier and the @option{stack}
19262 On Itanium platforms, you can instead assign the @samp{GNAT_STACK_SIZE} and
19263 @samp{GNAT_RBS_SIZE} logicals to the size of the primary and register
19264 stack in kilobytes. For example:
19267 $ define GNAT_RBS_SIZE 1024 ! Limit the RBS size to 1MB.
19271 @node Static Stack Usage Analysis
19272 @section Static Stack Usage Analysis
19273 @cindex Static Stack Usage Analysis
19274 @cindex -fstack-usage
19277 A unit compiled with @option{-fstack-usage} will generate an extra file
19279 the maximum amount of stack used, on a per-function basis.
19280 The file has the same
19281 basename as the target object file with a @file{.su} extension.
19282 Each line of this file is made up of three fields:
19286 The name of the function.
19290 One or more qualifiers: @code{static}, @code{dynamic}, @code{bounded}.
19293 The second field corresponds to the size of the known part of the function
19296 The qualifier @code{static} means that the function frame size
19298 It usually means that all local variables have a static size.
19299 In this case, the second field is a reliable measure of the function stack
19302 The qualifier @code{dynamic} means that the function frame size is not static.
19303 It happens mainly when some local variables have a dynamic size. When this
19304 qualifier appears alone, the second field is not a reliable measure
19305 of the function stack analysis. When it is qualified with @code{bounded}, it
19306 means that the second field is a reliable maximum of the function stack
19309 A unit compiled with @option{-Wstack-usage} will issue a warning for each
19310 subprogram whose stack usage might be larger than the specified amount of
19311 bytes. The wording is in keeping with the qualifier documented above.
19313 @node Dynamic Stack Usage Analysis
19314 @section Dynamic Stack Usage Analysis
19317 It is possible to measure the maximum amount of stack used by a task, by
19318 adding a switch to @command{gnatbind}, as:
19321 $ gnatbind -u0 file
19325 With this option, at each task termination, its stack usage is output on
19327 It is not always convenient to output the stack usage when the program
19328 is still running. Hence, it is possible to delay this output until program
19329 termination. for a given number of tasks specified as the argument of the
19330 @option{-u} option. For instance:
19333 $ gnatbind -u100 file
19337 will buffer the stack usage information of the first 100 tasks to terminate and
19338 output this info at program termination. Results are displayed in four
19342 Index | Task Name | Stack Size | Stack Usage
19349 is a number associated with each task.
19352 is the name of the task analyzed.
19355 is the maximum size for the stack.
19358 is the measure done by the stack analyzer. In order to prevent overflow, the stack
19359 is not entirely analyzed, and it's not possible to know exactly how
19360 much has actually been used.
19365 The environment task stack, e.g., the stack that contains the main unit, is
19366 only processed when the environment variable GNAT_STACK_LIMIT is set.
19369 The package @code{GNAT.Task_Stack_Usage} provides facilities to get
19370 stack usage reports at run-time. See its body for the details.
19372 @ifclear FSFEDITION
19373 @c *********************************
19375 @c *********************************
19376 @node Verifying Properties with gnatcheck
19377 @chapter Verifying Properties with @command{gnatcheck}
19379 @cindex @command{gnatcheck}
19382 The @command{gnatcheck} tool is an ASIS-based utility that checks properties
19383 of Ada source files according to a given set of semantic rules.
19386 In order to check compliance with a given rule, @command{gnatcheck} has to
19387 semantically analyze the Ada sources.
19388 Therefore, checks can only be performed on
19389 legal Ada units. Moreover, when a unit depends semantically upon units located
19390 outside the current directory, the source search path has to be provided when
19391 calling @command{gnatcheck}, either through a specified project file or
19392 through @command{gnatcheck} switches.
19394 For full details, refer to @cite{GNATcheck Reference Manual} document.
19397 @ifclear FSFEDITION
19398 @c *********************************
19399 @node Creating Sample Bodies with gnatstub
19400 @chapter Creating Sample Bodies with @command{gnatstub}
19404 @command{gnatstub} creates body stubs, that is, empty but compilable bodies
19405 for library unit declarations.
19407 To create a body stub, @command{gnatstub} invokes the Ada
19408 compiler and generates and uses the ASIS tree for the input source;
19409 thus the input must be legal Ada code, and the tool should have all the
19410 information needed to compile the input source. To provide this information,
19411 you may specify as a tool parameter the project file the input source belongs to
19412 (or you may call @command{gnatstub}
19413 through the @command{gnat} driver (see @ref{The GNAT Driver and
19414 Project Files}). Another possibility is to specify the source search
19415 path and needed configuration files in @option{-cargs} section of @command{gnatstub}
19416 call, see the description of the @command{gnatstub} switches below.
19418 If the @command{gnatstub} argument source contains preprocessing directives
19419 then the needed options should be provided to run preprocessor as a part of
19420 the @command{gnatstub} call, and the generated body stub will correspond to
19421 the preprocessed source.
19423 By default, all the program unit body stubs generated by @code{gnatstub}
19424 raise the predefined @code{Program_Error} exception, which will catch
19425 accidental calls of generated stubs. This behavior can be changed with
19426 option @option{^--no-exception^/NO_EXCEPTION^} (see below).
19429 * Running gnatstub::
19430 * Switches for gnatstub::
19433 @node Running gnatstub
19434 @section Running @command{gnatstub}
19437 @command{gnatstub} has a command-line interface of the form:
19440 @c $ gnatstub @ovar{switches} @var{filename} @ovar{directory}
19441 @c Expanding @ovar macro inline (explanation in macro def comments)
19442 $ gnatstub @r{[}@var{switches}@r{]} @var{filename} @r{[}@var{directory}@r{]} @r{[}-cargs @var{gcc_switches}@r{]}
19449 is the name of the source file that contains a library unit declaration
19450 for which a body must be created. The file name may contain the path
19452 The file name does not have to follow the GNAT file name conventions. If the
19454 does not follow GNAT file naming conventions, the name of the body file must
19456 explicitly as the value of the @option{^-o^/BODY=^@var{body-name}} option.
19457 If the file name follows the GNAT file naming
19458 conventions and the name of the body file is not provided,
19461 of the body file from the argument file name by replacing the @file{.ads}
19463 with the @file{.adb} suffix.
19466 indicates the directory in which the body stub is to be placed (the default
19470 @item @samp{@var{gcc_switches}} is a list of switches for
19471 @command{gcc}. They will be passed on to all compiler invocations made by
19472 @command{gnatstub} to generate the ASIS trees. Here you can provide
19473 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
19474 use the @option{-gnatec} switch to set the configuration file,
19475 use the @option{-gnat05} switch if sources should be compiled in
19479 is an optional sequence of switches as described in the next section
19482 @node Switches for gnatstub
19483 @section Switches for @command{gnatstub}
19489 @cindex @option{--version} @command{gnatstub}
19490 Display Copyright and version, then exit disregarding all other options.
19493 @cindex @option{--help} @command{gnatstub}
19494 Display usage, then exit disregarding all other options.
19496 @item -P @var{file}
19497 @cindex @option{-P} @command{gnatstub}
19498 Indicates the name of the project file that describes the set of sources
19501 @item -X@var{name}=@var{value}
19502 @cindex @option{-X} @command{gnatstub}
19503 Indicates that external variable @var{name} in the argument project
19504 has the value @var{value}. Has no effect if no project is specified as
19508 @cindex @option{^-f^/FULL^} (@command{gnatstub})
19509 If the destination directory already contains a file with the name of the
19511 for the argument spec file, replace it with the generated body stub.
19513 @item ^-hs^/HEADER=SPEC^
19514 @cindex @option{^-hs^/HEADER=SPEC^} (@command{gnatstub})
19515 Put the comment header (i.e., all the comments preceding the
19516 compilation unit) from the source of the library unit declaration
19517 into the body stub.
19519 @item ^-hg^/HEADER=GENERAL^
19520 @cindex @option{^-hg^/HEADER=GENERAL^} (@command{gnatstub})
19521 Put a sample comment header into the body stub.
19523 @item ^--header-file=@var{filename}^/FROM_HEADER_FILE=@var{filename}^
19524 @cindex @option{^--header-file^/FROM_HEADER_FILE=^} (@command{gnatstub})
19525 Use the content of the file as the comment header for a generated body stub.
19529 @cindex @option{-IDIR} (@command{gnatstub})
19531 @cindex @option{-I-} (@command{gnatstub})
19534 @item /NOCURRENT_DIRECTORY
19535 @cindex @option{/NOCURRENT_DIRECTORY} (@command{gnatstub})
19537 ^These switches have ^This switch has^ the same meaning as in calls to
19539 ^They define ^It defines ^ the source search path in the call to
19540 @command{gcc} issued
19541 by @command{gnatstub} to compile an argument source file.
19543 @item ^-gnatec^/CONFIGURATION_PRAGMAS_FILE=^@var{PATH}
19544 @cindex @option{^-gnatec^/CONFIGURATION_PRAGMAS_FILE^} (@command{gnatstub})
19545 This switch has the same meaning as in calls to @command{gcc}.
19546 It defines the additional configuration file to be passed to the call to
19547 @command{gcc} issued
19548 by @command{gnatstub} to compile an argument source file.
19550 @item ^-gnatyM^/MAX_LINE_LENGTH=^@var{n}
19551 @cindex @option{^-gnatyM^/MAX_LINE_LENGTH^} (@command{gnatstub})
19552 (@var{n} is a non-negative integer). Set the maximum line length that is
19553 allowed in a source file. The default is 79. The maximum value that can be
19554 specified is 32767. Note that in the special case of configuration
19555 pragma files, the maximum is always 32767 regardless of whether or
19556 not this switch appears.
19558 @item ^-gnaty^/STYLE_CHECKS=^@var{n}
19559 @cindex @option{^-gnaty^/STYLE_CHECKS=^} (@command{gnatstub})
19560 (@var{n} is a non-negative integer from 1 to 9). Set the indentation level in
19561 the generated body sample to @var{n}.
19562 The default indentation is 3.
19564 @item ^-gnatyo^/ORDERED_SUBPROGRAMS^
19565 @cindex @option{^-gnatyo^/ORDERED_SUBPROGRAMS^} (@command{gnatstub})
19566 Order local bodies alphabetically. (By default local bodies are ordered
19567 in the same way as the corresponding local specs in the argument spec file.)
19569 @item ^-i^/INDENTATION=^@var{n}
19570 @cindex @option{^-i^/INDENTATION^} (@command{gnatstub})
19571 Same as @option{^-gnaty^/STYLE_CHECKS=^@var{n}}
19573 @item ^-k^/TREE_FILE=SAVE^
19574 @cindex @option{^-k^/TREE_FILE=SAVE^} (@command{gnatstub})
19575 Do not remove the tree file (i.e., the snapshot of the compiler internal
19576 structures used by @command{gnatstub}) after creating the body stub.
19578 @item ^-l^/LINE_LENGTH=^@var{n}
19579 @cindex @option{^-l^/LINE_LENGTH^} (@command{gnatstub})
19580 Same as @option{^-gnatyM^/MAX_LINE_LENGTH=^@var{n}}
19582 @item ^--no-exception^/NO_EXCEPTION^
19583 @cindex @option{^--no-exception^/NO_EXCEPTION^} (@command{gnatstub})
19584 Avoid raising PROGRAM_ERROR in the generated bodies of program unit stubs.
19585 This is not always possible for function stubs.
19587 @item ^--no-local-header^/NO_LOCAL_HEADER^
19588 @cindex @option{^--no-local-header^/NO_LOCAL_HEADER^} (@command{gnatstub})
19589 Do not place local comment header with unit name before body stub for a
19592 @item ^-o ^/BODY=^@var{body-name}
19593 @cindex @option{^-o^/BODY^} (@command{gnatstub})
19594 Body file name. This should be set if the argument file name does not
19596 the GNAT file naming
19597 conventions. If this switch is omitted the default name for the body will be
19599 from the argument file name according to the GNAT file naming conventions.
19601 @item ^-W^/RESULT_ENCODING=^@var{e}
19602 @cindex @option{^-W^/RESULT_ENCODING=^} (@command{gnatstub})
19603 Specify the wide character encoding method for the output body file.
19604 @var{e} is one of the following:
19612 Upper half encoding
19614 @item ^s^SHIFT_JIS^
19624 Brackets encoding (default value)
19628 @cindex @option{^-q^/QUIET^} (@command{gnatstub})
19629 Quiet mode: do not generate a confirmation when a body is
19630 successfully created, and do not generate a message when a body is not
19634 @item ^-r^/TREE_FILE=REUSE^
19635 @cindex @option{^-r^/TREE_FILE=REUSE^} (@command{gnatstub})
19636 Reuse the tree file (if it exists) instead of creating it. Instead of
19637 creating the tree file for the library unit declaration, @command{gnatstub}
19638 tries to find it in the current directory and use it for creating
19639 a body. If the tree file is not found, no body is created. This option
19640 also implies @option{^-k^/SAVE^}, whether or not
19641 the latter is set explicitly.
19643 @item ^-t^/TREE_FILE=OVERWRITE^
19644 @cindex @option{^-t^/TREE_FILE=OVERWRITE^} (@command{gnatstub})
19645 Overwrite the existing tree file. If the current directory already
19646 contains the file which, according to the GNAT file naming rules should
19647 be considered as a tree file for the argument source file,
19649 will refuse to create the tree file needed to create a sample body
19650 unless this option is set.
19652 @item ^-v^/VERBOSE^
19653 @cindex @option{^-v^/VERBOSE^} (@command{gnatstub})
19654 Verbose mode: generate version information.
19659 @ifclear FSFEDITION
19660 @c *********************************
19661 @node Creating Unit Tests with gnattest
19662 @chapter Creating Unit Tests with @command{gnattest}
19666 @command{gnattest} is an ASIS-based utility that creates unit-test skeletons
19667 as well as a test driver infrastructure (harness). @command{gnattest} creates
19668 a skeleton for each visible subprogram in the packages under consideration when
19669 they do not exist already.
19671 In order to process source files from a project, @command{gnattest} has to
19672 semantically analyze the sources. Therefore, test skeletons can only be
19673 generated for legal Ada units. If a unit is dependent on other units,
19674 those units should be among the source files of the project or of other projects
19675 imported by this one.
19677 Generated skeletons and harnesses are based on the AUnit testing framework.
19678 AUnit is an Ada adaptation of the xxxUnit testing frameworks, similar to JUnit
19679 for Java or CppUnit for C++. While it is advised that gnattest users read
19680 the AUnit manual, deep knowledge of AUnit is not necessary for using gnattest.
19681 For correct operation of @command{gnattest}, AUnit should be installed and
19682 aunit.gpr must be on the project path. This happens automatically when Aunit
19683 is installed at its default location.
19685 * Running gnattest::
19686 * Switches for gnattest::
19687 * Project Attributes for gnattest::
19689 * Setting Up and Tearing Down the Testing Environment::
19690 * Regenerating Tests::
19691 * Default Test Behavior::
19692 * Testing Primitive Operations of Tagged Types::
19693 * Testing Inheritance::
19694 * Tagged Types Substitutability Testing::
19695 * Testing with Contracts::
19696 * Additional Tests::
19698 * Support for other platforms/run-times::
19700 * Current Limitations::
19703 @node Running gnattest
19704 @section Running @command{gnattest}
19707 @command{gnattest} has a command-line interface of the form
19710 @c $ gnattest @var{-Pprojname} @ovar{switches} @ovar{filename} @ovar{directory}
19711 @c Expanding @ovar macro inline (explanation in macro def comments)
19712 $ gnattest @var{-Pprojname} @r{[}@var{--harness-dir=dirname}@r{]} @r{[}@var{switches}@r{]} @r{[}@var{filename}@r{]} @r{[}-cargs @var{gcc_switches}@r{]}
19720 specifies the project defining the location of source files. When no
19721 file names are provided on the command line, all sources in the project
19722 are used as input. This switch is required.
19725 is the name of the source file containing the library unit package declaration
19726 for which a test package will be created. The file name may be given with a
19729 @item @samp{@var{gcc_switches}}
19730 is a list of switches for
19731 @command{gcc}. These switches will be passed on to all compiler invocations
19732 made by @command{gnattest} to generate a set of ASIS trees. Here you can provide
19733 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
19734 use the @option{-gnatec} switch to set the configuration file,
19735 use the @option{-gnat05} switch if sources should be compiled in
19736 Ada 2005 mode, etc.
19739 is an optional sequence of switches as described in the next section.
19743 @command{gnattest} results can be found in two different places.
19746 @item automatic harness:
19747 the harness code, which is located by default in "gnattest/harness" directory
19748 that is created in the object directory of corresponding project file. All of
19749 this code is generated completely automatically and can be destroyed and
19750 regenerated at will. It is not recommended to modify this code manually, since
19751 it could easily be overridden by mistake. The entry point in the harness code is
19752 the project file named @command{test_driver.gpr}. Tests can be compiled and run
19753 using a command such as:
19756 gnatmake -P<harness-dir>/test_driver
19760 Note that you might need to specify the necessary values of scenario variables
19761 when you are not using the AUnit defaults.
19763 @item actual unit test skeletons:
19764 a test skeleton for each visible subprogram is created in a separate file, if it
19765 doesn't exist already. By default, those separate test files are located in a
19766 "gnattest/tests" directory that is created in the object directory of
19767 corresponding project file. For example, if a source file my_unit.ads in
19768 directory src contains a visible subprogram Proc, then the corresponding unit
19769 test will be found in file src/tests/my_unit-test_data-tests-proc_<code>.adb.
19770 <code> is a signature encoding used to differentiate test names in case of
19773 Note that if the project already has both my_unit.ads and my_unit-test_data.ads,
19774 this will cause a name conflict with the generated test package.
19777 @node Switches for gnattest
19778 @section Switches for @command{gnattest}
19783 @item --harness-only
19784 @cindex @option{--harness-only} (@command{gnattest})
19785 When this option is given, @command{gnattest} creates a harness for all
19786 sources, treating them as test packages.
19788 @item --additional-tests=@var{projname}
19789 @cindex @option{--additional-tests} (@command{gnattest})
19790 Sources described in @var{projname} are considered potential additional
19791 manual tests to be added to the test suite.
19794 @cindex @option{-r} (@command{gnattest})
19795 Recursively consider all sources from all projects.
19797 @item -X@var{name=value}
19798 @cindex @option{-X} (@command{gnattest})
19799 Indicate that external variable @var{name} has the value @var{value}.
19802 @cindex @option{-q} (@command{gnattest})
19803 Suppresses noncritical output messages.
19806 @cindex @option{-v} (@command{gnattest})
19807 Verbose mode: generates version information.
19809 @item --validate-type-extensions
19810 @cindex @option{--validate-type-extensions} (@command{gnattest})
19811 Enables substitution check: run all tests from all parents in order
19812 to check substitutability.
19814 @item --skeleton-default=@var{val}
19815 @cindex @option{--skeleton-default} (@command{gnattest})
19816 Specifies the default behavior of generated skeletons. @var{val} can be either
19817 "fail" or "pass", "fail" being the default.
19819 @item --passed-tests=@var{val}
19820 @cindex @option{--skeleton-default} (@command{gnattest})
19821 Specifies whether or not passed tests should be shown. @var{val} can be either
19822 "show" or "hide", "show" being the default.
19825 @item --tests-root=@var{dirname}
19826 @cindex @option{--tests-root} (@command{gnattest})
19827 The directory hierarchy of tested sources is recreated in the @var{dirname}
19828 directory, and test packages are placed in corresponding directories.
19829 If the @var{dirname} is a relative path, it is considered relative to the object
19830 directory of the project file. When all sources from all projects are taken
19831 recursively from all projects, directory hierarchies of tested sources are
19832 recreated for each project in their object directories and test packages are
19833 placed accordingly.
19835 @item --subdir=@var{dirname}
19836 @cindex @option{--subdir} (@command{gnattest})
19837 Test packages are placed in subdirectories.
19839 @item --tests-dir=@var{dirname}
19840 @cindex @option{--tests-dir} (@command{gnattest})
19841 All test packages are placed in the @var{dirname} directory.
19842 If the @var{dirname} is a relative path, it is considered relative to the object
19843 directory of the project file. When all sources from all projects are taken
19844 recursively from all projects, @var{dirname} directories are created for each
19845 project in their object directories and test packages are placed accordingly.
19847 @item --harness-dir=@var{dirname}
19848 @cindex @option{--harness-dir} (@command{gnattest})
19849 specifies the directory that will hold the harness packages and project file
19850 for the test driver. If the @var{dirname} is a relative path, it is considered
19851 relative to the object directory of the project file.
19854 @cindex @option{--separates} (@command{gnattest})
19855 Bodies of all test routines are generated as separates. Note that this mode is
19856 kept for compatibility reasons only and it is not advised to use it due to
19857 possible problems with hash in names of test skeletons when using an
19858 inconsistent casing. Separate test skeletons can be incorporated to monolith
19859 test package with improved hash being used by using @option{--transition}
19864 @cindex @option{--transition} (@command{gnattest})
19865 This allows transition from separate test routines to monolith test packages.
19866 All matching test routines are overwritten with contents of corresponding
19867 separates. Note that if separate test routines had any manually added with
19868 clauses they will be moved to the test package body as is and have to be moved
19873 @option{--tests_root}, @option{--subdir} and @option{--tests-dir} switches are
19874 mutually exclusive.
19876 @node Project Attributes for gnattest
19877 @section Project Attributes for @command{gnattest}
19881 Most of the command-line options can also be passed to the tool by adding
19882 special attributes to the project file. Those attributes should be put in
19883 package gnattest. Here is the list of attributes:
19888 is used to select the same output mode as with the --tests-root option.
19889 This attribute cannot be used together with Subdir or Tests_Dir.
19892 is used to select the same output mode as with the --subdir option.
19893 This attribute cannot be used together with Tests_Root or Tests_Dir.
19896 is used to select the same output mode as with the --tests-dir option.
19897 This attribute cannot be used together with Subdir or Tests_Root.
19900 is used to specify the directory in which to place harness packages and project
19901 file for the test driver, otherwise specified by --harness-dir.
19903 @item Additional_Tests
19904 is used to specify the project file, otherwise given by
19905 --additional-tests switch.
19907 @item Skeletons_Default
19908 is used to specify the default behaviour of test skeletons, otherwise
19909 specified by --skeleton-default option. The value of this attribute
19910 should be either "pass" or "fail".
19914 Each of those attributes can be overridden from the command line if needed.
19915 Other @command{gnattest} switches can also be passed via the project
19916 file as an attribute list called GNATtest_Switches.
19918 @node Simple Example
19919 @section Simple Example
19923 Let's take a very simple example using the first @command{gnattest} example
19927 <install_prefix>/share/examples/gnattest/simple
19930 This project contains a simple package containing one subprogram. By running gnattest:
19933 $ gnattest --harness-dir=driver -Psimple.gpr
19936 a test driver is created in directory "driver". It can be compiled and run:
19940 $ gnatmake -Ptest_driver
19944 One failed test with diagnosis "test not implemented" is reported.
19945 Since no special output option was specified, the test package Simple.Tests
19949 <install_prefix>/share/examples/gnattest/simple/obj/gnattest/tests
19952 For each package containing visible subprograms, a child test package is
19953 generated. It contains one test routine per tested subprogram. Each
19954 declaration of a test subprogram has a comment specifying which tested
19955 subprogram it corresponds to. Bodies of test routines are placed in test package
19956 bodies and are surrounded by special comment sections. Those comment sections
19957 should not be removed or modified in order for gnattest to be able to regenerate
19958 test packages and keep already written tests in place.
19959 The test routine Test_Inc_5eaee3 located at simple-test_data-tests.adb contains
19960 a single statement: a call to procedure Assert. It has two arguments:
19961 the Boolean expression we want to check and the diagnosis message to display if
19962 the condition is false.
19964 That is where actual testing code should be written after a proper setup.
19965 An actual check can be performed by replacing the Assert call with:
19967 @smallexample @c ada
19968 Assert (Inc (1) = 2, "wrong incrementation");
19971 After recompiling and running the test driver, one successfully passed test
19974 @node Setting Up and Tearing Down the Testing Environment
19975 @section Setting Up and Tearing Down the Testing Environment
19979 Besides test routines themselves, each test package has a parent package
19980 Test_Data that has two procedures: Set_Up and Tear_Down. This package is never
19981 overwritten by the tool. Set_Up is called before each test routine of the
19982 package and Tear_Down is called after each test routine. Those two procedures
19983 can be used to perform necessary initialization and finalization,
19984 memory allocation, etc. Test type declared in Test_Data package is parent type
19985 for the test type of test package and can have user-defined components whose
19986 values can be set by Set_Up routine and used in test routines afterwards.
19988 @node Regenerating Tests
19989 @section Regenerating Tests
19993 Bodies of test routines and test_data packages are never overridden after they
19994 have been created once. As long as the name of the subprogram, full expanded Ada
19995 names, and the order of its parameters is the same, and comment sections are
19996 intact the old test routine will fit in its place and no test skeleton will be
19997 generated for the subprogram.
19999 This can be demonstrated with the previous example. By uncommenting declaration
20000 and body of function Dec in simple.ads and simple.adb, running
20001 @command{gnattest} on the project, and then running the test driver:
20004 gnattest --harness-dir=driver -Psimple.gpr
20006 gnatmake -Ptest_driver
20010 the old test is not replaced with a stub, nor is it lost, but a new test
20011 skeleton is created for function Dec.
20013 The only way of regenerating tests skeletons is to remove the previously created
20014 tests together with corresponding comment sections.
20016 @node Default Test Behavior
20017 @section Default Test Behavior
20021 The generated test driver can treat unimplemented tests in two ways:
20022 either count them all as failed (this is useful to see which tests are still
20023 left to implement) or as passed (to sort out unimplemented ones from those
20026 The test driver accepts a switch to specify this behavior:
20027 --skeleton-default=val, where val is either "pass" or "fail" (exactly as for
20028 @command{gnattest}).
20030 The default behavior of the test driver is set with the same switch
20031 as passed to gnattest when generating the test driver.
20033 Passing it to the driver generated on the first example:
20036 test_runner --skeleton-default=pass
20039 makes both tests pass, even the unimplemented one.
20041 @node Testing Primitive Operations of Tagged Types
20042 @section Testing Primitive Operations of Tagged Types
20046 Creation of test skeletons for primitive operations of tagged types entails
20047 a number of features. Test routines for all primitives of a given tagged type
20048 are placed in a separate child package named according to the tagged type. For
20049 example, if you have tagged type T in package P, all tests for primitives
20050 of T will be in P.T_Test_Data.T_Tests.
20052 Consider running gnattest on the second example (note: actual tests for this
20053 example already exist, so there's no need to worry if the tool reports that
20054 no new stubs were generated):
20057 cd <install_prefix>/share/examples/gnattest/tagged_rec
20058 gnattest --harness-dir=driver -Ptagged_rec.gpr
20061 Taking a closer look at the test type declared in the test package
20062 Speed1.Controller_Test_Data is necessary. It is declared in:
20065 <install_prefix>/share/examples/gnattest/tagged_rec/obj/gnattest/tests
20068 Test types are direct or indirect descendants of
20069 AUnit.Test_Fixtures.Test_Fixture type. In the case of nonprimitive tested
20070 subprograms, the user doesn't need to be concerned with them. However,
20071 when generating test packages for primitive operations, there are some things
20072 the user needs to know.
20074 Type Test_Controller has components that allow assignment of various
20075 derivations of type Controller. And if you look at the specification of
20076 package Speed2.Auto_Controller, you will see that Test_Auto_Controller
20077 actually derives from Test_Controller rather than AUnit type Test_Fixture.
20078 Thus, test types mirror the hierarchy of tested types.
20080 The Set_Up procedure of Test_Data package corresponding to a test package
20081 of primitive operations of type T assigns to Fixture a reference to an
20082 object of that exact type T. Notice, however, that if the tagged type has
20083 discriminants, the Set_Up only has a commented template for setting
20084 up the fixture, since filling the discriminant with actual value is up
20087 The knowledge of the structure of test types allows additional testing
20088 without additional effort. Those possibilities are described below.
20090 @node Testing Inheritance
20091 @section Testing Inheritance
20095 Since the test type hierarchy mimics the hierarchy of tested types, the
20096 inheritance of tests takes place. An example of such inheritance can be
20097 seen by running the test driver generated for the second example. As previously
20098 mentioned, actual tests are already written for this example.
20102 gnatmake -Ptest_driver
20106 There are 6 passed tests while there are only 5 testable subprograms. The test
20107 routine for function Speed has been inherited and run against objects of the
20110 @node Tagged Types Substitutability Testing
20111 @section Tagged Types Substitutability Testing
20115 Tagged Types Substitutability Testing is a way of verifying the global type
20116 consistency by testing. Global type consistency is a principle stating that if
20117 S is a subtype of T (in Ada, S is a derived type of tagged type T),
20118 then objects of type T may be replaced with objects of type S (that is,
20119 objects of type S may be substituted for objects of type T), without
20120 altering any of the desirable properties of the program. When the properties
20121 of the program are expressed in the form of subprogram preconditions and
20122 postconditions (let's call them pre and post), the principle is formulated as
20123 relations between the pre and post of primitive operations and the pre and post
20124 of their derived operations. The pre of a derived operation should not be
20125 stronger than the original pre, and the post of the derived operation should
20126 not be weaker than the original post. Those relations ensure that verifying if
20127 a dispatching call is safe can be done just by using the pre and post of the
20130 Verifying global type consistency by testing consists of running all the unit
20131 tests associated with the primitives of a given tagged type with objects of its
20134 In the example used in the previous section, there was clearly a violation of
20135 type consistency. The overriding primitive Adjust_Speed in package Speed2
20136 removes the functionality of the overridden primitive and thus doesn't respect
20137 the consistency principle.
20138 Gnattest has a special option to run overridden parent tests against objects
20139 of the type which have overriding primitives:
20142 gnattest --harness-dir=driver --validate-type-extensions -Ptagged_rec.gpr
20144 gnatmake -Ptest_driver
20148 While all the tests pass by themselves, the parent test for Adjust_Speed fails
20149 against objects of the derived type.
20151 Non-overridden tests are already inherited for derived test types, so the
20152 --validate-type-extensions enables the application of overriden tests to objects
20155 @node Testing with Contracts
20156 @section Testing with Contracts
20160 @command{gnattest} supports pragmas Precondition, Postcondition, and Test_Case,
20161 as well as corresponding aspects.
20162 Test routines are generated, one per each Test_Case associated with a tested
20163 subprogram. Those test routines have special wrappers for tested functions
20164 that have composition of pre- and postcondition of the subprogram with
20165 "requires" and "ensures" of the Test_Case (depending on the mode, pre and post
20166 either count for Nominal mode or do not count for Robustness mode).
20168 The third example demonstrates how this works:
20171 cd <install_prefix>/share/examples/gnattest/contracts
20172 gnattest --harness-dir=driver -Pcontracts.gpr
20175 Putting actual checks within the range of the contract does not cause any
20176 error reports. For example, for the test routine which corresponds to
20179 @smallexample @c ada
20180 Assert (Sqrt (9.0) = 3.0, "wrong sqrt");
20183 and for the test routine corresponding to test case 2:
20185 @smallexample @c ada
20186 Assert (Sqrt (-5.0) = -1.0, "wrong error indication");
20193 gnatmake -Ptest_driver
20197 However, by changing 9.0 to 25.0 and 3.0 to 5.0, for example, you can get
20198 a precondition violation for test case one. Also, by using any otherwise
20199 correct but positive pair of numbers in the second test routine, you can also
20200 get a precondition violation. Postconditions are checked and reported
20203 @node Additional Tests
20204 @section Additional Tests
20207 @command{gnattest} can add user-written tests to the main suite of the test
20208 driver. @command{gnattest} traverses the given packages and searches for test
20209 routines. All procedures with a single in out parameter of a type which is
20210 derived from AUnit.Test_Fixtures.Test_Fixture and that are declared in package
20211 specifications are added to the suites and are then executed by the test driver.
20212 (Set_Up and Tear_Down are filtered out.)
20214 An example illustrates two ways of creating test harnesses for user-written
20215 tests. Directory additional_tests contains an AUnit-based test driver written
20219 <install_prefix>/share/examples/gnattest/additional_tests/
20222 To create a test driver for already-written tests, use the --harness-only
20226 gnattest -Padditional/harness/harness.gpr --harness-dir=harness_only \
20228 gnatmake -Pharness_only/test_driver.gpr
20229 harness_only/test_runner
20232 Additional tests can also be executed together with generated tests:
20235 gnattest -Psimple.gpr --additional-tests=additional/harness/harness.gpr \
20236 --harness-dir=mixing
20237 gnatmake -Pmixing/test_driver.gpr
20242 @node Support for other platforms/run-times
20243 @section Support for other platforms/run-times
20246 @command{gnattest} can be used to generate the test harness for platforms
20247 and run-time libraries others than the default native target with the
20248 default full run-time. For example, when using a limited run-time library
20249 such as Zero FootPrint (ZFP), a simplified harness is generated.
20251 Two variables are used to tell the underlying AUnit framework how to generate
20252 the test harness: @code{PLATFORM}, which identifies the target, and
20253 @code{RUNTIME}, used to determine the run-time library for which the harness
20254 is generated. Corresponding prefix should also be used when calling
20255 @command{gnattest} for non-native targets. For example, the following options
20256 are used to generate the AUnit test harness for a PowerPC ELF target using
20257 the ZFP run-time library:
20260 powerpc-elf-gnattest -Psimple.gpr -XPLATFORM=powerpc-elf -XRUNTIME=zfp
20264 @node Current Limitations
20265 @section Current Limitations
20269 The tool currently does not support following features:
20272 @item generic tests for generic packages and package instantiations
20273 @item tests for protected subprograms and entries
20279 @c *********************************
20280 @node Performing Dimensionality Analysis in GNAT
20281 @chapter Performing Dimensionality Analysis in GNAT
20282 @cindex Dimensionality analysis
20285 The GNAT compiler now supports dimensionality checking. The user can
20286 specify physical units for objects, and the compiler will verify that uses
20287 of these objects are compatible with their dimensions, in a fashion that is
20288 familiar to engineering practice. The dimensions of algebraic expressions
20289 (including powers with static exponents) are computed from their constituents.
20291 This feature depends on Ada 2012 aspect specifications, and is available from
20292 version 7.0.1 of GNAT onwards.
20293 The GNAT-specific aspect @code{Dimension_System}
20294 @cindex @code{Dimension_System} aspect
20295 allows you to define a system of units; the aspect @code{Dimension}
20296 @cindex @code{Dimension} aspect
20297 then allows the user to declare dimensioned quantities within a given system.
20298 (These aspects are described in the @i{Implementation Defined Aspects}
20299 chapter of the @i{GNAT Reference Manual}).
20301 The major advantage of this model is that it does not require the declaration of
20302 multiple operators for all possible combinations of types: it is only necessary
20303 to use the proper subtypes in object declarations.
20305 The simplest way to impose dimensionality checking on a computation is to make
20306 use of the package @code{System.Dim.Mks},
20307 @cindex @code{System.Dim.Mks} package (GNAT library)
20308 which is part of the GNAT library. This
20309 package defines a floating-point type @code{MKS_Type},
20310 @cindex @code{MKS_Type} type
20311 for which a sequence of
20312 dimension names are specified, together with their conventional abbreviations.
20313 The following should be read together with the full specification of the
20314 package, in file @file{s-dimmks.ads}.
20315 @cindex @file{s-dimmks.ads} file
20317 @smallexample @c ada
20319 type Mks_Type is new Long_Long_Float
20321 Dimension_System => (
20322 (Unit_Name => Meter, Unit_Symbol => 'm', Dim_Symbol => 'L'),
20323 (Unit_Name => Kilogram, Unit_Symbol => "kg", Dim_Symbol => 'M'),
20324 (Unit_Name => Second, Unit_Symbol => 's', Dim_Symbol => 'T'),
20325 (Unit_Name => Ampere, Unit_Symbol => 'A', Dim_Symbol => 'I'),
20326 (Unit_Name => Kelvin, Unit_Symbol => 'K', Dim_Symbol => "Theta"),
20327 (Unit_Name => Mole, Unit_Symbol => "mol", Dim_Symbol => 'N'),
20328 (Unit_Name => Candela, Unit_Symbol => "cd", Dim_Symbol => 'J'));
20333 The package then defines a series of subtypes that correspond to these
20334 conventional units. For example:
20336 @smallexample @c ada
20338 subtype Length is Mks_Type
20340 Dimension => (Symbol => 'm', Meter => 1, others => 0);
20345 and similarly for @code{Mass}, @code{Time}, @code{Electric_Current},
20346 @code{Thermodynamic_Temperature}, @code{Amount_Of_Substance}, and
20347 @code{Luminous_Intensity} (the standard set of units of the SI system).
20349 The package also defines conventional names for values of each unit, for
20352 @smallexample @c ada
20354 m : constant Length := 1.0;
20355 kg : constant Mass := 1.0;
20356 s : constant Time := 1.0;
20357 A : constant Electric_Current := 1.0;
20362 as well as useful multiples of these units:
20364 @smallexample @c ada
20366 cm : constant Length := 1.0E-02;
20367 g : constant Mass := 1.0E-03;
20368 min : constant Time := 60.0;
20369 day : constant Time := 60.0 * 24.0 * min;
20375 Using this package, you can then define a derived unit by
20376 providing the aspect that
20377 specifies its dimensions within the MKS system, as well as the string to
20378 be used for output of a value of that unit:
20380 @smallexample @c ada
20382 subtype Acceleration is Mks_Type
20383 with Dimension => ("m/sec^^^2",
20391 Here is a complete example of use:
20393 @smallexample @c ada
20395 with System.Dim.MKS; use System.Dim.Mks;
20396 with System.Dim.Mks_IO; use System.Dim.Mks_IO;
20397 with Text_IO; use Text_IO;
20398 procedure Free_Fall is
20399 subtype Acceleration is Mks_Type
20400 with Dimension => ("m/sec^^^2", 1, 0, -2, others => 0);
20401 G : constant acceleration := 9.81 * m / (s ** 2);
20402 T : Time := 10.0*s;
20407 Put ("Gravitational constant: ");
20408 Put (G, Aft => 2, Exp => 0); Put_Line ("");
20409 Distance := 0.5 * G * T ** 2;
20410 Put ("distance travelled in 10 seconds of free fall ");
20411 Put (Distance, Aft => 2, Exp => 0);
20418 Execution of this program yields:
20421 Gravitational constant: 9.81 m/sec^^^2
20422 distance travelled in 10 seconds of free fall 490.50 m
20427 However, incorrect assignments such as:
20429 @smallexample @c ada
20432 Distance := 5.0 * kg:
20437 are rejected with the following diagnoses:
20442 >>> dimensions mismatch in assignment
20443 >>> left-hand side has dimension [L]
20444 >>> right-hand side is dimensionless
20448 Distance := 5.0 * kg:
20449 >>> dimensions mismatch in assignment
20450 >>> left-hand side has dimension [L]
20451 >>> right-hand side has dimension [M]
20456 The dimensions of an expression are properly displayed, even if there is
20457 no explicit subtype for it. If we add to the program:
20459 @smallexample @c ada
20461 Put ("Final velocity: ");
20462 Put (G * T, Aft =>2, Exp =>0);
20468 then the output includes:
20470 Final velocity: 98.10 m.s**(-1)
20474 @c *********************************
20475 @node Generating Ada Bindings for C and C++ headers
20476 @chapter Generating Ada Bindings for C and C++ headers
20480 GNAT now comes with a binding generator for C and C++ headers which is
20481 intended to do 95% of the tedious work of generating Ada specs from C
20482 or C++ header files.
20484 Note that this capability is not intended to generate 100% correct Ada specs,
20485 and will is some cases require manual adjustments, although it can often
20486 be used out of the box in practice.
20488 Some of the known limitations include:
20491 @item only very simple character constant macros are translated into Ada
20492 constants. Function macros (macros with arguments) are partially translated
20493 as comments, to be completed manually if needed.
20494 @item some extensions (e.g. vector types) are not supported
20495 @item pointers to pointers or complex structures are mapped to System.Address
20496 @item identifiers with identical name (except casing) will generate compilation
20497 errors (e.g. @code{shm_get} vs @code{SHM_GET}).
20500 The code generated is using the Ada 2005 syntax, which makes it
20501 easier to interface with other languages than previous versions of Ada.
20504 * Running the binding generator::
20505 * Generating bindings for C++ headers::
20509 @node Running the binding generator
20510 @section Running the binding generator
20513 The binding generator is part of the @command{gcc} compiler and can be
20514 invoked via the @option{-fdump-ada-spec} switch, which will generate Ada
20515 spec files for the header files specified on the command line, and all
20516 header files needed by these files transitively. For example:
20519 $ g++ -c -fdump-ada-spec -C /usr/include/time.h
20520 $ gcc -c -gnat05 *.ads
20523 will generate, under GNU/Linux, the following files: @file{time_h.ads},
20524 @file{bits_time_h.ads}, @file{stddef_h.ads}, @file{bits_types_h.ads} which
20525 correspond to the files @file{/usr/include/time.h},
20526 @file{/usr/include/bits/time.h}, etc@dots{}, and will then compile in Ada 2005
20527 mode these Ada specs.
20529 The @code{-C} switch tells @command{gcc} to extract comments from headers,
20530 and will attempt to generate corresponding Ada comments.
20532 If you want to generate a single Ada file and not the transitive closure, you
20533 can use instead the @option{-fdump-ada-spec-slim} switch.
20535 You can optionally specify a parent unit, of which all generated units will
20536 be children, using @code{-fada-spec-parent=}@var{unit}.
20538 Note that we recommend when possible to use the @command{g++} driver to
20539 generate bindings, even for most C headers, since this will in general
20540 generate better Ada specs. For generating bindings for C++ headers, it is
20541 mandatory to use the @command{g++} command, or @command{gcc -x c++} which
20542 is equivalent in this case. If @command{g++} cannot work on your C headers
20543 because of incompatibilities between C and C++, then you can fallback to
20544 @command{gcc} instead.
20546 For an example of better bindings generated from the C++ front-end,
20547 the name of the parameters (when available) are actually ignored by the C
20548 front-end. Consider the following C header:
20551 extern void foo (int variable);
20554 with the C front-end, @code{variable} is ignored, and the above is handled as:
20557 extern void foo (int);
20560 generating a generic:
20563 procedure foo (param1 : int);
20566 with the C++ front-end, the name is available, and we generate:
20569 procedure foo (variable : int);
20572 In some cases, the generated bindings will be more complete or more meaningful
20573 when defining some macros, which you can do via the @option{-D} switch. This
20574 is for example the case with @file{Xlib.h} under GNU/Linux:
20577 g++ -c -fdump-ada-spec -DXLIB_ILLEGAL_ACCESS -C /usr/include/X11/Xlib.h
20580 The above will generate more complete bindings than a straight call without
20581 the @option{-DXLIB_ILLEGAL_ACCESS} switch.
20583 In other cases, it is not possible to parse a header file in a stand-alone
20584 manner, because other include files need to be included first. In this
20585 case, the solution is to create a small header file including the needed
20586 @code{#include} and possible @code{#define} directives. For example, to
20587 generate Ada bindings for @file{readline/readline.h}, you need to first
20588 include @file{stdio.h}, so you can create a file with the following two
20589 lines in e.g. @file{readline1.h}:
20593 #include <readline/readline.h>
20596 and then generate Ada bindings from this file:
20599 $ g++ -c -fdump-ada-spec readline1.h
20602 @node Generating bindings for C++ headers
20603 @section Generating bindings for C++ headers
20606 Generating bindings for C++ headers is done using the same options, always
20607 with the @command{g++} compiler.
20609 In this mode, C++ classes will be mapped to Ada tagged types, constructors
20610 will be mapped using the @code{CPP_Constructor} pragma, and when possible,
20611 multiple inheritance of abstract classes will be mapped to Ada interfaces
20612 (@xref{Interfacing to C++,,,gnat_rm, GNAT Reference Manual}, for additional
20613 information on interfacing to C++).
20615 For example, given the following C++ header file:
20622 virtual int Number_Of_Teeth () = 0;
20627 virtual void Set_Owner (char* Name) = 0;
20633 virtual void Set_Age (int New_Age);
20636 class Dog : Animal, Carnivore, Domestic @{
20641 virtual int Number_Of_Teeth ();
20642 virtual void Set_Owner (char* Name);
20650 The corresponding Ada code is generated:
20652 @smallexample @c ada
20655 package Class_Carnivore is
20656 type Carnivore is limited interface;
20657 pragma Import (CPP, Carnivore);
20659 function Number_Of_Teeth (this : access Carnivore) return int is abstract;
20661 use Class_Carnivore;
20663 package Class_Domestic is
20664 type Domestic is limited interface;
20665 pragma Import (CPP, Domestic);
20667 procedure Set_Owner
20668 (this : access Domestic;
20669 Name : Interfaces.C.Strings.chars_ptr) is abstract;
20671 use Class_Domestic;
20673 package Class_Animal is
20674 type Animal is tagged limited record
20675 Age_Count : aliased int;
20677 pragma Import (CPP, Animal);
20679 procedure Set_Age (this : access Animal; New_Age : int);
20680 pragma Import (CPP, Set_Age, "_ZN6Animal7Set_AgeEi");
20684 package Class_Dog is
20685 type Dog is new Animal and Carnivore and Domestic with record
20686 Tooth_Count : aliased int;
20687 Owner : Interfaces.C.Strings.chars_ptr;
20689 pragma Import (CPP, Dog);
20691 function Number_Of_Teeth (this : access Dog) return int;
20692 pragma Import (CPP, Number_Of_Teeth, "_ZN3Dog15Number_Of_TeethEv");
20694 procedure Set_Owner
20695 (this : access Dog; Name : Interfaces.C.Strings.chars_ptr);
20696 pragma Import (CPP, Set_Owner, "_ZN3Dog9Set_OwnerEPc");
20698 function New_Dog return Dog;
20699 pragma CPP_Constructor (New_Dog);
20700 pragma Import (CPP, New_Dog, "_ZN3DogC1Ev");
20711 @item -fdump-ada-spec
20712 @cindex @option{-fdump-ada-spec} (@command{gcc})
20713 Generate Ada spec files for the given header files transitively (including
20714 all header files that these headers depend upon).
20716 @item -fdump-ada-spec-slim
20717 @cindex @option{-fdump-ada-spec-slim} (@command{gcc})
20718 Generate Ada spec files for the header files specified on the command line
20721 @item -fada-spec-parent=@var{unit}
20722 @cindex -fada-spec-parent (@command{gcc})
20723 Specifies that all files generated by @option{-fdump-ada-spec*} are
20724 to be child units of the specified parent unit.
20727 @cindex @option{-C} (@command{gcc})
20728 Extract comments from headers and generate Ada comments in the Ada spec files.
20731 @node Other Utility Programs
20732 @chapter Other Utility Programs
20735 This chapter discusses some other utility programs available in the Ada
20739 * Using Other Utility Programs with GNAT::
20740 * The External Symbol Naming Scheme of GNAT::
20741 * Converting Ada Files to html with gnathtml::
20742 * Installing gnathtml::
20749 @node Using Other Utility Programs with GNAT
20750 @section Using Other Utility Programs with GNAT
20753 The object files generated by GNAT are in standard system format and in
20754 particular the debugging information uses this format. This means
20755 programs generated by GNAT can be used with existing utilities that
20756 depend on these formats.
20759 In general, any utility program that works with C will also often work with
20760 Ada programs generated by GNAT. This includes software utilities such as
20761 gprof (a profiling program), @code{gdb} (the FSF debugger), and utilities such
20765 @node The External Symbol Naming Scheme of GNAT
20766 @section The External Symbol Naming Scheme of GNAT
20769 In order to interpret the output from GNAT, when using tools that are
20770 originally intended for use with other languages, it is useful to
20771 understand the conventions used to generate link names from the Ada
20774 All link names are in all lowercase letters. With the exception of library
20775 procedure names, the mechanism used is simply to use the full expanded
20776 Ada name with dots replaced by double underscores. For example, suppose
20777 we have the following package spec:
20779 @smallexample @c ada
20790 The variable @code{MN} has a full expanded Ada name of @code{QRS.MN}, so
20791 the corresponding link name is @code{qrs__mn}.
20793 Of course if a @code{pragma Export} is used this may be overridden:
20795 @smallexample @c ada
20800 pragma Export (Var1, C, External_Name => "var1_name");
20802 pragma Export (Var2, C, Link_Name => "var2_link_name");
20809 In this case, the link name for @var{Var1} is whatever link name the
20810 C compiler would assign for the C function @var{var1_name}. This typically
20811 would be either @var{var1_name} or @var{_var1_name}, depending on operating
20812 system conventions, but other possibilities exist. The link name for
20813 @var{Var2} is @var{var2_link_name}, and this is not operating system
20817 One exception occurs for library level procedures. A potential ambiguity
20818 arises between the required name @code{_main} for the C main program,
20819 and the name we would otherwise assign to an Ada library level procedure
20820 called @code{Main} (which might well not be the main program).
20822 To avoid this ambiguity, we attach the prefix @code{_ada_} to such
20823 names. So if we have a library level procedure such as
20825 @smallexample @c ada
20828 procedure Hello (S : String);
20834 the external name of this procedure will be @var{_ada_hello}.
20837 @node Converting Ada Files to html with gnathtml
20838 @section Converting Ada Files to HTML with @code{gnathtml}
20841 This @code{Perl} script allows Ada source files to be browsed using
20842 standard Web browsers. For installation procedure, see the section
20843 @xref{Installing gnathtml}.
20845 Ada reserved keywords are highlighted in a bold font and Ada comments in
20846 a blue font. Unless your program was compiled with the gcc @option{-gnatx}
20847 switch to suppress the generation of cross-referencing information, user
20848 defined variables and types will appear in a different color; you will
20849 be able to click on any identifier and go to its declaration.
20851 The command line is as follow:
20853 @c $ perl gnathtml.pl @ovar{^switches^options^} @var{ada-files}
20854 @c Expanding @ovar macro inline (explanation in macro def comments)
20855 $ perl gnathtml.pl @r{[}@var{^switches^options^}@r{]} @var{ada-files}
20859 You can pass it as many Ada files as you want. @code{gnathtml} will generate
20860 an html file for every ada file, and a global file called @file{index.htm}.
20861 This file is an index of every identifier defined in the files.
20863 The available ^switches^options^ are the following ones:
20867 @cindex @option{-83} (@code{gnathtml})
20868 Only the Ada 83 subset of keywords will be highlighted.
20870 @item -cc @var{color}
20871 @cindex @option{-cc} (@code{gnathtml})
20872 This option allows you to change the color used for comments. The default
20873 value is green. The color argument can be any name accepted by html.
20876 @cindex @option{-d} (@code{gnathtml})
20877 If the Ada files depend on some other files (for instance through
20878 @code{with} clauses, the latter files will also be converted to html.
20879 Only the files in the user project will be converted to html, not the files
20880 in the run-time library itself.
20883 @cindex @option{-D} (@code{gnathtml})
20884 This command is the same as @option{-d} above, but @command{gnathtml} will
20885 also look for files in the run-time library, and generate html files for them.
20887 @item -ext @var{extension}
20888 @cindex @option{-ext} (@code{gnathtml})
20889 This option allows you to change the extension of the generated HTML files.
20890 If you do not specify an extension, it will default to @file{htm}.
20893 @cindex @option{-f} (@code{gnathtml})
20894 By default, gnathtml will generate html links only for global entities
20895 ('with'ed units, global variables and types,@dots{}). If you specify
20896 @option{-f} on the command line, then links will be generated for local
20899 @item -l @var{number}
20900 @cindex @option{-l} (@code{gnathtml})
20901 If this ^switch^option^ is provided and @var{number} is not 0, then
20902 @code{gnathtml} will number the html files every @var{number} line.
20905 @cindex @option{-I} (@code{gnathtml})
20906 Specify a directory to search for library files (@file{.ALI} files) and
20907 source files. You can provide several -I switches on the command line,
20908 and the directories will be parsed in the order of the command line.
20911 @cindex @option{-o} (@code{gnathtml})
20912 Specify the output directory for html files. By default, gnathtml will
20913 saved the generated html files in a subdirectory named @file{html/}.
20915 @item -p @var{file}
20916 @cindex @option{-p} (@code{gnathtml})
20917 If you are using Emacs and the most recent Emacs Ada mode, which provides
20918 a full Integrated Development Environment for compiling, checking,
20919 running and debugging applications, you may use @file{.gpr} files
20920 to give the directories where Emacs can find sources and object files.
20922 Using this ^switch^option^, you can tell gnathtml to use these files.
20923 This allows you to get an html version of your application, even if it
20924 is spread over multiple directories.
20926 @item -sc @var{color}
20927 @cindex @option{-sc} (@code{gnathtml})
20928 This ^switch^option^ allows you to change the color used for symbol
20930 The default value is red. The color argument can be any name accepted by html.
20932 @item -t @var{file}
20933 @cindex @option{-t} (@code{gnathtml})
20934 This ^switch^option^ provides the name of a file. This file contains a list of
20935 file names to be converted, and the effect is exactly as though they had
20936 appeared explicitly on the command line. This
20937 is the recommended way to work around the command line length limit on some
20942 @node Installing gnathtml
20943 @section Installing @code{gnathtml}
20946 @code{Perl} needs to be installed on your machine to run this script.
20947 @code{Perl} is freely available for almost every architecture and
20948 Operating System via the Internet.
20950 On Unix systems, you may want to modify the first line of the script
20951 @code{gnathtml}, to explicitly tell the Operating system where Perl
20952 is. The syntax of this line is:
20954 #!full_path_name_to_perl
20958 Alternatively, you may run the script using the following command line:
20961 @c $ perl gnathtml.pl @ovar{switches} @var{files}
20962 @c Expanding @ovar macro inline (explanation in macro def comments)
20963 $ perl gnathtml.pl @r{[}@var{switches}@r{]} @var{files}
20972 The GNAT distribution provides an Ada 95 template for the HP Language
20973 Sensitive Editor (LSE), a component of DECset. In order to
20974 access it, invoke LSE with the qualifier /ENVIRONMENT=GNU:[LIB]ADA95.ENV.
20981 GNAT supports The HP Performance Coverage Analyzer (PCA), a component
20982 of DECset. To use it proceed as outlined under ``HELP PCA'', except for running
20983 the collection phase with the /DEBUG qualifier.
20986 $ GNAT MAKE /DEBUG <PROGRAM_NAME>
20987 $ DEFINE LIB$DEBUG PCA$COLLECTOR
20988 $ RUN/DEBUG <PROGRAM_NAME>
20994 @c ******************************
20995 @node Code Coverage and Profiling
20996 @chapter Code Coverage and Profiling
20997 @cindex Code Coverage
21001 This chapter describes how to use @code{gcov} - coverage testing tool - and
21002 @code{gprof} - profiler tool - on your Ada programs.
21005 * Code Coverage of Ada Programs with gcov::
21006 * Profiling an Ada Program with gprof::
21009 @node Code Coverage of Ada Programs with gcov
21010 @section Code Coverage of Ada Programs with gcov
21012 @cindex -fprofile-arcs
21013 @cindex -ftest-coverage
21015 @cindex Code Coverage
21018 @code{gcov} is a test coverage program: it analyzes the execution of a given
21019 program on selected tests, to help you determine the portions of the program
21020 that are still untested.
21022 @code{gcov} is part of the GCC suite, and is described in detail in the GCC
21023 User's Guide. You can refer to this documentation for a more complete
21026 This chapter provides a quick startup guide, and
21027 details some Gnat-specific features.
21030 * Quick startup guide::
21034 @node Quick startup guide
21035 @subsection Quick startup guide
21037 In order to perform coverage analysis of a program using @code{gcov}, 3
21042 Code instrumentation during the compilation process
21044 Execution of the instrumented program
21046 Execution of the @code{gcov} tool to generate the result.
21049 The code instrumentation needed by gcov is created at the object level:
21050 The source code is not modified in any way, because the instrumentation code is
21051 inserted by gcc during the compilation process. To compile your code with code
21052 coverage activated, you need to recompile your whole project using the
21054 @code{-fprofile-arcs} and @code{-ftest-coverage}, and link it using
21055 @code{-fprofile-arcs}.
21058 $ gnatmake -P my_project.gpr -f -cargs -fprofile-arcs -ftest-coverage \
21059 -largs -fprofile-arcs
21062 This compilation process will create @file{.gcno} files together with
21063 the usual object files.
21065 Once the program is compiled with coverage instrumentation, you can
21066 run it as many times as needed - on portions of a test suite for
21067 example. The first execution will produce @file{.gcda} files at the
21068 same location as the @file{.gcno} files. The following executions
21069 will update those files, so that a cumulative result of the covered
21070 portions of the program is generated.
21072 Finally, you need to call the @code{gcov} tool. The different options of
21073 @code{gcov} are available in the GCC User's Guide, section 'Invoking gcov'.
21075 This will create annotated source files with a @file{.gcov} extension:
21076 @file{my_main.adb} file will be analysed in @file{my_main.adb.gcov}.
21078 @node Gnat specifics
21079 @subsection Gnat specifics
21081 Because Ada semantics, portions of the source code may be shared among
21082 several object files. This is the case for example when generics are
21083 involved, when inlining is active or when declarations generate initialisation
21084 calls. In order to take
21085 into account this shared code, you need to call @code{gcov} on all
21086 source files of the tested program at once.
21088 The list of source files might exceed the system's maximum command line
21089 length. In order to bypass this limitation, a new mechanism has been
21090 implemented in @code{gcov}: you can now list all your project's files into a
21091 text file, and provide this file to gcov as a parameter, preceded by a @@
21092 (e.g. @samp{gcov @@mysrclist.txt}).
21094 Note that on AIX compiling a static library with @code{-fprofile-arcs} is
21095 not supported as there can be unresolved symbols during the final link.
21097 @node Profiling an Ada Program with gprof
21098 @section Profiling an Ada Program with gprof
21104 This section is not meant to be an exhaustive documentation of @code{gprof}.
21105 Full documentation for it can be found in the GNU Profiler User's Guide
21106 documentation that is part of this GNAT distribution.
21108 Profiling a program helps determine the parts of a program that are executed
21109 most often, and are therefore the most time-consuming.
21111 @code{gprof} is the standard GNU profiling tool; it has been enhanced to
21112 better handle Ada programs and multitasking.
21113 It is currently supported on the following platforms
21118 solaris sparc/sparc64/x86
21124 In order to profile a program using @code{gprof}, 3 steps are needed:
21128 Code instrumentation, requiring a full recompilation of the project with the
21131 Execution of the program under the analysis conditions, i.e. with the desired
21134 Analysis of the results using the @code{gprof} tool.
21138 The following sections detail the different steps, and indicate how
21139 to interpret the results:
21141 * Compilation for profiling::
21142 * Program execution::
21144 * Interpretation of profiling results::
21147 @node Compilation for profiling
21148 @subsection Compilation for profiling
21152 In order to profile a program the first step is to tell the compiler
21153 to generate the necessary profiling information. The compiler switch to be used
21154 is @code{-pg}, which must be added to other compilation switches. This
21155 switch needs to be specified both during compilation and link stages, and can
21156 be specified once when using gnatmake:
21159 gnatmake -f -pg -P my_project
21163 Note that only the objects that were compiled with the @samp{-pg} switch will
21164 be profiled; if you need to profile your whole project, use the @samp{-f}
21165 gnatmake switch to force full recompilation.
21167 @node Program execution
21168 @subsection Program execution
21171 Once the program has been compiled for profiling, you can run it as usual.
21173 The only constraint imposed by profiling is that the program must terminate
21174 normally. An interrupted program (via a Ctrl-C, kill, etc.) will not be
21177 Once the program completes execution, a data file called @file{gmon.out} is
21178 generated in the directory where the program was launched from. If this file
21179 already exists, it will be overwritten.
21181 @node Running gprof
21182 @subsection Running gprof
21185 The @code{gprof} tool is called as follow:
21188 gprof my_prog gmon.out
21199 The complete form of the gprof command line is the following:
21202 gprof [^switches^options^] [executable [data-file]]
21206 @code{gprof} supports numerous ^switch^options^. The order of these
21207 ^switch^options^ does not matter. The full list of options can be found in
21208 the GNU Profiler User's Guide documentation that comes with this documentation.
21210 The following is the subset of those switches that is most relevant:
21214 @item --demangle[=@var{style}]
21215 @itemx --no-demangle
21216 @cindex @option{--demangle} (@code{gprof})
21217 These options control whether symbol names should be demangled when
21218 printing output. The default is to demangle C++ symbols. The
21219 @code{--no-demangle} option may be used to turn off demangling. Different
21220 compilers have different mangling styles. The optional demangling style
21221 argument can be used to choose an appropriate demangling style for your
21222 compiler, in particular Ada symbols generated by GNAT can be demangled using
21223 @code{--demangle=gnat}.
21225 @item -e @var{function_name}
21226 @cindex @option{-e} (@code{gprof})
21227 The @samp{-e @var{function}} option tells @code{gprof} not to print
21228 information about the function @var{function_name} (and its
21229 children@dots{}) in the call graph. The function will still be listed
21230 as a child of any functions that call it, but its index number will be
21231 shown as @samp{[not printed]}. More than one @samp{-e} option may be
21232 given; only one @var{function_name} may be indicated with each @samp{-e}
21235 @item -E @var{function_name}
21236 @cindex @option{-E} (@code{gprof})
21237 The @code{-E @var{function}} option works like the @code{-e} option, but
21238 execution time spent in the function (and children who were not called from
21239 anywhere else), will not be used to compute the percentages-of-time for
21240 the call graph. More than one @samp{-E} option may be given; only one
21241 @var{function_name} may be indicated with each @samp{-E} option.
21243 @item -f @var{function_name}
21244 @cindex @option{-f} (@code{gprof})
21245 The @samp{-f @var{function}} option causes @code{gprof} to limit the
21246 call graph to the function @var{function_name} and its children (and
21247 their children@dots{}). More than one @samp{-f} option may be given;
21248 only one @var{function_name} may be indicated with each @samp{-f}
21251 @item -F @var{function_name}
21252 @cindex @option{-F} (@code{gprof})
21253 The @samp{-F @var{function}} option works like the @code{-f} option, but
21254 only time spent in the function and its children (and their
21255 children@dots{}) will be used to determine total-time and
21256 percentages-of-time for the call graph. More than one @samp{-F} option
21257 may be given; only one @var{function_name} may be indicated with each
21258 @samp{-F} option. The @samp{-F} option overrides the @samp{-E} option.
21262 @node Interpretation of profiling results
21263 @subsection Interpretation of profiling results
21267 The results of the profiling analysis are represented by two arrays: the
21268 'flat profile' and the 'call graph'. Full documentation of those outputs
21269 can be found in the GNU Profiler User's Guide.
21271 The flat profile shows the time spent in each function of the program, and how
21272 many time it has been called. This allows you to locate easily the most
21273 time-consuming functions.
21275 The call graph shows, for each subprogram, the subprograms that call it,
21276 and the subprograms that it calls. It also provides an estimate of the time
21277 spent in each of those callers/called subprograms.
21280 @c ******************************
21281 @node Running and Debugging Ada Programs
21282 @chapter Running and Debugging Ada Programs
21286 This chapter discusses how to debug Ada programs.
21288 It applies to GNAT on the Alpha OpenVMS platform;
21289 for I64 OpenVMS please refer to the @cite{OpenVMS Debugger Manual},
21290 since HP has implemented Ada support in the OpenVMS debugger on I64.
21293 An incorrect Ada program may be handled in three ways by the GNAT compiler:
21297 The illegality may be a violation of the static semantics of Ada. In
21298 that case GNAT diagnoses the constructs in the program that are illegal.
21299 It is then a straightforward matter for the user to modify those parts of
21303 The illegality may be a violation of the dynamic semantics of Ada. In
21304 that case the program compiles and executes, but may generate incorrect
21305 results, or may terminate abnormally with some exception.
21308 When presented with a program that contains convoluted errors, GNAT
21309 itself may terminate abnormally without providing full diagnostics on
21310 the incorrect user program.
21314 * The GNAT Debugger GDB::
21316 * Introduction to GDB Commands::
21317 * Using Ada Expressions::
21318 * Calling User-Defined Subprograms::
21319 * Using the Next Command in a Function::
21322 * Debugging Generic Units::
21323 * Remote Debugging with gdbserver::
21324 * GNAT Abnormal Termination or Failure to Terminate::
21325 * Naming Conventions for GNAT Source Files::
21326 * Getting Internal Debugging Information::
21327 * Stack Traceback::
21333 @node The GNAT Debugger GDB
21334 @section The GNAT Debugger GDB
21337 @code{GDB} is a general purpose, platform-independent debugger that
21338 can be used to debug mixed-language programs compiled with @command{gcc},
21339 and in particular is capable of debugging Ada programs compiled with
21340 GNAT. The latest versions of @code{GDB} are Ada-aware and can handle
21341 complex Ada data structures.
21343 @xref{Top,, Debugging with GDB, gdb, Debugging with GDB},
21345 located in the GNU:[DOCS] directory,
21347 for full details on the usage of @code{GDB}, including a section on
21348 its usage on programs. This manual should be consulted for full
21349 details. The section that follows is a brief introduction to the
21350 philosophy and use of @code{GDB}.
21352 When GNAT programs are compiled, the compiler optionally writes debugging
21353 information into the generated object file, including information on
21354 line numbers, and on declared types and variables. This information is
21355 separate from the generated code. It makes the object files considerably
21356 larger, but it does not add to the size of the actual executable that
21357 will be loaded into memory, and has no impact on run-time performance. The
21358 generation of debug information is triggered by the use of the
21359 ^-g^/DEBUG^ switch in the @command{gcc} or @command{gnatmake} command
21360 used to carry out the compilations. It is important to emphasize that
21361 the use of these options does not change the generated code.
21363 The debugging information is written in standard system formats that
21364 are used by many tools, including debuggers and profilers. The format
21365 of the information is typically designed to describe C types and
21366 semantics, but GNAT implements a translation scheme which allows full
21367 details about Ada types and variables to be encoded into these
21368 standard C formats. Details of this encoding scheme may be found in
21369 the file exp_dbug.ads in the GNAT source distribution. However, the
21370 details of this encoding are, in general, of no interest to a user,
21371 since @code{GDB} automatically performs the necessary decoding.
21373 When a program is bound and linked, the debugging information is
21374 collected from the object files, and stored in the executable image of
21375 the program. Again, this process significantly increases the size of
21376 the generated executable file, but it does not increase the size of
21377 the executable program itself. Furthermore, if this program is run in
21378 the normal manner, it runs exactly as if the debug information were
21379 not present, and takes no more actual memory.
21381 However, if the program is run under control of @code{GDB}, the
21382 debugger is activated. The image of the program is loaded, at which
21383 point it is ready to run. If a run command is given, then the program
21384 will run exactly as it would have if @code{GDB} were not present. This
21385 is a crucial part of the @code{GDB} design philosophy. @code{GDB} is
21386 entirely non-intrusive until a breakpoint is encountered. If no
21387 breakpoint is ever hit, the program will run exactly as it would if no
21388 debugger were present. When a breakpoint is hit, @code{GDB} accesses
21389 the debugging information and can respond to user commands to inspect
21390 variables, and more generally to report on the state of execution.
21394 @section Running GDB
21397 This section describes how to initiate the debugger.
21398 @c The above sentence is really just filler, but it was otherwise
21399 @c clumsy to get the first paragraph nonindented given the conditional
21400 @c nature of the description
21403 The debugger can be launched from a @code{GPS} menu or
21404 directly from the command line. The description below covers the latter use.
21405 All the commands shown can be used in the @code{GPS} debug console window,
21406 but there are usually more GUI-based ways to achieve the same effect.
21409 The command to run @code{GDB} is
21412 $ ^gdb program^GDB PROGRAM^
21416 where @code{^program^PROGRAM^} is the name of the executable file. This
21417 activates the debugger and results in a prompt for debugger commands.
21418 The simplest command is simply @code{run}, which causes the program to run
21419 exactly as if the debugger were not present. The following section
21420 describes some of the additional commands that can be given to @code{GDB}.
21422 @c *******************************
21423 @node Introduction to GDB Commands
21424 @section Introduction to GDB Commands
21427 @code{GDB} contains a large repertoire of commands. @xref{Top,,
21428 Debugging with GDB, gdb, Debugging with GDB},
21430 located in the GNU:[DOCS] directory,
21432 for extensive documentation on the use
21433 of these commands, together with examples of their use. Furthermore,
21434 the command @command{help} invoked from within GDB activates a simple help
21435 facility which summarizes the available commands and their options.
21436 In this section we summarize a few of the most commonly
21437 used commands to give an idea of what @code{GDB} is about. You should create
21438 a simple program with debugging information and experiment with the use of
21439 these @code{GDB} commands on the program as you read through the
21443 @item set args @var{arguments}
21444 The @var{arguments} list above is a list of arguments to be passed to
21445 the program on a subsequent run command, just as though the arguments
21446 had been entered on a normal invocation of the program. The @code{set args}
21447 command is not needed if the program does not require arguments.
21450 The @code{run} command causes execution of the program to start from
21451 the beginning. If the program is already running, that is to say if
21452 you are currently positioned at a breakpoint, then a prompt will ask
21453 for confirmation that you want to abandon the current execution and
21456 @item breakpoint @var{location}
21457 The breakpoint command sets a breakpoint, that is to say a point at which
21458 execution will halt and @code{GDB} will await further
21459 commands. @var{location} is
21460 either a line number within a file, given in the format @code{file:linenumber},
21461 or it is the name of a subprogram. If you request that a breakpoint be set on
21462 a subprogram that is overloaded, a prompt will ask you to specify on which of
21463 those subprograms you want to breakpoint. You can also
21464 specify that all of them should be breakpointed. If the program is run
21465 and execution encounters the breakpoint, then the program
21466 stops and @code{GDB} signals that the breakpoint was encountered by
21467 printing the line of code before which the program is halted.
21469 @item catch exception @var{name}
21470 This command causes the program execution to stop whenever exception
21471 @var{name} is raised. If @var{name} is omitted, then the execution is
21472 suspended when any exception is raised.
21474 @item print @var{expression}
21475 This will print the value of the given expression. Most simple
21476 Ada expression formats are properly handled by @code{GDB}, so the expression
21477 can contain function calls, variables, operators, and attribute references.
21480 Continues execution following a breakpoint, until the next breakpoint or the
21481 termination of the program.
21484 Executes a single line after a breakpoint. If the next statement
21485 is a subprogram call, execution continues into (the first statement of)
21486 the called subprogram.
21489 Executes a single line. If this line is a subprogram call, executes and
21490 returns from the call.
21493 Lists a few lines around the current source location. In practice, it
21494 is usually more convenient to have a separate edit window open with the
21495 relevant source file displayed. Successive applications of this command
21496 print subsequent lines. The command can be given an argument which is a
21497 line number, in which case it displays a few lines around the specified one.
21500 Displays a backtrace of the call chain. This command is typically
21501 used after a breakpoint has occurred, to examine the sequence of calls that
21502 leads to the current breakpoint. The display includes one line for each
21503 activation record (frame) corresponding to an active subprogram.
21506 At a breakpoint, @code{GDB} can display the values of variables local
21507 to the current frame. The command @code{up} can be used to
21508 examine the contents of other active frames, by moving the focus up
21509 the stack, that is to say from callee to caller, one frame at a time.
21512 Moves the focus of @code{GDB} down from the frame currently being
21513 examined to the frame of its callee (the reverse of the previous command),
21515 @item frame @var{n}
21516 Inspect the frame with the given number. The value 0 denotes the frame
21517 of the current breakpoint, that is to say the top of the call stack.
21520 Kills the child process in which the program is running under GDB.
21521 This may be useful for several purposes:
21524 It allows you to recompile and relink your program, since on many systems
21525 you cannot regenerate an executable file while it is running in a process.
21527 You can run your program outside the debugger, on systems that do not
21528 permit executing a program outside GDB while breakpoints are set
21531 It allows you to debug a core dump rather than a running process.
21536 The above list is a very short introduction to the commands that
21537 @code{GDB} provides. Important additional capabilities, including conditional
21538 breakpoints, the ability to execute command sequences on a breakpoint,
21539 the ability to debug at the machine instruction level and many other
21540 features are described in detail in @ref{Top,, Debugging with GDB, gdb,
21541 Debugging with GDB}. Note that most commands can be abbreviated
21542 (for example, c for continue, bt for backtrace).
21544 @node Using Ada Expressions
21545 @section Using Ada Expressions
21546 @cindex Ada expressions
21549 @code{GDB} supports a fairly large subset of Ada expression syntax, with some
21550 extensions. The philosophy behind the design of this subset is
21554 That @code{GDB} should provide basic literals and access to operations for
21555 arithmetic, dereferencing, field selection, indexing, and subprogram calls,
21556 leaving more sophisticated computations to subprograms written into the
21557 program (which therefore may be called from @code{GDB}).
21560 That type safety and strict adherence to Ada language restrictions
21561 are not particularly important to the @code{GDB} user.
21564 That brevity is important to the @code{GDB} user.
21568 Thus, for brevity, the debugger acts as if there were
21569 implicit @code{with} and @code{use} clauses in effect for all user-written
21570 packages, thus making it unnecessary to fully qualify most names with
21571 their packages, regardless of context. Where this causes ambiguity,
21572 @code{GDB} asks the user's intent.
21574 For details on the supported Ada syntax, see @ref{Top,, Debugging with
21575 GDB, gdb, Debugging with GDB}.
21577 @node Calling User-Defined Subprograms
21578 @section Calling User-Defined Subprograms
21581 An important capability of @code{GDB} is the ability to call user-defined
21582 subprograms while debugging. This is achieved simply by entering
21583 a subprogram call statement in the form:
21586 call subprogram-name (parameters)
21590 The keyword @code{call} can be omitted in the normal case where the
21591 @code{subprogram-name} does not coincide with any of the predefined
21592 @code{GDB} commands.
21594 The effect is to invoke the given subprogram, passing it the
21595 list of parameters that is supplied. The parameters can be expressions and
21596 can include variables from the program being debugged. The
21597 subprogram must be defined
21598 at the library level within your program, and @code{GDB} will call the
21599 subprogram within the environment of your program execution (which
21600 means that the subprogram is free to access or even modify variables
21601 within your program).
21603 The most important use of this facility is in allowing the inclusion of
21604 debugging routines that are tailored to particular data structures
21605 in your program. Such debugging routines can be written to provide a suitably
21606 high-level description of an abstract type, rather than a low-level dump
21607 of its physical layout. After all, the standard
21608 @code{GDB print} command only knows the physical layout of your
21609 types, not their abstract meaning. Debugging routines can provide information
21610 at the desired semantic level and are thus enormously useful.
21612 For example, when debugging GNAT itself, it is crucial to have access to
21613 the contents of the tree nodes used to represent the program internally.
21614 But tree nodes are represented simply by an integer value (which in turn
21615 is an index into a table of nodes).
21616 Using the @code{print} command on a tree node would simply print this integer
21617 value, which is not very useful. But the PN routine (defined in file
21618 treepr.adb in the GNAT sources) takes a tree node as input, and displays
21619 a useful high level representation of the tree node, which includes the
21620 syntactic category of the node, its position in the source, the integers
21621 that denote descendant nodes and parent node, as well as varied
21622 semantic information. To study this example in more detail, you might want to
21623 look at the body of the PN procedure in the stated file.
21625 @node Using the Next Command in a Function
21626 @section Using the Next Command in a Function
21629 When you use the @code{next} command in a function, the current source
21630 location will advance to the next statement as usual. A special case
21631 arises in the case of a @code{return} statement.
21633 Part of the code for a return statement is the ``epilog'' of the function.
21634 This is the code that returns to the caller. There is only one copy of
21635 this epilog code, and it is typically associated with the last return
21636 statement in the function if there is more than one return. In some
21637 implementations, this epilog is associated with the first statement
21640 The result is that if you use the @code{next} command from a return
21641 statement that is not the last return statement of the function you
21642 may see a strange apparent jump to the last return statement or to
21643 the start of the function. You should simply ignore this odd jump.
21644 The value returned is always that from the first return statement
21645 that was stepped through.
21647 @node Ada Exceptions
21648 @section Stopping when Ada Exceptions are Raised
21652 You can set catchpoints that stop the program execution when your program
21653 raises selected exceptions.
21656 @item catch exception
21657 Set a catchpoint that stops execution whenever (any task in the) program
21658 raises any exception.
21660 @item catch exception @var{name}
21661 Set a catchpoint that stops execution whenever (any task in the) program
21662 raises the exception @var{name}.
21664 @item catch exception unhandled
21665 Set a catchpoint that stops executing whenever (any task in the) program
21666 raises an exception for which there is no handler.
21668 @item info exceptions
21669 @itemx info exceptions @var{regexp}
21670 The @code{info exceptions} command permits the user to examine all defined
21671 exceptions within Ada programs. With a regular expression, @var{regexp}, as
21672 argument, prints out only those exceptions whose name matches @var{regexp}.
21680 @code{GDB} allows the following task-related commands:
21684 This command shows a list of current Ada tasks, as in the following example:
21691 ID TID P-ID Thread Pri State Name
21692 1 8088000 0 807e000 15 Child Activation Wait main_task
21693 2 80a4000 1 80ae000 15 Accept/Select Wait b
21694 3 809a800 1 80a4800 15 Child Activation Wait a
21695 * 4 80ae800 3 80b8000 15 Running c
21699 In this listing, the asterisk before the first task indicates it to be the
21700 currently running task. The first column lists the task ID that is used
21701 to refer to tasks in the following commands.
21703 @item break @var{linespec} task @var{taskid}
21704 @itemx break @var{linespec} task @var{taskid} if @dots{}
21705 @cindex Breakpoints and tasks
21706 These commands are like the @code{break @dots{} thread @dots{}}.
21707 @var{linespec} specifies source lines.
21709 Use the qualifier @samp{task @var{taskid}} with a breakpoint command
21710 to specify that you only want @code{GDB} to stop the program when a
21711 particular Ada task reaches this breakpoint. @var{taskid} is one of the
21712 numeric task identifiers assigned by @code{GDB}, shown in the first
21713 column of the @samp{info tasks} display.
21715 If you do not specify @samp{task @var{taskid}} when you set a
21716 breakpoint, the breakpoint applies to @emph{all} tasks of your
21719 You can use the @code{task} qualifier on conditional breakpoints as
21720 well; in this case, place @samp{task @var{taskid}} before the
21721 breakpoint condition (before the @code{if}).
21723 @item task @var{taskno}
21724 @cindex Task switching
21726 This command allows switching to the task referred by @var{taskno}. In
21727 particular, this allows browsing of the backtrace of the specified
21728 task. It is advisable to switch back to the original task before
21729 continuing execution otherwise the scheduling of the program may be
21734 For more detailed information on the tasking support,
21735 see @ref{Top,, Debugging with GDB, gdb, Debugging with GDB}.
21737 @node Debugging Generic Units
21738 @section Debugging Generic Units
21739 @cindex Debugging Generic Units
21743 GNAT always uses code expansion for generic instantiation. This means that
21744 each time an instantiation occurs, a complete copy of the original code is
21745 made, with appropriate substitutions of formals by actuals.
21747 It is not possible to refer to the original generic entities in
21748 @code{GDB}, but it is always possible to debug a particular instance of
21749 a generic, by using the appropriate expanded names. For example, if we have
21751 @smallexample @c ada
21756 generic package k is
21757 procedure kp (v1 : in out integer);
21761 procedure kp (v1 : in out integer) is
21767 package k1 is new k;
21768 package k2 is new k;
21770 var : integer := 1;
21783 Then to break on a call to procedure kp in the k2 instance, simply
21787 (gdb) break g.k2.kp
21791 When the breakpoint occurs, you can step through the code of the
21792 instance in the normal manner and examine the values of local variables, as for
21795 @node Remote Debugging with gdbserver
21796 @section Remote Debugging with gdbserver
21797 @cindex Remote Debugging with gdbserver
21800 On platforms where gdbserver is supported, it is possible to use this tool
21801 to debug your application remotely. This can be useful in situations
21802 where the program needs to be run on a target host that is different
21803 from the host used for development, particularly when the target has
21804 a limited amount of resources (either CPU and/or memory).
21806 To do so, start your program using gdbserver on the target machine.
21807 gdbserver then automatically suspends the execution of your program
21808 at its entry point, waiting for a debugger to connect to it. The
21809 following commands starts an application and tells gdbserver to
21810 wait for a connection with the debugger on localhost port 4444.
21813 $ gdbserver localhost:4444 program
21814 Process program created; pid = 5685
21815 Listening on port 4444
21818 Once gdbserver has started listening, we can tell the debugger to establish
21819 a connection with this gdbserver, and then start the same debugging session
21820 as if the program was being debugged on the same host, directly under
21821 the control of GDB.
21825 (gdb) target remote targethost:4444
21826 Remote debugging using targethost:4444
21827 0x00007f29936d0af0 in ?? () from /lib64/ld-linux-x86-64.so.
21829 Breakpoint 1 at 0x401f0c: file foo.adb, line 3.
21833 Breakpoint 1, foo () at foo.adb:4
21837 It is also possible to use gdbserver to attach to an already running
21838 program, in which case the execution of that program is simply suspended
21839 until the connection between the debugger and gdbserver is established.
21841 For more information on how to use gdbserver, @ref{Top, Server, Using
21842 the gdbserver Program, gdb, Debugging with GDB}. @value{EDITION} provides support
21843 for gdbserver on x86-linux, x86-windows and x86_64-linux.
21845 @node GNAT Abnormal Termination or Failure to Terminate
21846 @section GNAT Abnormal Termination or Failure to Terminate
21847 @cindex GNAT Abnormal Termination or Failure to Terminate
21850 When presented with programs that contain serious errors in syntax
21852 GNAT may on rare occasions experience problems in operation, such
21854 segmentation fault or illegal memory access, raising an internal
21855 exception, terminating abnormally, or failing to terminate at all.
21856 In such cases, you can activate
21857 various features of GNAT that can help you pinpoint the construct in your
21858 program that is the likely source of the problem.
21860 The following strategies are presented in increasing order of
21861 difficulty, corresponding to your experience in using GNAT and your
21862 familiarity with compiler internals.
21866 Run @command{gcc} with the @option{-gnatf}. This first
21867 switch causes all errors on a given line to be reported. In its absence,
21868 only the first error on a line is displayed.
21870 The @option{-gnatdO} switch causes errors to be displayed as soon as they
21871 are encountered, rather than after compilation is terminated. If GNAT
21872 terminates prematurely or goes into an infinite loop, the last error
21873 message displayed may help to pinpoint the culprit.
21876 Run @command{gcc} with the @option{^-v (verbose)^/VERBOSE^} switch. In this
21877 mode, @command{gcc} produces ongoing information about the progress of the
21878 compilation and provides the name of each procedure as code is
21879 generated. This switch allows you to find which Ada procedure was being
21880 compiled when it encountered a code generation problem.
21883 @cindex @option{-gnatdc} switch
21884 Run @command{gcc} with the @option{-gnatdc} switch. This is a GNAT specific
21885 switch that does for the front-end what @option{^-v^VERBOSE^} does
21886 for the back end. The system prints the name of each unit,
21887 either a compilation unit or nested unit, as it is being analyzed.
21889 Finally, you can start
21890 @code{gdb} directly on the @code{gnat1} executable. @code{gnat1} is the
21891 front-end of GNAT, and can be run independently (normally it is just
21892 called from @command{gcc}). You can use @code{gdb} on @code{gnat1} as you
21893 would on a C program (but @pxref{The GNAT Debugger GDB} for caveats). The
21894 @code{where} command is the first line of attack; the variable
21895 @code{lineno} (seen by @code{print lineno}), used by the second phase of
21896 @code{gnat1} and by the @command{gcc} backend, indicates the source line at
21897 which the execution stopped, and @code{input_file name} indicates the name of
21901 @node Naming Conventions for GNAT Source Files
21902 @section Naming Conventions for GNAT Source Files
21905 In order to examine the workings of the GNAT system, the following
21906 brief description of its organization may be helpful:
21910 Files with prefix @file{^sc^SC^} contain the lexical scanner.
21913 All files prefixed with @file{^par^PAR^} are components of the parser. The
21914 numbers correspond to chapters of the Ada Reference Manual. For example,
21915 parsing of select statements can be found in @file{par-ch9.adb}.
21918 All files prefixed with @file{^sem^SEM^} perform semantic analysis. The
21919 numbers correspond to chapters of the Ada standard. For example, all
21920 issues involving context clauses can be found in @file{sem_ch10.adb}. In
21921 addition, some features of the language require sufficient special processing
21922 to justify their own semantic files: sem_aggr for aggregates, sem_disp for
21923 dynamic dispatching, etc.
21926 All files prefixed with @file{^exp^EXP^} perform normalization and
21927 expansion of the intermediate representation (abstract syntax tree, or AST).
21928 these files use the same numbering scheme as the parser and semantics files.
21929 For example, the construction of record initialization procedures is done in
21930 @file{exp_ch3.adb}.
21933 The files prefixed with @file{^bind^BIND^} implement the binder, which
21934 verifies the consistency of the compilation, determines an order of
21935 elaboration, and generates the bind file.
21938 The files @file{atree.ads} and @file{atree.adb} detail the low-level
21939 data structures used by the front-end.
21942 The files @file{sinfo.ads} and @file{sinfo.adb} detail the structure of
21943 the abstract syntax tree as produced by the parser.
21946 The files @file{einfo.ads} and @file{einfo.adb} detail the attributes of
21947 all entities, computed during semantic analysis.
21950 Library management issues are dealt with in files with prefix
21956 Ada files with the prefix @file{^a-^A-^} are children of @code{Ada}, as
21957 defined in Annex A.
21962 Files with prefix @file{^i-^I-^} are children of @code{Interfaces}, as
21963 defined in Annex B.
21967 Files with prefix @file{^s-^S-^} are children of @code{System}. This includes
21968 both language-defined children and GNAT run-time routines.
21972 Files with prefix @file{^g-^G-^} are children of @code{GNAT}. These are useful
21973 general-purpose packages, fully documented in their specs. All
21974 the other @file{.c} files are modifications of common @command{gcc} files.
21977 @node Getting Internal Debugging Information
21978 @section Getting Internal Debugging Information
21981 Most compilers have internal debugging switches and modes. GNAT
21982 does also, except GNAT internal debugging switches and modes are not
21983 secret. A summary and full description of all the compiler and binder
21984 debug flags are in the file @file{debug.adb}. You must obtain the
21985 sources of the compiler to see the full detailed effects of these flags.
21987 The switches that print the source of the program (reconstructed from
21988 the internal tree) are of general interest for user programs, as are the
21990 the full internal tree, and the entity table (the symbol table
21991 information). The reconstructed source provides a readable version of the
21992 program after the front-end has completed analysis and expansion,
21993 and is useful when studying the performance of specific constructs.
21994 For example, constraint checks are indicated, complex aggregates
21995 are replaced with loops and assignments, and tasking primitives
21996 are replaced with run-time calls.
21998 @node Stack Traceback
21999 @section Stack Traceback
22001 @cindex stack traceback
22002 @cindex stack unwinding
22005 Traceback is a mechanism to display the sequence of subprogram calls that
22006 leads to a specified execution point in a program. Often (but not always)
22007 the execution point is an instruction at which an exception has been raised.
22008 This mechanism is also known as @i{stack unwinding} because it obtains
22009 its information by scanning the run-time stack and recovering the activation
22010 records of all active subprograms. Stack unwinding is one of the most
22011 important tools for program debugging.
22013 The first entry stored in traceback corresponds to the deepest calling level,
22014 that is to say the subprogram currently executing the instruction
22015 from which we want to obtain the traceback.
22017 Note that there is no runtime performance penalty when stack traceback
22018 is enabled, and no exception is raised during program execution.
22021 * Non-Symbolic Traceback::
22022 * Symbolic Traceback::
22025 @node Non-Symbolic Traceback
22026 @subsection Non-Symbolic Traceback
22027 @cindex traceback, non-symbolic
22030 Note: this feature is not supported on all platforms. See
22031 @file{GNAT.Traceback spec in g-traceb.ads} for a complete list of supported
22035 * Tracebacks From an Unhandled Exception::
22036 * Tracebacks From Exception Occurrences (non-symbolic)::
22037 * Tracebacks From Anywhere in a Program (non-symbolic)::
22040 @node Tracebacks From an Unhandled Exception
22041 @subsubsection Tracebacks From an Unhandled Exception
22044 A runtime non-symbolic traceback is a list of addresses of call instructions.
22045 To enable this feature you must use the @option{-E}
22046 @code{gnatbind}'s option. With this option a stack traceback is stored as part
22047 of exception information. You can retrieve this information using the
22048 @code{addr2line} tool.
22050 Here is a simple example:
22052 @smallexample @c ada
22058 raise Constraint_Error;
22073 $ gnatmake stb -bargs -E
22076 Execution terminated by unhandled exception
22077 Exception name: CONSTRAINT_ERROR
22079 Call stack traceback locations:
22080 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
22084 As we see the traceback lists a sequence of addresses for the unhandled
22085 exception @code{CONSTRAINT_ERROR} raised in procedure P1. It is easy to
22086 guess that this exception come from procedure P1. To translate these
22087 addresses into the source lines where the calls appear, the
22088 @code{addr2line} tool, described below, is invaluable. The use of this tool
22089 requires the program to be compiled with debug information.
22092 $ gnatmake -g stb -bargs -E
22095 Execution terminated by unhandled exception
22096 Exception name: CONSTRAINT_ERROR
22098 Call stack traceback locations:
22099 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
22101 $ addr2line --exe=stb 0x401373 0x40138b 0x40139c 0x401335 0x4011c4
22102 0x4011f1 0x77e892a4
22104 00401373 at d:/stb/stb.adb:5
22105 0040138B at d:/stb/stb.adb:10
22106 0040139C at d:/stb/stb.adb:14
22107 00401335 at d:/stb/b~stb.adb:104
22108 004011C4 at /build/@dots{}/crt1.c:200
22109 004011F1 at /build/@dots{}/crt1.c:222
22110 77E892A4 in ?? at ??:0
22114 The @code{addr2line} tool has several other useful options:
22118 to get the function name corresponding to any location
22120 @item --demangle=gnat
22121 to use the gnat decoding mode for the function names. Note that
22122 for binutils version 2.9.x the option is simply @option{--demangle}.
22126 $ addr2line --exe=stb --functions --demangle=gnat 0x401373 0x40138b
22127 0x40139c 0x401335 0x4011c4 0x4011f1
22129 00401373 in stb.p1 at d:/stb/stb.adb:5
22130 0040138B in stb.p2 at d:/stb/stb.adb:10
22131 0040139C in stb at d:/stb/stb.adb:14
22132 00401335 in main at d:/stb/b~stb.adb:104
22133 004011C4 in <__mingw_CRTStartup> at /build/@dots{}/crt1.c:200
22134 004011F1 in <mainCRTStartup> at /build/@dots{}/crt1.c:222
22138 From this traceback we can see that the exception was raised in
22139 @file{stb.adb} at line 5, which was reached from a procedure call in
22140 @file{stb.adb} at line 10, and so on. The @file{b~std.adb} is the binder file,
22141 which contains the call to the main program.
22142 @xref{Running gnatbind}. The remaining entries are assorted runtime routines,
22143 and the output will vary from platform to platform.
22145 It is also possible to use @code{GDB} with these traceback addresses to debug
22146 the program. For example, we can break at a given code location, as reported
22147 in the stack traceback:
22153 Furthermore, this feature is not implemented inside Windows DLL. Only
22154 the non-symbolic traceback is reported in this case.
22157 (gdb) break *0x401373
22158 Breakpoint 1 at 0x401373: file stb.adb, line 5.
22162 It is important to note that the stack traceback addresses
22163 do not change when debug information is included. This is particularly useful
22164 because it makes it possible to release software without debug information (to
22165 minimize object size), get a field report that includes a stack traceback
22166 whenever an internal bug occurs, and then be able to retrieve the sequence
22167 of calls with the same program compiled with debug information.
22169 @node Tracebacks From Exception Occurrences (non-symbolic)
22170 @subsubsection Tracebacks From Exception Occurrences
22173 Non-symbolic tracebacks are obtained by using the @option{-E} binder argument.
22174 The stack traceback is attached to the exception information string, and can
22175 be retrieved in an exception handler within the Ada program, by means of the
22176 Ada facilities defined in @code{Ada.Exceptions}. Here is a simple example:
22178 @smallexample @c ada
22180 with Ada.Exceptions;
22185 use Ada.Exceptions;
22193 Text_IO.Put_Line (Exception_Information (E));
22207 This program will output:
22212 Exception name: CONSTRAINT_ERROR
22213 Message: stb.adb:12
22214 Call stack traceback locations:
22215 0x4015e4 0x401633 0x401644 0x401461 0x4011c4 0x4011f1 0x77e892a4
22218 @node Tracebacks From Anywhere in a Program (non-symbolic)
22219 @subsubsection Tracebacks From Anywhere in a Program
22222 It is also possible to retrieve a stack traceback from anywhere in a
22223 program. For this you need to
22224 use the @code{GNAT.Traceback} API. This package includes a procedure called
22225 @code{Call_Chain} that computes a complete stack traceback, as well as useful
22226 display procedures described below. It is not necessary to use the
22227 @option{-E gnatbind} option in this case, because the stack traceback mechanism
22228 is invoked explicitly.
22231 In the following example we compute a traceback at a specific location in
22232 the program, and we display it using @code{GNAT.Debug_Utilities.Image} to
22233 convert addresses to strings:
22235 @smallexample @c ada
22237 with GNAT.Traceback;
22238 with GNAT.Debug_Utilities;
22244 use GNAT.Traceback;
22247 TB : Tracebacks_Array (1 .. 10);
22248 -- We are asking for a maximum of 10 stack frames.
22250 -- Len will receive the actual number of stack frames returned.
22252 Call_Chain (TB, Len);
22254 Text_IO.Put ("In STB.P1 : ");
22256 for K in 1 .. Len loop
22257 Text_IO.Put (Debug_Utilities.Image (TB (K)));
22278 In STB.P1 : 16#0040_F1E4# 16#0040_14F2# 16#0040_170B# 16#0040_171C#
22279 16#0040_1461# 16#0040_11C4# 16#0040_11F1# 16#77E8_92A4#
22283 You can then get further information by invoking the @code{addr2line}
22284 tool as described earlier (note that the hexadecimal addresses
22285 need to be specified in C format, with a leading ``0x'').
22287 @node Symbolic Traceback
22288 @subsection Symbolic Traceback
22289 @cindex traceback, symbolic
22292 A symbolic traceback is a stack traceback in which procedure names are
22293 associated with each code location.
22296 Note that this feature is not supported on all platforms. See
22297 @file{GNAT.Traceback.Symbolic spec in g-trasym.ads} for a complete
22298 list of currently supported platforms.
22301 Note that the symbolic traceback requires that the program be compiled
22302 with debug information. If it is not compiled with debug information
22303 only the non-symbolic information will be valid.
22306 * Tracebacks From Exception Occurrences (symbolic)::
22307 * Tracebacks From Anywhere in a Program (symbolic)::
22310 @node Tracebacks From Exception Occurrences (symbolic)
22311 @subsubsection Tracebacks From Exception Occurrences
22313 @smallexample @c ada
22315 with GNAT.Traceback.Symbolic;
22321 raise Constraint_Error;
22338 Ada.Text_IO.Put_Line (GNAT.Traceback.Symbolic.Symbolic_Traceback (E));
22343 $ gnatmake -g .\stb -bargs -E
22346 0040149F in stb.p1 at stb.adb:8
22347 004014B7 in stb.p2 at stb.adb:13
22348 004014CF in stb.p3 at stb.adb:18
22349 004015DD in ada.stb at stb.adb:22
22350 00401461 in main at b~stb.adb:168
22351 004011C4 in __mingw_CRTStartup at crt1.c:200
22352 004011F1 in mainCRTStartup at crt1.c:222
22353 77E892A4 in ?? at ??:0
22357 In the above example the ``.\'' syntax in the @command{gnatmake} command
22358 is currently required by @command{addr2line} for files that are in
22359 the current working directory.
22360 Moreover, the exact sequence of linker options may vary from platform
22362 The above @option{-largs} section is for Windows platforms. By contrast,
22363 under Unix there is no need for the @option{-largs} section.
22364 Differences across platforms are due to details of linker implementation.
22366 @node Tracebacks From Anywhere in a Program (symbolic)
22367 @subsubsection Tracebacks From Anywhere in a Program
22370 It is possible to get a symbolic stack traceback
22371 from anywhere in a program, just as for non-symbolic tracebacks.
22372 The first step is to obtain a non-symbolic
22373 traceback, and then call @code{Symbolic_Traceback} to compute the symbolic
22374 information. Here is an example:
22376 @smallexample @c ada
22378 with GNAT.Traceback;
22379 with GNAT.Traceback.Symbolic;
22384 use GNAT.Traceback;
22385 use GNAT.Traceback.Symbolic;
22388 TB : Tracebacks_Array (1 .. 10);
22389 -- We are asking for a maximum of 10 stack frames.
22391 -- Len will receive the actual number of stack frames returned.
22393 Call_Chain (TB, Len);
22394 Text_IO.Put_Line (Symbolic_Traceback (TB (1 .. Len)));
22407 @c ******************************
22409 @node Compatibility with HP Ada
22410 @chapter Compatibility with HP Ada
22411 @cindex Compatibility
22416 @cindex Compatibility between GNAT and HP Ada
22417 This chapter compares HP Ada (formerly known as ``DEC Ada'')
22418 for OpenVMS Alpha and GNAT for OpenVMS for Alpha and for I64.
22419 GNAT is highly compatible
22420 with HP Ada, and it should generally be straightforward to port code
22421 from the HP Ada environment to GNAT. However, there are a few language
22422 and implementation differences of which the user must be aware. These
22423 differences are discussed in this chapter. In
22424 addition, the operating environment and command structure for the
22425 compiler are different, and these differences are also discussed.
22427 For further details on these and other compatibility issues,
22428 see Appendix E of the HP publication
22429 @cite{HP Ada, Technical Overview and Comparison on HP Platforms}.
22431 Except where otherwise indicated, the description of GNAT for OpenVMS
22432 applies to both the Alpha and I64 platforms.
22434 For information on porting Ada code from GNAT on Alpha OpenVMS to GNAT on
22435 I64 OpenVMS, see @ref{Transitioning to 64-Bit GNAT for OpenVMS}.
22437 The discussion in this chapter addresses specifically the implementation
22438 of Ada 83 for HP OpenVMS Alpha Systems. In cases where the implementation
22439 of HP Ada differs between OpenVMS Alpha Systems and OpenVMS VAX Systems,
22440 GNAT always follows the Alpha implementation.
22442 For GNAT running on other than VMS systems, all the HP Ada 83 pragmas and
22443 attributes are recognized, although only a subset of them can sensibly
22444 be implemented. The description of pragmas in
22445 @xref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference Manual},
22446 indicates whether or not they are applicable to non-VMS systems.
22449 * Ada Language Compatibility::
22450 * Differences in the Definition of Package System::
22451 * Language-Related Features::
22452 * The Package STANDARD::
22453 * The Package SYSTEM::
22454 * Tasking and Task-Related Features::
22455 * Pragmas and Pragma-Related Features::
22456 * Library of Predefined Units::
22458 * Main Program Definition::
22459 * Implementation-Defined Attributes::
22460 * Compiler and Run-Time Interfacing::
22461 * Program Compilation and Library Management::
22463 * Implementation Limits::
22464 * Tools and Utilities::
22467 @node Ada Language Compatibility
22468 @section Ada Language Compatibility
22471 GNAT handles Ada 95 and Ada 2005 as well as Ada 83, whereas HP Ada is only
22472 for Ada 83. Ada 95 and Ada 2005 are almost completely upwards compatible
22473 with Ada 83, and therefore Ada 83 programs will compile
22474 and run under GNAT with
22475 no changes or only minor changes. The @cite{Annotated Ada Reference Manual}
22476 provides details on specific incompatibilities.
22478 GNAT provides the switch @option{/83} on the @command{GNAT COMPILE} command,
22479 as well as the pragma @code{ADA_83}, to force the compiler to
22480 operate in Ada 83 mode. This mode does not guarantee complete
22481 conformance to Ada 83, but in practice is sufficient to
22482 eliminate most sources of incompatibilities.
22483 In particular, it eliminates the recognition of the
22484 additional Ada 95 and Ada 2005 keywords, so that their use as identifiers
22485 in Ada 83 programs is legal, and handles the cases of packages
22486 with optional bodies, and generics that instantiate unconstrained
22487 types without the use of @code{(<>)}.
22489 @node Differences in the Definition of Package System
22490 @section Differences in the Definition of Package @code{System}
22493 An Ada compiler is allowed to add
22494 implementation-dependent declarations to package @code{System}.
22496 GNAT does not take advantage of this permission, and the version of
22497 @code{System} provided by GNAT exactly matches that defined in the Ada
22500 However, HP Ada adds an extensive set of declarations to package
22502 as fully documented in the HP Ada manuals. To minimize changes required
22503 for programs that make use of these extensions, GNAT provides the pragma
22504 @code{Extend_System} for extending the definition of package System. By using:
22505 @cindex pragma @code{Extend_System}
22506 @cindex @code{Extend_System} pragma
22508 @smallexample @c ada
22511 pragma Extend_System (Aux_DEC);
22517 the set of definitions in @code{System} is extended to include those in
22518 package @code{System.Aux_DEC}.
22519 @cindex @code{System.Aux_DEC} package
22520 @cindex @code{Aux_DEC} package (child of @code{System})
22521 These definitions are incorporated directly into package @code{System},
22522 as though they had been declared there. For a
22523 list of the declarations added, see the spec of this package,
22524 which can be found in the file @file{s-auxdec.ads} in the GNAT library.
22525 @cindex @file{s-auxdec.ads} file
22526 The pragma @code{Extend_System} is a configuration pragma, which means that
22527 it can be placed in the file @file{gnat.adc}, so that it will automatically
22528 apply to all subsequent compilations. See @ref{Configuration Pragmas},
22529 for further details.
22531 An alternative approach that avoids the use of the non-standard
22532 @code{Extend_System} pragma is to add a context clause to the unit that
22533 references these facilities:
22535 @smallexample @c ada
22537 with System.Aux_DEC;
22538 use System.Aux_DEC;
22543 The effect is not quite semantically identical to incorporating
22544 the declarations directly into package @code{System},
22545 but most programs will not notice a difference
22546 unless they use prefix notation (e.g.@: @code{System.Integer_8})
22547 to reference the entities directly in package @code{System}.
22548 For units containing such references,
22549 the prefixes must either be removed, or the pragma @code{Extend_System}
22552 @node Language-Related Features
22553 @section Language-Related Features
22556 The following sections highlight differences in types,
22557 representations of types, operations, alignment, and
22561 * Integer Types and Representations::
22562 * Floating-Point Types and Representations::
22563 * Pragmas Float_Representation and Long_Float::
22564 * Fixed-Point Types and Representations::
22565 * Record and Array Component Alignment::
22566 * Address Clauses::
22567 * Other Representation Clauses::
22570 @node Integer Types and Representations
22571 @subsection Integer Types and Representations
22574 The set of predefined integer types is identical in HP Ada and GNAT.
22575 Furthermore the representation of these integer types is also identical,
22576 including the capability of size clauses forcing biased representation.
22579 HP Ada for OpenVMS Alpha systems has defined the
22580 following additional integer types in package @code{System}:
22597 @code{LARGEST_INTEGER}
22601 In GNAT, the first four of these types may be obtained from the
22602 standard Ada package @code{Interfaces}.
22603 Alternatively, by use of the pragma @code{Extend_System}, identical
22604 declarations can be referenced directly in package @code{System}.
22605 On both GNAT and HP Ada, the maximum integer size is 64 bits.
22607 @node Floating-Point Types and Representations
22608 @subsection Floating-Point Types and Representations
22609 @cindex Floating-Point types
22612 The set of predefined floating-point types is identical in HP Ada and GNAT.
22613 Furthermore the representation of these floating-point
22614 types is also identical. One important difference is that the default
22615 representation for HP Ada is @code{VAX_Float}, but the default representation
22618 Specific types may be declared to be @code{VAX_Float} or IEEE, using the
22619 pragma @code{Float_Representation} as described in the HP Ada
22621 For example, the declarations:
22623 @smallexample @c ada
22625 type F_Float is digits 6;
22626 pragma Float_Representation (VAX_Float, F_Float);
22631 declares a type @code{F_Float} that will be represented in @code{VAX_Float}
22633 This set of declarations actually appears in @code{System.Aux_DEC},
22635 the full set of additional floating-point declarations provided in
22636 the HP Ada version of package @code{System}.
22637 This and similar declarations may be accessed in a user program
22638 by using pragma @code{Extend_System}. The use of this
22639 pragma, and the related pragma @code{Long_Float} is described in further
22640 detail in the following section.
22642 @node Pragmas Float_Representation and Long_Float
22643 @subsection Pragmas @code{Float_Representation} and @code{Long_Float}
22646 HP Ada provides the pragma @code{Float_Representation}, which
22647 acts as a program library switch to allow control over
22648 the internal representation chosen for the predefined
22649 floating-point types declared in the package @code{Standard}.
22650 The format of this pragma is as follows:
22652 @smallexample @c ada
22654 pragma Float_Representation(VAX_Float | IEEE_Float);
22659 This pragma controls the representation of floating-point
22664 @code{VAX_Float} specifies that floating-point
22665 types are represented by default with the VAX system hardware types
22666 @code{F-floating}, @code{D-floating}, @code{G-floating}.
22667 Note that the @code{H-floating}
22668 type was available only on VAX systems, and is not available
22669 in either HP Ada or GNAT.
22672 @code{IEEE_Float} specifies that floating-point
22673 types are represented by default with the IEEE single and
22674 double floating-point types.
22678 GNAT provides an identical implementation of the pragma
22679 @code{Float_Representation}, except that it functions as a
22680 configuration pragma. Note that the
22681 notion of configuration pragma corresponds closely to the
22682 HP Ada notion of a program library switch.
22684 When no pragma is used in GNAT, the default is @code{IEEE_Float},
22686 from HP Ada 83, where the default is @code{VAX_Float}. In addition, the
22687 predefined libraries in GNAT are built using @code{IEEE_Float}, so it is not
22688 advisable to change the format of numbers passed to standard library
22689 routines, and if necessary explicit type conversions may be needed.
22691 The use of @code{IEEE_Float} is recommended in GNAT since it is more
22692 efficient, and (given that it conforms to an international standard)
22693 potentially more portable.
22694 The situation in which @code{VAX_Float} may be useful is in interfacing
22695 to existing code and data that expect the use of @code{VAX_Float}.
22696 In such a situation use the predefined @code{VAX_Float}
22697 types in package @code{System}, as extended by
22698 @code{Extend_System}. For example, use @code{System.F_Float}
22699 to specify the 32-bit @code{F-Float} format.
22702 On OpenVMS systems, HP Ada provides the pragma @code{Long_Float}
22703 to allow control over the internal representation chosen
22704 for the predefined type @code{Long_Float} and for floating-point
22705 type declarations with digits specified in the range 7 .. 15.
22706 The format of this pragma is as follows:
22708 @smallexample @c ada
22710 pragma Long_Float (D_FLOAT | G_FLOAT);
22714 @node Fixed-Point Types and Representations
22715 @subsection Fixed-Point Types and Representations
22718 On HP Ada for OpenVMS Alpha systems, rounding is
22719 away from zero for both positive and negative numbers.
22720 Therefore, @code{+0.5} rounds to @code{1},
22721 and @code{-0.5} rounds to @code{-1}.
22723 On GNAT the results of operations
22724 on fixed-point types are in accordance with the Ada
22725 rules. In particular, results of operations on decimal
22726 fixed-point types are truncated.
22728 @node Record and Array Component Alignment
22729 @subsection Record and Array Component Alignment
22732 On HP Ada for OpenVMS Alpha, all non-composite components
22733 are aligned on natural boundaries. For example, 1-byte
22734 components are aligned on byte boundaries, 2-byte
22735 components on 2-byte boundaries, 4-byte components on 4-byte
22736 byte boundaries, and so on. The OpenVMS Alpha hardware
22737 runs more efficiently with naturally aligned data.
22739 On GNAT, alignment rules are compatible
22740 with HP Ada for OpenVMS Alpha.
22742 @node Address Clauses
22743 @subsection Address Clauses
22746 In HP Ada and GNAT, address clauses are supported for
22747 objects and imported subprograms.
22748 The predefined type @code{System.Address} is a private type
22749 in both compilers on Alpha OpenVMS, with the same representation
22750 (it is simply a machine pointer). Addition, subtraction, and comparison
22751 operations are available in the standard Ada package
22752 @code{System.Storage_Elements}, or in package @code{System}
22753 if it is extended to include @code{System.Aux_DEC} using a
22754 pragma @code{Extend_System} as previously described.
22756 Note that code that @code{with}'s both this extended package @code{System}
22757 and the package @code{System.Storage_Elements} should not @code{use}
22758 both packages, or ambiguities will result. In general it is better
22759 not to mix these two sets of facilities. The Ada package was
22760 designed specifically to provide the kind of features that HP Ada
22761 adds directly to package @code{System}.
22763 The type @code{System.Address} is a 64-bit integer type in GNAT for
22764 I64 OpenVMS. For more information,
22765 see @ref{Transitioning to 64-Bit GNAT for OpenVMS}.
22767 GNAT is compatible with HP Ada in its handling of address
22768 clauses, except for some limitations in
22769 the form of address clauses for composite objects with
22770 initialization. Such address clauses are easily replaced
22771 by the use of an explicitly-defined constant as described
22772 in the Ada Reference Manual (13.1(22)). For example, the sequence
22775 @smallexample @c ada
22777 X, Y : Integer := Init_Func;
22778 Q : String (X .. Y) := "abc";
22780 for Q'Address use Compute_Address;
22785 will be rejected by GNAT, since the address cannot be computed at the time
22786 that @code{Q} is declared. To achieve the intended effect, write instead:
22788 @smallexample @c ada
22791 X, Y : Integer := Init_Func;
22792 Q_Address : constant Address := Compute_Address;
22793 Q : String (X .. Y) := "abc";
22795 for Q'Address use Q_Address;
22801 which will be accepted by GNAT (and other Ada compilers), and is also
22802 compatible with Ada 83. A fuller description of the restrictions
22803 on address specifications is found in @ref{Top, GNAT Reference Manual,
22804 About This Guide, gnat_rm, GNAT Reference Manual}.
22806 @node Other Representation Clauses
22807 @subsection Other Representation Clauses
22810 GNAT implements in a compatible manner all the representation
22811 clauses supported by HP Ada. In addition, GNAT
22812 implements the representation clause forms that were introduced in Ada 95,
22813 including @code{COMPONENT_SIZE} and @code{SIZE} clauses for objects.
22815 @node The Package STANDARD
22816 @section The Package @code{STANDARD}
22819 The package @code{STANDARD}, as implemented by HP Ada, is fully
22820 described in the @cite{Ada Reference Manual} and in the
22821 @cite{HP Ada Language Reference Manual}. As implemented by GNAT, the
22822 package @code{STANDARD} is described in the @cite{Ada Reference Manual}.
22824 In addition, HP Ada supports the Latin-1 character set in
22825 the type @code{CHARACTER}. GNAT supports the Latin-1 character set
22826 in the type @code{CHARACTER} and also Unicode (ISO 10646 BMP) in
22827 the type @code{WIDE_CHARACTER}.
22829 The floating-point types supported by GNAT are those
22830 supported by HP Ada, but the defaults are different, and are controlled by
22831 pragmas. See @ref{Floating-Point Types and Representations}, for details.
22833 @node The Package SYSTEM
22834 @section The Package @code{SYSTEM}
22837 HP Ada provides a specific version of the package
22838 @code{SYSTEM} for each platform on which the language is implemented.
22839 For the complete spec of the package @code{SYSTEM}, see
22840 Appendix F of the @cite{HP Ada Language Reference Manual}.
22842 On HP Ada, the package @code{SYSTEM} includes the following conversion
22845 @item @code{TO_ADDRESS(INTEGER)}
22847 @item @code{TO_ADDRESS(UNSIGNED_LONGWORD)}
22849 @item @code{TO_ADDRESS(}@i{universal_integer}@code{)}
22851 @item @code{TO_INTEGER(ADDRESS)}
22853 @item @code{TO_UNSIGNED_LONGWORD(ADDRESS)}
22855 @item Function @code{IMPORT_VALUE return UNSIGNED_LONGWORD} and the
22856 functions @code{IMPORT_ADDRESS} and @code{IMPORT_LARGEST_VALUE}
22860 By default, GNAT supplies a version of @code{SYSTEM} that matches
22861 the definition given in the @cite{Ada Reference Manual}.
22863 is a subset of the HP system definitions, which is as
22864 close as possible to the original definitions. The only difference
22865 is that the definition of @code{SYSTEM_NAME} is different:
22867 @smallexample @c ada
22869 type Name is (SYSTEM_NAME_GNAT);
22870 System_Name : constant Name := SYSTEM_NAME_GNAT;
22875 Also, GNAT adds the Ada declarations for
22876 @code{BIT_ORDER} and @code{DEFAULT_BIT_ORDER}.
22878 However, the use of the following pragma causes GNAT
22879 to extend the definition of package @code{SYSTEM} so that it
22880 encompasses the full set of HP-specific extensions,
22881 including the functions listed above:
22883 @smallexample @c ada
22885 pragma Extend_System (Aux_DEC);
22890 The pragma @code{Extend_System} is a configuration pragma that
22891 is most conveniently placed in the @file{gnat.adc} file. @xref{Pragma
22892 Extend_System,,, gnat_rm, GNAT Reference Manual}, for further details.
22894 HP Ada does not allow the recompilation of the package
22895 @code{SYSTEM}. Instead HP Ada provides several pragmas
22896 (@code{SYSTEM_NAME}, @code{STORAGE_UNIT}, and @code{MEMORY_SIZE})
22897 to modify values in the package @code{SYSTEM}.
22898 On OpenVMS Alpha systems, the pragma
22899 @code{SYSTEM_NAME} takes the enumeration literal @code{OPENVMS_AXP} as
22900 its single argument.
22902 GNAT does permit the recompilation of package @code{SYSTEM} using
22903 the special switch @option{-gnatg}, and this switch can be used if
22904 it is necessary to modify the definitions in @code{SYSTEM}. GNAT does
22905 not permit the specification of @code{SYSTEM_NAME}, @code{STORAGE_UNIT}
22906 or @code{MEMORY_SIZE} by any other means.
22908 On GNAT systems, the pragma @code{SYSTEM_NAME} takes the
22909 enumeration literal @code{SYSTEM_NAME_GNAT}.
22911 The definitions provided by the use of
22913 @smallexample @c ada
22914 pragma Extend_System (AUX_Dec);
22918 are virtually identical to those provided by the HP Ada 83 package
22919 @code{SYSTEM}. One important difference is that the name of the
22921 function for type @code{UNSIGNED_LONGWORD} is changed to
22922 @code{TO_ADDRESS_LONG}.
22923 @xref{Address Clauses,,, gnat_rm, GNAT Reference Manual}, for a
22924 discussion of why this change was necessary.
22927 The version of @code{TO_ADDRESS} taking a @i{universal_integer} argument
22929 an extension to Ada 83 not strictly compatible with the reference manual.
22930 GNAT, in order to be exactly compatible with the standard,
22931 does not provide this capability. In HP Ada 83, the
22932 point of this definition is to deal with a call like:
22934 @smallexample @c ada
22935 TO_ADDRESS (16#12777#);
22939 Normally, according to Ada 83 semantics, one would expect this to be
22940 ambiguous, since it matches both the @code{INTEGER} and
22941 @code{UNSIGNED_LONGWORD} forms of @code{TO_ADDRESS}.
22942 However, in HP Ada 83, there is no ambiguity, since the
22943 definition using @i{universal_integer} takes precedence.
22945 In GNAT, since the version with @i{universal_integer} cannot be supplied,
22947 not possible to be 100% compatible. Since there are many programs using
22948 numeric constants for the argument to @code{TO_ADDRESS}, the decision in
22950 to change the name of the function in the @code{UNSIGNED_LONGWORD} case,
22951 so the declarations provided in the GNAT version of @code{AUX_Dec} are:
22953 @smallexample @c ada
22954 function To_Address (X : Integer) return Address;
22955 pragma Pure_Function (To_Address);
22957 function To_Address_Long (X : Unsigned_Longword) return Address;
22958 pragma Pure_Function (To_Address_Long);
22962 This means that programs using @code{TO_ADDRESS} for
22963 @code{UNSIGNED_LONGWORD} must change the name to @code{TO_ADDRESS_LONG}.
22965 @node Tasking and Task-Related Features
22966 @section Tasking and Task-Related Features
22969 This section compares the treatment of tasking in GNAT
22970 and in HP Ada for OpenVMS Alpha.
22971 The GNAT description applies to both Alpha and I64 OpenVMS.
22972 For detailed information on tasking in
22973 HP Ada, see the @cite{HP Ada Language Reference Manual} and the
22974 relevant run-time reference manual.
22977 * Implementation of Tasks in HP Ada for OpenVMS Alpha Systems::
22978 * Assigning Task IDs::
22979 * Task IDs and Delays::
22980 * Task-Related Pragmas::
22981 * Scheduling and Task Priority::
22983 * External Interrupts::
22986 @node Implementation of Tasks in HP Ada for OpenVMS Alpha Systems
22987 @subsection Implementation of Tasks in HP Ada for OpenVMS Alpha Systems
22990 On OpenVMS Alpha systems, each Ada task (except a passive
22991 task) is implemented as a single stream of execution
22992 that is created and managed by the kernel. On these
22993 systems, HP Ada tasking support is based on DECthreads,
22994 an implementation of the POSIX standard for threads.
22996 Also, on OpenVMS Alpha systems, HP Ada tasks and foreign
22997 code that calls DECthreads routines can be used together.
22998 The interaction between Ada tasks and DECthreads routines
22999 can have some benefits. For example when on OpenVMS Alpha,
23000 HP Ada can call C code that is already threaded.
23002 GNAT uses the facilities of DECthreads,
23003 and Ada tasks are mapped to threads.
23005 @node Assigning Task IDs
23006 @subsection Assigning Task IDs
23009 The HP Ada Run-Time Library always assigns @code{%TASK 1} to
23010 the environment task that executes the main program. On
23011 OpenVMS Alpha systems, @code{%TASK 0} is often used for tasks
23012 that have been created but are not yet activated.
23014 On OpenVMS Alpha systems, task IDs are assigned at
23015 activation. On GNAT systems, task IDs are also assigned at
23016 task creation but do not have the same form or values as
23017 task ID values in HP Ada. There is no null task, and the
23018 environment task does not have a specific task ID value.
23020 @node Task IDs and Delays
23021 @subsection Task IDs and Delays
23024 On OpenVMS Alpha systems, tasking delays are implemented
23025 using Timer System Services. The Task ID is used for the
23026 identification of the timer request (the @code{REQIDT} parameter).
23027 If Timers are used in the application take care not to use
23028 @code{0} for the identification, because cancelling such a timer
23029 will cancel all timers and may lead to unpredictable results.
23031 @node Task-Related Pragmas
23032 @subsection Task-Related Pragmas
23035 Ada supplies the pragma @code{TASK_STORAGE}, which allows
23036 specification of the size of the guard area for a task
23037 stack. (The guard area forms an area of memory that has no
23038 read or write access and thus helps in the detection of
23039 stack overflow.) On OpenVMS Alpha systems, if the pragma
23040 @code{TASK_STORAGE} specifies a value of zero, a minimal guard
23041 area is created. In the absence of a pragma @code{TASK_STORAGE},
23042 a default guard area is created.
23044 GNAT supplies the following task-related pragma:
23047 @item @code{TASK_STORAGE}
23049 GNAT implements pragma @code{TASK_STORAGE} in the same way as HP Ada.
23050 Both HP Ada and GNAT supply the pragmas @code{PASSIVE},
23051 @code{SUPPRESS}, and @code{VOLATILE}.
23054 @node Scheduling and Task Priority
23055 @subsection Scheduling and Task Priority
23058 HP Ada implements the Ada language requirement that
23059 when two tasks are eligible for execution and they have
23060 different priorities, the lower priority task does not
23061 execute while the higher priority task is waiting. The HP
23062 Ada Run-Time Library keeps a task running until either the
23063 task is suspended or a higher priority task becomes ready.
23065 On OpenVMS Alpha systems, the default strategy is round-
23066 robin with preemption. Tasks of equal priority take turns
23067 at the processor. A task is run for a certain period of
23068 time and then placed at the tail of the ready queue for
23069 its priority level.
23071 HP Ada provides the implementation-defined pragma @code{TIME_SLICE},
23072 which can be used to enable or disable round-robin
23073 scheduling of tasks with the same priority.
23074 See the relevant HP Ada run-time reference manual for
23075 information on using the pragmas to control HP Ada task
23078 GNAT follows the scheduling rules of Annex D (Real-Time
23079 Annex) of the @cite{Ada Reference Manual}. In general, this
23080 scheduling strategy is fully compatible with HP Ada
23081 although it provides some additional constraints (as
23082 fully documented in Annex D).
23083 GNAT implements time slicing control in a manner compatible with
23084 HP Ada 83, by means of the pragma @code{Time_Slice}, whose semantics
23085 are identical to the HP Ada 83 pragma of the same name.
23086 Note that it is not possible to mix GNAT tasking and
23087 HP Ada 83 tasking in the same program, since the two run-time
23088 libraries are not compatible.
23090 @node The Task Stack
23091 @subsection The Task Stack
23094 In HP Ada, a task stack is allocated each time a
23095 non-passive task is activated. As soon as the task is
23096 terminated, the storage for the task stack is deallocated.
23097 If you specify a size of zero (bytes) with @code{T'STORAGE_SIZE},
23098 a default stack size is used. Also, regardless of the size
23099 specified, some additional space is allocated for task
23100 management purposes. On OpenVMS Alpha systems, at least
23101 one page is allocated.
23103 GNAT handles task stacks in a similar manner. In accordance with
23104 the Ada rules, it provides the pragma @code{STORAGE_SIZE} as
23105 an alternative method for controlling the task stack size.
23106 The specification of the attribute @code{T'STORAGE_SIZE} is also
23107 supported in a manner compatible with HP Ada.
23109 @node External Interrupts
23110 @subsection External Interrupts
23113 On HP Ada, external interrupts can be associated with task entries.
23114 GNAT is compatible with HP Ada in its handling of external interrupts.
23116 @node Pragmas and Pragma-Related Features
23117 @section Pragmas and Pragma-Related Features
23120 Both HP Ada and GNAT supply all language-defined pragmas
23121 as specified by the Ada 83 standard. GNAT also supplies all
23122 language-defined pragmas introduced by Ada 95 and Ada 2005.
23123 In addition, GNAT implements the implementation-defined pragmas
23127 @item @code{AST_ENTRY}
23129 @item @code{COMMON_OBJECT}
23131 @item @code{COMPONENT_ALIGNMENT}
23133 @item @code{EXPORT_EXCEPTION}
23135 @item @code{EXPORT_FUNCTION}
23137 @item @code{EXPORT_OBJECT}
23139 @item @code{EXPORT_PROCEDURE}
23141 @item @code{EXPORT_VALUED_PROCEDURE}
23143 @item @code{FLOAT_REPRESENTATION}
23147 @item @code{IMPORT_EXCEPTION}
23149 @item @code{IMPORT_FUNCTION}
23151 @item @code{IMPORT_OBJECT}
23153 @item @code{IMPORT_PROCEDURE}
23155 @item @code{IMPORT_VALUED_PROCEDURE}
23157 @item @code{INLINE_GENERIC}
23159 @item @code{INTERFACE_NAME}
23161 @item @code{LONG_FLOAT}
23163 @item @code{MAIN_STORAGE}
23165 @item @code{PASSIVE}
23167 @item @code{PSECT_OBJECT}
23169 @item @code{SHARE_GENERIC}
23171 @item @code{SUPPRESS_ALL}
23173 @item @code{TASK_STORAGE}
23175 @item @code{TIME_SLICE}
23181 These pragmas are all fully implemented, with the exception of @code{TITLE},
23182 @code{PASSIVE}, and @code{SHARE_GENERIC}, which are
23183 recognized, but which have no
23184 effect in GNAT. The effect of @code{PASSIVE} may be obtained by the
23185 use of Ada protected objects. In GNAT, all generics are inlined.
23187 Unlike HP Ada, the GNAT ``@code{EXPORT_}@i{subprogram}'' pragmas require
23188 a separate subprogram specification which must appear before the
23191 GNAT also supplies a number of implementation-defined pragmas including the
23195 @item @code{ABORT_DEFER}
23197 @item @code{ADA_83}
23199 @item @code{ADA_95}
23201 @item @code{ADA_05}
23203 @item @code{Ada_2005}
23205 @item @code{Ada_12}
23207 @item @code{Ada_2012}
23209 @item @code{ALLOW_INTEGER_ADDRESS}
23211 @item @code{ANNOTATE}
23213 @item @code{ASSERT}
23215 @item @code{C_PASS_BY_COPY}
23217 @item @code{CPP_CLASS}
23219 @item @code{CPP_CONSTRUCTOR}
23221 @item @code{CPP_DESTRUCTOR}
23225 @item @code{EXTEND_SYSTEM}
23227 @item @code{LINKER_ALIAS}
23229 @item @code{LINKER_SECTION}
23231 @item @code{MACHINE_ATTRIBUTE}
23233 @item @code{NO_RETURN}
23235 @item @code{PURE_FUNCTION}
23237 @item @code{SOURCE_FILE_NAME}
23239 @item @code{SOURCE_REFERENCE}
23241 @item @code{UNCHECKED_UNION}
23243 @item @code{UNIMPLEMENTED_UNIT}
23245 @item @code{UNIVERSAL_DATA}
23247 @item @code{UNSUPPRESS}
23249 @item @code{WARNINGS}
23251 @item @code{WEAK_EXTERNAL}
23255 For full details on these and other GNAT implementation-defined pragmas,
23256 see @ref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference
23260 * Restrictions on the Pragma INLINE::
23261 * Restrictions on the Pragma INTERFACE::
23262 * Restrictions on the Pragma SYSTEM_NAME::
23265 @node Restrictions on the Pragma INLINE
23266 @subsection Restrictions on Pragma @code{INLINE}
23269 HP Ada enforces the following restrictions on the pragma @code{INLINE}:
23271 @item Parameters cannot have a task type.
23273 @item Function results cannot be task types, unconstrained
23274 array types, or unconstrained types with discriminants.
23276 @item Bodies cannot declare the following:
23278 @item Subprogram body or stub (imported subprogram is allowed)
23282 @item Generic declarations
23284 @item Instantiations
23288 @item Access types (types derived from access types allowed)
23290 @item Array or record types
23292 @item Dependent tasks
23294 @item Direct recursive calls of subprogram or containing
23295 subprogram, directly or via a renaming
23301 In GNAT, the only restriction on pragma @code{INLINE} is that the
23302 body must occur before the call if both are in the same
23303 unit, and the size must be appropriately small. There are
23304 no other specific restrictions which cause subprograms to
23305 be incapable of being inlined.
23307 @node Restrictions on the Pragma INTERFACE
23308 @subsection Restrictions on Pragma @code{INTERFACE}
23311 The following restrictions on pragma @code{INTERFACE}
23312 are enforced by both HP Ada and GNAT:
23314 @item Languages accepted: Ada, Bliss, C, Fortran, Default.
23315 Default is the default on OpenVMS Alpha systems.
23317 @item Parameter passing: Language specifies default
23318 mechanisms but can be overridden with an @code{EXPORT} pragma.
23321 @item Ada: Use internal Ada rules.
23323 @item Bliss, C: Parameters must be mode @code{in}; cannot be
23324 record or task type. Result cannot be a string, an
23325 array, or a record.
23327 @item Fortran: Parameters cannot have a task type. Result cannot
23328 be a string, an array, or a record.
23333 GNAT is entirely upwards compatible with HP Ada, and in addition allows
23334 record parameters for all languages.
23336 @node Restrictions on the Pragma SYSTEM_NAME
23337 @subsection Restrictions on Pragma @code{SYSTEM_NAME}
23340 For HP Ada for OpenVMS Alpha, the enumeration literal
23341 for the type @code{NAME} is @code{OPENVMS_AXP}.
23342 In GNAT, the enumeration
23343 literal for the type @code{NAME} is @code{SYSTEM_NAME_GNAT}.
23345 @node Library of Predefined Units
23346 @section Library of Predefined Units
23349 A library of predefined units is provided as part of the
23350 HP Ada and GNAT implementations. HP Ada does not provide
23351 the package @code{MACHINE_CODE} but instead recommends importing
23354 The GNAT versions of the HP Ada Run-Time Library (@code{ADA$PREDEFINED:})
23355 units are taken from the OpenVMS Alpha version, not the OpenVMS VAX
23357 The HP Ada Predefined Library units are modified to remove post-Ada 83
23358 incompatibilities and to make them interoperable with GNAT
23359 (@pxref{Changes to DECLIB}, for details).
23360 The units are located in the @file{DECLIB} directory.
23362 The GNAT RTL is contained in
23363 the @file{ADALIB} directory, and
23364 the default search path is set up to find @code{DECLIB} units in preference
23365 to @code{ADALIB} units with the same name (@code{TEXT_IO},
23366 @code{SEQUENTIAL_IO}, and @code{DIRECT_IO}, for example).
23369 * Changes to DECLIB::
23372 @node Changes to DECLIB
23373 @subsection Changes to @code{DECLIB}
23376 The changes made to the HP Ada predefined library for GNAT and post-Ada 83
23377 compatibility are minor and include the following:
23380 @item Adjusting the location of pragmas and record representation
23381 clauses to obey Ada 95 (and thus Ada 2005) rules
23383 @item Adding the proper notation to generic formal parameters
23384 that take unconstrained types in instantiation
23386 @item Adding pragma @code{ELABORATE_BODY} to package specs
23387 that have package bodies not otherwise allowed
23389 @item Replacing occurrences of the identifier ``@code{PROTECTED}'' by
23390 ``@code{PROTECTD}''.
23391 Currently these are found only in the @code{STARLET} package spec.
23393 @item Changing @code{SYSTEM.ADDRESS} to @code{SYSTEM.SHORT_ADDRESS}
23394 where the address size is constrained to 32 bits.
23398 None of the above changes is visible to users.
23404 On OpenVMS Alpha, HP Ada provides the following strongly-typed bindings:
23407 @item Command Language Interpreter (CLI interface)
23409 @item DECtalk Run-Time Library (DTK interface)
23411 @item Librarian utility routines (LBR interface)
23413 @item General Purpose Run-Time Library (LIB interface)
23415 @item Math Run-Time Library (MTH interface)
23417 @item National Character Set Run-Time Library (NCS interface)
23419 @item Compiled Code Support Run-Time Library (OTS interface)
23421 @item Parallel Processing Run-Time Library (PPL interface)
23423 @item Screen Management Run-Time Library (SMG interface)
23425 @item Sort Run-Time Library (SOR interface)
23427 @item String Run-Time Library (STR interface)
23429 @item STARLET System Library
23432 @item X Window System Version 11R4 and 11R5 (X, XLIB interface)
23434 @item X Windows Toolkit (XT interface)
23436 @item X/Motif Version 1.1.3 and 1.2 (XM interface)
23440 GNAT provides implementations of these HP bindings in the @code{DECLIB}
23441 directory, on both the Alpha and I64 OpenVMS platforms.
23443 The X components of DECLIB compatibility package are located in a separate
23444 library, called XDECGNAT, which is not linked with by default; this library
23445 must be explicitly linked with any application that makes use of any X facilities,
23446 with a command similar to
23448 @code{GNAT MAKE USE_X /LINK /LIBRARY=XDECGNAT}
23450 The X/Motif bindings used to build @code{DECLIB} are whatever versions are
23452 HP Ada @file{ADA$PREDEFINED} directory with extension @file{.ADC}.
23453 A pragma @code{Linker_Options} has been added to packages @code{Xm},
23454 @code{Xt}, and @code{X_Lib}
23455 causing the default X/Motif sharable image libraries to be linked in. This
23456 is done via options files named @file{xm.opt}, @file{xt.opt}, and
23457 @file{x_lib.opt} (also located in the @file{DECLIB} directory).
23459 It may be necessary to edit these options files to update or correct the
23460 library names if, for example, the newer X/Motif bindings from
23461 @file{ADA$EXAMPLES}
23462 had been (previous to installing GNAT) copied and renamed to supersede the
23463 default @file{ADA$PREDEFINED} versions.
23466 * Shared Libraries and Options Files::
23467 * Interfaces to C::
23470 @node Shared Libraries and Options Files
23471 @subsection Shared Libraries and Options Files
23474 When using the HP Ada
23475 predefined X and Motif bindings, the linking with their sharable images is
23476 done automatically by @command{GNAT LINK}.
23477 When using other X and Motif bindings, you need
23478 to add the corresponding sharable images to the command line for
23479 @code{GNAT LINK}. When linking with shared libraries, or with
23480 @file{.OPT} files, you must
23481 also add them to the command line for @command{GNAT LINK}.
23483 A shared library to be used with GNAT is built in the same way as other
23484 libraries under VMS. The VMS Link command can be used in standard fashion.
23486 @node Interfaces to C
23487 @subsection Interfaces to C
23491 provides the following Ada types and operations:
23494 @item C types package (@code{C_TYPES})
23496 @item C strings (@code{C_TYPES.NULL_TERMINATED})
23498 @item Other_types (@code{SHORT_INT})
23502 Interfacing to C with GNAT, you can use the above approach
23503 described for HP Ada or the facilities of Annex B of
23504 the @cite{Ada Reference Manual} (packages @code{INTERFACES.C},
23505 @code{INTERFACES.C.STRINGS} and @code{INTERFACES.C.POINTERS}). For more
23506 information, see @ref{Interfacing to C,,, gnat_rm, GNAT Reference Manual}.
23508 The @option{-gnatF} qualifier forces default and explicit
23509 @code{External_Name} parameters in pragmas @code{Import} and @code{Export}
23510 to be uppercased for compatibility with the default behavior
23511 of HP C. The qualifier has no effect on @code{Link_Name} parameters.
23513 @node Main Program Definition
23514 @section Main Program Definition
23517 The following section discusses differences in the
23518 definition of main programs on HP Ada and GNAT.
23519 On HP Ada, main programs are defined to meet the
23520 following conditions:
23522 @item Procedure with no formal parameters (returns @code{0} upon
23525 @item Procedure with no formal parameters (returns @code{42} when
23526 an unhandled exception is raised)
23528 @item Function with no formal parameters whose returned value
23529 is of a discrete type
23531 @item Procedure with one @code{out} formal of a discrete type for
23532 which a specification of pragma @code{EXPORT_VALUED_PROCEDURE} is given.
23537 When declared with the pragma @code{EXPORT_VALUED_PROCEDURE},
23538 a main function or main procedure returns a discrete
23539 value whose size is less than 64 bits (32 on VAX systems),
23540 the value is zero- or sign-extended as appropriate.
23541 On GNAT, main programs are defined as follows:
23543 @item Must be a non-generic, parameterless subprogram that
23544 is either a procedure or function returning an Ada
23545 @code{STANDARD.INTEGER} (the predefined type)
23547 @item Cannot be a generic subprogram or an instantiation of a
23551 @node Implementation-Defined Attributes
23552 @section Implementation-Defined Attributes
23555 GNAT provides all HP Ada implementation-defined
23558 @node Compiler and Run-Time Interfacing
23559 @section Compiler and Run-Time Interfacing
23562 HP Ada provides the following qualifiers to pass options to the linker
23565 @item @option{/WAIT} and @option{/SUBMIT}
23567 @item @option{/COMMAND}
23569 @item @option{/@r{[}NO@r{]}MAP}
23571 @item @option{/OUTPUT=@var{file-spec}}
23573 @item @option{/@r{[}NO@r{]}DEBUG} and @option{/@r{[}NO@r{]}TRACEBACK}
23577 To pass options to the linker, GNAT provides the following
23581 @item @option{/EXECUTABLE=@var{exec-name}}
23583 @item @option{/VERBOSE}
23585 @item @option{/@r{[}NO@r{]}DEBUG} and @option{/@r{[}NO@r{]}TRACEBACK}
23589 For more information on these switches, see
23590 @ref{Switches for gnatlink}.
23591 In HP Ada, the command-line switch @option{/OPTIMIZE} is available
23592 to control optimization. HP Ada also supplies the
23595 @item @code{OPTIMIZE}
23597 @item @code{INLINE}
23599 @item @code{INLINE_GENERIC}
23601 @item @code{SUPPRESS_ALL}
23603 @item @code{PASSIVE}
23607 In GNAT, optimization is controlled strictly by command
23608 line parameters, as described in the corresponding section of this guide.
23609 The HP pragmas for control of optimization are
23610 recognized but ignored.
23612 Note that in GNAT, the default is optimization off, whereas in HP Ada
23613 the default is that optimization is turned on.
23615 @node Program Compilation and Library Management
23616 @section Program Compilation and Library Management
23619 HP Ada and GNAT provide a comparable set of commands to
23620 build programs. HP Ada also provides a program library,
23621 which is a concept that does not exist on GNAT. Instead,
23622 GNAT provides directories of sources that are compiled as
23625 The following table summarizes
23626 the HP Ada commands and provides
23627 equivalent GNAT commands. In this table, some GNAT
23628 equivalents reflect the fact that GNAT does not use the
23629 concept of a program library. Instead, it uses a model
23630 in which collections of source and object files are used
23631 in a manner consistent with other languages like C and
23632 Fortran. Therefore, standard system file commands are used
23633 to manipulate these elements. Those GNAT commands are marked with
23635 Note that, unlike HP Ada, none of the GNAT commands accepts wild cards.
23638 @multitable @columnfractions .35 .65
23640 @item @emph{HP Ada Command}
23641 @tab @emph{GNAT Equivalent / Description}
23643 @item @command{ADA}
23644 @tab @command{GNAT COMPILE}@*
23645 Invokes the compiler to compile one or more Ada source files.
23647 @item @command{ACS ATTACH}@*
23648 @tab [No equivalent]@*
23649 Switches control of terminal from current process running the program
23652 @item @command{ACS CHECK}
23653 @tab @command{GNAT MAKE /DEPENDENCY_LIST}@*
23654 Forms the execution closure of one
23655 or more compiled units and checks completeness and currency.
23657 @item @command{ACS COMPILE}
23658 @tab @command{GNAT MAKE /ACTIONS=COMPILE}@*
23659 Forms the execution closure of one or
23660 more specified units, checks completeness and currency,
23661 identifies units that have revised source files, compiles same,
23662 and recompiles units that are or will become obsolete.
23663 Also completes incomplete generic instantiations.
23665 @item @command{ACS COPY FOREIGN}
23667 Copies a foreign object file into the program library as a
23670 @item @command{ACS COPY UNIT}
23672 Copies a compiled unit from one program library to another.
23674 @item @command{ACS CREATE LIBRARY}
23675 @tab Create /directory (*)@*
23676 Creates a program library.
23678 @item @command{ACS CREATE SUBLIBRARY}
23679 @tab Create /directory (*)@*
23680 Creates a program sublibrary.
23682 @item @command{ACS DELETE LIBRARY}
23684 Deletes a program library and its contents.
23686 @item @command{ACS DELETE SUBLIBRARY}
23688 Deletes a program sublibrary and its contents.
23690 @item @command{ACS DELETE UNIT}
23691 @tab Delete file (*)@*
23692 On OpenVMS systems, deletes one or more compiled units from
23693 the current program library.
23695 @item @command{ACS DIRECTORY}
23696 @tab Directory (*)@*
23697 On OpenVMS systems, lists units contained in the current
23700 @item @command{ACS ENTER FOREIGN}
23702 Allows the import of a foreign body as an Ada library
23703 spec and enters a reference to a pointer.
23705 @item @command{ACS ENTER UNIT}
23707 Enters a reference (pointer) from the current program library to
23708 a unit compiled into another program library.
23710 @item @command{ACS EXIT}
23711 @tab [No equivalent]@*
23712 Exits from the program library manager.
23714 @item @command{ACS EXPORT}
23716 Creates an object file that contains system-specific object code
23717 for one or more units. With GNAT, object files can simply be copied
23718 into the desired directory.
23720 @item @command{ACS EXTRACT SOURCE}
23722 Allows access to the copied source file for each Ada compilation unit
23724 @item @command{ACS HELP}
23725 @tab @command{HELP GNAT}@*
23726 Provides online help.
23728 @item @command{ACS LINK}
23729 @tab @command{GNAT LINK}@*
23730 Links an object file containing Ada units into an executable file.
23732 @item @command{ACS LOAD}
23734 Loads (partially compiles) Ada units into the program library.
23735 Allows loading a program from a collection of files into a library
23736 without knowing the relationship among units.
23738 @item @command{ACS MERGE}
23740 Merges into the current program library, one or more units from
23741 another library where they were modified.
23743 @item @command{ACS RECOMPILE}
23744 @tab @command{GNAT MAKE /ACTIONS=COMPILE}@*
23745 Recompiles from external or copied source files any obsolete
23746 unit in the closure. Also, completes any incomplete generic
23749 @item @command{ACS REENTER}
23750 @tab @command{GNAT MAKE}@*
23751 Reenters current references to units compiled after last entered
23752 with the @command{ACS ENTER UNIT} command.
23754 @item @command{ACS SET LIBRARY}
23755 @tab Set default (*)@*
23756 Defines a program library to be the compilation context as well
23757 as the target library for compiler output and commands in general.
23759 @item @command{ACS SET PRAGMA}
23760 @tab Edit @file{gnat.adc} (*)@*
23761 Redefines specified values of the library characteristics
23762 @code{LONG_ FLOAT}, @code{MEMORY_SIZE}, @code{SYSTEM_NAME},
23763 and @code{Float_Representation}.
23765 @item @command{ACS SET SOURCE}
23766 @tab Define @code{ADA_INCLUDE_PATH} path (*)@*
23767 Defines the source file search list for the @command{ACS COMPILE} command.
23769 @item @command{ACS SHOW LIBRARY}
23770 @tab Directory (*)@*
23771 Lists information about one or more program libraries.
23773 @item @command{ACS SHOW PROGRAM}
23774 @tab [No equivalent]@*
23775 Lists information about the execution closure of one or
23776 more units in the program library.
23778 @item @command{ACS SHOW SOURCE}
23779 @tab Show logical @code{ADA_INCLUDE_PATH}@*
23780 Shows the source file search used when compiling units.
23782 @item @command{ACS SHOW VERSION}
23783 @tab Compile with @option{VERBOSE} option
23784 Displays the version number of the compiler and program library
23787 @item @command{ACS SPAWN}
23788 @tab [No equivalent]@*
23789 Creates a subprocess of the current process (same as @command{DCL SPAWN}
23792 @item @command{ACS VERIFY}
23793 @tab [No equivalent]@*
23794 Performs a series of consistency checks on a program library to
23795 determine whether the library structure and library files are in
23802 @section Input-Output
23805 On OpenVMS Alpha systems, HP Ada uses OpenVMS Record
23806 Management Services (RMS) to perform operations on
23810 HP Ada and GNAT predefine an identical set of input-
23811 output packages. To make the use of the
23812 generic @code{TEXT_IO} operations more convenient, HP Ada
23813 provides predefined library packages that instantiate the
23814 integer and floating-point operations for the predefined
23815 integer and floating-point types as shown in the following table.
23817 @multitable @columnfractions .45 .55
23818 @item @emph{Package Name} @tab Instantiation
23820 @item @code{INTEGER_TEXT_IO}
23821 @tab @code{INTEGER_IO(INTEGER)}
23823 @item @code{SHORT_INTEGER_TEXT_IO}
23824 @tab @code{INTEGER_IO(SHORT_INTEGER)}
23826 @item @code{SHORT_SHORT_INTEGER_TEXT_IO}
23827 @tab @code{INTEGER_IO(SHORT_SHORT_INTEGER)}
23829 @item @code{FLOAT_TEXT_IO}
23830 @tab @code{FLOAT_IO(FLOAT)}
23832 @item @code{LONG_FLOAT_TEXT_IO}
23833 @tab @code{FLOAT_IO(LONG_FLOAT)}
23837 The HP Ada predefined packages and their operations
23838 are implemented using OpenVMS Alpha files and input-output
23839 facilities. HP Ada supports asynchronous input-output on OpenVMS Alpha.
23840 Familiarity with the following is recommended:
23842 @item RMS file organizations and access methods
23844 @item OpenVMS file specifications and directories
23846 @item OpenVMS File Definition Language (FDL)
23850 GNAT provides I/O facilities that are completely
23851 compatible with HP Ada. The distribution includes the
23852 standard HP Ada versions of all I/O packages, operating
23853 in a manner compatible with HP Ada. In particular, the
23854 following packages are by default the HP Ada (Ada 83)
23855 versions of these packages rather than the renamings
23856 suggested in Annex J of the Ada Reference Manual:
23858 @item @code{TEXT_IO}
23860 @item @code{SEQUENTIAL_IO}
23862 @item @code{DIRECT_IO}
23866 The use of the standard child package syntax (for
23867 example, @code{ADA.TEXT_IO}) retrieves the post-Ada 83 versions of these
23869 GNAT provides HP-compatible predefined instantiations
23870 of the @code{TEXT_IO} packages, and also
23871 provides the standard predefined instantiations required
23872 by the @cite{Ada Reference Manual}.
23874 For further information on how GNAT interfaces to the file
23875 system or how I/O is implemented in programs written in
23876 mixed languages, see @ref{Implementation of the Standard I/O,,,
23877 gnat_rm, GNAT Reference Manual}.
23878 This chapter covers the following:
23880 @item Standard I/O packages
23882 @item @code{FORM} strings
23884 @item @code{ADA.DIRECT_IO}
23886 @item @code{ADA.SEQUENTIAL_IO}
23888 @item @code{ADA.TEXT_IO}
23890 @item Stream pointer positioning
23892 @item Reading and writing non-regular files
23894 @item @code{GET_IMMEDIATE}
23896 @item Treating @code{TEXT_IO} files as streams
23903 @node Implementation Limits
23904 @section Implementation Limits
23907 The following table lists implementation limits for HP Ada
23909 @multitable @columnfractions .60 .20 .20
23911 @item @emph{Compilation Parameter}
23916 @item In a subprogram or entry declaration, maximum number of
23917 formal parameters that are of an unconstrained record type
23922 @item Maximum identifier length (number of characters)
23927 @item Maximum number of characters in a source line
23932 @item Maximum collection size (number of bytes)
23937 @item Maximum number of discriminants for a record type
23942 @item Maximum number of formal parameters in an entry or
23943 subprogram declaration
23948 @item Maximum number of dimensions in an array type
23953 @item Maximum number of library units and subunits in a compilation.
23958 @item Maximum number of library units and subunits in an execution.
23963 @item Maximum number of objects declared with the pragma @code{COMMON_OBJECT}
23964 or @code{PSECT_OBJECT}
23969 @item Maximum number of enumeration literals in an enumeration type
23975 @item Maximum number of lines in a source file
23980 @item Maximum number of bits in any object
23985 @item Maximum size of the static portion of a stack frame (approximate)
23990 @node Tools and Utilities
23991 @section Tools and Utilities
23994 The following table lists some of the OpenVMS development tools
23995 available for HP Ada, and the corresponding tools for
23996 use with @value{EDITION} on Alpha and I64 platforms.
23997 Aside from the debugger, all the OpenVMS tools identified are part
23998 of the DECset package.
24001 @c Specify table in TeX since Texinfo does a poor job
24005 \settabs\+Language-Sensitive Editor\quad
24006 &Product with HP Ada\quad
24009 &\it Product with HP Ada
24010 & \it Product with @value{EDITION}\cr
24012 \+Code Management System
24016 \+Language-Sensitive Editor
24018 & emacs or HP LSE (Alpha)\cr
24028 & OpenVMS Debug (I64)\cr
24030 \+Source Code Analyzer /
24047 \+Coverage Analyzer
24051 \+Module Management
24053 & Not applicable\cr
24063 @c This is the Texinfo version of the table. It renders poorly in pdf, hence
24064 @c the TeX version above for the printed version
24066 @c @multitable @columnfractions .3 .4 .4
24067 @multitable {Source Code Analyzer /}{Tool with HP Ada}{Tool with @value{EDITION}}
24069 @tab @i{Tool with HP Ada}
24070 @tab @i{Tool with @value{EDITION}}
24071 @item Code Management@*System
24074 @item Language-Sensitive@*Editor
24076 @tab emacs or HP LSE (Alpha)
24085 @tab OpenVMS Debug (I64)
24086 @item Source Code Analyzer /@*Cross Referencer
24090 @tab HP Digital Test@*Manager (DTM)
24092 @item Performance and@*Coverage Analyzer
24095 @item Module Management@*System
24097 @tab Not applicable
24104 @c **************************************
24105 @node Platform-Specific Information for the Run-Time Libraries
24106 @appendix Platform-Specific Information for the Run-Time Libraries
24107 @cindex Tasking and threads libraries
24108 @cindex Threads libraries and tasking
24109 @cindex Run-time libraries (platform-specific information)
24112 The GNAT run-time implementation may vary with respect to both the
24113 underlying threads library and the exception handling scheme.
24114 For threads support, one or more of the following are supplied:
24116 @item @b{native threads library}, a binding to the thread package from
24117 the underlying operating system
24119 @item @b{pthreads library} (Sparc Solaris only), a binding to the Solaris
24120 POSIX thread package
24124 For exception handling, either or both of two models are supplied:
24126 @item @b{Zero-Cost Exceptions} (``ZCX''),@footnote{
24127 Most programs should experience a substantial speed improvement by
24128 being compiled with a ZCX run-time.
24129 This is especially true for
24130 tasking applications or applications with many exception handlers.}
24131 @cindex Zero-Cost Exceptions
24132 @cindex ZCX (Zero-Cost Exceptions)
24133 which uses binder-generated tables that
24134 are interrogated at run time to locate a handler
24136 @item @b{setjmp / longjmp} (``SJLJ''),
24137 @cindex setjmp/longjmp Exception Model
24138 @cindex SJLJ (setjmp/longjmp Exception Model)
24139 which uses dynamically-set data to establish
24140 the set of handlers
24144 This appendix summarizes which combinations of threads and exception support
24145 are supplied on various GNAT platforms.
24146 It then shows how to select a particular library either
24147 permanently or temporarily,
24148 explains the properties of (and tradeoffs among) the various threads
24149 libraries, and provides some additional
24150 information about several specific platforms.
24153 * Summary of Run-Time Configurations::
24154 * Specifying a Run-Time Library::
24155 * Choosing the Scheduling Policy::
24156 * Solaris-Specific Considerations::
24157 * Linux-Specific Considerations::
24158 * AIX-Specific Considerations::
24159 * RTX-Specific Considerations::
24160 * HP-UX-Specific Considerations::
24163 @node Summary of Run-Time Configurations
24164 @section Summary of Run-Time Configurations
24166 @multitable @columnfractions .30 .70
24167 @item @b{alpha-openvms}
24168 @item @code{@ @ }@i{rts-native (default)}
24169 @item @code{@ @ @ @ }Tasking @tab native VMS threads
24170 @item @code{@ @ @ @ }Exceptions @tab ZCX
24172 @item @code{@ @ }@i{rts-sjlj}
24173 @item @code{@ @ @ @ }Tasking @tab native TRU64 threads
24174 @item @code{@ @ @ @ }Exceptions @tab SJLJ
24176 @item @b{ia64-hp_linux}
24177 @item @code{@ @ }@i{rts-native (default)}
24178 @item @code{@ @ @ @ }Tasking @tab pthread library
24179 @item @code{@ @ @ @ }Exceptions @tab ZCX
24181 @item @b{ia64-hpux}
24182 @item @code{@ @ }@i{rts-native (default)}
24183 @item @code{@ @ @ @ }Tasking @tab native HP-UX threads
24184 @item @code{@ @ @ @ }Exceptions @tab SJLJ
24186 @item @b{ia64-openvms}
24187 @item @code{@ @ }@i{rts-native (default)}
24188 @item @code{@ @ @ @ }Tasking @tab native VMS threads
24189 @item @code{@ @ @ @ }Exceptions @tab ZCX
24191 @item @b{ia64-sgi_linux}
24192 @item @code{@ @ }@i{rts-native (default)}
24193 @item @code{@ @ @ @ }Tasking @tab pthread library
24194 @item @code{@ @ @ @ }Exceptions @tab ZCX
24197 @item @code{@ @ }@i{rts-native (default)}
24198 @item @code{@ @ @ @ }Tasking @tab native HP-UX threads
24199 @item @code{@ @ @ @ }Exceptions @tab ZCX
24201 @item @code{@ @ }@i{rts-sjlj}
24202 @item @code{@ @ @ @ }Tasking @tab native HP-UX threads
24203 @item @code{@ @ @ @ }Exceptions @tab SJLJ
24206 @item @code{@ @ }@i{rts-native (default)}
24207 @item @code{@ @ @ @ }Tasking @tab native AIX threads
24208 @item @code{@ @ @ @ }Exceptions @tab ZCX
24210 @item @code{@ @ }@i{rts-sjlj}
24211 @item @code{@ @ @ @ }Tasking @tab native AIX threads
24212 @item @code{@ @ @ @ }Exceptions @tab SJLJ
24214 @item @b{ppc-darwin}
24215 @item @code{@ @ }@i{rts-native (default)}
24216 @item @code{@ @ @ @ }Tasking @tab native MacOS threads
24217 @item @code{@ @ @ @ }Exceptions @tab ZCX
24219 @item @b{sparc-solaris} @tab
24220 @item @code{@ @ }@i{rts-native (default)}
24221 @item @code{@ @ @ @ }Tasking @tab native Solaris threads library
24222 @item @code{@ @ @ @ }Exceptions @tab ZCX
24224 @item @code{@ @ }@i{rts-pthread}
24225 @item @code{@ @ @ @ }Tasking @tab pthread library
24226 @item @code{@ @ @ @ }Exceptions @tab ZCX
24228 @item @code{@ @ }@i{rts-sjlj}
24229 @item @code{@ @ @ @ }Tasking @tab native Solaris threads library
24230 @item @code{@ @ @ @ }Exceptions @tab SJLJ
24232 @item @b{sparc64-solaris} @tab
24233 @item @code{@ @ }@i{rts-native (default)}
24234 @item @code{@ @ @ @ }Tasking @tab native Solaris threads library
24235 @item @code{@ @ @ @ }Exceptions @tab ZCX
24237 @item @b{x86-linux}
24238 @item @code{@ @ }@i{rts-native (default)}
24239 @item @code{@ @ @ @ }Tasking @tab pthread library
24240 @item @code{@ @ @ @ }Exceptions @tab ZCX
24242 @item @code{@ @ }@i{rts-sjlj}
24243 @item @code{@ @ @ @ }Tasking @tab pthread library
24244 @item @code{@ @ @ @ }Exceptions @tab SJLJ
24247 @item @code{@ @ }@i{rts-native (default)}
24248 @item @code{@ @ @ @ }Tasking @tab native LynxOS threads
24249 @item @code{@ @ @ @ }Exceptions @tab SJLJ
24251 @item @b{x86-solaris}
24252 @item @code{@ @ }@i{rts-native (default)}
24253 @item @code{@ @ @ @ }Tasking @tab native Solaris threads
24254 @item @code{@ @ @ @ }Exceptions @tab ZCX
24256 @item @code{@ @ }@i{rts-sjlj}
24257 @item @code{@ @ @ @ }Tasking @tab native Solaris threads library
24258 @item @code{@ @ @ @ }Exceptions @tab SJLJ
24260 @item @b{x86-windows}
24261 @item @code{@ @ }@i{rts-native (default)}
24262 @item @code{@ @ @ @ }Tasking @tab native Win32 threads
24263 @item @code{@ @ @ @ }Exceptions @tab ZCX
24265 @item @code{@ @ }@i{rts-sjlj}
24266 @item @code{@ @ @ @ }Tasking @tab native Win32 threads
24267 @item @code{@ @ @ @ }Exceptions @tab SJLJ
24269 @item @b{x86-windows-rtx}
24270 @item @code{@ @ }@i{rts-rtx-rtss (default)}
24271 @item @code{@ @ @ @ }Tasking @tab RTX real-time subsystem RTSS threads (kernel mode)
24272 @item @code{@ @ @ @ }Exceptions @tab SJLJ
24274 @item @code{@ @ }@i{rts-rtx-w32}
24275 @item @code{@ @ @ @ }Tasking @tab RTX Win32 threads (user mode)
24276 @item @code{@ @ @ @ }Exceptions @tab ZCX
24278 @item @b{x86_64-linux}
24279 @item @code{@ @ }@i{rts-native (default)}
24280 @item @code{@ @ @ @ }Tasking @tab pthread library
24281 @item @code{@ @ @ @ }Exceptions @tab ZCX
24283 @item @code{@ @ }@i{rts-sjlj}
24284 @item @code{@ @ @ @ }Tasking @tab pthread library
24285 @item @code{@ @ @ @ }Exceptions @tab SJLJ
24289 @node Specifying a Run-Time Library
24290 @section Specifying a Run-Time Library
24293 The @file{adainclude} subdirectory containing the sources of the GNAT
24294 run-time library, and the @file{adalib} subdirectory containing the
24295 @file{ALI} files and the static and/or shared GNAT library, are located
24296 in the gcc target-dependent area:
24299 target=$prefix/lib/gcc/gcc-@i{dumpmachine}/gcc-@i{dumpversion}/
24303 As indicated above, on some platforms several run-time libraries are supplied.
24304 These libraries are installed in the target dependent area and
24305 contain a complete source and binary subdirectory. The detailed description
24306 below explains the differences between the different libraries in terms of
24307 their thread support.
24309 The default run-time library (when GNAT is installed) is @emph{rts-native}.
24310 This default run time is selected by the means of soft links.
24311 For example on x86-linux:
24317 +--- adainclude----------+
24319 +--- adalib-----------+ |
24321 +--- rts-native | |
24323 | +--- adainclude <---+
24325 | +--- adalib <----+
24336 If the @i{rts-sjlj} library is to be selected on a permanent basis,
24337 these soft links can be modified with the following commands:
24341 $ rm -f adainclude adalib
24342 $ ln -s rts-sjlj/adainclude adainclude
24343 $ ln -s rts-sjlj/adalib adalib
24347 Alternatively, you can specify @file{rts-sjlj/adainclude} in the file
24348 @file{$target/ada_source_path} and @file{rts-sjlj/adalib} in
24349 @file{$target/ada_object_path}.
24351 Selecting another run-time library temporarily can be
24352 achieved by using the @option{--RTS} switch, e.g., @option{--RTS=sjlj}
24353 @cindex @option{--RTS} option
24355 @node Choosing the Scheduling Policy
24356 @section Choosing the Scheduling Policy
24359 When using a POSIX threads implementation, you have a choice of several
24360 scheduling policies: @code{SCHED_FIFO},
24361 @cindex @code{SCHED_FIFO} scheduling policy
24363 @cindex @code{SCHED_RR} scheduling policy
24364 and @code{SCHED_OTHER}.
24365 @cindex @code{SCHED_OTHER} scheduling policy
24366 Typically, the default is @code{SCHED_OTHER}, while using @code{SCHED_FIFO}
24367 or @code{SCHED_RR} requires special (e.g., root) privileges.
24369 By default, GNAT uses the @code{SCHED_OTHER} policy. To specify
24371 @cindex @code{SCHED_FIFO} scheduling policy
24372 you can use one of the following:
24376 @code{pragma Time_Slice (0.0)}
24377 @cindex pragma Time_Slice
24379 the corresponding binder option @option{-T0}
24380 @cindex @option{-T0} option
24382 @code{pragma Task_Dispatching_Policy (FIFO_Within_Priorities)}
24383 @cindex pragma Task_Dispatching_Policy
24387 To specify @code{SCHED_RR},
24388 @cindex @code{SCHED_RR} scheduling policy
24389 you should use @code{pragma Time_Slice} with a
24390 value greater than @code{0.0}, or else use the corresponding @option{-T}
24393 @node Solaris-Specific Considerations
24394 @section Solaris-Specific Considerations
24395 @cindex Solaris Sparc threads libraries
24398 This section addresses some topics related to the various threads libraries
24402 * Solaris Threads Issues::
24405 @node Solaris Threads Issues
24406 @subsection Solaris Threads Issues
24409 GNAT under Solaris/Sparc 32 bits comes with an alternate tasking run-time
24410 library based on POSIX threads --- @emph{rts-pthread}.
24411 @cindex rts-pthread threads library
24412 This run-time library has the advantage of being mostly shared across all
24413 POSIX-compliant thread implementations, and it also provides under
24414 @w{Solaris 8} the @code{PTHREAD_PRIO_INHERIT}
24415 @cindex @code{PTHREAD_PRIO_INHERIT} policy (under rts-pthread)
24416 and @code{PTHREAD_PRIO_PROTECT}
24417 @cindex @code{PTHREAD_PRIO_PROTECT} policy (under rts-pthread)
24418 semantics that can be selected using the predefined pragma
24419 @code{Locking_Policy}
24420 @cindex pragma Locking_Policy (under rts-pthread)
24422 @code{Inheritance_Locking} and @code{Ceiling_Locking} as the policy.
24423 @cindex @code{Inheritance_Locking} (under rts-pthread)
24424 @cindex @code{Ceiling_Locking} (under rts-pthread)
24426 As explained above, the native run-time library is based on the Solaris thread
24427 library (@code{libthread}) and is the default library.
24429 When the Solaris threads library is used (this is the default), programs
24430 compiled with GNAT can automatically take advantage of
24431 and can thus execute on multiple processors.
24432 The user can alternatively specify a processor on which the program should run
24433 to emulate a single-processor system. The multiprocessor / uniprocessor choice
24435 setting the environment variable @env{GNAT_PROCESSOR}
24436 @cindex @env{GNAT_PROCESSOR} environment variable (on Sparc Solaris)
24437 to one of the following:
24441 Use the default configuration (run the program on all
24442 available processors) - this is the same as having @code{GNAT_PROCESSOR}
24446 Let the run-time implementation choose one processor and run the program on
24449 @item 0 .. Last_Proc
24450 Run the program on the specified processor.
24451 @code{Last_Proc} is equal to @code{_SC_NPROCESSORS_CONF - 1}
24452 (where @code{_SC_NPROCESSORS_CONF} is a system variable).
24455 @node Linux-Specific Considerations
24456 @section Linux-Specific Considerations
24457 @cindex Linux threads libraries
24460 On GNU/Linux without NPTL support (usually system with GNU C Library
24461 older than 2.3), the signal model is not POSIX compliant, which means
24462 that to send a signal to the process, you need to send the signal to all
24463 threads, e.g.@: by using @code{killpg()}.
24465 @node AIX-Specific Considerations
24466 @section AIX-Specific Considerations
24467 @cindex AIX resolver library
24470 On AIX, the resolver library initializes some internal structure on
24471 the first call to @code{get*by*} functions, which are used to implement
24472 @code{GNAT.Sockets.Get_Host_By_Name} and
24473 @code{GNAT.Sockets.Get_Host_By_Address}.
24474 If such initialization occurs within an Ada task, and the stack size for
24475 the task is the default size, a stack overflow may occur.
24477 To avoid this overflow, the user should either ensure that the first call
24478 to @code{GNAT.Sockets.Get_Host_By_Name} or
24479 @code{GNAT.Sockets.Get_Host_By_Addrss}
24480 occurs in the environment task, or use @code{pragma Storage_Size} to
24481 specify a sufficiently large size for the stack of the task that contains
24484 @node RTX-Specific Considerations
24485 @section RTX-Specific Considerations
24486 @cindex RTX libraries
24489 The Real-time Extension (RTX) to Windows is based on the Windows Win32
24490 API. Applications can be built to work in two different modes:
24494 Windows executables that run in Ring 3 to utilize memory protection
24495 (@emph{rts-rtx-w32}).
24498 Real-time subsystem (RTSS) executables that run in Ring 0, where
24499 performance can be optimized with RTSS applications taking precedent
24500 over all Windows applications (@emph{rts-rtx-rtss}). This mode requires
24501 the Microsoft linker to handle RTSS libraries.
24505 @node HP-UX-Specific Considerations
24506 @section HP-UX-Specific Considerations
24507 @cindex HP-UX Scheduling
24510 On HP-UX, appropriate privileges are required to change the scheduling
24511 parameters of a task. The calling process must have appropriate
24512 privileges or be a member of a group having @code{PRIV_RTSCHED} access to
24513 successfully change the scheduling parameters.
24515 By default, GNAT uses the @code{SCHED_HPUX} policy. To have access to the
24516 priority range 0-31 either the @code{FIFO_Within_Priorities} or the
24517 @code{Round_Robin_Within_Priorities} scheduling policies need to be set.
24519 To specify the @code{FIFO_Within_Priorities} scheduling policy you can use
24520 one of the following:
24524 @code{pragma Time_Slice (0.0)}
24525 @cindex pragma Time_Slice
24527 the corresponding binder option @option{-T0}
24528 @cindex @option{-T0} option
24530 @code{pragma Task_Dispatching_Policy (FIFO_Within_Priorities)}
24531 @cindex pragma Task_Dispatching_Policy
24535 To specify the @code{Round_Robin_Within_Priorities}, scheduling policy
24536 you should use @code{pragma Time_Slice} with a
24537 value greater than @code{0.0}, or use the corresponding @option{-T}
24538 binder option, or set the @code{pragma Task_Dispatching_Policy
24539 (Round_Robin_Within_Priorities)}.
24541 @c *******************************
24542 @node Example of Binder Output File
24543 @appendix Example of Binder Output File
24546 This Appendix displays the source code for @command{gnatbind}'s output
24547 file generated for a simple ``Hello World'' program.
24548 Comments have been added for clarification purposes.
24550 @smallexample @c adanocomment
24554 -- The package is called Ada_Main unless this name is actually used
24555 -- as a unit name in the partition, in which case some other unique
24559 package ada_main is
24561 Elab_Final_Code : Integer;
24562 pragma Import (C, Elab_Final_Code, "__gnat_inside_elab_final_code");
24564 -- The main program saves the parameters (argument count,
24565 -- argument values, environment pointer) in global variables
24566 -- for later access by other units including
24567 -- Ada.Command_Line.
24569 gnat_argc : Integer;
24570 gnat_argv : System.Address;
24571 gnat_envp : System.Address;
24573 -- The actual variables are stored in a library routine. This
24574 -- is useful for some shared library situations, where there
24575 -- are problems if variables are not in the library.
24577 pragma Import (C, gnat_argc);
24578 pragma Import (C, gnat_argv);
24579 pragma Import (C, gnat_envp);
24581 -- The exit status is similarly an external location
24583 gnat_exit_status : Integer;
24584 pragma Import (C, gnat_exit_status);
24586 GNAT_Version : constant String :=
24587 "GNAT Version: 6.0.0w (20061115)";
24588 pragma Export (C, GNAT_Version, "__gnat_version");
24590 -- This is the generated adafinal routine that performs
24591 -- finalization at the end of execution. In the case where
24592 -- Ada is the main program, this main program makes a call
24593 -- to adafinal at program termination.
24595 procedure adafinal;
24596 pragma Export (C, adafinal, "adafinal");
24598 -- This is the generated adainit routine that performs
24599 -- initialization at the start of execution. In the case
24600 -- where Ada is the main program, this main program makes
24601 -- a call to adainit at program startup.
24604 pragma Export (C, adainit, "adainit");
24606 -- This routine is called at the start of execution. It is
24607 -- a dummy routine that is used by the debugger to breakpoint
24608 -- at the start of execution.
24610 procedure Break_Start;
24611 pragma Import (C, Break_Start, "__gnat_break_start");
24613 -- This is the actual generated main program (it would be
24614 -- suppressed if the no main program switch were used). As
24615 -- required by standard system conventions, this program has
24616 -- the external name main.
24620 argv : System.Address;
24621 envp : System.Address)
24623 pragma Export (C, main, "main");
24625 -- The following set of constants give the version
24626 -- identification values for every unit in the bound
24627 -- partition. This identification is computed from all
24628 -- dependent semantic units, and corresponds to the
24629 -- string that would be returned by use of the
24630 -- Body_Version or Version attributes.
24632 type Version_32 is mod 2 ** 32;
24633 u00001 : constant Version_32 := 16#7880BEB3#;
24634 u00002 : constant Version_32 := 16#0D24CBD0#;
24635 u00003 : constant Version_32 := 16#3283DBEB#;
24636 u00004 : constant Version_32 := 16#2359F9ED#;
24637 u00005 : constant Version_32 := 16#664FB847#;
24638 u00006 : constant Version_32 := 16#68E803DF#;
24639 u00007 : constant Version_32 := 16#5572E604#;
24640 u00008 : constant Version_32 := 16#46B173D8#;
24641 u00009 : constant Version_32 := 16#156A40CF#;
24642 u00010 : constant Version_32 := 16#033DABE0#;
24643 u00011 : constant Version_32 := 16#6AB38FEA#;
24644 u00012 : constant Version_32 := 16#22B6217D#;
24645 u00013 : constant Version_32 := 16#68A22947#;
24646 u00014 : constant Version_32 := 16#18CC4A56#;
24647 u00015 : constant Version_32 := 16#08258E1B#;
24648 u00016 : constant Version_32 := 16#367D5222#;
24649 u00017 : constant Version_32 := 16#20C9ECA4#;
24650 u00018 : constant Version_32 := 16#50D32CB6#;
24651 u00019 : constant Version_32 := 16#39A8BB77#;
24652 u00020 : constant Version_32 := 16#5CF8FA2B#;
24653 u00021 : constant Version_32 := 16#2F1EB794#;
24654 u00022 : constant Version_32 := 16#31AB6444#;
24655 u00023 : constant Version_32 := 16#1574B6E9#;
24656 u00024 : constant Version_32 := 16#5109C189#;
24657 u00025 : constant Version_32 := 16#56D770CD#;
24658 u00026 : constant Version_32 := 16#02F9DE3D#;
24659 u00027 : constant Version_32 := 16#08AB6B2C#;
24660 u00028 : constant Version_32 := 16#3FA37670#;
24661 u00029 : constant Version_32 := 16#476457A0#;
24662 u00030 : constant Version_32 := 16#731E1B6E#;
24663 u00031 : constant Version_32 := 16#23C2E789#;
24664 u00032 : constant Version_32 := 16#0F1BD6A1#;
24665 u00033 : constant Version_32 := 16#7C25DE96#;
24666 u00034 : constant Version_32 := 16#39ADFFA2#;
24667 u00035 : constant Version_32 := 16#571DE3E7#;
24668 u00036 : constant Version_32 := 16#5EB646AB#;
24669 u00037 : constant Version_32 := 16#4249379B#;
24670 u00038 : constant Version_32 := 16#0357E00A#;
24671 u00039 : constant Version_32 := 16#3784FB72#;
24672 u00040 : constant Version_32 := 16#2E723019#;
24673 u00041 : constant Version_32 := 16#623358EA#;
24674 u00042 : constant Version_32 := 16#107F9465#;
24675 u00043 : constant Version_32 := 16#6843F68A#;
24676 u00044 : constant Version_32 := 16#63305874#;
24677 u00045 : constant Version_32 := 16#31E56CE1#;
24678 u00046 : constant Version_32 := 16#02917970#;
24679 u00047 : constant Version_32 := 16#6CCBA70E#;
24680 u00048 : constant Version_32 := 16#41CD4204#;
24681 u00049 : constant Version_32 := 16#572E3F58#;
24682 u00050 : constant Version_32 := 16#20729FF5#;
24683 u00051 : constant Version_32 := 16#1D4F93E8#;
24684 u00052 : constant Version_32 := 16#30B2EC3D#;
24685 u00053 : constant Version_32 := 16#34054F96#;
24686 u00054 : constant Version_32 := 16#5A199860#;
24687 u00055 : constant Version_32 := 16#0E7F912B#;
24688 u00056 : constant Version_32 := 16#5760634A#;
24689 u00057 : constant Version_32 := 16#5D851835#;
24691 -- The following Export pragmas export the version numbers
24692 -- with symbolic names ending in B (for body) or S
24693 -- (for spec) so that they can be located in a link. The
24694 -- information provided here is sufficient to track down
24695 -- the exact versions of units used in a given build.
24697 pragma Export (C, u00001, "helloB");
24698 pragma Export (C, u00002, "system__standard_libraryB");
24699 pragma Export (C, u00003, "system__standard_libraryS");
24700 pragma Export (C, u00004, "adaS");
24701 pragma Export (C, u00005, "ada__text_ioB");
24702 pragma Export (C, u00006, "ada__text_ioS");
24703 pragma Export (C, u00007, "ada__exceptionsB");
24704 pragma Export (C, u00008, "ada__exceptionsS");
24705 pragma Export (C, u00009, "gnatS");
24706 pragma Export (C, u00010, "gnat__heap_sort_aB");
24707 pragma Export (C, u00011, "gnat__heap_sort_aS");
24708 pragma Export (C, u00012, "systemS");
24709 pragma Export (C, u00013, "system__exception_tableB");
24710 pragma Export (C, u00014, "system__exception_tableS");
24711 pragma Export (C, u00015, "gnat__htableB");
24712 pragma Export (C, u00016, "gnat__htableS");
24713 pragma Export (C, u00017, "system__exceptionsS");
24714 pragma Export (C, u00018, "system__machine_state_operationsB");
24715 pragma Export (C, u00019, "system__machine_state_operationsS");
24716 pragma Export (C, u00020, "system__machine_codeS");
24717 pragma Export (C, u00021, "system__storage_elementsB");
24718 pragma Export (C, u00022, "system__storage_elementsS");
24719 pragma Export (C, u00023, "system__secondary_stackB");
24720 pragma Export (C, u00024, "system__secondary_stackS");
24721 pragma Export (C, u00025, "system__parametersB");
24722 pragma Export (C, u00026, "system__parametersS");
24723 pragma Export (C, u00027, "system__soft_linksB");
24724 pragma Export (C, u00028, "system__soft_linksS");
24725 pragma Export (C, u00029, "system__stack_checkingB");
24726 pragma Export (C, u00030, "system__stack_checkingS");
24727 pragma Export (C, u00031, "system__tracebackB");
24728 pragma Export (C, u00032, "system__tracebackS");
24729 pragma Export (C, u00033, "ada__streamsS");
24730 pragma Export (C, u00034, "ada__tagsB");
24731 pragma Export (C, u00035, "ada__tagsS");
24732 pragma Export (C, u00036, "system__string_opsB");
24733 pragma Export (C, u00037, "system__string_opsS");
24734 pragma Export (C, u00038, "interfacesS");
24735 pragma Export (C, u00039, "interfaces__c_streamsB");
24736 pragma Export (C, u00040, "interfaces__c_streamsS");
24737 pragma Export (C, u00041, "system__file_ioB");
24738 pragma Export (C, u00042, "system__file_ioS");
24739 pragma Export (C, u00043, "ada__finalizationB");
24740 pragma Export (C, u00044, "ada__finalizationS");
24741 pragma Export (C, u00045, "system__finalization_rootB");
24742 pragma Export (C, u00046, "system__finalization_rootS");
24743 pragma Export (C, u00047, "system__finalization_implementationB");
24744 pragma Export (C, u00048, "system__finalization_implementationS");
24745 pragma Export (C, u00049, "system__string_ops_concat_3B");
24746 pragma Export (C, u00050, "system__string_ops_concat_3S");
24747 pragma Export (C, u00051, "system__stream_attributesB");
24748 pragma Export (C, u00052, "system__stream_attributesS");
24749 pragma Export (C, u00053, "ada__io_exceptionsS");
24750 pragma Export (C, u00054, "system__unsigned_typesS");
24751 pragma Export (C, u00055, "system__file_control_blockS");
24752 pragma Export (C, u00056, "ada__finalization__list_controllerB");
24753 pragma Export (C, u00057, "ada__finalization__list_controllerS");
24755 -- BEGIN ELABORATION ORDER
24758 -- gnat.heap_sort_a (spec)
24759 -- gnat.heap_sort_a (body)
24760 -- gnat.htable (spec)
24761 -- gnat.htable (body)
24762 -- interfaces (spec)
24764 -- system.machine_code (spec)
24765 -- system.parameters (spec)
24766 -- system.parameters (body)
24767 -- interfaces.c_streams (spec)
24768 -- interfaces.c_streams (body)
24769 -- system.standard_library (spec)
24770 -- ada.exceptions (spec)
24771 -- system.exception_table (spec)
24772 -- system.exception_table (body)
24773 -- ada.io_exceptions (spec)
24774 -- system.exceptions (spec)
24775 -- system.storage_elements (spec)
24776 -- system.storage_elements (body)
24777 -- system.machine_state_operations (spec)
24778 -- system.machine_state_operations (body)
24779 -- system.secondary_stack (spec)
24780 -- system.stack_checking (spec)
24781 -- system.soft_links (spec)
24782 -- system.soft_links (body)
24783 -- system.stack_checking (body)
24784 -- system.secondary_stack (body)
24785 -- system.standard_library (body)
24786 -- system.string_ops (spec)
24787 -- system.string_ops (body)
24790 -- ada.streams (spec)
24791 -- system.finalization_root (spec)
24792 -- system.finalization_root (body)
24793 -- system.string_ops_concat_3 (spec)
24794 -- system.string_ops_concat_3 (body)
24795 -- system.traceback (spec)
24796 -- system.traceback (body)
24797 -- ada.exceptions (body)
24798 -- system.unsigned_types (spec)
24799 -- system.stream_attributes (spec)
24800 -- system.stream_attributes (body)
24801 -- system.finalization_implementation (spec)
24802 -- system.finalization_implementation (body)
24803 -- ada.finalization (spec)
24804 -- ada.finalization (body)
24805 -- ada.finalization.list_controller (spec)
24806 -- ada.finalization.list_controller (body)
24807 -- system.file_control_block (spec)
24808 -- system.file_io (spec)
24809 -- system.file_io (body)
24810 -- ada.text_io (spec)
24811 -- ada.text_io (body)
24813 -- END ELABORATION ORDER
24817 -- The following source file name pragmas allow the generated file
24818 -- names to be unique for different main programs. They are needed
24819 -- since the package name will always be Ada_Main.
24821 pragma Source_File_Name (ada_main, Spec_File_Name => "b~hello.ads");
24822 pragma Source_File_Name (ada_main, Body_File_Name => "b~hello.adb");
24824 -- Generated package body for Ada_Main starts here
24826 package body ada_main is
24828 -- The actual finalization is performed by calling the
24829 -- library routine in System.Standard_Library.Adafinal
24831 procedure Do_Finalize;
24832 pragma Import (C, Do_Finalize, "system__standard_library__adafinal");
24839 procedure adainit is
24841 -- These booleans are set to True once the associated unit has
24842 -- been elaborated. It is also used to avoid elaborating the
24843 -- same unit twice.
24846 pragma Import (Ada, E040, "interfaces__c_streams_E");
24849 pragma Import (Ada, E008, "ada__exceptions_E");
24852 pragma Import (Ada, E014, "system__exception_table_E");
24855 pragma Import (Ada, E053, "ada__io_exceptions_E");
24858 pragma Import (Ada, E017, "system__exceptions_E");
24861 pragma Import (Ada, E024, "system__secondary_stack_E");
24864 pragma Import (Ada, E030, "system__stack_checking_E");
24867 pragma Import (Ada, E028, "system__soft_links_E");
24870 pragma Import (Ada, E035, "ada__tags_E");
24873 pragma Import (Ada, E033, "ada__streams_E");
24876 pragma Import (Ada, E046, "system__finalization_root_E");
24879 pragma Import (Ada, E048, "system__finalization_implementation_E");
24882 pragma Import (Ada, E044, "ada__finalization_E");
24885 pragma Import (Ada, E057, "ada__finalization__list_controller_E");
24888 pragma Import (Ada, E055, "system__file_control_block_E");
24891 pragma Import (Ada, E042, "system__file_io_E");
24894 pragma Import (Ada, E006, "ada__text_io_E");
24896 -- Set_Globals is a library routine that stores away the
24897 -- value of the indicated set of global values in global
24898 -- variables within the library.
24900 procedure Set_Globals
24901 (Main_Priority : Integer;
24902 Time_Slice_Value : Integer;
24903 WC_Encoding : Character;
24904 Locking_Policy : Character;
24905 Queuing_Policy : Character;
24906 Task_Dispatching_Policy : Character;
24907 Adafinal : System.Address;
24908 Unreserve_All_Interrupts : Integer;
24909 Exception_Tracebacks : Integer);
24910 @findex __gnat_set_globals
24911 pragma Import (C, Set_Globals, "__gnat_set_globals");
24913 -- SDP_Table_Build is a library routine used to build the
24914 -- exception tables. See unit Ada.Exceptions in files
24915 -- a-except.ads/adb for full details of how zero cost
24916 -- exception handling works. This procedure, the call to
24917 -- it, and the two following tables are all omitted if the
24918 -- build is in longjmp/setjmp exception mode.
24920 @findex SDP_Table_Build
24921 @findex Zero Cost Exceptions
24922 procedure SDP_Table_Build
24923 (SDP_Addresses : System.Address;
24924 SDP_Count : Natural;
24925 Elab_Addresses : System.Address;
24926 Elab_Addr_Count : Natural);
24927 pragma Import (C, SDP_Table_Build, "__gnat_SDP_Table_Build");
24929 -- Table of Unit_Exception_Table addresses. Used for zero
24930 -- cost exception handling to build the top level table.
24932 ST : aliased constant array (1 .. 23) of System.Address := (
24934 Ada.Text_Io'UET_Address,
24935 Ada.Exceptions'UET_Address,
24936 Gnat.Heap_Sort_A'UET_Address,
24937 System.Exception_Table'UET_Address,
24938 System.Machine_State_Operations'UET_Address,
24939 System.Secondary_Stack'UET_Address,
24940 System.Parameters'UET_Address,
24941 System.Soft_Links'UET_Address,
24942 System.Stack_Checking'UET_Address,
24943 System.Traceback'UET_Address,
24944 Ada.Streams'UET_Address,
24945 Ada.Tags'UET_Address,
24946 System.String_Ops'UET_Address,
24947 Interfaces.C_Streams'UET_Address,
24948 System.File_Io'UET_Address,
24949 Ada.Finalization'UET_Address,
24950 System.Finalization_Root'UET_Address,
24951 System.Finalization_Implementation'UET_Address,
24952 System.String_Ops_Concat_3'UET_Address,
24953 System.Stream_Attributes'UET_Address,
24954 System.File_Control_Block'UET_Address,
24955 Ada.Finalization.List_Controller'UET_Address);
24957 -- Table of addresses of elaboration routines. Used for
24958 -- zero cost exception handling to make sure these
24959 -- addresses are included in the top level procedure
24962 EA : aliased constant array (1 .. 23) of System.Address := (
24963 adainit'Code_Address,
24964 Do_Finalize'Code_Address,
24965 Ada.Exceptions'Elab_Spec'Address,
24966 System.Exceptions'Elab_Spec'Address,
24967 Interfaces.C_Streams'Elab_Spec'Address,
24968 System.Exception_Table'Elab_Body'Address,
24969 Ada.Io_Exceptions'Elab_Spec'Address,
24970 System.Stack_Checking'Elab_Spec'Address,
24971 System.Soft_Links'Elab_Body'Address,
24972 System.Secondary_Stack'Elab_Body'Address,
24973 Ada.Tags'Elab_Spec'Address,
24974 Ada.Tags'Elab_Body'Address,
24975 Ada.Streams'Elab_Spec'Address,
24976 System.Finalization_Root'Elab_Spec'Address,
24977 Ada.Exceptions'Elab_Body'Address,
24978 System.Finalization_Implementation'Elab_Spec'Address,
24979 System.Finalization_Implementation'Elab_Body'Address,
24980 Ada.Finalization'Elab_Spec'Address,
24981 Ada.Finalization.List_Controller'Elab_Spec'Address,
24982 System.File_Control_Block'Elab_Spec'Address,
24983 System.File_Io'Elab_Body'Address,
24984 Ada.Text_Io'Elab_Spec'Address,
24985 Ada.Text_Io'Elab_Body'Address);
24987 -- Start of processing for adainit
24991 -- Call SDP_Table_Build to build the top level procedure
24992 -- table for zero cost exception handling (omitted in
24993 -- longjmp/setjmp mode).
24995 SDP_Table_Build (ST'Address, 23, EA'Address, 23);
24997 -- Call Set_Globals to record various information for
24998 -- this partition. The values are derived by the binder
24999 -- from information stored in the ali files by the compiler.
25001 @findex __gnat_set_globals
25003 (Main_Priority => -1,
25004 -- Priority of main program, -1 if no pragma Priority used
25006 Time_Slice_Value => -1,
25007 -- Time slice from Time_Slice pragma, -1 if none used
25009 WC_Encoding => 'b',
25010 -- Wide_Character encoding used, default is brackets
25012 Locking_Policy => ' ',
25013 -- Locking_Policy used, default of space means not
25014 -- specified, otherwise it is the first character of
25015 -- the policy name.
25017 Queuing_Policy => ' ',
25018 -- Queuing_Policy used, default of space means not
25019 -- specified, otherwise it is the first character of
25020 -- the policy name.
25022 Task_Dispatching_Policy => ' ',
25023 -- Task_Dispatching_Policy used, default of space means
25024 -- not specified, otherwise first character of the
25027 Adafinal => System.Null_Address,
25028 -- Address of Adafinal routine, not used anymore
25030 Unreserve_All_Interrupts => 0,
25031 -- Set true if pragma Unreserve_All_Interrupts was used
25033 Exception_Tracebacks => 0);
25034 -- Indicates if exception tracebacks are enabled
25036 Elab_Final_Code := 1;
25038 -- Now we have the elaboration calls for all units in the partition.
25039 -- The Elab_Spec and Elab_Body attributes generate references to the
25040 -- implicit elaboration procedures generated by the compiler for
25041 -- each unit that requires elaboration.
25044 Interfaces.C_Streams'Elab_Spec;
25048 Ada.Exceptions'Elab_Spec;
25051 System.Exception_Table'Elab_Body;
25055 Ada.Io_Exceptions'Elab_Spec;
25059 System.Exceptions'Elab_Spec;
25063 System.Stack_Checking'Elab_Spec;
25066 System.Soft_Links'Elab_Body;
25071 System.Secondary_Stack'Elab_Body;
25075 Ada.Tags'Elab_Spec;
25078 Ada.Tags'Elab_Body;
25082 Ada.Streams'Elab_Spec;
25086 System.Finalization_Root'Elab_Spec;
25090 Ada.Exceptions'Elab_Body;
25094 System.Finalization_Implementation'Elab_Spec;
25097 System.Finalization_Implementation'Elab_Body;
25101 Ada.Finalization'Elab_Spec;
25105 Ada.Finalization.List_Controller'Elab_Spec;
25109 System.File_Control_Block'Elab_Spec;
25113 System.File_Io'Elab_Body;
25117 Ada.Text_Io'Elab_Spec;
25120 Ada.Text_Io'Elab_Body;
25124 Elab_Final_Code := 0;
25132 procedure adafinal is
25141 -- main is actually a function, as in the ANSI C standard,
25142 -- defined to return the exit status. The three parameters
25143 -- are the argument count, argument values and environment
25146 @findex Main Program
25149 argv : System.Address;
25150 envp : System.Address)
25153 -- The initialize routine performs low level system
25154 -- initialization using a standard library routine which
25155 -- sets up signal handling and performs any other
25156 -- required setup. The routine can be found in file
25159 @findex __gnat_initialize
25160 procedure initialize;
25161 pragma Import (C, initialize, "__gnat_initialize");
25163 -- The finalize routine performs low level system
25164 -- finalization using a standard library routine. The
25165 -- routine is found in file a-final.c and in the standard
25166 -- distribution is a dummy routine that does nothing, so
25167 -- really this is a hook for special user finalization.
25169 @findex __gnat_finalize
25170 procedure finalize;
25171 pragma Import (C, finalize, "__gnat_finalize");
25173 -- We get to the main program of the partition by using
25174 -- pragma Import because if we try to with the unit and
25175 -- call it Ada style, then not only do we waste time
25176 -- recompiling it, but also, we don't really know the right
25177 -- switches (e.g.@: identifier character set) to be used
25180 procedure Ada_Main_Program;
25181 pragma Import (Ada, Ada_Main_Program, "_ada_hello");
25183 -- Start of processing for main
25186 -- Save global variables
25192 -- Call low level system initialization
25196 -- Call our generated Ada initialization routine
25200 -- This is the point at which we want the debugger to get
25205 -- Now we call the main program of the partition
25209 -- Perform Ada finalization
25213 -- Perform low level system finalization
25217 -- Return the proper exit status
25218 return (gnat_exit_status);
25221 -- This section is entirely comments, so it has no effect on the
25222 -- compilation of the Ada_Main package. It provides the list of
25223 -- object files and linker options, as well as some standard
25224 -- libraries needed for the link. The gnatlink utility parses
25225 -- this b~hello.adb file to read these comment lines to generate
25226 -- the appropriate command line arguments for the call to the
25227 -- system linker. The BEGIN/END lines are used for sentinels for
25228 -- this parsing operation.
25230 -- The exact file names will of course depend on the environment,
25231 -- host/target and location of files on the host system.
25233 @findex Object file list
25234 -- BEGIN Object file/option list
25237 -- -L/usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/
25238 -- /usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/libgnat.a
25239 -- END Object file/option list
25245 The Ada code in the above example is exactly what is generated by the
25246 binder. We have added comments to more clearly indicate the function
25247 of each part of the generated @code{Ada_Main} package.
25249 The code is standard Ada in all respects, and can be processed by any
25250 tools that handle Ada. In particular, it is possible to use the debugger
25251 in Ada mode to debug the generated @code{Ada_Main} package. For example,
25252 suppose that for reasons that you do not understand, your program is crashing
25253 during elaboration of the body of @code{Ada.Text_IO}. To locate this bug,
25254 you can place a breakpoint on the call:
25256 @smallexample @c ada
25257 Ada.Text_Io'Elab_Body;
25261 and trace the elaboration routine for this package to find out where
25262 the problem might be (more usually of course you would be debugging
25263 elaboration code in your own application).
25265 @node Elaboration Order Handling in GNAT
25266 @appendix Elaboration Order Handling in GNAT
25267 @cindex Order of elaboration
25268 @cindex Elaboration control
25271 * Elaboration Code::
25272 * Checking the Elaboration Order::
25273 * Controlling the Elaboration Order::
25274 * Controlling Elaboration in GNAT - Internal Calls::
25275 * Controlling Elaboration in GNAT - External Calls::
25276 * Default Behavior in GNAT - Ensuring Safety::
25277 * Treatment of Pragma Elaborate::
25278 * Elaboration Issues for Library Tasks::
25279 * Mixing Elaboration Models::
25280 * What to Do If the Default Elaboration Behavior Fails::
25281 * Elaboration for Indirect Calls::
25282 * Summary of Procedures for Elaboration Control::
25283 * Other Elaboration Order Considerations::
25284 * Determining the Chosen Elaboration Order::
25288 This chapter describes the handling of elaboration code in Ada and
25289 in GNAT, and discusses how the order of elaboration of program units can
25290 be controlled in GNAT, either automatically or with explicit programming
25293 @node Elaboration Code
25294 @section Elaboration Code
25297 Ada provides rather general mechanisms for executing code at elaboration
25298 time, that is to say before the main program starts executing. Such code arises
25302 @item Initializers for variables.
25303 Variables declared at the library level, in package specs or bodies, can
25304 require initialization that is performed at elaboration time, as in:
25305 @smallexample @c ada
25307 Sqrt_Half : Float := Sqrt (0.5);
25311 @item Package initialization code
25312 Code in a @code{BEGIN-END} section at the outer level of a package body is
25313 executed as part of the package body elaboration code.
25315 @item Library level task allocators
25316 Tasks that are declared using task allocators at the library level
25317 start executing immediately and hence can execute at elaboration time.
25321 Subprogram calls are possible in any of these contexts, which means that
25322 any arbitrary part of the program may be executed as part of the elaboration
25323 code. It is even possible to write a program which does all its work at
25324 elaboration time, with a null main program, although stylistically this
25325 would usually be considered an inappropriate way to structure
25328 An important concern arises in the context of elaboration code:
25329 we have to be sure that it is executed in an appropriate order. What we
25330 have is a series of elaboration code sections, potentially one section
25331 for each unit in the program. It is important that these execute
25332 in the correct order. Correctness here means that, taking the above
25333 example of the declaration of @code{Sqrt_Half},
25334 if some other piece of
25335 elaboration code references @code{Sqrt_Half},
25336 then it must run after the
25337 section of elaboration code that contains the declaration of
25340 There would never be any order of elaboration problem if we made a rule
25341 that whenever you @code{with} a unit, you must elaborate both the spec and body
25342 of that unit before elaborating the unit doing the @code{with}'ing:
25344 @smallexample @c ada
25348 package Unit_2 is @dots{}
25354 would require that both the body and spec of @code{Unit_1} be elaborated
25355 before the spec of @code{Unit_2}. However, a rule like that would be far too
25356 restrictive. In particular, it would make it impossible to have routines
25357 in separate packages that were mutually recursive.
25359 You might think that a clever enough compiler could look at the actual
25360 elaboration code and determine an appropriate correct order of elaboration,
25361 but in the general case, this is not possible. Consider the following
25364 In the body of @code{Unit_1}, we have a procedure @code{Func_1}
25366 the variable @code{Sqrt_1}, which is declared in the elaboration code
25367 of the body of @code{Unit_1}:
25369 @smallexample @c ada
25371 Sqrt_1 : Float := Sqrt (0.1);
25376 The elaboration code of the body of @code{Unit_1} also contains:
25378 @smallexample @c ada
25381 if expression_1 = 1 then
25382 Q := Unit_2.Func_2;
25389 @code{Unit_2} is exactly parallel,
25390 it has a procedure @code{Func_2} that references
25391 the variable @code{Sqrt_2}, which is declared in the elaboration code of
25392 the body @code{Unit_2}:
25394 @smallexample @c ada
25396 Sqrt_2 : Float := Sqrt (0.1);
25401 The elaboration code of the body of @code{Unit_2} also contains:
25403 @smallexample @c ada
25406 if expression_2 = 2 then
25407 Q := Unit_1.Func_1;
25414 Now the question is, which of the following orders of elaboration is
25439 If you carefully analyze the flow here, you will see that you cannot tell
25440 at compile time the answer to this question.
25441 If @code{expression_1} is not equal to 1,
25442 and @code{expression_2} is not equal to 2,
25443 then either order is acceptable, because neither of the function calls is
25444 executed. If both tests evaluate to true, then neither order is acceptable
25445 and in fact there is no correct order.
25447 If one of the two expressions is true, and the other is false, then one
25448 of the above orders is correct, and the other is incorrect. For example,
25449 if @code{expression_1} /= 1 and @code{expression_2} = 2,
25450 then the call to @code{Func_1}
25451 will occur, but not the call to @code{Func_2.}
25452 This means that it is essential
25453 to elaborate the body of @code{Unit_1} before
25454 the body of @code{Unit_2}, so the first
25455 order of elaboration is correct and the second is wrong.
25457 By making @code{expression_1} and @code{expression_2}
25458 depend on input data, or perhaps
25459 the time of day, we can make it impossible for the compiler or binder
25460 to figure out which of these expressions will be true, and hence it
25461 is impossible to guarantee a safe order of elaboration at run time.
25463 @node Checking the Elaboration Order
25464 @section Checking the Elaboration Order
25467 In some languages that involve the same kind of elaboration problems,
25468 e.g.@: Java and C++, the programmer is expected to worry about these
25469 ordering problems himself, and it is common to
25470 write a program in which an incorrect elaboration order gives
25471 surprising results, because it references variables before they
25473 Ada is designed to be a safe language, and a programmer-beware approach is
25474 clearly not sufficient. Consequently, the language provides three lines
25478 @item Standard rules
25479 Some standard rules restrict the possible choice of elaboration
25480 order. In particular, if you @code{with} a unit, then its spec is always
25481 elaborated before the unit doing the @code{with}. Similarly, a parent
25482 spec is always elaborated before the child spec, and finally
25483 a spec is always elaborated before its corresponding body.
25485 @item Dynamic elaboration checks
25486 @cindex Elaboration checks
25487 @cindex Checks, elaboration
25488 Dynamic checks are made at run time, so that if some entity is accessed
25489 before it is elaborated (typically by means of a subprogram call)
25490 then the exception (@code{Program_Error}) is raised.
25492 @item Elaboration control
25493 Facilities are provided for the programmer to specify the desired order
25497 Let's look at these facilities in more detail. First, the rules for
25498 dynamic checking. One possible rule would be simply to say that the
25499 exception is raised if you access a variable which has not yet been
25500 elaborated. The trouble with this approach is that it could require
25501 expensive checks on every variable reference. Instead Ada has two
25502 rules which are a little more restrictive, but easier to check, and
25506 @item Restrictions on calls
25507 A subprogram can only be called at elaboration time if its body
25508 has been elaborated. The rules for elaboration given above guarantee
25509 that the spec of the subprogram has been elaborated before the
25510 call, but not the body. If this rule is violated, then the
25511 exception @code{Program_Error} is raised.
25513 @item Restrictions on instantiations
25514 A generic unit can only be instantiated if the body of the generic
25515 unit has been elaborated. Again, the rules for elaboration given above
25516 guarantee that the spec of the generic unit has been elaborated
25517 before the instantiation, but not the body. If this rule is
25518 violated, then the exception @code{Program_Error} is raised.
25522 The idea is that if the body has been elaborated, then any variables
25523 it references must have been elaborated; by checking for the body being
25524 elaborated we guarantee that none of its references causes any
25525 trouble. As we noted above, this is a little too restrictive, because a
25526 subprogram that has no non-local references in its body may in fact be safe
25527 to call. However, it really would be unsafe to rely on this, because
25528 it would mean that the caller was aware of details of the implementation
25529 in the body. This goes against the basic tenets of Ada.
25531 A plausible implementation can be described as follows.
25532 A Boolean variable is associated with each subprogram
25533 and each generic unit. This variable is initialized to False, and is set to
25534 True at the point body is elaborated. Every call or instantiation checks the
25535 variable, and raises @code{Program_Error} if the variable is False.
25537 Note that one might think that it would be good enough to have one Boolean
25538 variable for each package, but that would not deal with cases of trying
25539 to call a body in the same package as the call
25540 that has not been elaborated yet.
25541 Of course a compiler may be able to do enough analysis to optimize away
25542 some of the Boolean variables as unnecessary, and @code{GNAT} indeed
25543 does such optimizations, but still the easiest conceptual model is to
25544 think of there being one variable per subprogram.
25546 @node Controlling the Elaboration Order
25547 @section Controlling the Elaboration Order
25550 In the previous section we discussed the rules in Ada which ensure
25551 that @code{Program_Error} is raised if an incorrect elaboration order is
25552 chosen. This prevents erroneous executions, but we need mechanisms to
25553 specify a correct execution and avoid the exception altogether.
25554 To achieve this, Ada provides a number of features for controlling
25555 the order of elaboration. We discuss these features in this section.
25557 First, there are several ways of indicating to the compiler that a given
25558 unit has no elaboration problems:
25561 @item packages that do not require a body
25562 A library package that does not require a body does not permit
25563 a body (this rule was introduced in Ada 95).
25564 Thus if we have a such a package, as in:
25566 @smallexample @c ada
25569 package Definitions is
25571 type m is new integer;
25573 type a is array (1 .. 10) of m;
25574 type b is array (1 .. 20) of m;
25582 A package that @code{with}'s @code{Definitions} may safely instantiate
25583 @code{Definitions.Subp} because the compiler can determine that there
25584 definitely is no package body to worry about in this case
25587 @cindex pragma Pure
25589 Places sufficient restrictions on a unit to guarantee that
25590 no call to any subprogram in the unit can result in an
25591 elaboration problem. This means that the compiler does not need
25592 to worry about the point of elaboration of such units, and in
25593 particular, does not need to check any calls to any subprograms
25596 @item pragma Preelaborate
25597 @findex Preelaborate
25598 @cindex pragma Preelaborate
25599 This pragma places slightly less stringent restrictions on a unit than
25601 but these restrictions are still sufficient to ensure that there
25602 are no elaboration problems with any calls to the unit.
25604 @item pragma Elaborate_Body
25605 @findex Elaborate_Body
25606 @cindex pragma Elaborate_Body
25607 This pragma requires that the body of a unit be elaborated immediately
25608 after its spec. Suppose a unit @code{A} has such a pragma,
25609 and unit @code{B} does
25610 a @code{with} of unit @code{A}. Recall that the standard rules require
25611 the spec of unit @code{A}
25612 to be elaborated before the @code{with}'ing unit; given the pragma in
25613 @code{A}, we also know that the body of @code{A}
25614 will be elaborated before @code{B}, so
25615 that calls to @code{A} are safe and do not need a check.
25620 unlike pragma @code{Pure} and pragma @code{Preelaborate},
25622 @code{Elaborate_Body} does not guarantee that the program is
25623 free of elaboration problems, because it may not be possible
25624 to satisfy the requested elaboration order.
25625 Let's go back to the example with @code{Unit_1} and @code{Unit_2}.
25627 marks @code{Unit_1} as @code{Elaborate_Body},
25628 and not @code{Unit_2,} then the order of
25629 elaboration will be:
25641 Now that means that the call to @code{Func_1} in @code{Unit_2}
25642 need not be checked,
25643 it must be safe. But the call to @code{Func_2} in
25644 @code{Unit_1} may still fail if
25645 @code{Expression_1} is equal to 1,
25646 and the programmer must still take
25647 responsibility for this not being the case.
25649 If all units carry a pragma @code{Elaborate_Body}, then all problems are
25650 eliminated, except for calls entirely within a body, which are
25651 in any case fully under programmer control. However, using the pragma
25652 everywhere is not always possible.
25653 In particular, for our @code{Unit_1}/@code{Unit_2} example, if
25654 we marked both of them as having pragma @code{Elaborate_Body}, then
25655 clearly there would be no possible elaboration order.
25657 The above pragmas allow a server to guarantee safe use by clients, and
25658 clearly this is the preferable approach. Consequently a good rule
25659 is to mark units as @code{Pure} or @code{Preelaborate} if possible,
25660 and if this is not possible,
25661 mark them as @code{Elaborate_Body} if possible.
25662 As we have seen, there are situations where neither of these
25663 three pragmas can be used.
25664 So we also provide methods for clients to control the
25665 order of elaboration of the servers on which they depend:
25668 @item pragma Elaborate (unit)
25670 @cindex pragma Elaborate
25671 This pragma is placed in the context clause, after a @code{with} clause,
25672 and it requires that the body of the named unit be elaborated before
25673 the unit in which the pragma occurs. The idea is to use this pragma
25674 if the current unit calls at elaboration time, directly or indirectly,
25675 some subprogram in the named unit.
25677 @item pragma Elaborate_All (unit)
25678 @findex Elaborate_All
25679 @cindex pragma Elaborate_All
25680 This is a stronger version of the Elaborate pragma. Consider the
25684 Unit A @code{with}'s unit B and calls B.Func in elab code
25685 Unit B @code{with}'s unit C, and B.Func calls C.Func
25689 Now if we put a pragma @code{Elaborate (B)}
25690 in unit @code{A}, this ensures that the
25691 body of @code{B} is elaborated before the call, but not the
25692 body of @code{C}, so
25693 the call to @code{C.Func} could still cause @code{Program_Error} to
25696 The effect of a pragma @code{Elaborate_All} is stronger, it requires
25697 not only that the body of the named unit be elaborated before the
25698 unit doing the @code{with}, but also the bodies of all units that the
25699 named unit uses, following @code{with} links transitively. For example,
25700 if we put a pragma @code{Elaborate_All (B)} in unit @code{A},
25702 not only that the body of @code{B} be elaborated before @code{A},
25704 body of @code{C}, because @code{B} @code{with}'s @code{C}.
25708 We are now in a position to give a usage rule in Ada for avoiding
25709 elaboration problems, at least if dynamic dispatching and access to
25710 subprogram values are not used. We will handle these cases separately
25713 The rule is simple. If a unit has elaboration code that can directly or
25714 indirectly make a call to a subprogram in a @code{with}'ed unit, or instantiate
25715 a generic package in a @code{with}'ed unit,
25716 then if the @code{with}'ed unit does not have
25717 pragma @code{Pure} or @code{Preelaborate}, then the client should have
25718 a pragma @code{Elaborate_All}
25719 for the @code{with}'ed unit. By following this rule a client is
25720 assured that calls can be made without risk of an exception.
25722 For generic subprogram instantiations, the rule can be relaxed to
25723 require only a pragma @code{Elaborate} since elaborating the body
25724 of a subprogram cannot cause any transitive elaboration (we are
25725 not calling the subprogram in this case, just elaborating its
25728 If this rule is not followed, then a program may be in one of four
25732 @item No order exists
25733 No order of elaboration exists which follows the rules, taking into
25734 account any @code{Elaborate}, @code{Elaborate_All},
25735 or @code{Elaborate_Body} pragmas. In
25736 this case, an Ada compiler must diagnose the situation at bind
25737 time, and refuse to build an executable program.
25739 @item One or more orders exist, all incorrect
25740 One or more acceptable elaboration orders exist, and all of them
25741 generate an elaboration order problem. In this case, the binder
25742 can build an executable program, but @code{Program_Error} will be raised
25743 when the program is run.
25745 @item Several orders exist, some right, some incorrect
25746 One or more acceptable elaboration orders exists, and some of them
25747 work, and some do not. The programmer has not controlled
25748 the order of elaboration, so the binder may or may not pick one of
25749 the correct orders, and the program may or may not raise an
25750 exception when it is run. This is the worst case, because it means
25751 that the program may fail when moved to another compiler, or even
25752 another version of the same compiler.
25754 @item One or more orders exists, all correct
25755 One ore more acceptable elaboration orders exist, and all of them
25756 work. In this case the program runs successfully. This state of
25757 affairs can be guaranteed by following the rule we gave above, but
25758 may be true even if the rule is not followed.
25762 Note that one additional advantage of following our rules on the use
25763 of @code{Elaborate} and @code{Elaborate_All}
25764 is that the program continues to stay in the ideal (all orders OK) state
25765 even if maintenance
25766 changes some bodies of some units. Conversely, if a program that does
25767 not follow this rule happens to be safe at some point, this state of affairs
25768 may deteriorate silently as a result of maintenance changes.
25770 You may have noticed that the above discussion did not mention
25771 the use of @code{Elaborate_Body}. This was a deliberate omission. If you
25772 @code{with} an @code{Elaborate_Body} unit, it still may be the case that
25773 code in the body makes calls to some other unit, so it is still necessary
25774 to use @code{Elaborate_All} on such units.
25776 @node Controlling Elaboration in GNAT - Internal Calls
25777 @section Controlling Elaboration in GNAT - Internal Calls
25780 In the case of internal calls, i.e., calls within a single package, the
25781 programmer has full control over the order of elaboration, and it is up
25782 to the programmer to elaborate declarations in an appropriate order. For
25785 @smallexample @c ada
25788 function One return Float;
25792 function One return Float is
25801 will obviously raise @code{Program_Error} at run time, because function
25802 One will be called before its body is elaborated. In this case GNAT will
25803 generate a warning that the call will raise @code{Program_Error}:
25809 2. function One return Float;
25811 4. Q : Float := One;
25813 >>> warning: cannot call "One" before body is elaborated
25814 >>> warning: Program_Error will be raised at run time
25817 6. function One return Float is
25830 Note that in this particular case, it is likely that the call is safe, because
25831 the function @code{One} does not access any global variables.
25832 Nevertheless in Ada, we do not want the validity of the check to depend on
25833 the contents of the body (think about the separate compilation case), so this
25834 is still wrong, as we discussed in the previous sections.
25836 The error is easily corrected by rearranging the declarations so that the
25837 body of @code{One} appears before the declaration containing the call
25838 (note that in Ada 95 and Ada 2005,
25839 declarations can appear in any order, so there is no restriction that
25840 would prevent this reordering, and if we write:
25842 @smallexample @c ada
25845 function One return Float;
25847 function One return Float is
25858 then all is well, no warning is generated, and no
25859 @code{Program_Error} exception
25861 Things are more complicated when a chain of subprograms is executed:
25863 @smallexample @c ada
25866 function A return Integer;
25867 function B return Integer;
25868 function C return Integer;
25870 function B return Integer is begin return A; end;
25871 function C return Integer is begin return B; end;
25875 function A return Integer is begin return 1; end;
25881 Now the call to @code{C}
25882 at elaboration time in the declaration of @code{X} is correct, because
25883 the body of @code{C} is already elaborated,
25884 and the call to @code{B} within the body of
25885 @code{C} is correct, but the call
25886 to @code{A} within the body of @code{B} is incorrect, because the body
25887 of @code{A} has not been elaborated, so @code{Program_Error}
25888 will be raised on the call to @code{A}.
25889 In this case GNAT will generate a
25890 warning that @code{Program_Error} may be
25891 raised at the point of the call. Let's look at the warning:
25897 2. function A return Integer;
25898 3. function B return Integer;
25899 4. function C return Integer;
25901 6. function B return Integer is begin return A; end;
25903 >>> warning: call to "A" before body is elaborated may
25904 raise Program_Error
25905 >>> warning: "B" called at line 7
25906 >>> warning: "C" called at line 9
25908 7. function C return Integer is begin return B; end;
25910 9. X : Integer := C;
25912 11. function A return Integer is begin return 1; end;
25922 Note that the message here says ``may raise'', instead of the direct case,
25923 where the message says ``will be raised''. That's because whether
25925 actually called depends in general on run-time flow of control.
25926 For example, if the body of @code{B} said
25928 @smallexample @c ada
25931 function B return Integer is
25933 if some-condition-depending-on-input-data then
25944 then we could not know until run time whether the incorrect call to A would
25945 actually occur, so @code{Program_Error} might
25946 or might not be raised. It is possible for a compiler to
25947 do a better job of analyzing bodies, to
25948 determine whether or not @code{Program_Error}
25949 might be raised, but it certainly
25950 couldn't do a perfect job (that would require solving the halting problem
25951 and is provably impossible), and because this is a warning anyway, it does
25952 not seem worth the effort to do the analysis. Cases in which it
25953 would be relevant are rare.
25955 In practice, warnings of either of the forms given
25956 above will usually correspond to
25957 real errors, and should be examined carefully and eliminated.
25958 In the rare case where a warning is bogus, it can be suppressed by any of
25959 the following methods:
25963 Compile with the @option{-gnatws} switch set
25966 Suppress @code{Elaboration_Check} for the called subprogram
25969 Use pragma @code{Warnings_Off} to turn warnings off for the call
25973 For the internal elaboration check case,
25974 GNAT by default generates the
25975 necessary run-time checks to ensure
25976 that @code{Program_Error} is raised if any
25977 call fails an elaboration check. Of course this can only happen if a
25978 warning has been issued as described above. The use of pragma
25979 @code{Suppress (Elaboration_Check)} may (but is not guaranteed to) suppress
25980 some of these checks, meaning that it may be possible (but is not
25981 guaranteed) for a program to be able to call a subprogram whose body
25982 is not yet elaborated, without raising a @code{Program_Error} exception.
25984 @node Controlling Elaboration in GNAT - External Calls
25985 @section Controlling Elaboration in GNAT - External Calls
25988 The previous section discussed the case in which the execution of a
25989 particular thread of elaboration code occurred entirely within a
25990 single unit. This is the easy case to handle, because a programmer
25991 has direct and total control over the order of elaboration, and
25992 furthermore, checks need only be generated in cases which are rare
25993 and which the compiler can easily detect.
25994 The situation is more complex when separate compilation is taken into account.
25995 Consider the following:
25997 @smallexample @c ada
26001 function Sqrt (Arg : Float) return Float;
26004 package body Math is
26005 function Sqrt (Arg : Float) return Float is
26014 X : Float := Math.Sqrt (0.5);
26027 where @code{Main} is the main program. When this program is executed, the
26028 elaboration code must first be executed, and one of the jobs of the
26029 binder is to determine the order in which the units of a program are
26030 to be elaborated. In this case we have four units: the spec and body
26032 the spec of @code{Stuff} and the body of @code{Main}).
26033 In what order should the four separate sections of elaboration code
26036 There are some restrictions in the order of elaboration that the binder
26037 can choose. In particular, if unit U has a @code{with}
26038 for a package @code{X}, then you
26039 are assured that the spec of @code{X}
26040 is elaborated before U , but you are
26041 not assured that the body of @code{X}
26042 is elaborated before U.
26043 This means that in the above case, the binder is allowed to choose the
26054 but that's not good, because now the call to @code{Math.Sqrt}
26055 that happens during
26056 the elaboration of the @code{Stuff}
26057 spec happens before the body of @code{Math.Sqrt} is
26058 elaborated, and hence causes @code{Program_Error} exception to be raised.
26059 At first glance, one might say that the binder is misbehaving, because
26060 obviously you want to elaborate the body of something you @code{with}
26062 that is not a general rule that can be followed in all cases. Consider
26064 @smallexample @c ada
26067 package X is @dots{}
26069 package Y is @dots{}
26072 package body Y is @dots{}
26075 package body X is @dots{}
26081 This is a common arrangement, and, apart from the order of elaboration
26082 problems that might arise in connection with elaboration code, this works fine.
26083 A rule that says that you must first elaborate the body of anything you
26084 @code{with} cannot work in this case:
26085 the body of @code{X} @code{with}'s @code{Y},
26086 which means you would have to
26087 elaborate the body of @code{Y} first, but that @code{with}'s @code{X},
26089 you have to elaborate the body of @code{X} first, but @dots{} and we have a
26090 loop that cannot be broken.
26092 It is true that the binder can in many cases guess an order of elaboration
26093 that is unlikely to cause a @code{Program_Error}
26094 exception to be raised, and it tries to do so (in the
26095 above example of @code{Math/Stuff/Spec}, the GNAT binder will
26097 elaborate the body of @code{Math} right after its spec, so all will be well).
26099 However, a program that blindly relies on the binder to be helpful can
26100 get into trouble, as we discussed in the previous sections, so
26102 provides a number of facilities for assisting the programmer in
26103 developing programs that are robust with respect to elaboration order.
26105 @node Default Behavior in GNAT - Ensuring Safety
26106 @section Default Behavior in GNAT - Ensuring Safety
26109 The default behavior in GNAT ensures elaboration safety. In its
26110 default mode GNAT implements the
26111 rule we previously described as the right approach. Let's restate it:
26115 @emph{If a unit has elaboration code that can directly or indirectly make a
26116 call to a subprogram in a @code{with}'ed unit, or instantiate a generic
26117 package in a @code{with}'ed unit, then if the @code{with}'ed unit
26118 does not have pragma @code{Pure} or
26119 @code{Preelaborate}, then the client should have an
26120 @code{Elaborate_All} pragma for the @code{with}'ed unit.}
26122 @emph{In the case of instantiating a generic subprogram, it is always
26123 sufficient to have only an @code{Elaborate} pragma for the
26124 @code{with}'ed unit.}
26128 By following this rule a client is assured that calls and instantiations
26129 can be made without risk of an exception.
26131 In this mode GNAT traces all calls that are potentially made from
26132 elaboration code, and puts in any missing implicit @code{Elaborate}
26133 and @code{Elaborate_All} pragmas.
26134 The advantage of this approach is that no elaboration problems
26135 are possible if the binder can find an elaboration order that is
26136 consistent with these implicit @code{Elaborate} and
26137 @code{Elaborate_All} pragmas. The
26138 disadvantage of this approach is that no such order may exist.
26140 If the binder does not generate any diagnostics, then it means that it has
26141 found an elaboration order that is guaranteed to be safe. However, the binder
26142 may still be relying on implicitly generated @code{Elaborate} and
26143 @code{Elaborate_All} pragmas so portability to other compilers than GNAT is not
26146 If it is important to guarantee portability, then the compilations should
26149 (info messages for elaboration prag mas) switch. This will cause info messages
26150 to be generated indicating the missing @code{Elaborate} and
26151 @code{Elaborate_All} pragmas.
26152 Consider the following source program:
26154 @smallexample @c ada
26159 m : integer := k.r;
26166 where it is clear that there
26167 should be a pragma @code{Elaborate_All}
26168 for unit @code{k}. An implicit pragma will be generated, and it is
26169 likely that the binder will be able to honor it. However, if you want
26170 to port this program to some other Ada compiler than GNAT.
26171 it is safer to include the pragma explicitly in the source. If this
26172 unit is compiled with the
26174 switch, then the compiler outputs an information message:
26181 3. m : integer := k.r;
26183 >>> info: call to "r" may raise Program_Error
26184 >>> info: missing pragma Elaborate_All for "k"
26192 and these messages can be used as a guide for supplying manually
26193 the missing pragmas. It is usually a bad idea to use this
26194 option during development. That's because it will tell you when
26195 you need to put in a pragma, but cannot tell you when it is time
26196 to take it out. So the use of pragma @code{Elaborate_All} may lead to
26197 unnecessary dependencies and even false circularities.
26199 This default mode is more restrictive than the Ada Reference
26200 Manual, and it is possible to construct programs which will compile
26201 using the dynamic model described there, but will run into a
26202 circularity using the safer static model we have described.
26204 Of course any Ada compiler must be able to operate in a mode
26205 consistent with the requirements of the Ada Reference Manual,
26206 and in particular must have the capability of implementing the
26207 standard dynamic model of elaboration with run-time checks.
26209 In GNAT, this standard mode can be achieved either by the use of
26210 the @option{-gnatE} switch on the compiler (@command{gcc} or
26211 @command{gnatmake}) command, or by the use of the configuration pragma:
26213 @smallexample @c ada
26214 pragma Elaboration_Checks (DYNAMIC);
26218 Either approach will cause the unit affected to be compiled using the
26219 standard dynamic run-time elaboration checks described in the Ada
26220 Reference Manual. The static model is generally preferable, since it
26221 is clearly safer to rely on compile and link time checks rather than
26222 run-time checks. However, in the case of legacy code, it may be
26223 difficult to meet the requirements of the static model. This
26224 issue is further discussed in
26225 @ref{What to Do If the Default Elaboration Behavior Fails}.
26227 Note that the static model provides a strict subset of the allowed
26228 behavior and programs of the Ada Reference Manual, so if you do
26229 adhere to the static model and no circularities exist,
26230 then you are assured that your program will
26231 work using the dynamic model, providing that you remove any
26232 pragma Elaborate statements from the source.
26234 @node Treatment of Pragma Elaborate
26235 @section Treatment of Pragma Elaborate
26236 @cindex Pragma Elaborate
26239 The use of @code{pragma Elaborate}
26240 should generally be avoided in Ada 95 and Ada 2005 programs,
26241 since there is no guarantee that transitive calls
26242 will be properly handled. Indeed at one point, this pragma was placed
26243 in Annex J (Obsolescent Features), on the grounds that it is never useful.
26245 Now that's a bit restrictive. In practice, the case in which
26246 @code{pragma Elaborate} is useful is when the caller knows that there
26247 are no transitive calls, or that the called unit contains all necessary
26248 transitive @code{pragma Elaborate} statements, and legacy code often
26249 contains such uses.
26251 Strictly speaking the static mode in GNAT should ignore such pragmas,
26252 since there is no assurance at compile time that the necessary safety
26253 conditions are met. In practice, this would cause GNAT to be incompatible
26254 with correctly written Ada 83 code that had all necessary
26255 @code{pragma Elaborate} statements in place. Consequently, we made the
26256 decision that GNAT in its default mode will believe that if it encounters
26257 a @code{pragma Elaborate} then the programmer knows what they are doing,
26258 and it will trust that no elaboration errors can occur.
26260 The result of this decision is two-fold. First to be safe using the
26261 static mode, you should remove all @code{pragma Elaborate} statements.
26262 Second, when fixing circularities in existing code, you can selectively
26263 use @code{pragma Elaborate} statements to convince the static mode of
26264 GNAT that it need not generate an implicit @code{pragma Elaborate_All}
26267 When using the static mode with @option{-gnatwl}, any use of
26268 @code{pragma Elaborate} will generate a warning about possible
26271 @node Elaboration Issues for Library Tasks
26272 @section Elaboration Issues for Library Tasks
26273 @cindex Library tasks, elaboration issues
26274 @cindex Elaboration of library tasks
26277 In this section we examine special elaboration issues that arise for
26278 programs that declare library level tasks.
26280 Generally the model of execution of an Ada program is that all units are
26281 elaborated, and then execution of the program starts. However, the
26282 declaration of library tasks definitely does not fit this model. The
26283 reason for this is that library tasks start as soon as they are declared
26284 (more precisely, as soon as the statement part of the enclosing package
26285 body is reached), that is to say before elaboration
26286 of the program is complete. This means that if such a task calls a
26287 subprogram, or an entry in another task, the callee may or may not be
26288 elaborated yet, and in the standard
26289 Reference Manual model of dynamic elaboration checks, you can even
26290 get timing dependent Program_Error exceptions, since there can be
26291 a race between the elaboration code and the task code.
26293 The static model of elaboration in GNAT seeks to avoid all such
26294 dynamic behavior, by being conservative, and the conservative
26295 approach in this particular case is to assume that all the code
26296 in a task body is potentially executed at elaboration time if
26297 a task is declared at the library level.
26299 This can definitely result in unexpected circularities. Consider
26300 the following example
26302 @smallexample @c ada
26308 type My_Int is new Integer;
26310 function Ident (M : My_Int) return My_Int;
26314 package body Decls is
26315 task body Lib_Task is
26321 function Ident (M : My_Int) return My_Int is
26329 procedure Put_Val (Arg : Decls.My_Int);
26333 package body Utils is
26334 procedure Put_Val (Arg : Decls.My_Int) is
26336 Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
26343 Decls.Lib_Task.Start;
26348 If the above example is compiled in the default static elaboration
26349 mode, then a circularity occurs. The circularity comes from the call
26350 @code{Utils.Put_Val} in the task body of @code{Decls.Lib_Task}. Since
26351 this call occurs in elaboration code, we need an implicit pragma
26352 @code{Elaborate_All} for @code{Utils}. This means that not only must
26353 the spec and body of @code{Utils} be elaborated before the body
26354 of @code{Decls}, but also the spec and body of any unit that is
26355 @code{with'ed} by the body of @code{Utils} must also be elaborated before
26356 the body of @code{Decls}. This is the transitive implication of
26357 pragma @code{Elaborate_All} and it makes sense, because in general
26358 the body of @code{Put_Val} might have a call to something in a
26359 @code{with'ed} unit.
26361 In this case, the body of Utils (actually its spec) @code{with's}
26362 @code{Decls}. Unfortunately this means that the body of @code{Decls}
26363 must be elaborated before itself, in case there is a call from the
26364 body of @code{Utils}.
26366 Here is the exact chain of events we are worrying about:
26370 In the body of @code{Decls} a call is made from within the body of a library
26371 task to a subprogram in the package @code{Utils}. Since this call may
26372 occur at elaboration time (given that the task is activated at elaboration
26373 time), we have to assume the worst, i.e., that the
26374 call does happen at elaboration time.
26377 This means that the body and spec of @code{Util} must be elaborated before
26378 the body of @code{Decls} so that this call does not cause an access before
26382 Within the body of @code{Util}, specifically within the body of
26383 @code{Util.Put_Val} there may be calls to any unit @code{with}'ed
26387 One such @code{with}'ed package is package @code{Decls}, so there
26388 might be a call to a subprogram in @code{Decls} in @code{Put_Val}.
26389 In fact there is such a call in this example, but we would have to
26390 assume that there was such a call even if it were not there, since
26391 we are not supposed to write the body of @code{Decls} knowing what
26392 is in the body of @code{Utils}; certainly in the case of the
26393 static elaboration model, the compiler does not know what is in
26394 other bodies and must assume the worst.
26397 This means that the spec and body of @code{Decls} must also be
26398 elaborated before we elaborate the unit containing the call, but
26399 that unit is @code{Decls}! This means that the body of @code{Decls}
26400 must be elaborated before itself, and that's a circularity.
26404 Indeed, if you add an explicit pragma @code{Elaborate_All} for @code{Utils} in
26405 the body of @code{Decls} you will get a true Ada Reference Manual
26406 circularity that makes the program illegal.
26408 In practice, we have found that problems with the static model of
26409 elaboration in existing code often arise from library tasks, so
26410 we must address this particular situation.
26412 Note that if we compile and run the program above, using the dynamic model of
26413 elaboration (that is to say use the @option{-gnatE} switch),
26414 then it compiles, binds,
26415 links, and runs, printing the expected result of 2. Therefore in some sense
26416 the circularity here is only apparent, and we need to capture
26417 the properties of this program that distinguish it from other library-level
26418 tasks that have real elaboration problems.
26420 We have four possible answers to this question:
26425 Use the dynamic model of elaboration.
26427 If we use the @option{-gnatE} switch, then as noted above, the program works.
26428 Why is this? If we examine the task body, it is apparent that the task cannot
26430 @code{accept} statement until after elaboration has been completed, because
26431 the corresponding entry call comes from the main program, not earlier.
26432 This is why the dynamic model works here. But that's really giving
26433 up on a precise analysis, and we prefer to take this approach only if we cannot
26435 problem in any other manner. So let us examine two ways to reorganize
26436 the program to avoid the potential elaboration problem.
26439 Split library tasks into separate packages.
26441 Write separate packages, so that library tasks are isolated from
26442 other declarations as much as possible. Let us look at a variation on
26445 @smallexample @c ada
26453 package body Decls1 is
26454 task body Lib_Task is
26462 type My_Int is new Integer;
26463 function Ident (M : My_Int) return My_Int;
26467 package body Decls2 is
26468 function Ident (M : My_Int) return My_Int is
26476 procedure Put_Val (Arg : Decls2.My_Int);
26480 package body Utils is
26481 procedure Put_Val (Arg : Decls2.My_Int) is
26483 Text_IO.Put_Line (Decls2.My_Int'Image (Decls2.Ident (Arg)));
26490 Decls1.Lib_Task.Start;
26495 All we have done is to split @code{Decls} into two packages, one
26496 containing the library task, and one containing everything else. Now
26497 there is no cycle, and the program compiles, binds, links and executes
26498 using the default static model of elaboration.
26501 Declare separate task types.
26503 A significant part of the problem arises because of the use of the
26504 single task declaration form. This means that the elaboration of
26505 the task type, and the elaboration of the task itself (i.e.@: the
26506 creation of the task) happen at the same time. A good rule
26507 of style in Ada is to always create explicit task types. By
26508 following the additional step of placing task objects in separate
26509 packages from the task type declaration, many elaboration problems
26510 are avoided. Here is another modified example of the example program:
26512 @smallexample @c ada
26514 task type Lib_Task_Type is
26518 type My_Int is new Integer;
26520 function Ident (M : My_Int) return My_Int;
26524 package body Decls is
26525 task body Lib_Task_Type is
26531 function Ident (M : My_Int) return My_Int is
26539 procedure Put_Val (Arg : Decls.My_Int);
26543 package body Utils is
26544 procedure Put_Val (Arg : Decls.My_Int) is
26546 Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
26552 Lib_Task : Decls.Lib_Task_Type;
26558 Declst.Lib_Task.Start;
26563 What we have done here is to replace the @code{task} declaration in
26564 package @code{Decls} with a @code{task type} declaration. Then we
26565 introduce a separate package @code{Declst} to contain the actual
26566 task object. This separates the elaboration issues for
26567 the @code{task type}
26568 declaration, which causes no trouble, from the elaboration issues
26569 of the task object, which is also unproblematic, since it is now independent
26570 of the elaboration of @code{Utils}.
26571 This separation of concerns also corresponds to
26572 a generally sound engineering principle of separating declarations
26573 from instances. This version of the program also compiles, binds, links,
26574 and executes, generating the expected output.
26577 Use No_Entry_Calls_In_Elaboration_Code restriction.
26578 @cindex No_Entry_Calls_In_Elaboration_Code
26580 The previous two approaches described how a program can be restructured
26581 to avoid the special problems caused by library task bodies. in practice,
26582 however, such restructuring may be difficult to apply to existing legacy code,
26583 so we must consider solutions that do not require massive rewriting.
26585 Let us consider more carefully why our original sample program works
26586 under the dynamic model of elaboration. The reason is that the code
26587 in the task body blocks immediately on the @code{accept}
26588 statement. Now of course there is nothing to prohibit elaboration
26589 code from making entry calls (for example from another library level task),
26590 so we cannot tell in isolation that
26591 the task will not execute the accept statement during elaboration.
26593 However, in practice it is very unusual to see elaboration code
26594 make any entry calls, and the pattern of tasks starting
26595 at elaboration time and then immediately blocking on @code{accept} or
26596 @code{select} statements is very common. What this means is that
26597 the compiler is being too pessimistic when it analyzes the
26598 whole package body as though it might be executed at elaboration
26601 If we know that the elaboration code contains no entry calls, (a very safe
26602 assumption most of the time, that could almost be made the default
26603 behavior), then we can compile all units of the program under control
26604 of the following configuration pragma:
26607 pragma Restrictions (No_Entry_Calls_In_Elaboration_Code);
26611 This pragma can be placed in the @file{gnat.adc} file in the usual
26612 manner. If we take our original unmodified program and compile it
26613 in the presence of a @file{gnat.adc} containing the above pragma,
26614 then once again, we can compile, bind, link, and execute, obtaining
26615 the expected result. In the presence of this pragma, the compiler does
26616 not trace calls in a task body, that appear after the first @code{accept}
26617 or @code{select} statement, and therefore does not report a potential
26618 circularity in the original program.
26620 The compiler will check to the extent it can that the above
26621 restriction is not violated, but it is not always possible to do a
26622 complete check at compile time, so it is important to use this
26623 pragma only if the stated restriction is in fact met, that is to say
26624 no task receives an entry call before elaboration of all units is completed.
26628 @node Mixing Elaboration Models
26629 @section Mixing Elaboration Models
26631 So far, we have assumed that the entire program is either compiled
26632 using the dynamic model or static model, ensuring consistency. It
26633 is possible to mix the two models, but rules have to be followed
26634 if this mixing is done to ensure that elaboration checks are not
26637 The basic rule is that @emph{a unit compiled with the static model cannot
26638 be @code{with'ed} by a unit compiled with the dynamic model}. The
26639 reason for this is that in the static model, a unit assumes that
26640 its clients guarantee to use (the equivalent of) pragma
26641 @code{Elaborate_All} so that no elaboration checks are required
26642 in inner subprograms, and this assumption is violated if the
26643 client is compiled with dynamic checks.
26645 The precise rule is as follows. A unit that is compiled with dynamic
26646 checks can only @code{with} a unit that meets at least one of the
26647 following criteria:
26652 The @code{with'ed} unit is itself compiled with dynamic elaboration
26653 checks (that is with the @option{-gnatE} switch.
26656 The @code{with'ed} unit is an internal GNAT implementation unit from
26657 the System, Interfaces, Ada, or GNAT hierarchies.
26660 The @code{with'ed} unit has pragma Preelaborate or pragma Pure.
26663 The @code{with'ing} unit (that is the client) has an explicit pragma
26664 @code{Elaborate_All} for the @code{with'ed} unit.
26669 If this rule is violated, that is if a unit with dynamic elaboration
26670 checks @code{with's} a unit that does not meet one of the above four
26671 criteria, then the binder (@code{gnatbind}) will issue a warning
26672 similar to that in the following example:
26675 warning: "x.ads" has dynamic elaboration checks and with's
26676 warning: "y.ads" which has static elaboration checks
26680 These warnings indicate that the rule has been violated, and that as a result
26681 elaboration checks may be missed in the resulting executable file.
26682 This warning may be suppressed using the @option{-ws} binder switch
26683 in the usual manner.
26685 One useful application of this mixing rule is in the case of a subsystem
26686 which does not itself @code{with} units from the remainder of the
26687 application. In this case, the entire subsystem can be compiled with
26688 dynamic checks to resolve a circularity in the subsystem, while
26689 allowing the main application that uses this subsystem to be compiled
26690 using the more reliable default static model.
26692 @node What to Do If the Default Elaboration Behavior Fails
26693 @section What to Do If the Default Elaboration Behavior Fails
26696 If the binder cannot find an acceptable order, it outputs detailed
26697 diagnostics. For example:
26703 error: elaboration circularity detected
26704 info: "proc (body)" must be elaborated before "pack (body)"
26705 info: reason: Elaborate_All probably needed in unit "pack (body)"
26706 info: recompile "pack (body)" with -gnatel
26707 info: for full details
26708 info: "proc (body)"
26709 info: is needed by its spec:
26710 info: "proc (spec)"
26711 info: which is withed by:
26712 info: "pack (body)"
26713 info: "pack (body)" must be elaborated before "proc (body)"
26714 info: reason: pragma Elaborate in unit "proc (body)"
26720 In this case we have a cycle that the binder cannot break. On the one
26721 hand, there is an explicit pragma Elaborate in @code{proc} for
26722 @code{pack}. This means that the body of @code{pack} must be elaborated
26723 before the body of @code{proc}. On the other hand, there is elaboration
26724 code in @code{pack} that calls a subprogram in @code{proc}. This means
26725 that for maximum safety, there should really be a pragma
26726 Elaborate_All in @code{pack} for @code{proc} which would require that
26727 the body of @code{proc} be elaborated before the body of
26728 @code{pack}. Clearly both requirements cannot be satisfied.
26729 Faced with a circularity of this kind, you have three different options.
26732 @item Fix the program
26733 The most desirable option from the point of view of long-term maintenance
26734 is to rearrange the program so that the elaboration problems are avoided.
26735 One useful technique is to place the elaboration code into separate
26736 child packages. Another is to move some of the initialization code to
26737 explicitly called subprograms, where the program controls the order
26738 of initialization explicitly. Although this is the most desirable option,
26739 it may be impractical and involve too much modification, especially in
26740 the case of complex legacy code.
26742 @item Perform dynamic checks
26743 If the compilations are done using the
26745 (dynamic elaboration check) switch, then GNAT behaves in a quite different
26746 manner. Dynamic checks are generated for all calls that could possibly result
26747 in raising an exception. With this switch, the compiler does not generate
26748 implicit @code{Elaborate} or @code{Elaborate_All} pragmas. The behavior then is
26749 exactly as specified in the @cite{Ada Reference Manual}.
26750 The binder will generate
26751 an executable program that may or may not raise @code{Program_Error}, and then
26752 it is the programmer's job to ensure that it does not raise an exception. Note
26753 that it is important to compile all units with the switch, it cannot be used
26756 @item Suppress checks
26757 The drawback of dynamic checks is that they generate a
26758 significant overhead at run time, both in space and time. If you
26759 are absolutely sure that your program cannot raise any elaboration
26760 exceptions, and you still want to use the dynamic elaboration model,
26761 then you can use the configuration pragma
26762 @code{Suppress (Elaboration_Check)} to suppress all such checks. For
26763 example this pragma could be placed in the @file{gnat.adc} file.
26765 @item Suppress checks selectively
26766 When you know that certain calls or instantiations in elaboration code cannot
26767 possibly lead to an elaboration error, and the binder nevertheless complains
26768 about implicit @code{Elaborate} and @code{Elaborate_All} pragmas that lead to
26769 elaboration circularities, it is possible to remove those warnings locally and
26770 obtain a program that will bind. Clearly this can be unsafe, and it is the
26771 responsibility of the programmer to make sure that the resulting program has no
26772 elaboration anomalies. The pragma @code{Suppress (Elaboration_Check)} can be
26773 used with different granularity to suppress warnings and break elaboration
26778 Place the pragma that names the called subprogram in the declarative part
26779 that contains the call.
26782 Place the pragma in the declarative part, without naming an entity. This
26783 disables warnings on all calls in the corresponding declarative region.
26786 Place the pragma in the package spec that declares the called subprogram,
26787 and name the subprogram. This disables warnings on all elaboration calls to
26791 Place the pragma in the package spec that declares the called subprogram,
26792 without naming any entity. This disables warnings on all elaboration calls to
26793 all subprograms declared in this spec.
26795 @item Use Pragma Elaborate
26796 As previously described in section @xref{Treatment of Pragma Elaborate},
26797 GNAT in static mode assumes that a @code{pragma} Elaborate indicates correctly
26798 that no elaboration checks are required on calls to the designated unit.
26799 There may be cases in which the caller knows that no transitive calls
26800 can occur, so that a @code{pragma Elaborate} will be sufficient in a
26801 case where @code{pragma Elaborate_All} would cause a circularity.
26805 These five cases are listed in order of decreasing safety, and therefore
26806 require increasing programmer care in their application. Consider the
26809 @smallexample @c adanocomment
26811 function F1 return Integer;
26816 function F2 return Integer;
26817 function Pure (x : integer) return integer;
26818 -- pragma Suppress (Elaboration_Check, On => Pure); -- (3)
26819 -- pragma Suppress (Elaboration_Check); -- (4)
26823 package body Pack1 is
26824 function F1 return Integer is
26828 Val : integer := Pack2.Pure (11); -- Elab. call (1)
26831 -- pragma Suppress(Elaboration_Check, Pack2.F2); -- (1)
26832 -- pragma Suppress(Elaboration_Check); -- (2)
26834 X1 := Pack2.F2 + 1; -- Elab. call (2)
26839 package body Pack2 is
26840 function F2 return Integer is
26844 function Pure (x : integer) return integer is
26846 return x ** 3 - 3 * x;
26850 with Pack1, Ada.Text_IO;
26853 Ada.Text_IO.Put_Line(Pack1.X1'Img); -- 101
26856 In the absence of any pragmas, an attempt to bind this program produces
26857 the following diagnostics:
26863 error: elaboration circularity detected
26864 info: "pack1 (body)" must be elaborated before "pack1 (body)"
26865 info: reason: Elaborate_All probably needed in unit "pack1 (body)"
26866 info: recompile "pack1 (body)" with -gnatel for full details
26867 info: "pack1 (body)"
26868 info: must be elaborated along with its spec:
26869 info: "pack1 (spec)"
26870 info: which is withed by:
26871 info: "pack2 (body)"
26872 info: which must be elaborated along with its spec:
26873 info: "pack2 (spec)"
26874 info: which is withed by:
26875 info: "pack1 (body)"
26878 The sources of the circularity are the two calls to @code{Pack2.Pure} and
26879 @code{Pack2.F2} in the body of @code{Pack1}. We can see that the call to
26880 F2 is safe, even though F2 calls F1, because the call appears after the
26881 elaboration of the body of F1. Therefore the pragma (1) is safe, and will
26882 remove the warning on the call. It is also possible to use pragma (2)
26883 because there are no other potentially unsafe calls in the block.
26886 The call to @code{Pure} is safe because this function does not depend on the
26887 state of @code{Pack2}. Therefore any call to this function is safe, and it
26888 is correct to place pragma (3) in the corresponding package spec.
26891 Finally, we could place pragma (4) in the spec of @code{Pack2} to disable
26892 warnings on all calls to functions declared therein. Note that this is not
26893 necessarily safe, and requires more detailed examination of the subprogram
26894 bodies involved. In particular, a call to @code{F2} requires that @code{F1}
26895 be already elaborated.
26899 It is hard to generalize on which of these four approaches should be
26900 taken. Obviously if it is possible to fix the program so that the default
26901 treatment works, this is preferable, but this may not always be practical.
26902 It is certainly simple enough to use
26904 but the danger in this case is that, even if the GNAT binder
26905 finds a correct elaboration order, it may not always do so,
26906 and certainly a binder from another Ada compiler might not. A
26907 combination of testing and analysis (for which the
26908 information messages generated with the
26910 switch can be useful) must be used to ensure that the program is free
26911 of errors. One switch that is useful in this testing is the
26912 @option{^-p (pessimistic elaboration order)^/PESSIMISTIC_ELABORATION_ORDER^}
26915 Normally the binder tries to find an order that has the best chance
26916 of avoiding elaboration problems. However, if this switch is used, the binder
26917 plays a devil's advocate role, and tries to choose the order that
26918 has the best chance of failing. If your program works even with this
26919 switch, then it has a better chance of being error free, but this is still
26922 For an example of this approach in action, consider the C-tests (executable
26923 tests) from the ACVC suite. If these are compiled and run with the default
26924 treatment, then all but one of them succeed without generating any error
26925 diagnostics from the binder. However, there is one test that fails, and
26926 this is not surprising, because the whole point of this test is to ensure
26927 that the compiler can handle cases where it is impossible to determine
26928 a correct order statically, and it checks that an exception is indeed
26929 raised at run time.
26931 This one test must be compiled and run using the
26933 switch, and then it passes. Alternatively, the entire suite can
26934 be run using this switch. It is never wrong to run with the dynamic
26935 elaboration switch if your code is correct, and we assume that the
26936 C-tests are indeed correct (it is less efficient, but efficiency is
26937 not a factor in running the ACVC tests.)
26939 @node Elaboration for Indirect Calls
26940 @section Elaboration for Indirect Calls
26941 @cindex Dispatching calls
26942 @cindex Indirect calls
26945 In rare cases, the static elaboration model fails to prevent
26946 dispatching calls to not-yet-elaborated subprograms. In such cases, we
26947 fall back to run-time checks; premature calls to any primitive
26948 operation of a tagged type before the body of the operation has been
26949 elaborated will raise @code{Program_Error}.
26951 Access-to-subprogram types, however, are handled conservatively, and
26952 do not require run-time checks. This was not true in earlier versions
26953 of the compiler; you can use the @option{-gnatd.U} debug switch to
26954 revert to the old behavior if the new conservative behavior causes
26955 elaboration cycles. Here, ``conservative'' means that if you do
26956 @code{P'Access} during elaboration, the compiler will assume that you
26957 might call @code{P} indirectly during elaboration, so it adds an
26958 implicit @code{pragma Elaborate_All} on the library unit containing
26959 @code{P}. The @option{-gnatd.U} switch is safe if you know there are
26960 no such calls. If the program worked before, it will continue to work
26961 with @option{-gnatd.U}. But beware that code modifications such as
26962 adding an indirect call can cause erroneous behavior in the presence
26963 of @option{-gnatd.U}.
26965 @node Summary of Procedures for Elaboration Control
26966 @section Summary of Procedures for Elaboration Control
26967 @cindex Elaboration control
26970 First, compile your program with the default options, using none of
26971 the special elaboration control switches. If the binder successfully
26972 binds your program, then you can be confident that, apart from issues
26973 raised by the use of access-to-subprogram types and dynamic dispatching,
26974 the program is free of elaboration errors. If it is important that the
26975 program be portable to other compilers than GNAT, then use the
26977 switch to generate messages about missing @code{Elaborate} or
26978 @code{Elaborate_All} pragmas, and supply the missing pragmas.
26980 If the program fails to bind using the default static elaboration
26981 handling, then you can fix the program to eliminate the binder
26982 message, or recompile the entire program with the
26983 @option{-gnatE} switch to generate dynamic elaboration checks,
26984 and, if you are sure there really are no elaboration problems,
26985 use a global pragma @code{Suppress (Elaboration_Check)}.
26987 @node Other Elaboration Order Considerations
26988 @section Other Elaboration Order Considerations
26990 This section has been entirely concerned with the issue of finding a valid
26991 elaboration order, as defined by the Ada Reference Manual. In a case
26992 where several elaboration orders are valid, the task is to find one
26993 of the possible valid elaboration orders (and the static model in GNAT
26994 will ensure that this is achieved).
26996 The purpose of the elaboration rules in the Ada Reference Manual is to
26997 make sure that no entity is accessed before it has been elaborated. For
26998 a subprogram, this means that the spec and body must have been elaborated
26999 before the subprogram is called. For an object, this means that the object
27000 must have been elaborated before its value is read or written. A violation
27001 of either of these two requirements is an access before elaboration order,
27002 and this section has been all about avoiding such errors.
27004 In the case where more than one order of elaboration is possible, in the
27005 sense that access before elaboration errors are avoided, then any one of
27006 the orders is ``correct'' in the sense that it meets the requirements of
27007 the Ada Reference Manual, and no such error occurs.
27009 However, it may be the case for a given program, that there are
27010 constraints on the order of elaboration that come not from consideration
27011 of avoiding elaboration errors, but rather from extra-lingual logic
27012 requirements. Consider this example:
27014 @smallexample @c ada
27015 with Init_Constants;
27016 package Constants is
27021 package Init_Constants is
27022 procedure P; -- require a body
27023 end Init_Constants;
27026 package body Init_Constants is
27027 procedure P is begin null; end;
27031 end Init_Constants;
27035 Z : Integer := Constants.X + Constants.Y;
27039 with Text_IO; use Text_IO;
27042 Put_Line (Calc.Z'Img);
27047 In this example, there is more than one valid order of elaboration. For
27048 example both the following are correct orders:
27051 Init_Constants spec
27054 Init_Constants body
27059 Init_Constants spec
27060 Init_Constants body
27067 There is no language rule to prefer one or the other, both are correct
27068 from an order of elaboration point of view. But the programmatic effects
27069 of the two orders are very different. In the first, the elaboration routine
27070 of @code{Calc} initializes @code{Z} to zero, and then the main program
27071 runs with this value of zero. But in the second order, the elaboration
27072 routine of @code{Calc} runs after the body of Init_Constants has set
27073 @code{X} and @code{Y} and thus @code{Z} is set to 7 before @code{Main}
27076 One could perhaps by applying pretty clever non-artificial intelligence
27077 to the situation guess that it is more likely that the second order of
27078 elaboration is the one desired, but there is no formal linguistic reason
27079 to prefer one over the other. In fact in this particular case, GNAT will
27080 prefer the second order, because of the rule that bodies are elaborated
27081 as soon as possible, but it's just luck that this is what was wanted
27082 (if indeed the second order was preferred).
27084 If the program cares about the order of elaboration routines in a case like
27085 this, it is important to specify the order required. In this particular
27086 case, that could have been achieved by adding to the spec of Calc:
27088 @smallexample @c ada
27089 pragma Elaborate_All (Constants);
27093 which requires that the body (if any) and spec of @code{Constants},
27094 as well as the body and spec of any unit @code{with}'ed by
27095 @code{Constants} be elaborated before @code{Calc} is elaborated.
27097 Clearly no automatic method can always guess which alternative you require,
27098 and if you are working with legacy code that had constraints of this kind
27099 which were not properly specified by adding @code{Elaborate} or
27100 @code{Elaborate_All} pragmas, then indeed it is possible that two different
27101 compilers can choose different orders.
27103 However, GNAT does attempt to diagnose the common situation where there
27104 are uninitialized variables in the visible part of a package spec, and the
27105 corresponding package body has an elaboration block that directly or
27106 indirectly initialized one or more of these variables. This is the situation
27107 in which a pragma Elaborate_Body is usually desirable, and GNAT will generate
27108 a warning that suggests this addition if it detects this situation.
27110 The @code{gnatbind}
27111 @option{^-p^/PESSIMISTIC_ELABORATION^} switch may be useful in smoking
27112 out problems. This switch causes bodies to be elaborated as late as possible
27113 instead of as early as possible. In the example above, it would have forced
27114 the choice of the first elaboration order. If you get different results
27115 when using this switch, and particularly if one set of results is right,
27116 and one is wrong as far as you are concerned, it shows that you have some
27117 missing @code{Elaborate} pragmas. For the example above, we have the
27121 gnatmake -f -q main
27124 gnatmake -f -q main -bargs -p
27130 It is of course quite unlikely that both these results are correct, so
27131 it is up to you in a case like this to investigate the source of the
27132 difference, by looking at the two elaboration orders that are chosen,
27133 and figuring out which is correct, and then adding the necessary
27134 @code{Elaborate} or @code{Elaborate_All} pragmas to ensure the desired order.
27136 @node Determining the Chosen Elaboration Order
27137 @section Determining the Chosen Elaboration Order
27140 To see the elaboration order that the binder chooses, you can look at
27141 the last part of the b~xxx.adb binder output file. Here is an example:
27143 @smallexample @c ada
27144 System.Soft_Links'Elab_Body;
27146 System.Secondary_Stack'Elab_Body;
27148 System.Exception_Table'Elab_Body;
27150 Ada.Io_Exceptions'Elab_Spec;
27152 Ada.Tags'Elab_Spec;
27153 Ada.Streams'Elab_Spec;
27155 Interfaces.C'Elab_Spec;
27157 System.Finalization_Root'Elab_Spec;
27159 System.Os_Lib'Elab_Body;
27161 System.Finalization_Implementation'Elab_Spec;
27162 System.Finalization_Implementation'Elab_Body;
27164 Ada.Finalization'Elab_Spec;
27166 Ada.Finalization.List_Controller'Elab_Spec;
27168 System.File_Control_Block'Elab_Spec;
27170 System.File_Io'Elab_Body;
27172 Ada.Tags'Elab_Body;
27174 Ada.Text_Io'Elab_Spec;
27175 Ada.Text_Io'Elab_Body;
27180 Here Elab_Spec elaborates the spec
27181 and Elab_Body elaborates the body. The assignments to the Exx flags
27182 flag that the corresponding body is now elaborated.
27184 You can also ask the binder to generate a more
27185 readable list of the elaboration order using the
27186 @code{-l} switch when invoking the binder. Here is
27187 an example of the output generated by this switch:
27193 system.case_util (spec)
27194 system.case_util (body)
27195 system.concat_2 (spec)
27196 system.concat_2 (body)
27197 system.concat_3 (spec)
27198 system.concat_3 (body)
27199 system.htable (spec)
27200 system.parameters (spec)
27201 system.parameters (body)
27203 interfaces.c_streams (spec)
27204 interfaces.c_streams (body)
27205 system.restrictions (spec)
27206 system.restrictions (body)
27207 system.standard_library (spec)
27208 system.exceptions (spec)
27209 system.exceptions (body)
27210 system.storage_elements (spec)
27211 system.storage_elements (body)
27212 system.secondary_stack (spec)
27213 system.stack_checking (spec)
27214 system.stack_checking (body)
27215 system.string_hash (spec)
27216 system.string_hash (body)
27217 system.htable (body)
27218 system.strings (spec)
27219 system.strings (body)
27220 system.traceback (spec)
27221 system.traceback (body)
27222 system.traceback_entries (spec)
27223 system.traceback_entries (body)
27224 ada.exceptions (spec)
27225 ada.exceptions.last_chance_handler (spec)
27226 system.soft_links (spec)
27227 system.soft_links (body)
27228 ada.exceptions.last_chance_handler (body)
27229 system.secondary_stack (body)
27230 system.exception_table (spec)
27231 system.exception_table (body)
27232 ada.io_exceptions (spec)
27235 interfaces.c (spec)
27236 interfaces.c (body)
27237 system.finalization_root (spec)
27238 system.finalization_root (body)
27239 system.memory (spec)
27240 system.memory (body)
27241 system.standard_library (body)
27242 system.os_lib (spec)
27243 system.os_lib (body)
27244 system.unsigned_types (spec)
27245 system.stream_attributes (spec)
27246 system.stream_attributes (body)
27247 system.finalization_implementation (spec)
27248 system.finalization_implementation (body)
27249 ada.finalization (spec)
27250 ada.finalization (body)
27251 ada.finalization.list_controller (spec)
27252 ada.finalization.list_controller (body)
27253 system.file_control_block (spec)
27254 system.file_io (spec)
27255 system.file_io (body)
27256 system.val_uns (spec)
27257 system.val_util (spec)
27258 system.val_util (body)
27259 system.val_uns (body)
27260 system.wch_con (spec)
27261 system.wch_con (body)
27262 system.wch_cnv (spec)
27263 system.wch_jis (spec)
27264 system.wch_jis (body)
27265 system.wch_cnv (body)
27266 system.wch_stw (spec)
27267 system.wch_stw (body)
27269 ada.exceptions (body)
27276 @c **********************************
27277 @node Overflow Check Handling in GNAT
27278 @appendix Overflow Check Handling in GNAT
27279 @cindex Overflow checks
27280 @cindex Checks (overflow)
27281 @c **********************************
27285 * Overflow Checking Modes in GNAT::
27286 * Specifying the Desired Mode::
27287 * Default Settings::
27288 * Implementation Notes::
27293 @section Background
27296 Overflow checks are checks that the compiler may make to ensure
27297 that intermediate results are not out of range. For example:
27299 @smallexample @c ada
27306 if @code{A} has the value @code{Integer'Last}, then the addition may cause
27307 overflow since the result is out of range of the type @code{Integer}.
27308 In this case @code{Constraint_Error} will be raised if checks are
27311 A trickier situation arises in examples like the following:
27313 @smallexample @c ada
27320 where @code{A} is @code{Integer'Last} and @code{C} is @code{-1}.
27321 Now the final result of the expression on the right hand side is
27322 @code{Integer'Last} which is in range, but the question arises whether the
27323 intermediate addition of @code{(A + 1)} raises an overflow error.
27325 The (perhaps surprising) answer is that the Ada language
27326 definition does not answer this question. Instead it leaves
27327 it up to the implementation to do one of two things if overflow
27328 checks are enabled.
27332 raise an exception (@code{Constraint_Error}), or
27335 yield the correct mathematical result which is then used in
27336 subsequent operations.
27340 If the compiler chooses the first approach, then the assignment of this
27341 example will indeed raise @code{Constraint_Error} if overflow checking is
27342 enabled, or result in erroneous execution if overflow checks are suppressed.
27344 But if the compiler
27345 chooses the second approach, then it can perform both additions yielding
27346 the correct mathematical result, which is in range, so no exception
27347 will be raised, and the right result is obtained, regardless of whether
27348 overflow checks are suppressed.
27350 Note that in the first example an
27351 exception will be raised in either case, since if the compiler
27352 gives the correct mathematical result for the addition, it will
27353 be out of range of the target type of the assignment, and thus
27354 fails the range check.
27356 This lack of specified behavior in the handling of overflow for
27357 intermediate results is a source of non-portability, and can thus
27358 be problematic when programs are ported. Most typically this arises
27359 in a situation where the original compiler did not raise an exception,
27360 and then the application is moved to a compiler where the check is
27361 performed on the intermediate result and an unexpected exception is
27364 Furthermore, when using Ada 2012's preconditions and other
27365 assertion forms, another issue arises. Consider:
27367 @smallexample @c ada
27368 procedure P (A, B : Integer) with
27369 Pre => A + B <= Integer'Last;
27373 One often wants to regard arithmetic in a context like this from
27374 a mathematical point of view. So for example, if the two actual parameters
27375 for a call to @code{P} are both @code{Integer'Last}, then
27376 the precondition should be regarded as False. If we are executing
27377 in a mode with run-time checks enabled for preconditions, then we would
27378 like this precondition to fail, rather than raising an exception
27379 because of the intermediate overflow.
27381 However, the language definition leaves the specification of
27382 whether the above condition fails (raising @code{Assert_Error}) or
27383 causes an intermediate overflow (raising @code{Constraint_Error})
27384 up to the implementation.
27386 The situation is worse in a case such as the following:
27388 @smallexample @c ada
27389 procedure Q (A, B, C : Integer) with
27390 Pre => A + B + C <= Integer'Last;
27396 @smallexample @c ada
27397 Q (A => Integer'Last, B => 1, C => -1);
27401 From a mathematical point of view the precondition
27402 is True, but at run time we may (but are not guaranteed to) get an
27403 exception raised because of the intermediate overflow (and we really
27404 would prefer this precondition to be considered True at run time).
27406 @node Overflow Checking Modes in GNAT
27407 @section Overflow Checking Modes in GNAT
27410 To deal with the portability issue, and with the problem of
27411 mathematical versus run-time interpretation of the expressions in
27412 assertions, GNAT provides comprehensive control over the handling
27413 of intermediate overflow. GNAT can operate in three modes, and
27414 furthemore, permits separate selection of operating modes for
27415 the expressions within assertions (here the term ``assertions''
27416 is used in the technical sense, which includes preconditions and so forth)
27417 and for expressions appearing outside assertions.
27419 The three modes are:
27422 @item @i{Use base type for intermediate operations} (@code{STRICT})
27424 In this mode, all intermediate results for predefined arithmetic
27425 operators are computed using the base type, and the result must
27426 be in range of the base type. If this is not the
27427 case then either an exception is raised (if overflow checks are
27428 enabled) or the execution is erroneous (if overflow checks are suppressed).
27429 This is the normal default mode.
27431 @item @i{Most intermediate overflows avoided} (@code{MINIMIZED})
27433 In this mode, the compiler attempts to avoid intermediate overflows by
27434 using a larger integer type, typically @code{Long_Long_Integer},
27435 as the type in which arithmetic is
27436 performed for predefined arithmetic operators. This may be slightly more
27438 run time (compared to suppressing intermediate overflow checks), though
27439 the cost is negligible on modern 64-bit machines. For the examples given
27440 earlier, no intermediate overflows would have resulted in exceptions,
27441 since the intermediate results are all in the range of
27442 @code{Long_Long_Integer} (typically 64-bits on nearly all implementations
27443 of GNAT). In addition, if checks are enabled, this reduces the number of
27444 checks that must be made, so this choice may actually result in an
27445 improvement in space and time behavior.
27447 However, there are cases where @code{Long_Long_Integer} is not large
27448 enough, consider the following example:
27450 @smallexample @c ada
27451 procedure R (A, B, C, D : Integer) with
27452 Pre => (A**2 * B**2) / (C**2 * D**2) <= 10;
27455 where @code{A} = @code{B} = @code{C} = @code{D} = @code{Integer'Last}.
27456 Now the intermediate results are
27457 out of the range of @code{Long_Long_Integer} even though the final result
27458 is in range and the precondition is True (from a mathematical point
27459 of view). In such a case, operating in this mode, an overflow occurs
27460 for the intermediate computation (which is why this mode
27461 says @i{most} intermediate overflows are avoided). In this case,
27462 an exception is raised if overflow checks are enabled, and the
27463 execution is erroneous if overflow checks are suppressed.
27465 @item @i{All intermediate overflows avoided} (@code{ELIMINATED})
27467 In this mode, the compiler avoids all intermediate overflows
27468 by using arbitrary precision arithmetic as required. In this
27469 mode, the above example with @code{A**2 * B**2} would
27470 not cause intermediate overflow, because the intermediate result
27471 would be evaluated using sufficient precision, and the result
27472 of evaluating the precondition would be True.
27474 This mode has the advantage of avoiding any intermediate
27475 overflows, but at the expense of significant run-time overhead,
27476 including the use of a library (included automatically in this
27477 mode) for multiple-precision arithmetic.
27479 This mode provides cleaner semantics for assertions, since now
27480 the run-time behavior emulates true arithmetic behavior for the
27481 predefined arithmetic operators, meaning that there is never a
27482 conflict between the mathematical view of the assertion, and its
27485 Note that in this mode, the behavior is unaffected by whether or
27486 not overflow checks are suppressed, since overflow does not occur.
27487 It is possible for gigantic intermediate expressions to raise
27488 @code{Storage_Error} as a result of attempting to compute the
27489 results of such expressions (e.g. @code{Integer'Last ** Integer'Last})
27490 but overflow is impossible.
27496 Note that these modes apply only to the evaluation of predefined
27497 arithmetic, membership, and comparison operators for signed integer
27500 For fixed-point arithmetic, checks can be suppressed. But if checks
27502 then fixed-point values are always checked for overflow against the
27503 base type for intermediate expressions (that is such checks always
27504 operate in the equivalent of @code{STRICT} mode).
27506 For floating-point, on nearly all architectures, @code{Machine_Overflows}
27507 is False, and IEEE infinities are generated, so overflow exceptions
27508 are never raised. If you want to avoid infinities, and check that
27509 final results of expressions are in range, then you can declare a
27510 constrained floating-point type, and range checks will be carried
27511 out in the normal manner (with infinite values always failing all
27515 @c -------------------------
27516 @node Specifying the Desired Mode
27517 @section Specifying the Desired Mode
27520 The desired mode of for handling intermediate overflow can be specified using
27521 either the @code{Overflow_Mode} pragma or an equivalent compiler switch.
27522 The pragma has the form
27523 @cindex pragma @code{Overflow_Mode}
27525 @smallexample @c ada
27526 pragma Overflow_Mode ([General =>] MODE [, [Assertions =>] MODE]);
27530 where @code{MODE} is one of
27533 @item @code{STRICT}: intermediate overflows checked (using base type)
27534 @item @code{MINIMIZED}: minimize intermediate overflows
27535 @item @code{ELIMINATED}: eliminate intermediate overflows
27539 The case is ignored, so @code{MINIMIZED}, @code{Minimized} and
27540 @code{minimized} all have the same effect.
27542 If only the @code{General} parameter is present, then the given @code{MODE}
27544 to expressions both within and outside assertions. If both arguments
27545 are present, then @code{General} applies to expressions outside assertions,
27546 and @code{Assertions} applies to expressions within assertions. For example:
27548 @smallexample @c ada
27549 pragma Overflow_Mode
27550 (General => Minimized, Assertions => Eliminated);
27554 specifies that general expressions outside assertions be evaluated
27555 in ``minimize intermediate overflows'' mode, and expressions within
27556 assertions be evaluated in ``eliminate intermediate overflows'' mode.
27557 This is often a reasonable choice, avoiding excessive overhead
27558 outside assertions, but assuring a high degree of portability
27559 when importing code from another compiler, while incurring
27560 the extra overhead for assertion expressions to ensure that
27561 the behavior at run time matches the expected mathematical
27564 The @code{Overflow_Mode} pragma has the same scoping and placement
27565 rules as pragma @code{Suppress}, so it can occur either as a
27566 configuration pragma, specifying a default for the whole
27567 program, or in a declarative scope, where it applies to the
27568 remaining declarations and statements in that scope.
27570 Note that pragma @code{Overflow_Mode} does not affect whether
27571 overflow checks are enabled or suppressed. It only controls the
27572 method used to compute intermediate values. To control whether
27573 overflow checking is enabled or suppressed, use pragma @code{Suppress}
27574 or @code{Unsuppress} in the usual manner
27576 Additionally, a compiler switch @option{-gnato?} or @option{-gnato??}
27577 can be used to control the checking mode default (which can be subsequently
27578 overridden using pragmas).
27579 @cindex @option{-gnato?} (gcc)
27580 @cindex @option{-gnato??} (gcc)
27582 Here `@code{?}' is one of the digits `@code{1}' through `@code{3}':
27586 use base type for intermediate operations (@code{STRICT})
27588 minimize intermediate overflows (@code{MINIMIZED})
27590 eliminate intermediate overflows (@code{ELIMINATED})
27594 As with the pragma, if only one digit appears then it applies to all
27595 cases; if two digits are given, then the first applies outside
27596 assertions, and the second within assertions. Thus the equivalent
27597 of the example pragma above would be
27598 @option{^-gnato23^/OVERFLOW_CHECKS=23^}.
27600 If no digits follow the @option{-gnato}, then it is equivalent to
27601 @option{^-gnato11^/OVERFLOW_CHECKS=11^},
27602 causing all intermediate operations to be computed using the base
27603 type (@code{STRICT} mode).
27605 In addition to setting the mode used for computation of intermediate
27606 results, the @code{-gnato} switch also enables overflow checking (which
27607 is suppressed by default). It thus combines the effect of using
27608 a pragma @code{Overflow_Mode} and pragma @code{Unsuppress}.
27611 @c -------------------------
27612 @node Default Settings
27613 @section Default Settings
27615 The default mode for overflow checks is
27622 which causes all computations both inside and outside assertions to use
27623 the base type. In addition overflow checks are suppressed.
27625 This retains compatibility with previous versions of
27626 GNAT which suppressed overflow checks by default and always
27627 used the base type for computation of intermediate results.
27629 The switch @option{-gnato} (with no digits following) is equivalent to
27630 @cindex @option{-gnato} (gcc)
27637 which causes overflow checking of all intermediate overflows
27638 both inside and outside assertions against the base type.
27639 This provides compatibility
27640 with this switch as implemented in previous versions of GNAT.
27642 The pragma @code{Suppress (Overflow_Check)} disables overflow
27643 checking, but it has no effect on the method used for computing
27644 intermediate results.
27646 The pragma @code{Unsuppress (Overflow_Check)} enables overflow
27647 checking, but it has no effect on the method used for computing
27648 intermediate results.
27650 @c -------------------------
27651 @node Implementation Notes
27652 @section Implementation Notes
27654 In practice on typical 64-bit machines, the @code{MINIMIZED} mode is
27655 reasonably efficient, and can be generally used. It also helps
27656 to ensure compatibility with code imported from some other
27659 Setting all intermediate overflows checking (@code{CHECKED} mode)
27660 makes sense if you want to
27661 make sure that your code is compatible with any other possible
27662 Ada implementation. This may be useful in ensuring portability
27663 for code that is to be exported to some other compiler than GNAT.
27666 The Ada standard allows the reassociation of expressions at
27667 the same precedence level if no parentheses are present. For
27668 example, @w{@code{A+B+C}} parses as though it were @w{@code{(A+B)+C}}, but
27669 the compiler can reintepret this as @w{@code{A+(B+C)}}, possibly
27670 introducing or eliminating an overflow exception. The GNAT
27671 compiler never takes advantage of this freedom, and the
27672 expression @w{@code{A+B+C}} will be evaluated as @w{@code{(A+B)+C}}.
27673 If you need the other order, you can write the parentheses
27674 explicitly @w{@code{A+(B+C)}} and GNAT will respect this order.
27676 The use of @code{ELIMINATED} mode will cause the compiler to
27677 automatically include an appropriate arbitrary precision
27678 integer arithmetic package. The compiler will make calls
27679 to this package, though only in cases where it cannot be
27680 sure that @code{Long_Long_Integer} is sufficient to guard against
27681 intermediate overflows. This package does not use dynamic
27682 alllocation, but it does use the secondary stack, so an
27683 appropriate secondary stack package must be present (this
27684 is always true for standard full Ada, but may require
27685 specific steps for restricted run times such as ZFP).
27687 Although @code{ELIMINATED} mode causes expressions to use arbitrary
27688 precision arithmetic, avoiding overflow, the final result
27689 must be in an appropriate range. This is true even if the
27690 final result is of type @code{[Long_[Long_]]Integer'Base}, which
27691 still has the same bounds as its associated constrained
27694 Currently, the @code{ELIMINATED} mode is only available on target
27695 platforms for which @code{Long_Long_Integer} is 64-bits (nearly all GNAT
27698 @c *******************************
27699 @node Conditional Compilation
27700 @appendix Conditional Compilation
27701 @c *******************************
27702 @cindex Conditional compilation
27705 It is often necessary to arrange for a single source program
27706 to serve multiple purposes, where it is compiled in different
27707 ways to achieve these different goals. Some examples of the
27708 need for this feature are
27711 @item Adapting a program to a different hardware environment
27712 @item Adapting a program to a different target architecture
27713 @item Turning debugging features on and off
27714 @item Arranging for a program to compile with different compilers
27718 In C, or C++, the typical approach would be to use the preprocessor
27719 that is defined as part of the language. The Ada language does not
27720 contain such a feature. This is not an oversight, but rather a very
27721 deliberate design decision, based on the experience that overuse of
27722 the preprocessing features in C and C++ can result in programs that
27723 are extremely difficult to maintain. For example, if we have ten
27724 switches that can be on or off, this means that there are a thousand
27725 separate programs, any one of which might not even be syntactically
27726 correct, and even if syntactically correct, the resulting program
27727 might not work correctly. Testing all combinations can quickly become
27730 Nevertheless, the need to tailor programs certainly exists, and in
27731 this Appendix we will discuss how this can
27732 be achieved using Ada in general, and GNAT in particular.
27735 * Use of Boolean Constants::
27736 * Debugging - A Special Case::
27737 * Conditionalizing Declarations::
27738 * Use of Alternative Implementations::
27742 @node Use of Boolean Constants
27743 @section Use of Boolean Constants
27746 In the case where the difference is simply which code
27747 sequence is executed, the cleanest solution is to use Boolean
27748 constants to control which code is executed.
27750 @smallexample @c ada
27752 FP_Initialize_Required : constant Boolean := True;
27754 if FP_Initialize_Required then
27761 Not only will the code inside the @code{if} statement not be executed if
27762 the constant Boolean is @code{False}, but it will also be completely
27763 deleted from the program.
27764 However, the code is only deleted after the @code{if} statement
27765 has been checked for syntactic and semantic correctness.
27766 (In contrast, with preprocessors the code is deleted before the
27767 compiler ever gets to see it, so it is not checked until the switch
27769 @cindex Preprocessors (contrasted with conditional compilation)
27771 Typically the Boolean constants will be in a separate package,
27774 @smallexample @c ada
27777 FP_Initialize_Required : constant Boolean := True;
27778 Reset_Available : constant Boolean := False;
27785 The @code{Config} package exists in multiple forms for the various targets,
27786 with an appropriate script selecting the version of @code{Config} needed.
27787 Then any other unit requiring conditional compilation can do a @code{with}
27788 of @code{Config} to make the constants visible.
27791 @node Debugging - A Special Case
27792 @section Debugging - A Special Case
27795 A common use of conditional code is to execute statements (for example
27796 dynamic checks, or output of intermediate results) under control of a
27797 debug switch, so that the debugging behavior can be turned on and off.
27798 This can be done using a Boolean constant to control whether the code
27801 @smallexample @c ada
27804 Put_Line ("got to the first stage!");
27812 @smallexample @c ada
27814 if Debugging and then Temperature > 999.0 then
27815 raise Temperature_Crazy;
27821 Since this is a common case, there are special features to deal with
27822 this in a convenient manner. For the case of tests, Ada 2005 has added
27823 a pragma @code{Assert} that can be used for such tests. This pragma is modeled
27824 @cindex pragma @code{Assert}
27825 on the @code{Assert} pragma that has always been available in GNAT, so this
27826 feature may be used with GNAT even if you are not using Ada 2005 features.
27827 The use of pragma @code{Assert} is described in
27828 @ref{Pragma Assert,,, gnat_rm, GNAT Reference Manual}, but as an
27829 example, the last test could be written:
27831 @smallexample @c ada
27832 pragma Assert (Temperature <= 999.0, "Temperature Crazy");
27838 @smallexample @c ada
27839 pragma Assert (Temperature <= 999.0);
27843 In both cases, if assertions are active and the temperature is excessive,
27844 the exception @code{Assert_Failure} will be raised, with the given string in
27845 the first case or a string indicating the location of the pragma in the second
27846 case used as the exception message.
27848 You can turn assertions on and off by using the @code{Assertion_Policy}
27850 @cindex pragma @code{Assertion_Policy}
27851 This is an Ada 2005 pragma which is implemented in all modes by
27852 GNAT, but only in the latest versions of GNAT which include Ada 2005
27853 capability. Alternatively, you can use the @option{-gnata} switch
27854 @cindex @option{-gnata} switch
27855 to enable assertions from the command line (this is recognized by all versions
27858 For the example above with the @code{Put_Line}, the GNAT-specific pragma
27859 @code{Debug} can be used:
27860 @cindex pragma @code{Debug}
27862 @smallexample @c ada
27863 pragma Debug (Put_Line ("got to the first stage!"));
27867 If debug pragmas are enabled, the argument, which must be of the form of
27868 a procedure call, is executed (in this case, @code{Put_Line} will be called).
27869 Only one call can be present, but of course a special debugging procedure
27870 containing any code you like can be included in the program and then
27871 called in a pragma @code{Debug} argument as needed.
27873 One advantage of pragma @code{Debug} over the @code{if Debugging then}
27874 construct is that pragma @code{Debug} can appear in declarative contexts,
27875 such as at the very beginning of a procedure, before local declarations have
27878 Debug pragmas are enabled using either the @option{-gnata} switch that also
27879 controls assertions, or with a separate Debug_Policy pragma.
27880 @cindex pragma @code{Debug_Policy}
27881 The latter pragma is new in the Ada 2005 versions of GNAT (but it can be used
27882 in Ada 95 and Ada 83 programs as well), and is analogous to
27883 pragma @code{Assertion_Policy} to control assertions.
27885 @code{Assertion_Policy} and @code{Debug_Policy} are configuration pragmas,
27886 and thus they can appear in @file{gnat.adc} if you are not using a
27887 project file, or in the file designated to contain configuration pragmas
27889 They then apply to all subsequent compilations. In practice the use of
27890 the @option{-gnata} switch is often the most convenient method of controlling
27891 the status of these pragmas.
27893 Note that a pragma is not a statement, so in contexts where a statement
27894 sequence is required, you can't just write a pragma on its own. You have
27895 to add a @code{null} statement.
27897 @smallexample @c ada
27900 @dots{} -- some statements
27902 pragma Assert (Num_Cases < 10);
27909 @node Conditionalizing Declarations
27910 @section Conditionalizing Declarations
27913 In some cases, it may be necessary to conditionalize declarations to meet
27914 different requirements. For example we might want a bit string whose length
27915 is set to meet some hardware message requirement.
27917 In some cases, it may be possible to do this using declare blocks controlled
27918 by conditional constants:
27920 @smallexample @c ada
27922 if Small_Machine then
27924 X : Bit_String (1 .. 10);
27930 X : Large_Bit_String (1 .. 1000);
27939 Note that in this approach, both declarations are analyzed by the
27940 compiler so this can only be used where both declarations are legal,
27941 even though one of them will not be used.
27943 Another approach is to define integer constants, e.g.@: @code{Bits_Per_Word},
27944 or Boolean constants, e.g.@: @code{Little_Endian}, and then write declarations
27945 that are parameterized by these constants. For example
27947 @smallexample @c ada
27950 Field1 at 0 range Boolean'Pos (Little_Endian) * 10 .. Bits_Per_Word;
27956 If @code{Bits_Per_Word} is set to 32, this generates either
27958 @smallexample @c ada
27961 Field1 at 0 range 0 .. 32;
27967 for the big endian case, or
27969 @smallexample @c ada
27972 Field1 at 0 range 10 .. 32;
27978 for the little endian case. Since a powerful subset of Ada expression
27979 notation is usable for creating static constants, clever use of this
27980 feature can often solve quite difficult problems in conditionalizing
27981 compilation (note incidentally that in Ada 95, the little endian
27982 constant was introduced as @code{System.Default_Bit_Order}, so you do not
27983 need to define this one yourself).
27986 @node Use of Alternative Implementations
27987 @section Use of Alternative Implementations
27990 In some cases, none of the approaches described above are adequate. This
27991 can occur for example if the set of declarations required is radically
27992 different for two different configurations.
27994 In this situation, the official Ada way of dealing with conditionalizing
27995 such code is to write separate units for the different cases. As long as
27996 this does not result in excessive duplication of code, this can be done
27997 without creating maintenance problems. The approach is to share common
27998 code as far as possible, and then isolate the code and declarations
27999 that are different. Subunits are often a convenient method for breaking
28000 out a piece of a unit that is to be conditionalized, with separate files
28001 for different versions of the subunit for different targets, where the
28002 build script selects the right one to give to the compiler.
28003 @cindex Subunits (and conditional compilation)
28005 As an example, consider a situation where a new feature in Ada 2005
28006 allows something to be done in a really nice way. But your code must be able
28007 to compile with an Ada 95 compiler. Conceptually you want to say:
28009 @smallexample @c ada
28012 @dots{} neat Ada 2005 code
28014 @dots{} not quite as neat Ada 95 code
28020 where @code{Ada_2005} is a Boolean constant.
28022 But this won't work when @code{Ada_2005} is set to @code{False},
28023 since the @code{then} clause will be illegal for an Ada 95 compiler.
28024 (Recall that although such unreachable code would eventually be deleted
28025 by the compiler, it still needs to be legal. If it uses features
28026 introduced in Ada 2005, it will be illegal in Ada 95.)
28028 So instead we write
28030 @smallexample @c ada
28031 procedure Insert is separate;
28035 Then we have two files for the subunit @code{Insert}, with the two sets of
28037 If the package containing this is called @code{File_Queries}, then we might
28041 @item @file{file_queries-insert-2005.adb}
28042 @item @file{file_queries-insert-95.adb}
28046 and the build script renames the appropriate file to
28049 file_queries-insert.adb
28053 and then carries out the compilation.
28055 This can also be done with project files' naming schemes. For example:
28057 @smallexample @c project
28058 For Body ("File_Queries.Insert") use "file_queries-insert-2005.ada";
28062 Note also that with project files it is desirable to use a different extension
28063 than @file{ads} / @file{adb} for alternative versions. Otherwise a naming
28064 conflict may arise through another commonly used feature: to declare as part
28065 of the project a set of directories containing all the sources obeying the
28066 default naming scheme.
28068 The use of alternative units is certainly feasible in all situations,
28069 and for example the Ada part of the GNAT run-time is conditionalized
28070 based on the target architecture using this approach. As a specific example,
28071 consider the implementation of the AST feature in VMS. There is one
28079 which is the same for all architectures, and three bodies:
28083 used for all non-VMS operating systems
28084 @item s-asthan-vms-alpha.adb
28085 used for VMS on the Alpha
28086 @item s-asthan-vms-ia64.adb
28087 used for VMS on the ia64
28091 The dummy version @file{s-asthan.adb} simply raises exceptions noting that
28092 this operating system feature is not available, and the two remaining
28093 versions interface with the corresponding versions of VMS to provide
28094 VMS-compatible AST handling. The GNAT build script knows the architecture
28095 and operating system, and automatically selects the right version,
28096 renaming it if necessary to @file{s-asthan.adb} before the run-time build.
28098 Another style for arranging alternative implementations is through Ada's
28099 access-to-subprogram facility.
28100 In case some functionality is to be conditionally included,
28101 you can declare an access-to-procedure variable @code{Ref} that is initialized
28102 to designate a ``do nothing'' procedure, and then invoke @code{Ref.all}
28104 In some library package, set @code{Ref} to @code{Proc'Access} for some
28105 procedure @code{Proc} that performs the relevant processing.
28106 The initialization only occurs if the library package is included in the
28108 The same idea can also be implemented using tagged types and dispatching
28112 @node Preprocessing
28113 @section Preprocessing
28114 @cindex Preprocessing
28117 Although it is quite possible to conditionalize code without the use of
28118 C-style preprocessing, as described earlier in this section, it is
28119 nevertheless convenient in some cases to use the C approach. Moreover,
28120 older Ada compilers have often provided some preprocessing capability,
28121 so legacy code may depend on this approach, even though it is not
28124 To accommodate such use, GNAT provides a preprocessor (modeled to a large
28125 extent on the various preprocessors that have been used
28126 with legacy code on other compilers, to enable easier transition).
28128 The preprocessor may be used in two separate modes. It can be used quite
28129 separately from the compiler, to generate a separate output source file
28130 that is then fed to the compiler as a separate step. This is the
28131 @code{gnatprep} utility, whose use is fully described in
28132 @ref{Preprocessing with gnatprep}.
28133 @cindex @code{gnatprep}
28135 The preprocessing language allows such constructs as
28139 #if DEBUG or else (PRIORITY > 4) then
28140 bunch of declarations
28142 completely different bunch of declarations
28148 The values of the symbols @code{DEBUG} and @code{PRIORITY} can be
28149 defined either on the command line or in a separate file.
28151 The other way of running the preprocessor is even closer to the C style and
28152 often more convenient. In this approach the preprocessing is integrated into
28153 the compilation process. The compiler is fed the preprocessor input which
28154 includes @code{#if} lines etc, and then the compiler carries out the
28155 preprocessing internally and processes the resulting output.
28156 For more details on this approach, see @ref{Integrated Preprocessing}.
28159 @c *******************************
28160 @node Inline Assembler
28161 @appendix Inline Assembler
28162 @c *******************************
28165 If you need to write low-level software that interacts directly
28166 with the hardware, Ada provides two ways to incorporate assembly
28167 language code into your program. First, you can import and invoke
28168 external routines written in assembly language, an Ada feature fully
28169 supported by GNAT@. However, for small sections of code it may be simpler
28170 or more efficient to include assembly language statements directly
28171 in your Ada source program, using the facilities of the implementation-defined
28172 package @code{System.Machine_Code}, which incorporates the gcc
28173 Inline Assembler. The Inline Assembler approach offers a number of advantages,
28174 including the following:
28177 @item No need to use non-Ada tools
28178 @item Consistent interface over different targets
28179 @item Automatic usage of the proper calling conventions
28180 @item Access to Ada constants and variables
28181 @item Definition of intrinsic routines
28182 @item Possibility of inlining a subprogram comprising assembler code
28183 @item Code optimizer can take Inline Assembler code into account
28186 This chapter presents a series of examples to show you how to use
28187 the Inline Assembler. Although it focuses on the Intel x86,
28188 the general approach applies also to other processors.
28189 It is assumed that you are familiar with Ada
28190 and with assembly language programming.
28193 * Basic Assembler Syntax::
28194 * A Simple Example of Inline Assembler::
28195 * Output Variables in Inline Assembler::
28196 * Input Variables in Inline Assembler::
28197 * Inlining Inline Assembler Code::
28198 * Other Asm Functionality::
28201 @c ---------------------------------------------------------------------------
28202 @node Basic Assembler Syntax
28203 @section Basic Assembler Syntax
28206 The assembler used by GNAT and gcc is based not on the Intel assembly
28207 language, but rather on a language that descends from the AT&T Unix
28208 assembler @emph{as} (and which is often referred to as ``AT&T syntax'').
28209 The following table summarizes the main features of @emph{as} syntax
28210 and points out the differences from the Intel conventions.
28211 See the gcc @emph{as} and @emph{gas} (an @emph{as} macro
28212 pre-processor) documentation for further information.
28215 @item Register names
28216 gcc / @emph{as}: Prefix with ``%''; for example @code{%eax}
28218 Intel: No extra punctuation; for example @code{eax}
28220 @item Immediate operand
28221 gcc / @emph{as}: Prefix with ``$''; for example @code{$4}
28223 Intel: No extra punctuation; for example @code{4}
28226 gcc / @emph{as}: Prefix with ``$''; for example @code{$loc}
28228 Intel: No extra punctuation; for example @code{loc}
28230 @item Memory contents
28231 gcc / @emph{as}: No extra punctuation; for example @code{loc}
28233 Intel: Square brackets; for example @code{[loc]}
28235 @item Register contents
28236 gcc / @emph{as}: Parentheses; for example @code{(%eax)}
28238 Intel: Square brackets; for example @code{[eax]}
28240 @item Hexadecimal numbers
28241 gcc / @emph{as}: Leading ``0x'' (C language syntax); for example @code{0xA0}
28243 Intel: Trailing ``h''; for example @code{A0h}
28246 gcc / @emph{as}: Explicit in op code; for example @code{movw} to move
28249 Intel: Implicit, deduced by assembler; for example @code{mov}
28251 @item Instruction repetition
28252 gcc / @emph{as}: Split into two lines; for example
28258 Intel: Keep on one line; for example @code{rep stosl}
28260 @item Order of operands
28261 gcc / @emph{as}: Source first; for example @code{movw $4, %eax}
28263 Intel: Destination first; for example @code{mov eax, 4}
28266 @c ---------------------------------------------------------------------------
28267 @node A Simple Example of Inline Assembler
28268 @section A Simple Example of Inline Assembler
28271 The following example will generate a single assembly language statement,
28272 @code{nop}, which does nothing. Despite its lack of run-time effect,
28273 the example will be useful in illustrating the basics of
28274 the Inline Assembler facility.
28276 @smallexample @c ada
28278 with System.Machine_Code; use System.Machine_Code;
28279 procedure Nothing is
28286 @code{Asm} is a procedure declared in package @code{System.Machine_Code};
28287 here it takes one parameter, a @emph{template string} that must be a static
28288 expression and that will form the generated instruction.
28289 @code{Asm} may be regarded as a compile-time procedure that parses
28290 the template string and additional parameters (none here),
28291 from which it generates a sequence of assembly language instructions.
28293 The examples in this chapter will illustrate several of the forms
28294 for invoking @code{Asm}; a complete specification of the syntax
28295 is found in @ref{Machine Code Insertions,,, gnat_rm, GNAT Reference
28298 Under the standard GNAT conventions, the @code{Nothing} procedure
28299 should be in a file named @file{nothing.adb}.
28300 You can build the executable in the usual way:
28304 However, the interesting aspect of this example is not its run-time behavior
28305 but rather the generated assembly code.
28306 To see this output, invoke the compiler as follows:
28308 gcc -c -S -fomit-frame-pointer -gnatp @file{nothing.adb}
28310 where the options are:
28314 compile only (no bind or link)
28316 generate assembler listing
28317 @item -fomit-frame-pointer
28318 do not set up separate stack frames
28320 do not add runtime checks
28323 This gives a human-readable assembler version of the code. The resulting
28324 file will have the same name as the Ada source file, but with a @code{.s}
28325 extension. In our example, the file @file{nothing.s} has the following
28330 .file "nothing.adb"
28332 ___gnu_compiled_ada:
28335 .globl __ada_nothing
28347 The assembly code you included is clearly indicated by
28348 the compiler, between the @code{#APP} and @code{#NO_APP}
28349 delimiters. The character before the 'APP' and 'NOAPP'
28350 can differ on different targets. For example, GNU/Linux uses '#APP' while
28351 on NT you will see '/APP'.
28353 If you make a mistake in your assembler code (such as using the
28354 wrong size modifier, or using a wrong operand for the instruction) GNAT
28355 will report this error in a temporary file, which will be deleted when
28356 the compilation is finished. Generating an assembler file will help
28357 in such cases, since you can assemble this file separately using the
28358 @emph{as} assembler that comes with gcc.
28360 Assembling the file using the command
28363 as @file{nothing.s}
28366 will give you error messages whose lines correspond to the assembler
28367 input file, so you can easily find and correct any mistakes you made.
28368 If there are no errors, @emph{as} will generate an object file
28369 @file{nothing.out}.
28371 @c ---------------------------------------------------------------------------
28372 @node Output Variables in Inline Assembler
28373 @section Output Variables in Inline Assembler
28376 The examples in this section, showing how to access the processor flags,
28377 illustrate how to specify the destination operands for assembly language
28380 @smallexample @c ada
28382 with Interfaces; use Interfaces;
28383 with Ada.Text_IO; use Ada.Text_IO;
28384 with System.Machine_Code; use System.Machine_Code;
28385 procedure Get_Flags is
28386 Flags : Unsigned_32;
28389 Asm ("pushfl" & LF & HT & -- push flags on stack
28390 "popl %%eax" & LF & HT & -- load eax with flags
28391 "movl %%eax, %0", -- store flags in variable
28392 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
28393 Put_Line ("Flags register:" & Flags'Img);
28398 In order to have a nicely aligned assembly listing, we have separated
28399 multiple assembler statements in the Asm template string with linefeed
28400 (ASCII.LF) and horizontal tab (ASCII.HT) characters.
28401 The resulting section of the assembly output file is:
28408 movl %eax, -40(%ebp)
28413 It would have been legal to write the Asm invocation as:
28416 Asm ("pushfl popl %%eax movl %%eax, %0")
28419 but in the generated assembler file, this would come out as:
28423 pushfl popl %eax movl %eax, -40(%ebp)
28427 which is not so convenient for the human reader.
28429 We use Ada comments
28430 at the end of each line to explain what the assembler instructions
28431 actually do. This is a useful convention.
28433 When writing Inline Assembler instructions, you need to precede each register
28434 and variable name with a percent sign. Since the assembler already requires
28435 a percent sign at the beginning of a register name, you need two consecutive
28436 percent signs for such names in the Asm template string, thus @code{%%eax}.
28437 In the generated assembly code, one of the percent signs will be stripped off.
28439 Names such as @code{%0}, @code{%1}, @code{%2}, etc., denote input or output
28440 variables: operands you later define using @code{Input} or @code{Output}
28441 parameters to @code{Asm}.
28442 An output variable is illustrated in
28443 the third statement in the Asm template string:
28447 The intent is to store the contents of the eax register in a variable that can
28448 be accessed in Ada. Simply writing @code{movl %%eax, Flags} would not
28449 necessarily work, since the compiler might optimize by using a register
28450 to hold Flags, and the expansion of the @code{movl} instruction would not be
28451 aware of this optimization. The solution is not to store the result directly
28452 but rather to advise the compiler to choose the correct operand form;
28453 that is the purpose of the @code{%0} output variable.
28455 Information about the output variable is supplied in the @code{Outputs}
28456 parameter to @code{Asm}:
28458 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
28461 The output is defined by the @code{Asm_Output} attribute of the target type;
28462 the general format is
28464 Type'Asm_Output (constraint_string, variable_name)
28467 The constraint string directs the compiler how
28468 to store/access the associated variable. In the example
28470 Unsigned_32'Asm_Output ("=m", Flags);
28472 the @code{"m"} (memory) constraint tells the compiler that the variable
28473 @code{Flags} should be stored in a memory variable, thus preventing
28474 the optimizer from keeping it in a register. In contrast,
28476 Unsigned_32'Asm_Output ("=r", Flags);
28478 uses the @code{"r"} (register) constraint, telling the compiler to
28479 store the variable in a register.
28481 If the constraint is preceded by the equal character (@strong{=}), it tells
28482 the compiler that the variable will be used to store data into it.
28484 In the @code{Get_Flags} example, we used the @code{"g"} (global) constraint,
28485 allowing the optimizer to choose whatever it deems best.
28487 There are a fairly large number of constraints, but the ones that are
28488 most useful (for the Intel x86 processor) are the following:
28494 global (i.e.@: can be stored anywhere)
28512 use one of eax, ebx, ecx or edx
28514 use one of eax, ebx, ecx, edx, esi or edi
28517 The full set of constraints is described in the gcc and @emph{as}
28518 documentation; note that it is possible to combine certain constraints
28519 in one constraint string.
28521 You specify the association of an output variable with an assembler operand
28522 through the @code{%}@emph{n} notation, where @emph{n} is a non-negative
28524 @smallexample @c ada
28526 Asm ("pushfl" & LF & HT & -- push flags on stack
28527 "popl %%eax" & LF & HT & -- load eax with flags
28528 "movl %%eax, %0", -- store flags in variable
28529 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
28533 @code{%0} will be replaced in the expanded code by the appropriate operand,
28535 the compiler decided for the @code{Flags} variable.
28537 In general, you may have any number of output variables:
28540 Count the operands starting at 0; thus @code{%0}, @code{%1}, etc.
28542 Specify the @code{Outputs} parameter as a parenthesized comma-separated list
28543 of @code{Asm_Output} attributes
28547 @smallexample @c ada
28549 Asm ("movl %%eax, %0" & LF & HT &
28550 "movl %%ebx, %1" & LF & HT &
28552 Outputs => (Unsigned_32'Asm_Output ("=g", Var_A), -- %0 = Var_A
28553 Unsigned_32'Asm_Output ("=g", Var_B), -- %1 = Var_B
28554 Unsigned_32'Asm_Output ("=g", Var_C))); -- %2 = Var_C
28558 where @code{Var_A}, @code{Var_B}, and @code{Var_C} are variables
28559 in the Ada program.
28561 As a variation on the @code{Get_Flags} example, we can use the constraints
28562 string to direct the compiler to store the eax register into the @code{Flags}
28563 variable, instead of including the store instruction explicitly in the
28564 @code{Asm} template string:
28566 @smallexample @c ada
28568 with Interfaces; use Interfaces;
28569 with Ada.Text_IO; use Ada.Text_IO;
28570 with System.Machine_Code; use System.Machine_Code;
28571 procedure Get_Flags_2 is
28572 Flags : Unsigned_32;
28575 Asm ("pushfl" & LF & HT & -- push flags on stack
28576 "popl %%eax", -- save flags in eax
28577 Outputs => Unsigned_32'Asm_Output ("=a", Flags));
28578 Put_Line ("Flags register:" & Flags'Img);
28584 The @code{"a"} constraint tells the compiler that the @code{Flags}
28585 variable will come from the eax register. Here is the resulting code:
28593 movl %eax,-40(%ebp)
28598 The compiler generated the store of eax into Flags after
28599 expanding the assembler code.
28601 Actually, there was no need to pop the flags into the eax register;
28602 more simply, we could just pop the flags directly into the program variable:
28604 @smallexample @c ada
28606 with Interfaces; use Interfaces;
28607 with Ada.Text_IO; use Ada.Text_IO;
28608 with System.Machine_Code; use System.Machine_Code;
28609 procedure Get_Flags_3 is
28610 Flags : Unsigned_32;
28613 Asm ("pushfl" & LF & HT & -- push flags on stack
28614 "pop %0", -- save flags in Flags
28615 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
28616 Put_Line ("Flags register:" & Flags'Img);
28621 @c ---------------------------------------------------------------------------
28622 @node Input Variables in Inline Assembler
28623 @section Input Variables in Inline Assembler
28626 The example in this section illustrates how to specify the source operands
28627 for assembly language statements.
28628 The program simply increments its input value by 1:
28630 @smallexample @c ada
28632 with Interfaces; use Interfaces;
28633 with Ada.Text_IO; use Ada.Text_IO;
28634 with System.Machine_Code; use System.Machine_Code;
28635 procedure Increment is
28637 function Incr (Value : Unsigned_32) return Unsigned_32 is
28638 Result : Unsigned_32;
28641 Outputs => Unsigned_32'Asm_Output ("=a", Result),
28642 Inputs => Unsigned_32'Asm_Input ("a", Value));
28646 Value : Unsigned_32;
28650 Put_Line ("Value before is" & Value'Img);
28651 Value := Incr (Value);
28652 Put_Line ("Value after is" & Value'Img);
28657 The @code{Outputs} parameter to @code{Asm} specifies
28658 that the result will be in the eax register and that it is to be stored
28659 in the @code{Result} variable.
28661 The @code{Inputs} parameter looks much like the @code{Outputs} parameter,
28662 but with an @code{Asm_Input} attribute.
28663 The @code{"="} constraint, indicating an output value, is not present.
28665 You can have multiple input variables, in the same way that you can have more
28666 than one output variable.
28668 The parameter count (%0, %1) etc, still starts at the first output statement,
28669 and continues with the input statements.
28671 Just as the @code{Outputs} parameter causes the register to be stored into the
28672 target variable after execution of the assembler statements, so does the
28673 @code{Inputs} parameter cause its variable to be loaded into the register
28674 before execution of the assembler statements.
28676 Thus the effect of the @code{Asm} invocation is:
28678 @item load the 32-bit value of @code{Value} into eax
28679 @item execute the @code{incl %eax} instruction
28680 @item store the contents of eax into the @code{Result} variable
28683 The resulting assembler file (with @option{-O2} optimization) contains:
28686 _increment__incr.1:
28699 @c ---------------------------------------------------------------------------
28700 @node Inlining Inline Assembler Code
28701 @section Inlining Inline Assembler Code
28704 For a short subprogram such as the @code{Incr} function in the previous
28705 section, the overhead of the call and return (creating / deleting the stack
28706 frame) can be significant, compared to the amount of code in the subprogram
28707 body. A solution is to apply Ada's @code{Inline} pragma to the subprogram,
28708 which directs the compiler to expand invocations of the subprogram at the
28709 point(s) of call, instead of setting up a stack frame for out-of-line calls.
28710 Here is the resulting program:
28712 @smallexample @c ada
28714 with Interfaces; use Interfaces;
28715 with Ada.Text_IO; use Ada.Text_IO;
28716 with System.Machine_Code; use System.Machine_Code;
28717 procedure Increment_2 is
28719 function Incr (Value : Unsigned_32) return Unsigned_32 is
28720 Result : Unsigned_32;
28723 Outputs => Unsigned_32'Asm_Output ("=a", Result),
28724 Inputs => Unsigned_32'Asm_Input ("a", Value));
28727 pragma Inline (Increment);
28729 Value : Unsigned_32;
28733 Put_Line ("Value before is" & Value'Img);
28734 Value := Increment (Value);
28735 Put_Line ("Value after is" & Value'Img);
28740 Compile the program with both optimization (@option{-O2}) and inlining
28741 (@option{-gnatn}) enabled.
28743 The @code{Incr} function is still compiled as usual, but at the
28744 point in @code{Increment} where our function used to be called:
28749 call _increment__incr.1
28754 the code for the function body directly appears:
28767 thus saving the overhead of stack frame setup and an out-of-line call.
28769 @c ---------------------------------------------------------------------------
28770 @node Other Asm Functionality
28771 @section Other @code{Asm} Functionality
28774 This section describes two important parameters to the @code{Asm}
28775 procedure: @code{Clobber}, which identifies register usage;
28776 and @code{Volatile}, which inhibits unwanted optimizations.
28779 * The Clobber Parameter::
28780 * The Volatile Parameter::
28783 @c ---------------------------------------------------------------------------
28784 @node The Clobber Parameter
28785 @subsection The @code{Clobber} Parameter
28788 One of the dangers of intermixing assembly language and a compiled language
28789 such as Ada is that the compiler needs to be aware of which registers are
28790 being used by the assembly code. In some cases, such as the earlier examples,
28791 the constraint string is sufficient to indicate register usage (e.g.,
28793 the eax register). But more generally, the compiler needs an explicit
28794 identification of the registers that are used by the Inline Assembly
28797 Using a register that the compiler doesn't know about
28798 could be a side effect of an instruction (like @code{mull}
28799 storing its result in both eax and edx).
28800 It can also arise from explicit register usage in your
28801 assembly code; for example:
28804 Asm ("movl %0, %%ebx" & LF & HT &
28806 Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
28807 Inputs => Unsigned_32'Asm_Input ("g", Var_In));
28811 where the compiler (since it does not analyze the @code{Asm} template string)
28812 does not know you are using the ebx register.
28814 In such cases you need to supply the @code{Clobber} parameter to @code{Asm},
28815 to identify the registers that will be used by your assembly code:
28819 Asm ("movl %0, %%ebx" & LF & HT &
28821 Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
28822 Inputs => Unsigned_32'Asm_Input ("g", Var_In),
28827 The Clobber parameter is a static string expression specifying the
28828 register(s) you are using. Note that register names are @emph{not} prefixed
28829 by a percent sign. Also, if more than one register is used then their names
28830 are separated by commas; e.g., @code{"eax, ebx"}
28832 The @code{Clobber} parameter has several additional uses:
28834 @item Use ``register'' name @code{cc} to indicate that flags might have changed
28835 @item Use ``register'' name @code{memory} if you changed a memory location
28838 @c ---------------------------------------------------------------------------
28839 @node The Volatile Parameter
28840 @subsection The @code{Volatile} Parameter
28841 @cindex Volatile parameter
28844 Compiler optimizations in the presence of Inline Assembler may sometimes have
28845 unwanted effects. For example, when an @code{Asm} invocation with an input
28846 variable is inside a loop, the compiler might move the loading of the input
28847 variable outside the loop, regarding it as a one-time initialization.
28849 If this effect is not desired, you can disable such optimizations by setting
28850 the @code{Volatile} parameter to @code{True}; for example:
28852 @smallexample @c ada
28854 Asm ("movl %0, %%ebx" & LF & HT &
28856 Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
28857 Inputs => Unsigned_32'Asm_Input ("g", Var_In),
28863 By default, @code{Volatile} is set to @code{False} unless there is no
28864 @code{Outputs} parameter.
28866 Although setting @code{Volatile} to @code{True} prevents unwanted
28867 optimizations, it will also disable other optimizations that might be
28868 important for efficiency. In general, you should set @code{Volatile}
28869 to @code{True} only if the compiler's optimizations have created
28871 @c END OF INLINE ASSEMBLER CHAPTER
28872 @c ===============================
28874 @c ***********************************
28875 @c * Compatibility and Porting Guide *
28876 @c ***********************************
28877 @node Compatibility and Porting Guide
28878 @appendix Compatibility and Porting Guide
28881 This chapter describes the compatibility issues that may arise between
28882 GNAT and other Ada compilation systems (including those for Ada 83),
28883 and shows how GNAT can expedite porting
28884 applications developed in other Ada environments.
28887 * Compatibility with Ada 83::
28888 * Compatibility between Ada 95 and Ada 2005::
28889 * Implementation-dependent characteristics::
28890 * Compatibility with Other Ada Systems::
28891 * Representation Clauses::
28893 @c Brief section is only in non-VMS version
28894 @c Full chapter is in VMS version
28895 * Compatibility with HP Ada 83::
28898 * Transitioning to 64-Bit GNAT for OpenVMS::
28902 @node Compatibility with Ada 83
28903 @section Compatibility with Ada 83
28904 @cindex Compatibility (between Ada 83 and Ada 95 / Ada 2005)
28907 Ada 95 and Ada 2005 are highly upwards compatible with Ada 83. In
28908 particular, the design intention was that the difficulties associated
28909 with moving from Ada 83 to Ada 95 or Ada 2005 should be no greater than those
28910 that occur when moving from one Ada 83 system to another.
28912 However, there are a number of points at which there are minor
28913 incompatibilities. The @cite{Ada 95 Annotated Reference Manual} contains
28914 full details of these issues,
28915 and should be consulted for a complete treatment.
28917 following subsections treat the most likely issues to be encountered.
28920 * Legal Ada 83 programs that are illegal in Ada 95::
28921 * More deterministic semantics::
28922 * Changed semantics::
28923 * Other language compatibility issues::
28926 @node Legal Ada 83 programs that are illegal in Ada 95
28927 @subsection Legal Ada 83 programs that are illegal in Ada 95
28929 Some legal Ada 83 programs are illegal (i.e., they will fail to compile) in
28930 Ada 95 and thus also in Ada 2005:
28933 @item Character literals
28934 Some uses of character literals are ambiguous. Since Ada 95 has introduced
28935 @code{Wide_Character} as a new predefined character type, some uses of
28936 character literals that were legal in Ada 83 are illegal in Ada 95.
28938 @smallexample @c ada
28939 for Char in 'A' .. 'Z' loop @dots{} end loop;
28943 The problem is that @code{'A'} and @code{'Z'} could be from either
28944 @code{Character} or @code{Wide_Character}. The simplest correction
28945 is to make the type explicit; e.g.:
28946 @smallexample @c ada
28947 for Char in Character range 'A' .. 'Z' loop @dots{} end loop;
28950 @item New reserved words
28951 The identifiers @code{abstract}, @code{aliased}, @code{protected},
28952 @code{requeue}, @code{tagged}, and @code{until} are reserved in Ada 95.
28953 Existing Ada 83 code using any of these identifiers must be edited to
28954 use some alternative name.
28956 @item Freezing rules
28957 The rules in Ada 95 are slightly different with regard to the point at
28958 which entities are frozen, and representation pragmas and clauses are
28959 not permitted past the freeze point. This shows up most typically in
28960 the form of an error message complaining that a representation item
28961 appears too late, and the appropriate corrective action is to move
28962 the item nearer to the declaration of the entity to which it refers.
28964 A particular case is that representation pragmas
28967 extended HP Ada 83 compatibility pragmas such as @code{Export_Procedure})
28969 cannot be applied to a subprogram body. If necessary, a separate subprogram
28970 declaration must be introduced to which the pragma can be applied.
28972 @item Optional bodies for library packages
28973 In Ada 83, a package that did not require a package body was nevertheless
28974 allowed to have one. This lead to certain surprises in compiling large
28975 systems (situations in which the body could be unexpectedly ignored by the
28976 binder). In Ada 95, if a package does not require a body then it is not
28977 permitted to have a body. To fix this problem, simply remove a redundant
28978 body if it is empty, or, if it is non-empty, introduce a dummy declaration
28979 into the spec that makes the body required. One approach is to add a private
28980 part to the package declaration (if necessary), and define a parameterless
28981 procedure called @code{Requires_Body}, which must then be given a dummy
28982 procedure body in the package body, which then becomes required.
28983 Another approach (assuming that this does not introduce elaboration
28984 circularities) is to add an @code{Elaborate_Body} pragma to the package spec,
28985 since one effect of this pragma is to require the presence of a package body.
28987 @item @code{Numeric_Error} is now the same as @code{Constraint_Error}
28988 In Ada 95, the exception @code{Numeric_Error} is a renaming of
28989 @code{Constraint_Error}.
28990 This means that it is illegal to have separate exception handlers for
28991 the two exceptions. The fix is simply to remove the handler for the
28992 @code{Numeric_Error} case (since even in Ada 83, a compiler was free to raise
28993 @code{Constraint_Error} in place of @code{Numeric_Error} in all cases).
28995 @item Indefinite subtypes in generics
28996 In Ada 83, it was permissible to pass an indefinite type (e.g.@: @code{String})
28997 as the actual for a generic formal private type, but then the instantiation
28998 would be illegal if there were any instances of declarations of variables
28999 of this type in the generic body. In Ada 95, to avoid this clear violation
29000 of the methodological principle known as the ``contract model'',
29001 the generic declaration explicitly indicates whether
29002 or not such instantiations are permitted. If a generic formal parameter
29003 has explicit unknown discriminants, indicated by using @code{(<>)} after the
29004 subtype name, then it can be instantiated with indefinite types, but no
29005 stand-alone variables can be declared of this type. Any attempt to declare
29006 such a variable will result in an illegality at the time the generic is
29007 declared. If the @code{(<>)} notation is not used, then it is illegal
29008 to instantiate the generic with an indefinite type.
29009 This is the potential incompatibility issue when porting Ada 83 code to Ada 95.
29010 It will show up as a compile time error, and
29011 the fix is usually simply to add the @code{(<>)} to the generic declaration.
29014 @node More deterministic semantics
29015 @subsection More deterministic semantics
29019 Conversions from real types to integer types round away from 0. In Ada 83
29020 the conversion Integer(2.5) could deliver either 2 or 3 as its value. This
29021 implementation freedom was intended to support unbiased rounding in
29022 statistical applications, but in practice it interfered with portability.
29023 In Ada 95 the conversion semantics are unambiguous, and rounding away from 0
29024 is required. Numeric code may be affected by this change in semantics.
29025 Note, though, that this issue is no worse than already existed in Ada 83
29026 when porting code from one vendor to another.
29029 The Real-Time Annex introduces a set of policies that define the behavior of
29030 features that were implementation dependent in Ada 83, such as the order in
29031 which open select branches are executed.
29034 @node Changed semantics
29035 @subsection Changed semantics
29038 The worst kind of incompatibility is one where a program that is legal in
29039 Ada 83 is also legal in Ada 95 but can have an effect in Ada 95 that was not
29040 possible in Ada 83. Fortunately this is extremely rare, but the one
29041 situation that you should be alert to is the change in the predefined type
29042 @code{Character} from 7-bit ASCII to 8-bit Latin-1.
29045 @item Range of type @code{Character}
29046 The range of @code{Standard.Character} is now the full 256 characters
29047 of Latin-1, whereas in most Ada 83 implementations it was restricted
29048 to 128 characters. Although some of the effects of
29049 this change will be manifest in compile-time rejection of legal
29050 Ada 83 programs it is possible for a working Ada 83 program to have
29051 a different effect in Ada 95, one that was not permitted in Ada 83.
29052 As an example, the expression
29053 @code{Character'Pos(Character'Last)} returned @code{127} in Ada 83 and now
29054 delivers @code{255} as its value.
29055 In general, you should look at the logic of any
29056 character-processing Ada 83 program and see whether it needs to be adapted
29057 to work correctly with Latin-1. Note that the predefined Ada 95 API has a
29058 character handling package that may be relevant if code needs to be adapted
29059 to account for the additional Latin-1 elements.
29060 The desirable fix is to
29061 modify the program to accommodate the full character set, but in some cases
29062 it may be convenient to define a subtype or derived type of Character that
29063 covers only the restricted range.
29067 @node Other language compatibility issues
29068 @subsection Other language compatibility issues
29071 @item @option{-gnat83} switch
29072 All implementations of GNAT provide a switch that causes GNAT to operate
29073 in Ada 83 mode. In this mode, some but not all compatibility problems
29074 of the type described above are handled automatically. For example, the
29075 new reserved words introduced in Ada 95 and Ada 2005 are treated simply
29076 as identifiers as in Ada 83.
29078 in practice, it is usually advisable to make the necessary modifications
29079 to the program to remove the need for using this switch.
29080 See @ref{Compiling Different Versions of Ada}.
29082 @item Support for removed Ada 83 pragmas and attributes
29083 A number of pragmas and attributes from Ada 83 were removed from Ada 95,
29084 generally because they were replaced by other mechanisms. Ada 95 and Ada 2005
29085 compilers are allowed, but not required, to implement these missing
29086 elements. In contrast with some other compilers, GNAT implements all
29087 such pragmas and attributes, eliminating this compatibility concern. These
29088 include @code{pragma Interface} and the floating point type attributes
29089 (@code{Emax}, @code{Mantissa}, etc.), among other items.
29093 @node Compatibility between Ada 95 and Ada 2005
29094 @section Compatibility between Ada 95 and Ada 2005
29095 @cindex Compatibility between Ada 95 and Ada 2005
29098 Although Ada 2005 was designed to be upwards compatible with Ada 95, there are
29099 a number of incompatibilities. Several are enumerated below;
29100 for a complete description please see the
29101 Annotated Ada 2005 Reference Manual, or section 9.1.1 in
29102 @cite{Rationale for Ada 2005}.
29105 @item New reserved words.
29106 The words @code{interface}, @code{overriding} and @code{synchronized} are
29107 reserved in Ada 2005.
29108 A pre-Ada 2005 program that uses any of these as an identifier will be
29111 @item New declarations in predefined packages.
29112 A number of packages in the predefined environment contain new declarations:
29113 @code{Ada.Exceptions}, @code{Ada.Real_Time}, @code{Ada.Strings},
29114 @code{Ada.Strings.Fixed}, @code{Ada.Strings.Bounded},
29115 @code{Ada.Strings.Unbounded}, @code{Ada.Strings.Wide_Fixed},
29116 @code{Ada.Strings.Wide_Bounded}, @code{Ada.Strings.Wide_Unbounded},
29117 @code{Ada.Tags}, @code{Ada.Text_IO}, and @code{Interfaces.C}.
29118 If an Ada 95 program does a @code{with} and @code{use} of any of these
29119 packages, the new declarations may cause name clashes.
29121 @item Access parameters.
29122 A nondispatching subprogram with an access parameter cannot be renamed
29123 as a dispatching operation. This was permitted in Ada 95.
29125 @item Access types, discriminants, and constraints.
29126 Rule changes in this area have led to some incompatibilities; for example,
29127 constrained subtypes of some access types are not permitted in Ada 2005.
29129 @item Aggregates for limited types.
29130 The allowance of aggregates for limited types in Ada 2005 raises the
29131 possibility of ambiguities in legal Ada 95 programs, since additional types
29132 now need to be considered in expression resolution.
29134 @item Fixed-point multiplication and division.
29135 Certain expressions involving ``*'' or ``/'' for a fixed-point type, which
29136 were legal in Ada 95 and invoked the predefined versions of these operations,
29138 The ambiguity may be resolved either by applying a type conversion to the
29139 expression, or by explicitly invoking the operation from package
29142 @item Return-by-reference types.
29143 The Ada 95 return-by-reference mechanism has been removed. Instead, the user
29144 can declare a function returning a value from an anonymous access type.
29148 @node Implementation-dependent characteristics
29149 @section Implementation-dependent characteristics
29151 Although the Ada language defines the semantics of each construct as
29152 precisely as practical, in some situations (for example for reasons of
29153 efficiency, or where the effect is heavily dependent on the host or target
29154 platform) the implementation is allowed some freedom. In porting Ada 83
29155 code to GNAT, you need to be aware of whether / how the existing code
29156 exercised such implementation dependencies. Such characteristics fall into
29157 several categories, and GNAT offers specific support in assisting the
29158 transition from certain Ada 83 compilers.
29161 * Implementation-defined pragmas::
29162 * Implementation-defined attributes::
29164 * Elaboration order::
29165 * Target-specific aspects::
29168 @node Implementation-defined pragmas
29169 @subsection Implementation-defined pragmas
29172 Ada compilers are allowed to supplement the language-defined pragmas, and
29173 these are a potential source of non-portability. All GNAT-defined pragmas
29174 are described in @ref{Implementation Defined Pragmas,,, gnat_rm, GNAT
29175 Reference Manual}, and these include several that are specifically
29176 intended to correspond to other vendors' Ada 83 pragmas.
29177 For migrating from VADS, the pragma @code{Use_VADS_Size} may be useful.
29178 For compatibility with HP Ada 83, GNAT supplies the pragmas
29179 @code{Extend_System}, @code{Ident}, @code{Inline_Generic},
29180 @code{Interface_Name}, @code{Passive}, @code{Suppress_All},
29181 and @code{Volatile}.
29182 Other relevant pragmas include @code{External} and @code{Link_With}.
29183 Some vendor-specific
29184 Ada 83 pragmas (@code{Share_Generic}, @code{Subtitle}, and @code{Title}) are
29186 avoiding compiler rejection of units that contain such pragmas; they are not
29187 relevant in a GNAT context and hence are not otherwise implemented.
29189 @node Implementation-defined attributes
29190 @subsection Implementation-defined attributes
29192 Analogous to pragmas, the set of attributes may be extended by an
29193 implementation. All GNAT-defined attributes are described in
29194 @ref{Implementation Defined Attributes,,, gnat_rm, GNAT Reference
29195 Manual}, and these include several that are specifically intended
29196 to correspond to other vendors' Ada 83 attributes. For migrating from VADS,
29197 the attribute @code{VADS_Size} may be useful. For compatibility with HP
29198 Ada 83, GNAT supplies the attributes @code{Bit}, @code{Machine_Size} and
29202 @subsection Libraries
29204 Vendors may supply libraries to supplement the standard Ada API. If Ada 83
29205 code uses vendor-specific libraries then there are several ways to manage
29206 this in Ada 95 or Ada 2005:
29209 If the source code for the libraries (specs and bodies) are
29210 available, then the libraries can be migrated in the same way as the
29213 If the source code for the specs but not the bodies are
29214 available, then you can reimplement the bodies.
29216 Some features introduced by Ada 95 obviate the need for library support. For
29217 example most Ada 83 vendors supplied a package for unsigned integers. The
29218 Ada 95 modular type feature is the preferred way to handle this need, so
29219 instead of migrating or reimplementing the unsigned integer package it may
29220 be preferable to retrofit the application using modular types.
29223 @node Elaboration order
29224 @subsection Elaboration order
29226 The implementation can choose any elaboration order consistent with the unit
29227 dependency relationship. This freedom means that some orders can result in
29228 Program_Error being raised due to an ``Access Before Elaboration'': an attempt
29229 to invoke a subprogram its body has been elaborated, or to instantiate a
29230 generic before the generic body has been elaborated. By default GNAT
29231 attempts to choose a safe order (one that will not encounter access before
29232 elaboration problems) by implicitly inserting @code{Elaborate} or
29233 @code{Elaborate_All} pragmas where
29234 needed. However, this can lead to the creation of elaboration circularities
29235 and a resulting rejection of the program by gnatbind. This issue is
29236 thoroughly described in @ref{Elaboration Order Handling in GNAT}.
29237 In brief, there are several
29238 ways to deal with this situation:
29242 Modify the program to eliminate the circularities, e.g.@: by moving
29243 elaboration-time code into explicitly-invoked procedures
29245 Constrain the elaboration order by including explicit @code{Elaborate_Body} or
29246 @code{Elaborate} pragmas, and then inhibit the generation of implicit
29247 @code{Elaborate_All}
29248 pragmas either globally (as an effect of the @option{-gnatE} switch) or locally
29249 (by selectively suppressing elaboration checks via pragma
29250 @code{Suppress(Elaboration_Check)} when it is safe to do so).
29253 @node Target-specific aspects
29254 @subsection Target-specific aspects
29256 Low-level applications need to deal with machine addresses, data
29257 representations, interfacing with assembler code, and similar issues. If
29258 such an Ada 83 application is being ported to different target hardware (for
29259 example where the byte endianness has changed) then you will need to
29260 carefully examine the program logic; the porting effort will heavily depend
29261 on the robustness of the original design. Moreover, Ada 95 (and thus
29262 Ada 2005) are sometimes
29263 incompatible with typical Ada 83 compiler practices regarding implicit
29264 packing, the meaning of the Size attribute, and the size of access values.
29265 GNAT's approach to these issues is described in @ref{Representation Clauses}.
29267 @node Compatibility with Other Ada Systems
29268 @section Compatibility with Other Ada Systems
29271 If programs avoid the use of implementation dependent and
29272 implementation defined features, as documented in the @cite{Ada
29273 Reference Manual}, there should be a high degree of portability between
29274 GNAT and other Ada systems. The following are specific items which
29275 have proved troublesome in moving Ada 95 programs from GNAT to other Ada 95
29276 compilers, but do not affect porting code to GNAT@.
29277 (As of @value{NOW}, GNAT is the only compiler available for Ada 2005;
29278 the following issues may or may not arise for Ada 2005 programs
29279 when other compilers appear.)
29282 @item Ada 83 Pragmas and Attributes
29283 Ada 95 compilers are allowed, but not required, to implement the missing
29284 Ada 83 pragmas and attributes that are no longer defined in Ada 95.
29285 GNAT implements all such pragmas and attributes, eliminating this as
29286 a compatibility concern, but some other Ada 95 compilers reject these
29287 pragmas and attributes.
29289 @item Specialized Needs Annexes
29290 GNAT implements the full set of special needs annexes. At the
29291 current time, it is the only Ada 95 compiler to do so. This means that
29292 programs making use of these features may not be portable to other Ada
29293 95 compilation systems.
29295 @item Representation Clauses
29296 Some other Ada 95 compilers implement only the minimal set of
29297 representation clauses required by the Ada 95 reference manual. GNAT goes
29298 far beyond this minimal set, as described in the next section.
29301 @node Representation Clauses
29302 @section Representation Clauses
29305 The Ada 83 reference manual was quite vague in describing both the minimal
29306 required implementation of representation clauses, and also their precise
29307 effects. Ada 95 (and thus also Ada 2005) are much more explicit, but the
29308 minimal set of capabilities required is still quite limited.
29310 GNAT implements the full required set of capabilities in
29311 Ada 95 and Ada 2005, but also goes much further, and in particular
29312 an effort has been made to be compatible with existing Ada 83 usage to the
29313 greatest extent possible.
29315 A few cases exist in which Ada 83 compiler behavior is incompatible with
29316 the requirements in Ada 95 (and thus also Ada 2005). These are instances of
29317 intentional or accidental dependence on specific implementation dependent
29318 characteristics of these Ada 83 compilers. The following is a list of
29319 the cases most likely to arise in existing Ada 83 code.
29322 @item Implicit Packing
29323 Some Ada 83 compilers allowed a Size specification to cause implicit
29324 packing of an array or record. This could cause expensive implicit
29325 conversions for change of representation in the presence of derived
29326 types, and the Ada design intends to avoid this possibility.
29327 Subsequent AI's were issued to make it clear that such implicit
29328 change of representation in response to a Size clause is inadvisable,
29329 and this recommendation is represented explicitly in the Ada 95 (and Ada 2005)
29330 Reference Manuals as implementation advice that is followed by GNAT@.
29331 The problem will show up as an error
29332 message rejecting the size clause. The fix is simply to provide
29333 the explicit pragma @code{Pack}, or for more fine tuned control, provide
29334 a Component_Size clause.
29336 @item Meaning of Size Attribute
29337 The Size attribute in Ada 95 (and Ada 2005) for discrete types is defined as
29338 the minimal number of bits required to hold values of the type. For example,
29339 on a 32-bit machine, the size of @code{Natural} will typically be 31 and not
29340 32 (since no sign bit is required). Some Ada 83 compilers gave 31, and
29341 some 32 in this situation. This problem will usually show up as a compile
29342 time error, but not always. It is a good idea to check all uses of the
29343 'Size attribute when porting Ada 83 code. The GNAT specific attribute
29344 Object_Size can provide a useful way of duplicating the behavior of
29345 some Ada 83 compiler systems.
29347 @item Size of Access Types
29348 A common assumption in Ada 83 code is that an access type is in fact a pointer,
29349 and that therefore it will be the same size as a System.Address value. This
29350 assumption is true for GNAT in most cases with one exception. For the case of
29351 a pointer to an unconstrained array type (where the bounds may vary from one
29352 value of the access type to another), the default is to use a ``fat pointer'',
29353 which is represented as two separate pointers, one to the bounds, and one to
29354 the array. This representation has a number of advantages, including improved
29355 efficiency. However, it may cause some difficulties in porting existing Ada 83
29356 code which makes the assumption that, for example, pointers fit in 32 bits on
29357 a machine with 32-bit addressing.
29359 To get around this problem, GNAT also permits the use of ``thin pointers'' for
29360 access types in this case (where the designated type is an unconstrained array
29361 type). These thin pointers are indeed the same size as a System.Address value.
29362 To specify a thin pointer, use a size clause for the type, for example:
29364 @smallexample @c ada
29365 type X is access all String;
29366 for X'Size use Standard'Address_Size;
29370 which will cause the type X to be represented using a single pointer.
29371 When using this representation, the bounds are right behind the array.
29372 This representation is slightly less efficient, and does not allow quite
29373 such flexibility in the use of foreign pointers or in using the
29374 Unrestricted_Access attribute to create pointers to non-aliased objects.
29375 But for any standard portable use of the access type it will work in
29376 a functionally correct manner and allow porting of existing code.
29377 Note that another way of forcing a thin pointer representation
29378 is to use a component size clause for the element size in an array,
29379 or a record representation clause for an access field in a record.
29381 See the documentation of Unrestricted_Access in the GNAT RM for a
29382 full discussion of possible problems using this attribute in conjunction
29383 with thin pointers.
29387 @c This brief section is only in the non-VMS version
29388 @c The complete chapter on HP Ada is in the VMS version
29389 @node Compatibility with HP Ada 83
29390 @section Compatibility with HP Ada 83
29393 The VMS version of GNAT fully implements all the pragmas and attributes
29394 provided by HP Ada 83, as well as providing the standard HP Ada 83
29395 libraries, including Starlet. In addition, data layouts and parameter
29396 passing conventions are highly compatible. This means that porting
29397 existing HP Ada 83 code to GNAT in VMS systems should be easier than
29398 most other porting efforts. The following are some of the most
29399 significant differences between GNAT and HP Ada 83.
29402 @item Default floating-point representation
29403 In GNAT, the default floating-point format is IEEE, whereas in HP Ada 83,
29404 it is VMS format. GNAT does implement the necessary pragmas
29405 (Long_Float, Float_Representation) for changing this default.
29408 The package System in GNAT exactly corresponds to the definition in the
29409 Ada 95 reference manual, which means that it excludes many of the
29410 HP Ada 83 extensions. However, a separate package Aux_DEC is provided
29411 that contains the additional definitions, and a special pragma,
29412 Extend_System allows this package to be treated transparently as an
29413 extension of package System.
29416 The definitions provided by Aux_DEC are exactly compatible with those
29417 in the HP Ada 83 version of System, with one exception.
29418 HP Ada provides the following declarations:
29420 @smallexample @c ada
29421 TO_ADDRESS (INTEGER)
29422 TO_ADDRESS (UNSIGNED_LONGWORD)
29423 TO_ADDRESS (@i{universal_integer})
29427 The version of TO_ADDRESS taking a @i{universal integer} argument is in fact
29428 an extension to Ada 83 not strictly compatible with the reference manual.
29429 In GNAT, we are constrained to be exactly compatible with the standard,
29430 and this means we cannot provide this capability. In HP Ada 83, the
29431 point of this definition is to deal with a call like:
29433 @smallexample @c ada
29434 TO_ADDRESS (16#12777#);
29438 Normally, according to the Ada 83 standard, one would expect this to be
29439 ambiguous, since it matches both the INTEGER and UNSIGNED_LONGWORD forms
29440 of TO_ADDRESS@. However, in HP Ada 83, there is no ambiguity, since the
29441 definition using @i{universal_integer} takes precedence.
29443 In GNAT, since the version with @i{universal_integer} cannot be supplied, it
29444 is not possible to be 100% compatible. Since there are many programs using
29445 numeric constants for the argument to TO_ADDRESS, the decision in GNAT was
29446 to change the name of the function in the UNSIGNED_LONGWORD case, so the
29447 declarations provided in the GNAT version of AUX_Dec are:
29449 @smallexample @c ada
29450 function To_Address (X : Integer) return Address;
29451 pragma Pure_Function (To_Address);
29453 function To_Address_Long (X : Unsigned_Longword)
29455 pragma Pure_Function (To_Address_Long);
29459 This means that programs using TO_ADDRESS for UNSIGNED_LONGWORD must
29460 change the name to TO_ADDRESS_LONG@.
29462 @item Task_Id values
29463 The Task_Id values assigned will be different in the two systems, and GNAT
29464 does not provide a specified value for the Task_Id of the environment task,
29465 which in GNAT is treated like any other declared task.
29469 For full details on these and other less significant compatibility issues,
29470 see appendix E of the HP publication entitled @cite{HP Ada, Technical
29471 Overview and Comparison on HP Platforms}.
29473 For GNAT running on other than VMS systems, all the HP Ada 83 pragmas and
29474 attributes are recognized, although only a subset of them can sensibly
29475 be implemented. The description of pragmas in @ref{Implementation
29476 Defined Pragmas,,, gnat_rm, GNAT Reference Manual}
29477 indicates whether or not they are applicable to non-VMS systems.
29481 @node Transitioning to 64-Bit GNAT for OpenVMS
29482 @section Transitioning to 64-Bit @value{EDITION} for OpenVMS
29485 This section is meant to assist users of pre-2006 @value{EDITION}
29486 for Alpha OpenVMS who are transitioning to 64-bit @value{EDITION},
29487 the version of the GNAT technology supplied in 2006 and later for
29488 OpenVMS on both Alpha and I64.
29491 * Introduction to transitioning::
29492 * Migration of 32 bit code::
29493 * Taking advantage of 64 bit addressing::
29494 * Technical details::
29497 @node Introduction to transitioning
29498 @subsection Introduction
29501 64-bit @value{EDITION} for Open VMS has been designed to meet
29506 Providing a full conforming implementation of Ada 95 and Ada 2005
29509 Allowing maximum backward compatibility, thus easing migration of existing
29513 Supplying a path for exploiting the full 64-bit address range
29517 Ada's strong typing semantics has made it
29518 impractical to have different 32-bit and 64-bit modes. As soon as
29519 one object could possibly be outside the 32-bit address space, this
29520 would make it necessary for the @code{System.Address} type to be 64 bits.
29521 In particular, this would cause inconsistencies if 32-bit code is
29522 called from 64-bit code that raises an exception.
29524 This issue has been resolved by always using 64-bit addressing
29525 at the system level, but allowing for automatic conversions between
29526 32-bit and 64-bit addresses where required. Thus users who
29527 do not currently require 64-bit addressing capabilities, can
29528 recompile their code with only minimal changes (and indeed
29529 if the code is written in portable Ada, with no assumptions about
29530 the size of the @code{Address} type, then no changes at all are necessary).
29532 this approach provides a simple, gradual upgrade path to future
29533 use of larger memories than available for 32-bit systems.
29534 Also, newly written applications or libraries will by default
29535 be fully compatible with future systems exploiting 64-bit
29536 addressing capabilities.
29538 @ref{Migration of 32 bit code}, will focus on porting applications
29539 that do not require more than 2 GB of
29540 addressable memory. This code will be referred to as
29541 @emph{32-bit code}.
29542 For applications intending to exploit the full 64-bit address space,
29543 @ref{Taking advantage of 64 bit addressing},
29544 will consider further changes that may be required.
29545 Such code will be referred to below as @emph{64-bit code}.
29547 @node Migration of 32 bit code
29548 @subsection Migration of 32-bit code
29552 * Access types and 32/64-bit allocation::
29553 * Unchecked conversions::
29554 * Predefined constants::
29555 * Interfacing with C::
29556 * 32/64-bit descriptors::
29557 * Experience with source compatibility::
29560 @node Address types
29561 @subsubsection Address types
29564 To solve the problem of mixing 64-bit and 32-bit addressing,
29565 while maintaining maximum backward compatibility, the following
29566 approach has been taken:
29570 @code{System.Address} always has a size of 64 bits
29571 @cindex @code{System.Address} size
29572 @cindex @code{Address} size
29575 @code{System.Short_Address} is a 32-bit subtype of @code{System.Address}
29576 @cindex @code{System.Short_Address} size
29577 @cindex @code{Short_Address} size
29581 Since @code{System.Short_Address} is a subtype of @code{System.Address},
29582 a @code{Short_Address}
29583 may be used where an @code{Address} is required, and vice versa, without
29584 needing explicit type conversions.
29585 By virtue of the Open VMS parameter passing conventions,
29587 and exported subprograms that have 32-bit address parameters are
29588 compatible with those that have 64-bit address parameters.
29589 (See @ref{Making code 64 bit clean} for details.)
29591 The areas that may need attention are those where record types have
29592 been defined that contain components of the type @code{System.Address}, and
29593 where objects of this type are passed to code expecting a record layout with
29596 Different compilers on different platforms cannot be
29597 expected to represent the same type in the same way,
29598 since alignment constraints
29599 and other system-dependent properties affect the compiler's decision.
29600 For that reason, Ada code
29601 generally uses representation clauses to specify the expected
29602 layout where required.
29604 If such a representation clause uses 32 bits for a component having
29605 the type @code{System.Address}, 64-bit @value{EDITION} for OpenVMS
29606 will detect that error and produce a specific diagnostic message.
29607 The developer should then determine whether the representation
29608 should be 64 bits or not and make either of two changes:
29609 change the size to 64 bits and leave the type as @code{System.Address}, or
29610 leave the size as 32 bits and change the type to @code{System.Short_Address}.
29611 Since @code{Short_Address} is a subtype of @code{Address}, no changes are
29612 required in any code setting or accessing the field; the compiler will
29613 automatically perform any needed conversions between address
29616 @node Access types and 32/64-bit allocation
29617 @subsubsection Access types and 32/64-bit allocation
29618 @cindex 32-bit allocation
29619 @cindex 64-bit allocation
29622 By default, objects designated by access values are always allocated in
29623 the 64-bit address space, and access values themselves are represented
29624 in 64 bits. If these defaults are not appropriate, and 32-bit allocation
29625 is required (for example if the address of an allocated object is assigned
29626 to a @code{Short_Address} variable), then several alternatives are available:
29630 A pool-specific access type (ie, an @w{Ada 83} access type, whose
29631 definition is @code{access T} versus @code{access all T} or
29632 @code{access constant T}), may be declared with a @code{'Size} representation
29633 clause that establishes the size as 32 bits.
29634 In such circumstances allocations for that type will
29635 be from the 32-bit heap. Such a clause is not permitted
29636 for a general access type (declared with @code{access all} or
29637 @code{access constant}) as values of such types must be able to refer
29638 to any object of the designated type, including objects residing outside
29639 the 32-bit address range. Existing @w{Ada 83} code will not contain such
29640 type definitions, however, since general access types were introduced
29644 Switches for @command{GNAT BIND} control whether the internal GNAT
29645 allocation routine @code{__gnat_malloc} uses 64-bit or 32-bit allocations.
29646 @cindex @code{__gnat_malloc}
29647 The switches are respectively @option{-H64} (the default) and
29649 @cindex @option{-H32} (@command{gnatbind})
29650 @cindex @option{-H64} (@command{gnatbind})
29653 The environment variable (logical name) @code{GNAT$NO_MALLOC_64}
29654 @cindex @code{GNAT$NO_MALLOC_64} environment variable
29655 may be used to force @code{__gnat_malloc} to use 32-bit allocation.
29656 If this variable is left
29657 undefined, or defined as @code{"DISABLE"}, @code{"FALSE"}, or @code{"0"},
29658 then the default (64-bit) allocation is used.
29659 If defined as @code{"ENABLE"}, @code{"TRUE"}, or @code{"1"},
29660 then 32-bit allocation is used. The gnatbind qualifiers described above
29661 override this logical name.
29664 A ^gcc switch^gcc switch^ for OpenVMS, @option{-mno-malloc64}, operates
29665 @cindex @option{-mno-malloc64} (^gcc^gcc^)
29666 at a low level to convert explicit calls to @code{malloc} and related
29667 functions from the C run-time library so that they perform allocations
29668 in the 32-bit heap.
29669 Since all internal allocations from GNAT use @code{__gnat_malloc},
29670 this switch is not required unless the program makes explicit calls on
29671 @code{malloc} (or related functions) from interfaced C code.
29675 @node Unchecked conversions
29676 @subsubsection Unchecked conversions
29679 In the case of an @code{Unchecked_Conversion} where the source type is a
29680 64-bit access type or the type @code{System.Address}, and the target
29681 type is a 32-bit type, the compiler will generate a warning.
29682 Even though the generated code will still perform the required
29683 conversions, it is highly recommended in these cases to use
29684 respectively a 32-bit access type or @code{System.Short_Address}
29685 as the source type.
29687 @node Predefined constants
29688 @subsubsection Predefined constants
29691 The following table shows the correspondence between pre-2006 versions of
29692 @value{EDITION} on Alpha OpenVMS (``Old'') and 64-bit @value{EDITION}
29695 @multitable {@code{System.Short_Memory_Size}} {2**32} {2**64}
29696 @item @b{Constant} @tab @b{Old} @tab @b{New}
29697 @item @code{System.Word_Size} @tab 32 @tab 64
29698 @item @code{System.Memory_Size} @tab 2**32 @tab 2**64
29699 @item @code{System.Short_Memory_Size} @tab 2**32 @tab 2**32
29700 @item @code{System.Address_Size} @tab 32 @tab 64
29704 If you need to refer to the specific
29705 memory size of a 32-bit implementation, instead of the
29706 actual memory size, use @code{System.Short_Memory_Size}
29707 rather than @code{System.Memory_Size}.
29708 Similarly, references to @code{System.Address_Size} may need
29709 to be replaced by @code{System.Short_Address'Size}.
29710 The program @command{gnatfind} may be useful for locating
29711 references to the above constants, so that you can verify that they
29714 @node Interfacing with C
29715 @subsubsection Interfacing with C
29718 In order to minimize the impact of the transition to 64-bit addresses on
29719 legacy programs, some fundamental types in the @code{Interfaces.C}
29720 package hierarchy continue to be represented in 32 bits.
29721 These types are: @code{ptrdiff_t}, @code{size_t}, and @code{chars_ptr}.
29722 This eases integration with the default HP C layout choices, for example
29723 as found in the system routines in @code{DECC$SHR.EXE}.
29724 Because of this implementation choice, the type fully compatible with
29725 @code{chars_ptr} is now @code{Short_Address} and not @code{Address}.
29726 Depending on the context the compiler will issue a
29727 warning or an error when type @code{Address} is used, alerting the user to a
29728 potential problem. Otherwise 32-bit programs that use
29729 @code{Interfaces.C} should normally not require code modifications
29731 The other issue arising with C interfacing concerns pragma @code{Convention}.
29732 For VMS 64-bit systems, there is an issue of the appropriate default size
29733 of C convention pointers in the absence of an explicit size clause. The HP
29734 C compiler can choose either 32 or 64 bits depending on compiler options.
29735 GNAT chooses 32-bits rather than 64-bits in the default case where no size
29736 clause is given. This proves a better choice for porting 32-bit legacy
29737 applications. In order to have a 64-bit representation, it is necessary to
29738 specify a size representation clause. For example:
29740 @smallexample @c ada
29741 type int_star is access Interfaces.C.int;
29742 pragma Convention(C, int_star);
29743 for int_star'Size use 64; -- Necessary to get 64 and not 32 bits
29746 @node 32/64-bit descriptors
29747 @subsubsection 32/64-bit descriptors
29750 By default, GNAT uses a 64-bit descriptor mechanism. For an imported
29751 subprogram (i.e., a subprogram identified by pragma @code{Import_Function},
29752 @code{Import_Procedure}, or @code{Import_Valued_Procedure}) that specifies
29753 @code{Short_Descriptor} as its mechanism, a 32-bit descriptor is used.
29754 @cindex @code{Short_Descriptor} mechanism for imported subprograms
29756 If the configuration pragma @code{Short_Descriptors} is supplied, then
29757 all descriptors will be 32 bits.
29758 @cindex pragma @code{Short_Descriptors}
29760 @node Experience with source compatibility
29761 @subsubsection Experience with source compatibility
29764 The Security Server and STARLET on I64 provide an interesting ``test case''
29765 for source compatibility issues, since it is in such system code
29766 where assumptions about @code{Address} size might be expected to occur.
29767 Indeed, there were a small number of occasions in the Security Server
29768 file @file{jibdef.ads}
29769 where a representation clause for a record type specified
29770 32 bits for a component of type @code{Address}.
29771 All of these errors were detected by the compiler.
29772 The repair was obvious and immediate; to simply replace @code{Address} by
29773 @code{Short_Address}.
29775 In the case of STARLET, there were several record types that should
29776 have had representation clauses but did not. In these record types
29777 there was an implicit assumption that an @code{Address} value occupied
29779 These compiled without error, but their usage resulted in run-time error
29780 returns from STARLET system calls.
29781 Future GNAT technology enhancements may include a tool that detects and flags
29782 these sorts of potential source code porting problems.
29784 @c ****************************************
29785 @node Taking advantage of 64 bit addressing
29786 @subsection Taking advantage of 64-bit addressing
29789 * Making code 64 bit clean::
29790 * Allocating memory from the 64 bit storage pool::
29791 * Restrictions on use of 64 bit objects::
29792 * STARLET and other predefined libraries::
29795 @node Making code 64 bit clean
29796 @subsubsection Making code 64-bit clean
29799 In order to prevent problems that may occur when (parts of) a
29800 system start using memory outside the 32-bit address range,
29801 we recommend some additional guidelines:
29805 For imported subprograms that take parameters of the
29806 type @code{System.Address}, ensure that these subprograms can
29807 indeed handle 64-bit addresses. If not, or when in doubt,
29808 change the subprogram declaration to specify
29809 @code{System.Short_Address} instead.
29812 Resolve all warnings related to size mismatches in
29813 unchecked conversions. Failing to do so causes
29814 erroneous execution if the source object is outside
29815 the 32-bit address space.
29818 (optional) Explicitly use the 32-bit storage pool
29819 for access types used in a 32-bit context, or use
29820 generic access types where possible
29821 (@pxref{Restrictions on use of 64 bit objects}).
29825 If these rules are followed, the compiler will automatically insert
29826 any necessary checks to ensure that no addresses or access values
29827 passed to 32-bit code ever refer to objects outside the 32-bit
29829 Any attempt to do this will raise @code{Constraint_Error}.
29831 @node Allocating memory from the 64 bit storage pool
29832 @subsubsection Allocating memory from the 64-bit storage pool
29835 By default, all allocations -- for both pool-specific and general
29836 access types -- use the 64-bit storage pool. To override
29837 this default, for an individual access type or globally, see
29838 @ref{Access types and 32/64-bit allocation}.
29840 @node Restrictions on use of 64 bit objects
29841 @subsubsection Restrictions on use of 64-bit objects
29844 Taking the address of an object allocated from a 64-bit storage pool,
29845 and then passing this address to a subprogram expecting
29846 @code{System.Short_Address},
29847 or assigning it to a variable of type @code{Short_Address}, will cause
29848 @code{Constraint_Error} to be raised. In case the code is not 64-bit clean
29849 (@pxref{Making code 64 bit clean}), or checks are suppressed,
29850 no exception is raised and execution
29851 will become erroneous.
29853 @node STARLET and other predefined libraries
29854 @subsubsection STARLET and other predefined libraries
29857 All code that comes as part of GNAT is 64-bit clean, but the
29858 restrictions given in @ref{Restrictions on use of 64 bit objects},
29859 still apply. Look at the package
29860 specs to see in which contexts objects allocated
29861 in 64-bit address space are acceptable.
29863 @node Technical details
29864 @subsection Technical details
29867 64-bit @value{EDITION} for Open VMS takes advantage of the freedom given in the
29868 Ada standard with respect to the type of @code{System.Address}. Previous
29869 versions of @value{EDITION} have defined this type as private and implemented it as a
29872 In order to allow defining @code{System.Short_Address} as a proper subtype,
29873 and to match the implicit sign extension in parameter passing,
29874 in 64-bit @value{EDITION} for Open VMS, @code{System.Address} is defined as a
29875 visible (i.e., non-private) integer type.
29876 Standard operations on the type, such as the binary operators ``+'', ``-'',
29877 etc., that take @code{Address} operands and return an @code{Address} result,
29878 have been hidden by declaring these
29879 @code{abstract}, a feature introduced in Ada 95 that helps avoid the potential
29880 ambiguities that would otherwise result from overloading.
29881 (Note that, although @code{Address} is a visible integer type,
29882 good programming practice dictates against exploiting the type's
29883 integer properties such as literals, since this will compromise
29886 Defining @code{Address} as a visible integer type helps achieve
29887 maximum compatibility for existing Ada code,
29888 without sacrificing the capabilities of the 64-bit architecture.
29891 @c ************************************************
29892 @node Microsoft Windows Topics
29893 @appendix Microsoft Windows Topics
29899 This chapter describes topics that are specific to the Microsoft Windows
29900 platforms (NT, 2000, and XP Professional).
29903 @ifclear FSFEDITION
29904 * Installing from the Command Line::
29906 * Using GNAT on Windows::
29907 * Using a network installation of GNAT::
29908 * CONSOLE and WINDOWS subsystems::
29909 * Temporary Files::
29910 * Mixed-Language Programming on Windows::
29911 * Windows Calling Conventions::
29912 * Introduction to Dynamic Link Libraries (DLLs)::
29913 * Using DLLs with GNAT::
29914 * Building DLLs with GNAT Project files::
29915 * Building DLLs with GNAT::
29916 * Building DLLs with gnatdll::
29917 * GNAT and Windows Resources::
29918 * Debugging a DLL::
29919 * Setting Stack Size from gnatlink::
29920 * Setting Heap Size from gnatlink::
29923 @ifclear FSFEDITION
29924 @node Installing from the Command Line
29925 @section Installing from the Command Line
29926 @cindex Batch installation
29927 @cindex Silent installation
29928 @cindex Unassisted installation
29931 By default the @value{EDITION} installers display a GUI that prompts the user
29932 to enter installation path and similar information, and guide him through the
29933 installation process. It is also possible to perform silent installations
29934 using the command-line interface.
29936 In order to install one of the @value{EDITION} installers from the command
29937 line you should pass parameter @code{/S} (and, optionally,
29938 @code{/D=<directory>}) as command-line arguments.
29941 For example, for an unattended installation of
29942 @value{EDITION} 7.0.2 into the default directory
29943 @code{C:\GNATPRO\7.0.2} you would run:
29946 gnatpro-7.0.2-i686-pc-mingw32-bin.exe /S
29949 To install into a custom directory, say, @code{C:\TOOLS\GNATPRO\7.0.2}:
29952 gnatpro-7.0.2-i686-pc-mingw32-bin /S /D=C:\TOOLS\GNATPRO\7.0.2
29957 For example, for an unattended installation of
29958 @value{EDITION} 2012 into @code{C:\GNAT\2012}:
29961 gnat-gpl-2012-i686-pc-mingw32-bin /S /D=C:\GNAT\2012
29965 You can use the same syntax for all installers.
29967 Note that unattended installations don't modify system path, nor create file
29968 associations, so such activities need to be done by hand.
29971 @node Using GNAT on Windows
29972 @section Using GNAT on Windows
29975 One of the strengths of the GNAT technology is that its tool set
29976 (@command{gcc}, @command{gnatbind}, @command{gnatlink}, @command{gnatmake}, the
29977 @code{gdb} debugger, etc.) is used in the same way regardless of the
29980 On Windows this tool set is complemented by a number of Microsoft-specific
29981 tools that have been provided to facilitate interoperability with Windows
29982 when this is required. With these tools:
29987 You can build applications using the @code{CONSOLE} or @code{WINDOWS}
29991 You can use any Dynamically Linked Library (DLL) in your Ada code (both
29992 relocatable and non-relocatable DLLs are supported).
29995 You can build Ada DLLs for use in other applications. These applications
29996 can be written in a language other than Ada (e.g., C, C++, etc). Again both
29997 relocatable and non-relocatable Ada DLLs are supported.
30000 You can include Windows resources in your Ada application.
30003 You can use or create COM/DCOM objects.
30007 Immediately below are listed all known general GNAT-for-Windows restrictions.
30008 Other restrictions about specific features like Windows Resources and DLLs
30009 are listed in separate sections below.
30014 It is not possible to use @code{GetLastError} and @code{SetLastError}
30015 when tasking, protected records, or exceptions are used. In these
30016 cases, in order to implement Ada semantics, the GNAT run-time system
30017 calls certain Win32 routines that set the last error variable to 0 upon
30018 success. It should be possible to use @code{GetLastError} and
30019 @code{SetLastError} when tasking, protected record, and exception
30020 features are not used, but it is not guaranteed to work.
30023 It is not possible to link against Microsoft C++ libraries except for
30024 import libraries. Interfacing must be done by the mean of DLLs.
30027 It is possible to link against Microsoft C libraries. Yet the preferred
30028 solution is to use C/C++ compiler that comes with @value{EDITION}, since it
30029 doesn't require having two different development environments and makes the
30030 inter-language debugging experience smoother.
30033 When the compilation environment is located on FAT32 drives, users may
30034 experience recompilations of the source files that have not changed if
30035 Daylight Saving Time (DST) state has changed since the last time files
30036 were compiled. NTFS drives do not have this problem.
30039 No components of the GNAT toolset use any entries in the Windows
30040 registry. The only entries that can be created are file associations and
30041 PATH settings, provided the user has chosen to create them at installation
30042 time, as well as some minimal book-keeping information needed to correctly
30043 uninstall or integrate different GNAT products.
30046 @node Using a network installation of GNAT
30047 @section Using a network installation of GNAT
30050 Make sure the system on which GNAT is installed is accessible from the
30051 current machine, i.e., the install location is shared over the network.
30052 Shared resources are accessed on Windows by means of UNC paths, which
30053 have the format @code{\\server\sharename\path}
30055 In order to use such a network installation, simply add the UNC path of the
30056 @file{bin} directory of your GNAT installation in front of your PATH. For
30057 example, if GNAT is installed in @file{\GNAT} directory of a share location
30058 called @file{c-drive} on a machine @file{LOKI}, the following command will
30061 @code{@ @ @ path \\loki\c-drive\gnat\bin;%path%}
30063 Be aware that every compilation using the network installation results in the
30064 transfer of large amounts of data across the network and will likely cause
30065 serious performance penalty.
30067 @node CONSOLE and WINDOWS subsystems
30068 @section CONSOLE and WINDOWS subsystems
30069 @cindex CONSOLE Subsystem
30070 @cindex WINDOWS Subsystem
30074 There are two main subsystems under Windows. The @code{CONSOLE} subsystem
30075 (which is the default subsystem) will always create a console when
30076 launching the application. This is not something desirable when the
30077 application has a Windows GUI. To get rid of this console the
30078 application must be using the @code{WINDOWS} subsystem. To do so
30079 the @option{-mwindows} linker option must be specified.
30082 $ gnatmake winprog -largs -mwindows
30085 @node Temporary Files
30086 @section Temporary Files
30087 @cindex Temporary files
30090 It is possible to control where temporary files gets created by setting
30091 the @env{TMP} environment variable. The file will be created:
30094 @item Under the directory pointed to by the @env{TMP} environment variable if
30095 this directory exists.
30097 @item Under @file{c:\temp}, if the @env{TMP} environment variable is not
30098 set (or not pointing to a directory) and if this directory exists.
30100 @item Under the current working directory otherwise.
30104 This allows you to determine exactly where the temporary
30105 file will be created. This is particularly useful in networked
30106 environments where you may not have write access to some
30109 @node Mixed-Language Programming on Windows
30110 @section Mixed-Language Programming on Windows
30113 Developing pure Ada applications on Windows is no different than on
30114 other GNAT-supported platforms. However, when developing or porting an
30115 application that contains a mix of Ada and C/C++, the choice of your
30116 Windows C/C++ development environment conditions your overall
30117 interoperability strategy.
30119 If you use @command{gcc} or Microsoft C to compile the non-Ada part of
30120 your application, there are no Windows-specific restrictions that
30121 affect the overall interoperability with your Ada code. If you do want
30122 to use the Microsoft tools for your C++ code, you have two choices:
30126 Encapsulate your C++ code in a DLL to be linked with your Ada
30127 application. In this case, use the Microsoft or whatever environment to
30128 build the DLL and use GNAT to build your executable
30129 (@pxref{Using DLLs with GNAT}).
30132 Or you can encapsulate your Ada code in a DLL to be linked with the
30133 other part of your application. In this case, use GNAT to build the DLL
30134 (@pxref{Building DLLs with GNAT Project files}) and use the Microsoft
30135 or whatever environment to build your executable.
30138 In addition to the description about C main in
30139 @pxref{Mixed Language Programming} section, if the C main uses a
30140 stand-alone library it is required on x86-windows to
30141 setup the SEH context. For this the C main must looks like this:
30145 extern void adainit (void);
30146 extern void adafinal (void);
30147 extern void __gnat_initialize(void*);
30148 extern void call_to_ada (void);
30150 int main (int argc, char *argv[])
30154 /* Initialize the SEH context */
30155 __gnat_initialize (&SEH);
30159 /* Then call Ada services in the stand-alone library */
30167 Note that this is not needed on x86_64-windows where the Windows
30168 native SEH support is used.
30170 @node Windows Calling Conventions
30171 @section Windows Calling Conventions
30175 This section pertain only to Win32. On Win64 there is a single native
30176 calling convention. All convention specifiers are ignored on this
30180 * C Calling Convention::
30181 * Stdcall Calling Convention::
30182 * Win32 Calling Convention::
30183 * DLL Calling Convention::
30187 When a subprogram @code{F} (caller) calls a subprogram @code{G}
30188 (callee), there are several ways to push @code{G}'s parameters on the
30189 stack and there are several possible scenarios to clean up the stack
30190 upon @code{G}'s return. A calling convention is an agreed upon software
30191 protocol whereby the responsibilities between the caller (@code{F}) and
30192 the callee (@code{G}) are clearly defined. Several calling conventions
30193 are available for Windows:
30197 @code{C} (Microsoft defined)
30200 @code{Stdcall} (Microsoft defined)
30203 @code{Win32} (GNAT specific)
30206 @code{DLL} (GNAT specific)
30209 @node C Calling Convention
30210 @subsection @code{C} Calling Convention
30213 This is the default calling convention used when interfacing to C/C++
30214 routines compiled with either @command{gcc} or Microsoft Visual C++.
30216 In the @code{C} calling convention subprogram parameters are pushed on the
30217 stack by the caller from right to left. The caller itself is in charge of
30218 cleaning up the stack after the call. In addition, the name of a routine
30219 with @code{C} calling convention is mangled by adding a leading underscore.
30221 The name to use on the Ada side when importing (or exporting) a routine
30222 with @code{C} calling convention is the name of the routine. For
30223 instance the C function:
30226 int get_val (long);
30230 should be imported from Ada as follows:
30232 @smallexample @c ada
30234 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
30235 pragma Import (C, Get_Val, External_Name => "get_val");
30240 Note that in this particular case the @code{External_Name} parameter could
30241 have been omitted since, when missing, this parameter is taken to be the
30242 name of the Ada entity in lower case. When the @code{Link_Name} parameter
30243 is missing, as in the above example, this parameter is set to be the
30244 @code{External_Name} with a leading underscore.
30246 When importing a variable defined in C, you should always use the @code{C}
30247 calling convention unless the object containing the variable is part of a
30248 DLL (in which case you should use the @code{Stdcall} calling
30249 convention, @pxref{Stdcall Calling Convention}).
30251 @node Stdcall Calling Convention
30252 @subsection @code{Stdcall} Calling Convention
30255 This convention, which was the calling convention used for Pascal
30256 programs, is used by Microsoft for all the routines in the Win32 API for
30257 efficiency reasons. It must be used to import any routine for which this
30258 convention was specified.
30260 In the @code{Stdcall} calling convention subprogram parameters are pushed
30261 on the stack by the caller from right to left. The callee (and not the
30262 caller) is in charge of cleaning the stack on routine exit. In addition,
30263 the name of a routine with @code{Stdcall} calling convention is mangled by
30264 adding a leading underscore (as for the @code{C} calling convention) and a
30265 trailing @code{@@}@code{@var{nn}}, where @var{nn} is the overall size (in
30266 bytes) of the parameters passed to the routine.
30268 The name to use on the Ada side when importing a C routine with a
30269 @code{Stdcall} calling convention is the name of the C routine. The leading
30270 underscore and trailing @code{@@}@code{@var{nn}} are added automatically by
30271 the compiler. For instance the Win32 function:
30274 @b{APIENTRY} int get_val (long);
30278 should be imported from Ada as follows:
30280 @smallexample @c ada
30282 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
30283 pragma Import (Stdcall, Get_Val);
30284 -- On the x86 a long is 4 bytes, so the Link_Name is "_get_val@@4"
30289 As for the @code{C} calling convention, when the @code{External_Name}
30290 parameter is missing, it is taken to be the name of the Ada entity in lower
30291 case. If instead of writing the above import pragma you write:
30293 @smallexample @c ada
30295 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
30296 pragma Import (Stdcall, Get_Val, External_Name => "retrieve_val");
30301 then the imported routine is @code{_retrieve_val@@4}. However, if instead
30302 of specifying the @code{External_Name} parameter you specify the
30303 @code{Link_Name} as in the following example:
30305 @smallexample @c ada
30307 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
30308 pragma Import (Stdcall, Get_Val, Link_Name => "retrieve_val");
30313 then the imported routine is @code{retrieve_val}, that is, there is no
30314 decoration at all. No leading underscore and no Stdcall suffix
30315 @code{@@}@code{@var{nn}}.
30318 This is especially important as in some special cases a DLL's entry
30319 point name lacks a trailing @code{@@}@code{@var{nn}} while the exported
30320 name generated for a call has it.
30323 It is also possible to import variables defined in a DLL by using an
30324 import pragma for a variable. As an example, if a DLL contains a
30325 variable defined as:
30332 then, to access this variable from Ada you should write:
30334 @smallexample @c ada
30336 My_Var : Interfaces.C.int;
30337 pragma Import (Stdcall, My_Var);
30342 Note that to ease building cross-platform bindings this convention
30343 will be handled as a @code{C} calling convention on non-Windows platforms.
30345 @node Win32 Calling Convention
30346 @subsection @code{Win32} Calling Convention
30349 This convention, which is GNAT-specific is fully equivalent to the
30350 @code{Stdcall} calling convention described above.
30352 @node DLL Calling Convention
30353 @subsection @code{DLL} Calling Convention
30356 This convention, which is GNAT-specific is fully equivalent to the
30357 @code{Stdcall} calling convention described above.
30359 @node Introduction to Dynamic Link Libraries (DLLs)
30360 @section Introduction to Dynamic Link Libraries (DLLs)
30364 A Dynamically Linked Library (DLL) is a library that can be shared by
30365 several applications running under Windows. A DLL can contain any number of
30366 routines and variables.
30368 One advantage of DLLs is that you can change and enhance them without
30369 forcing all the applications that depend on them to be relinked or
30370 recompiled. However, you should be aware than all calls to DLL routines are
30371 slower since, as you will understand below, such calls are indirect.
30373 To illustrate the remainder of this section, suppose that an application
30374 wants to use the services of a DLL @file{API.dll}. To use the services
30375 provided by @file{API.dll} you must statically link against the DLL or
30376 an import library which contains a jump table with an entry for each
30377 routine and variable exported by the DLL. In the Microsoft world this
30378 import library is called @file{API.lib}. When using GNAT this import
30379 library is called either @file{libAPI.dll.a}, @file{libapi.dll.a},
30380 @file{libAPI.a} or @file{libapi.a} (names are case insensitive).
30382 After you have linked your application with the DLL or the import library
30383 and you run your application, here is what happens:
30387 Your application is loaded into memory.
30390 The DLL @file{API.dll} is mapped into the address space of your
30391 application. This means that:
30395 The DLL will use the stack of the calling thread.
30398 The DLL will use the virtual address space of the calling process.
30401 The DLL will allocate memory from the virtual address space of the calling
30405 Handles (pointers) can be safely exchanged between routines in the DLL
30406 routines and routines in the application using the DLL.
30410 The entries in the jump table (from the import library @file{libAPI.dll.a}
30411 or @file{API.lib} or automatically created when linking against a DLL)
30412 which is part of your application are initialized with the addresses
30413 of the routines and variables in @file{API.dll}.
30416 If present in @file{API.dll}, routines @code{DllMain} or
30417 @code{DllMainCRTStartup} are invoked. These routines typically contain
30418 the initialization code needed for the well-being of the routines and
30419 variables exported by the DLL.
30423 There is an additional point which is worth mentioning. In the Windows
30424 world there are two kind of DLLs: relocatable and non-relocatable
30425 DLLs. Non-relocatable DLLs can only be loaded at a very specific address
30426 in the target application address space. If the addresses of two
30427 non-relocatable DLLs overlap and these happen to be used by the same
30428 application, a conflict will occur and the application will run
30429 incorrectly. Hence, when possible, it is always preferable to use and
30430 build relocatable DLLs. Both relocatable and non-relocatable DLLs are
30431 supported by GNAT. Note that the @option{-s} linker option (see GNU Linker
30432 User's Guide) removes the debugging symbols from the DLL but the DLL can
30433 still be relocated.
30435 As a side note, an interesting difference between Microsoft DLLs and
30436 Unix shared libraries, is the fact that on most Unix systems all public
30437 routines are exported by default in a Unix shared library, while under
30438 Windows it is possible (but not required) to list exported routines in
30439 a definition file (@pxref{The Definition File}).
30441 @node Using DLLs with GNAT
30442 @section Using DLLs with GNAT
30445 * Creating an Ada Spec for the DLL Services::
30446 * Creating an Import Library::
30450 To use the services of a DLL, say @file{API.dll}, in your Ada application
30455 The Ada spec for the routines and/or variables you want to access in
30456 @file{API.dll}. If not available this Ada spec must be built from the C/C++
30457 header files provided with the DLL.
30460 The import library (@file{libAPI.dll.a} or @file{API.lib}). As previously
30461 mentioned an import library is a statically linked library containing the
30462 import table which will be filled at load time to point to the actual
30463 @file{API.dll} routines. Sometimes you don't have an import library for the
30464 DLL you want to use. The following sections will explain how to build
30465 one. Note that this is optional.
30468 The actual DLL, @file{API.dll}.
30472 Once you have all the above, to compile an Ada application that uses the
30473 services of @file{API.dll} and whose main subprogram is @code{My_Ada_App},
30474 you simply issue the command
30477 $ gnatmake my_ada_app -largs -lAPI
30481 The argument @option{-largs -lAPI} at the end of the @command{gnatmake} command
30482 tells the GNAT linker to look for an import library. The linker will
30483 look for a library name in this specific order:
30486 @item @file{libAPI.dll.a}
30487 @item @file{API.dll.a}
30488 @item @file{libAPI.a}
30489 @item @file{API.lib}
30490 @item @file{libAPI.dll}
30491 @item @file{API.dll}
30494 The first three are the GNU style import libraries. The third is the
30495 Microsoft style import libraries. The last two are the actual DLL names.
30497 Note that if the Ada package spec for @file{API.dll} contains the
30500 @smallexample @c ada
30501 pragma Linker_Options ("-lAPI");
30505 you do not have to add @option{-largs -lAPI} at the end of the
30506 @command{gnatmake} command.
30508 If any one of the items above is missing you will have to create it
30509 yourself. The following sections explain how to do so using as an
30510 example a fictitious DLL called @file{API.dll}.
30512 @node Creating an Ada Spec for the DLL Services
30513 @subsection Creating an Ada Spec for the DLL Services
30516 A DLL typically comes with a C/C++ header file which provides the
30517 definitions of the routines and variables exported by the DLL. The Ada
30518 equivalent of this header file is a package spec that contains definitions
30519 for the imported entities. If the DLL you intend to use does not come with
30520 an Ada spec you have to generate one such spec yourself. For example if
30521 the header file of @file{API.dll} is a file @file{api.h} containing the
30522 following two definitions:
30534 then the equivalent Ada spec could be:
30536 @smallexample @c ada
30539 with Interfaces.C.Strings;
30544 function Get (Str : C.Strings.Chars_Ptr) return C.int;
30547 pragma Import (C, Get);
30548 pragma Import (DLL, Some_Var);
30554 @node Creating an Import Library
30555 @subsection Creating an Import Library
30556 @cindex Import library
30559 * The Definition File::
30560 * GNAT-Style Import Library::
30561 * Microsoft-Style Import Library::
30565 If a Microsoft-style import library @file{API.lib} or a GNAT-style
30566 import library @file{libAPI.dll.a} or @file{libAPI.a} is available
30567 with @file{API.dll} you can skip this section. You can also skip this
30568 section if @file{API.dll} or @file{libAPI.dll} is built with GNU tools
30569 as in this case it is possible to link directly against the
30570 DLL. Otherwise read on.
30572 @node The Definition File
30573 @subsubsection The Definition File
30574 @cindex Definition file
30578 As previously mentioned, and unlike Unix systems, the list of symbols
30579 that are exported from a DLL must be provided explicitly in Windows.
30580 The main goal of a definition file is precisely that: list the symbols
30581 exported by a DLL. A definition file (usually a file with a @code{.def}
30582 suffix) has the following structure:
30587 @r{[}LIBRARY @var{name}@r{]}
30588 @r{[}DESCRIPTION @var{string}@r{]}
30598 @item LIBRARY @var{name}
30599 This section, which is optional, gives the name of the DLL.
30601 @item DESCRIPTION @var{string}
30602 This section, which is optional, gives a description string that will be
30603 embedded in the import library.
30606 This section gives the list of exported symbols (procedures, functions or
30607 variables). For instance in the case of @file{API.dll} the @code{EXPORTS}
30608 section of @file{API.def} looks like:
30622 Note that you must specify the correct suffix (@code{@@}@code{@var{nn}})
30623 (@pxref{Windows Calling Conventions}) for a Stdcall
30624 calling convention function in the exported symbols list.
30627 There can actually be other sections in a definition file, but these
30628 sections are not relevant to the discussion at hand.
30630 @node GNAT-Style Import Library
30631 @subsubsection GNAT-Style Import Library
30634 To create a static import library from @file{API.dll} with the GNAT tools
30635 you should proceed as follows:
30639 Create the definition file @file{API.def} (@pxref{The Definition File}).
30640 For that use the @code{dll2def} tool as follows:
30643 $ dll2def API.dll > API.def
30647 @code{dll2def} is a very simple tool: it takes as input a DLL and prints
30648 to standard output the list of entry points in the DLL. Note that if
30649 some routines in the DLL have the @code{Stdcall} convention
30650 (@pxref{Windows Calling Conventions}) with stripped @code{@@}@var{nn}
30651 suffix then you'll have to edit @file{api.def} to add it, and specify
30652 @option{-k} to @command{gnatdll} when creating the import library.
30655 Here are some hints to find the right @code{@@}@var{nn} suffix.
30659 If you have the Microsoft import library (.lib), it is possible to get
30660 the right symbols by using Microsoft @code{dumpbin} tool (see the
30661 corresponding Microsoft documentation for further details).
30664 $ dumpbin /exports api.lib
30668 If you have a message about a missing symbol at link time the compiler
30669 tells you what symbol is expected. You just have to go back to the
30670 definition file and add the right suffix.
30674 Build the import library @code{libAPI.dll.a}, using @code{gnatdll}
30675 (@pxref{Using gnatdll}) as follows:
30678 $ gnatdll -e API.def -d API.dll
30682 @code{gnatdll} takes as input a definition file @file{API.def} and the
30683 name of the DLL containing the services listed in the definition file
30684 @file{API.dll}. The name of the static import library generated is
30685 computed from the name of the definition file as follows: if the
30686 definition file name is @var{xyz}@code{.def}, the import library name will
30687 be @code{lib}@var{xyz}@code{.a}. Note that in the previous example option
30688 @option{-e} could have been removed because the name of the definition
30689 file (before the ``@code{.def}'' suffix) is the same as the name of the
30690 DLL (@pxref{Using gnatdll} for more information about @code{gnatdll}).
30693 @node Microsoft-Style Import Library
30694 @subsubsection Microsoft-Style Import Library
30697 With GNAT you can either use a GNAT-style or Microsoft-style import
30698 library. A Microsoft import library is needed only if you plan to make an
30699 Ada DLL available to applications developed with Microsoft
30700 tools (@pxref{Mixed-Language Programming on Windows}).
30702 To create a Microsoft-style import library for @file{API.dll} you
30703 should proceed as follows:
30707 Create the definition file @file{API.def} from the DLL. For this use either
30708 the @code{dll2def} tool as described above or the Microsoft @code{dumpbin}
30709 tool (see the corresponding Microsoft documentation for further details).
30712 Build the actual import library using Microsoft's @code{lib} utility:
30715 $ lib -machine:IX86 -def:API.def -out:API.lib
30719 If you use the above command the definition file @file{API.def} must
30720 contain a line giving the name of the DLL:
30727 See the Microsoft documentation for further details about the usage of
30731 @node Building DLLs with GNAT Project files
30732 @section Building DLLs with GNAT Project files
30733 @cindex DLLs, building
30736 There is nothing specific to Windows in the build process.
30737 @pxref{Library Projects}.
30740 Due to a system limitation, it is not possible under Windows to create threads
30741 when inside the @code{DllMain} routine which is used for auto-initialization
30742 of shared libraries, so it is not possible to have library level tasks in SALs.
30744 @node Building DLLs with GNAT
30745 @section Building DLLs with GNAT
30746 @cindex DLLs, building
30749 This section explain how to build DLLs using the GNAT built-in DLL
30750 support. With the following procedure it is straight forward to build
30751 and use DLLs with GNAT.
30755 @item building object files
30757 The first step is to build all objects files that are to be included
30758 into the DLL. This is done by using the standard @command{gnatmake} tool.
30760 @item building the DLL
30762 To build the DLL you must use @command{gcc}'s @option{-shared} and
30763 @option{-shared-libgcc} options. It is quite simple to use this method:
30766 $ gcc -shared -shared-libgcc -o api.dll obj1.o obj2.o @dots{}
30769 It is important to note that in this case all symbols found in the
30770 object files are automatically exported. It is possible to restrict
30771 the set of symbols to export by passing to @command{gcc} a definition
30772 file, @pxref{The Definition File}. For example:
30775 $ gcc -shared -shared-libgcc -o api.dll api.def obj1.o obj2.o @dots{}
30778 If you use a definition file you must export the elaboration procedures
30779 for every package that required one. Elaboration procedures are named
30780 using the package name followed by "_E".
30782 @item preparing DLL to be used
30784 For the DLL to be used by client programs the bodies must be hidden
30785 from it and the .ali set with read-only attribute. This is very important
30786 otherwise GNAT will recompile all packages and will not actually use
30787 the code in the DLL. For example:
30791 $ copy *.ads *.ali api.dll apilib
30792 $ attrib +R apilib\*.ali
30797 At this point it is possible to use the DLL by directly linking
30798 against it. Note that you must use the GNAT shared runtime when using
30799 GNAT shared libraries. This is achieved by using @option{-shared} binder's
30803 $ gnatmake main -Iapilib -bargs -shared -largs -Lapilib -lAPI
30806 @node Building DLLs with gnatdll
30807 @section Building DLLs with gnatdll
30808 @cindex DLLs, building
30811 * Limitations When Using Ada DLLs from Ada::
30812 * Exporting Ada Entities::
30813 * Ada DLLs and Elaboration::
30814 * Ada DLLs and Finalization::
30815 * Creating a Spec for Ada DLLs::
30816 * Creating the Definition File::
30821 Note that it is preferred to use GNAT Project files
30822 (@pxref{Building DLLs with GNAT Project files}) or the built-in GNAT
30823 DLL support (@pxref{Building DLLs with GNAT}) or to build DLLs.
30825 This section explains how to build DLLs containing Ada code using
30826 @code{gnatdll}. These DLLs will be referred to as Ada DLLs in the
30827 remainder of this section.
30829 The steps required to build an Ada DLL that is to be used by Ada as well as
30830 non-Ada applications are as follows:
30834 You need to mark each Ada @i{entity} exported by the DLL with a @code{C} or
30835 @code{Stdcall} calling convention to avoid any Ada name mangling for the
30836 entities exported by the DLL (@pxref{Exporting Ada Entities}). You can
30837 skip this step if you plan to use the Ada DLL only from Ada applications.
30840 Your Ada code must export an initialization routine which calls the routine
30841 @code{adainit} generated by @command{gnatbind} to perform the elaboration of
30842 the Ada code in the DLL (@pxref{Ada DLLs and Elaboration}). The initialization
30843 routine exported by the Ada DLL must be invoked by the clients of the DLL
30844 to initialize the DLL.
30847 When useful, the DLL should also export a finalization routine which calls
30848 routine @code{adafinal} generated by @command{gnatbind} to perform the
30849 finalization of the Ada code in the DLL (@pxref{Ada DLLs and Finalization}).
30850 The finalization routine exported by the Ada DLL must be invoked by the
30851 clients of the DLL when the DLL services are no further needed.
30854 You must provide a spec for the services exported by the Ada DLL in each
30855 of the programming languages to which you plan to make the DLL available.
30858 You must provide a definition file listing the exported entities
30859 (@pxref{The Definition File}).
30862 Finally you must use @code{gnatdll} to produce the DLL and the import
30863 library (@pxref{Using gnatdll}).
30867 Note that a relocatable DLL stripped using the @code{strip}
30868 binutils tool will not be relocatable anymore. To build a DLL without
30869 debug information pass @code{-largs -s} to @code{gnatdll}. This
30870 restriction does not apply to a DLL built using a Library Project.
30871 @pxref{Library Projects}.
30873 @node Limitations When Using Ada DLLs from Ada
30874 @subsection Limitations When Using Ada DLLs from Ada
30877 When using Ada DLLs from Ada applications there is a limitation users
30878 should be aware of. Because on Windows the GNAT run time is not in a DLL of
30879 its own, each Ada DLL includes a part of the GNAT run time. Specifically,
30880 each Ada DLL includes the services of the GNAT run time that are necessary
30881 to the Ada code inside the DLL. As a result, when an Ada program uses an
30882 Ada DLL there are two independent GNAT run times: one in the Ada DLL and
30883 one in the main program.
30885 It is therefore not possible to exchange GNAT run-time objects between the
30886 Ada DLL and the main Ada program. Example of GNAT run-time objects are file
30887 handles (e.g.@: @code{Text_IO.File_Type}), tasks types, protected objects
30890 It is completely safe to exchange plain elementary, array or record types,
30891 Windows object handles, etc.
30893 @node Exporting Ada Entities
30894 @subsection Exporting Ada Entities
30895 @cindex Export table
30898 Building a DLL is a way to encapsulate a set of services usable from any
30899 application. As a result, the Ada entities exported by a DLL should be
30900 exported with the @code{C} or @code{Stdcall} calling conventions to avoid
30901 any Ada name mangling. As an example here is an Ada package
30902 @code{API}, spec and body, exporting two procedures, a function, and a
30905 @smallexample @c ada
30908 with Interfaces.C; use Interfaces;
30910 Count : C.int := 0;
30911 function Factorial (Val : C.int) return C.int;
30913 procedure Initialize_API;
30914 procedure Finalize_API;
30915 -- Initialization & Finalization routines. More in the next section.
30917 pragma Export (C, Initialize_API);
30918 pragma Export (C, Finalize_API);
30919 pragma Export (C, Count);
30920 pragma Export (C, Factorial);
30926 @smallexample @c ada
30929 package body API is
30930 function Factorial (Val : C.int) return C.int is
30933 Count := Count + 1;
30934 for K in 1 .. Val loop
30940 procedure Initialize_API is
30942 pragma Import (C, Adainit);
30945 end Initialize_API;
30947 procedure Finalize_API is
30948 procedure Adafinal;
30949 pragma Import (C, Adafinal);
30959 If the Ada DLL you are building will only be used by Ada applications
30960 you do not have to export Ada entities with a @code{C} or @code{Stdcall}
30961 convention. As an example, the previous package could be written as
30964 @smallexample @c ada
30968 Count : Integer := 0;
30969 function Factorial (Val : Integer) return Integer;
30971 procedure Initialize_API;
30972 procedure Finalize_API;
30973 -- Initialization and Finalization routines.
30979 @smallexample @c ada
30982 package body API is
30983 function Factorial (Val : Integer) return Integer is
30984 Fact : Integer := 1;
30986 Count := Count + 1;
30987 for K in 1 .. Val loop
30994 -- The remainder of this package body is unchanged.
31001 Note that if you do not export the Ada entities with a @code{C} or
31002 @code{Stdcall} convention you will have to provide the mangled Ada names
31003 in the definition file of the Ada DLL
31004 (@pxref{Creating the Definition File}).
31006 @node Ada DLLs and Elaboration
31007 @subsection Ada DLLs and Elaboration
31008 @cindex DLLs and elaboration
31011 The DLL that you are building contains your Ada code as well as all the
31012 routines in the Ada library that are needed by it. The first thing a
31013 user of your DLL must do is elaborate the Ada code
31014 (@pxref{Elaboration Order Handling in GNAT}).
31016 To achieve this you must export an initialization routine
31017 (@code{Initialize_API} in the previous example), which must be invoked
31018 before using any of the DLL services. This elaboration routine must call
31019 the Ada elaboration routine @code{adainit} generated by the GNAT binder
31020 (@pxref{Binding with Non-Ada Main Programs}). See the body of
31021 @code{Initialize_Api} for an example. Note that the GNAT binder is
31022 automatically invoked during the DLL build process by the @code{gnatdll}
31023 tool (@pxref{Using gnatdll}).
31025 When a DLL is loaded, Windows systematically invokes a routine called
31026 @code{DllMain}. It would therefore be possible to call @code{adainit}
31027 directly from @code{DllMain} without having to provide an explicit
31028 initialization routine. Unfortunately, it is not possible to call
31029 @code{adainit} from the @code{DllMain} if your program has library level
31030 tasks because access to the @code{DllMain} entry point is serialized by
31031 the system (that is, only a single thread can execute ``through'' it at a
31032 time), which means that the GNAT run time will deadlock waiting for the
31033 newly created task to complete its initialization.
31035 @node Ada DLLs and Finalization
31036 @subsection Ada DLLs and Finalization
31037 @cindex DLLs and finalization
31040 When the services of an Ada DLL are no longer needed, the client code should
31041 invoke the DLL finalization routine, if available. The DLL finalization
31042 routine is in charge of releasing all resources acquired by the DLL. In the
31043 case of the Ada code contained in the DLL, this is achieved by calling
31044 routine @code{adafinal} generated by the GNAT binder
31045 (@pxref{Binding with Non-Ada Main Programs}).
31046 See the body of @code{Finalize_Api} for an
31047 example. As already pointed out the GNAT binder is automatically invoked
31048 during the DLL build process by the @code{gnatdll} tool
31049 (@pxref{Using gnatdll}).
31051 @node Creating a Spec for Ada DLLs
31052 @subsection Creating a Spec for Ada DLLs
31055 To use the services exported by the Ada DLL from another programming
31056 language (e.g.@: C), you have to translate the specs of the exported Ada
31057 entities in that language. For instance in the case of @code{API.dll},
31058 the corresponding C header file could look like:
31063 extern int *_imp__count;
31064 #define count (*_imp__count)
31065 int factorial (int);
31071 It is important to understand that when building an Ada DLL to be used by
31072 other Ada applications, you need two different specs for the packages
31073 contained in the DLL: one for building the DLL and the other for using
31074 the DLL. This is because the @code{DLL} calling convention is needed to
31075 use a variable defined in a DLL, but when building the DLL, the variable
31076 must have either the @code{Ada} or @code{C} calling convention. As an
31077 example consider a DLL comprising the following package @code{API}:
31079 @smallexample @c ada
31083 Count : Integer := 0;
31085 -- Remainder of the package omitted.
31092 After producing a DLL containing package @code{API}, the spec that
31093 must be used to import @code{API.Count} from Ada code outside of the
31096 @smallexample @c ada
31101 pragma Import (DLL, Count);
31107 @node Creating the Definition File
31108 @subsection Creating the Definition File
31111 The definition file is the last file needed to build the DLL. It lists
31112 the exported symbols. As an example, the definition file for a DLL
31113 containing only package @code{API} (where all the entities are exported
31114 with a @code{C} calling convention) is:
31129 If the @code{C} calling convention is missing from package @code{API},
31130 then the definition file contains the mangled Ada names of the above
31131 entities, which in this case are:
31140 api__initialize_api
31145 @node Using gnatdll
31146 @subsection Using @code{gnatdll}
31150 * gnatdll Example::
31151 * gnatdll behind the Scenes::
31156 @code{gnatdll} is a tool to automate the DLL build process once all the Ada
31157 and non-Ada sources that make up your DLL have been compiled.
31158 @code{gnatdll} is actually in charge of two distinct tasks: build the
31159 static import library for the DLL and the actual DLL. The form of the
31160 @code{gnatdll} command is
31164 @c $ gnatdll @ovar{switches} @var{list-of-files} @r{[}-largs @var{opts}@r{]}
31165 @c Expanding @ovar macro inline (explanation in macro def comments)
31166 $ gnatdll @r{[}@var{switches}@r{]} @var{list-of-files} @r{[}-largs @var{opts}@r{]}
31171 where @var{list-of-files} is a list of ALI and object files. The object
31172 file list must be the exact list of objects corresponding to the non-Ada
31173 sources whose services are to be included in the DLL. The ALI file list
31174 must be the exact list of ALI files for the corresponding Ada sources
31175 whose services are to be included in the DLL. If @var{list-of-files} is
31176 missing, only the static import library is generated.
31179 You may specify any of the following switches to @code{gnatdll}:
31182 @c @item -a@ovar{address}
31183 @c Expanding @ovar macro inline (explanation in macro def comments)
31184 @item -a@r{[}@var{address}@r{]}
31185 @cindex @option{-a} (@code{gnatdll})
31186 Build a non-relocatable DLL at @var{address}. If @var{address} is not
31187 specified the default address @var{0x11000000} will be used. By default,
31188 when this switch is missing, @code{gnatdll} builds relocatable DLL. We
31189 advise the reader to build relocatable DLL.
31191 @item -b @var{address}
31192 @cindex @option{-b} (@code{gnatdll})
31193 Set the relocatable DLL base address. By default the address is
31196 @item -bargs @var{opts}
31197 @cindex @option{-bargs} (@code{gnatdll})
31198 Binder options. Pass @var{opts} to the binder.
31200 @item -d @var{dllfile}
31201 @cindex @option{-d} (@code{gnatdll})
31202 @var{dllfile} is the name of the DLL. This switch must be present for
31203 @code{gnatdll} to do anything. The name of the generated import library is
31204 obtained algorithmically from @var{dllfile} as shown in the following
31205 example: if @var{dllfile} is @code{xyz.dll}, the import library name is
31206 @code{libxyz.dll.a}. The name of the definition file to use (if not specified
31207 by option @option{-e}) is obtained algorithmically from @var{dllfile}
31208 as shown in the following example:
31209 if @var{dllfile} is @code{xyz.dll}, the definition
31210 file used is @code{xyz.def}.
31212 @item -e @var{deffile}
31213 @cindex @option{-e} (@code{gnatdll})
31214 @var{deffile} is the name of the definition file.
31217 @cindex @option{-g} (@code{gnatdll})
31218 Generate debugging information. This information is stored in the object
31219 file and copied from there to the final DLL file by the linker,
31220 where it can be read by the debugger. You must use the
31221 @option{-g} switch if you plan on using the debugger or the symbolic
31225 @cindex @option{-h} (@code{gnatdll})
31226 Help mode. Displays @code{gnatdll} switch usage information.
31229 @cindex @option{-I} (@code{gnatdll})
31230 Direct @code{gnatdll} to search the @var{dir} directory for source and
31231 object files needed to build the DLL.
31232 (@pxref{Search Paths and the Run-Time Library (RTL)}).
31235 @cindex @option{-k} (@code{gnatdll})
31236 Removes the @code{@@}@var{nn} suffix from the import library's exported
31237 names, but keeps them for the link names. You must specify this
31238 option if you want to use a @code{Stdcall} function in a DLL for which
31239 the @code{@@}@var{nn} suffix has been removed. This is the case for most
31240 of the Windows NT DLL for example. This option has no effect when
31241 @option{-n} option is specified.
31243 @item -l @var{file}
31244 @cindex @option{-l} (@code{gnatdll})
31245 The list of ALI and object files used to build the DLL are listed in
31246 @var{file}, instead of being given in the command line. Each line in
31247 @var{file} contains the name of an ALI or object file.
31250 @cindex @option{-n} (@code{gnatdll})
31251 No Import. Do not create the import library.
31254 @cindex @option{-q} (@code{gnatdll})
31255 Quiet mode. Do not display unnecessary messages.
31258 @cindex @option{-v} (@code{gnatdll})
31259 Verbose mode. Display extra information.
31261 @item -largs @var{opts}
31262 @cindex @option{-largs} (@code{gnatdll})
31263 Linker options. Pass @var{opts} to the linker.
31266 @node gnatdll Example
31267 @subsubsection @code{gnatdll} Example
31270 As an example the command to build a relocatable DLL from @file{api.adb}
31271 once @file{api.adb} has been compiled and @file{api.def} created is
31274 $ gnatdll -d api.dll api.ali
31278 The above command creates two files: @file{libapi.dll.a} (the import
31279 library) and @file{api.dll} (the actual DLL). If you want to create
31280 only the DLL, just type:
31283 $ gnatdll -d api.dll -n api.ali
31287 Alternatively if you want to create just the import library, type:
31290 $ gnatdll -d api.dll
31293 @node gnatdll behind the Scenes
31294 @subsubsection @code{gnatdll} behind the Scenes
31297 This section details the steps involved in creating a DLL. @code{gnatdll}
31298 does these steps for you. Unless you are interested in understanding what
31299 goes on behind the scenes, you should skip this section.
31301 We use the previous example of a DLL containing the Ada package @code{API},
31302 to illustrate the steps necessary to build a DLL. The starting point is a
31303 set of objects that will make up the DLL and the corresponding ALI
31304 files. In the case of this example this means that @file{api.o} and
31305 @file{api.ali} are available. To build a relocatable DLL, @code{gnatdll} does
31310 @code{gnatdll} builds the base file (@file{api.base}). A base file gives
31311 the information necessary to generate relocation information for the
31317 $ gnatlink api -o api.jnk -mdll -Wl,--base-file,api.base
31322 In addition to the base file, the @command{gnatlink} command generates an
31323 output file @file{api.jnk} which can be discarded. The @option{-mdll} switch
31324 asks @command{gnatlink} to generate the routines @code{DllMain} and
31325 @code{DllMainCRTStartup} that are called by the Windows loader when the DLL
31326 is loaded into memory.
31329 @code{gnatdll} uses @code{dlltool} (@pxref{Using dlltool}) to build the
31330 export table (@file{api.exp}). The export table contains the relocation
31331 information in a form which can be used during the final link to ensure
31332 that the Windows loader is able to place the DLL anywhere in memory.
31336 $ dlltool --dllname api.dll --def api.def --base-file api.base \
31337 --output-exp api.exp
31342 @code{gnatdll} builds the base file using the new export table. Note that
31343 @command{gnatbind} must be called once again since the binder generated file
31344 has been deleted during the previous call to @command{gnatlink}.
31349 $ gnatlink api -o api.jnk api.exp -mdll
31350 -Wl,--base-file,api.base
31355 @code{gnatdll} builds the new export table using the new base file and
31356 generates the DLL import library @file{libAPI.dll.a}.
31360 $ dlltool --dllname api.dll --def api.def --base-file api.base \
31361 --output-exp api.exp --output-lib libAPI.a
31366 Finally @code{gnatdll} builds the relocatable DLL using the final export
31372 $ gnatlink api api.exp -o api.dll -mdll
31377 @node Using dlltool
31378 @subsubsection Using @code{dlltool}
31381 @code{dlltool} is the low-level tool used by @code{gnatdll} to build
31382 DLLs and static import libraries. This section summarizes the most
31383 common @code{dlltool} switches. The form of the @code{dlltool} command
31387 @c $ dlltool @ovar{switches}
31388 @c Expanding @ovar macro inline (explanation in macro def comments)
31389 $ dlltool @r{[}@var{switches}@r{]}
31393 @code{dlltool} switches include:
31396 @item --base-file @var{basefile}
31397 @cindex @option{--base-file} (@command{dlltool})
31398 Read the base file @var{basefile} generated by the linker. This switch
31399 is used to create a relocatable DLL.
31401 @item --def @var{deffile}
31402 @cindex @option{--def} (@command{dlltool})
31403 Read the definition file.
31405 @item --dllname @var{name}
31406 @cindex @option{--dllname} (@command{dlltool})
31407 Gives the name of the DLL. This switch is used to embed the name of the
31408 DLL in the static import library generated by @code{dlltool} with switch
31409 @option{--output-lib}.
31412 @cindex @option{-k} (@command{dlltool})
31413 Kill @code{@@}@var{nn} from exported names
31414 (@pxref{Windows Calling Conventions}
31415 for a discussion about @code{Stdcall}-style symbols.
31418 @cindex @option{--help} (@command{dlltool})
31419 Prints the @code{dlltool} switches with a concise description.
31421 @item --output-exp @var{exportfile}
31422 @cindex @option{--output-exp} (@command{dlltool})
31423 Generate an export file @var{exportfile}. The export file contains the
31424 export table (list of symbols in the DLL) and is used to create the DLL.
31426 @item --output-lib @var{libfile}
31427 @cindex @option{--output-lib} (@command{dlltool})
31428 Generate a static import library @var{libfile}.
31431 @cindex @option{-v} (@command{dlltool})
31434 @item --as @var{assembler-name}
31435 @cindex @option{--as} (@command{dlltool})
31436 Use @var{assembler-name} as the assembler. The default is @code{as}.
31439 @node GNAT and Windows Resources
31440 @section GNAT and Windows Resources
31441 @cindex Resources, windows
31444 * Building Resources::
31445 * Compiling Resources::
31446 * Using Resources::
31450 Resources are an easy way to add Windows specific objects to your
31451 application. The objects that can be added as resources include:
31460 @item string tables
31470 @item version information
31473 For example, a version information resource can be defined as follow and
31474 embedded into an executable or DLL:
31476 A version information resource can be used to embed information into an
31477 executable or a DLL. These information can be viewed using the file properties
31478 from the Windows Explorer. Here is an example of a version information
31484 FILEVERSION 1,0,0,0
31485 PRODUCTVERSION 1,0,0,0
31487 BLOCK "StringFileInfo"
31491 VALUE "CompanyName", "My Company Name"
31492 VALUE "FileDescription", "My application"
31493 VALUE "FileVersion", "1.0"
31494 VALUE "InternalName", "my_app"
31495 VALUE "LegalCopyright", "My Name"
31496 VALUE "OriginalFilename", "my_app.exe"
31497 VALUE "ProductName", "My App"
31498 VALUE "ProductVersion", "1.0"
31502 BLOCK "VarFileInfo"
31504 VALUE "Translation", 0x809, 1252
31510 The value @code{0809} (langID) is for the U.K English language and
31511 @code{04E4} (charsetID), which is equal to @code{1252} decimal, for
31515 This section explains how to build, compile and use resources. Note that this
31516 section does not cover all resource objects, for a complete description see
31517 the corresponding Microsoft documentation.
31519 @node Building Resources
31520 @subsection Building Resources
31521 @cindex Resources, building
31524 A resource file is an ASCII file. By convention resource files have an
31525 @file{.rc} extension.
31526 The easiest way to build a resource file is to use Microsoft tools
31527 such as @code{imagedit.exe} to build bitmaps, icons and cursors and
31528 @code{dlgedit.exe} to build dialogs.
31529 It is always possible to build an @file{.rc} file yourself by writing a
31532 It is not our objective to explain how to write a resource file. A
31533 complete description of the resource script language can be found in the
31534 Microsoft documentation.
31536 @node Compiling Resources
31537 @subsection Compiling Resources
31540 @cindex Resources, compiling
31543 This section describes how to build a GNAT-compatible (COFF) object file
31544 containing the resources. This is done using the Resource Compiler
31545 @code{windres} as follows:
31548 $ windres -i myres.rc -o myres.o
31552 By default @code{windres} will run @command{gcc} to preprocess the @file{.rc}
31553 file. You can specify an alternate preprocessor (usually named
31554 @file{cpp.exe}) using the @code{windres} @option{--preprocessor}
31555 parameter. A list of all possible options may be obtained by entering
31556 the command @code{windres} @option{--help}.
31558 It is also possible to use the Microsoft resource compiler @code{rc.exe}
31559 to produce a @file{.res} file (binary resource file). See the
31560 corresponding Microsoft documentation for further details. In this case
31561 you need to use @code{windres} to translate the @file{.res} file to a
31562 GNAT-compatible object file as follows:
31565 $ windres -i myres.res -o myres.o
31568 @node Using Resources
31569 @subsection Using Resources
31570 @cindex Resources, using
31573 To include the resource file in your program just add the
31574 GNAT-compatible object file for the resource(s) to the linker
31575 arguments. With @command{gnatmake} this is done by using the @option{-largs}
31579 $ gnatmake myprog -largs myres.o
31582 @node Debugging a DLL
31583 @section Debugging a DLL
31584 @cindex DLL debugging
31587 * Program and DLL Both Built with GCC/GNAT::
31588 * Program Built with Foreign Tools and DLL Built with GCC/GNAT::
31592 Debugging a DLL is similar to debugging a standard program. But
31593 we have to deal with two different executable parts: the DLL and the
31594 program that uses it. We have the following four possibilities:
31598 The program and the DLL are built with @code{GCC/GNAT}.
31600 The program is built with foreign tools and the DLL is built with
31603 The program is built with @code{GCC/GNAT} and the DLL is built with
31608 In this section we address only cases one and two above.
31609 There is no point in trying to debug
31610 a DLL with @code{GNU/GDB}, if there is no GDB-compatible debugging
31611 information in it. To do so you must use a debugger compatible with the
31612 tools suite used to build the DLL.
31614 @node Program and DLL Both Built with GCC/GNAT
31615 @subsection Program and DLL Both Built with GCC/GNAT
31618 This is the simplest case. Both the DLL and the program have @code{GDB}
31619 compatible debugging information. It is then possible to break anywhere in
31620 the process. Let's suppose here that the main procedure is named
31621 @code{ada_main} and that in the DLL there is an entry point named
31625 The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) and
31626 program must have been built with the debugging information (see GNAT -g
31627 switch). Here are the step-by-step instructions for debugging it:
31630 @item Launch @code{GDB} on the main program.
31636 @item Start the program and stop at the beginning of the main procedure
31643 This step is required to be able to set a breakpoint inside the DLL. As long
31644 as the program is not run, the DLL is not loaded. This has the
31645 consequence that the DLL debugging information is also not loaded, so it is not
31646 possible to set a breakpoint in the DLL.
31648 @item Set a breakpoint inside the DLL
31651 (gdb) break ada_dll
31658 At this stage a breakpoint is set inside the DLL. From there on
31659 you can use the standard approach to debug the whole program
31660 (@pxref{Running and Debugging Ada Programs}).
31663 @c This used to work, probably because the DLLs were non-relocatable
31664 @c keep this section around until the problem is sorted out.
31666 To break on the @code{DllMain} routine it is not possible to follow
31667 the procedure above. At the time the program stop on @code{ada_main}
31668 the @code{DllMain} routine as already been called. Either you can use
31669 the procedure below @pxref{Debugging the DLL Directly} or this procedure:
31672 @item Launch @code{GDB} on the main program.
31678 @item Load DLL symbols
31681 (gdb) add-sym api.dll
31684 @item Set a breakpoint inside the DLL
31687 (gdb) break ada_dll.adb:45
31690 Note that at this point it is not possible to break using the routine symbol
31691 directly as the program is not yet running. The solution is to break
31692 on the proper line (break in @file{ada_dll.adb} line 45).
31694 @item Start the program
31703 @node Program Built with Foreign Tools and DLL Built with GCC/GNAT
31704 @subsection Program Built with Foreign Tools and DLL Built with GCC/GNAT
31707 * Debugging the DLL Directly::
31708 * Attaching to a Running Process::
31712 In this case things are slightly more complex because it is not possible to
31713 start the main program and then break at the beginning to load the DLL and the
31714 associated DLL debugging information. It is not possible to break at the
31715 beginning of the program because there is no @code{GDB} debugging information,
31716 and therefore there is no direct way of getting initial control. This
31717 section addresses this issue by describing some methods that can be used
31718 to break somewhere in the DLL to debug it.
31721 First suppose that the main procedure is named @code{main} (this is for
31722 example some C code built with Microsoft Visual C) and that there is a
31723 DLL named @code{test.dll} containing an Ada entry point named
31727 The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) must have
31728 been built with debugging information (see GNAT -g option).
31730 @node Debugging the DLL Directly
31731 @subsubsection Debugging the DLL Directly
31735 Find out the executable starting address
31738 $ objdump --file-header main.exe
31741 The starting address is reported on the last line. For example:
31744 main.exe: file format pei-i386
31745 architecture: i386, flags 0x0000010a:
31746 EXEC_P, HAS_DEBUG, D_PAGED
31747 start address 0x00401010
31751 Launch the debugger on the executable.
31758 Set a breakpoint at the starting address, and launch the program.
31761 $ (gdb) break *0x00401010
31765 The program will stop at the given address.
31768 Set a breakpoint on a DLL subroutine.
31771 (gdb) break ada_dll.adb:45
31774 Or if you want to break using a symbol on the DLL, you need first to
31775 select the Ada language (language used by the DLL).
31778 (gdb) set language ada
31779 (gdb) break ada_dll
31783 Continue the program.
31790 This will run the program until it reaches the breakpoint that has been
31791 set. From that point you can use the standard way to debug a program
31792 as described in (@pxref{Running and Debugging Ada Programs}).
31797 It is also possible to debug the DLL by attaching to a running process.
31799 @node Attaching to a Running Process
31800 @subsubsection Attaching to a Running Process
31801 @cindex DLL debugging, attach to process
31804 With @code{GDB} it is always possible to debug a running process by
31805 attaching to it. It is possible to debug a DLL this way. The limitation
31806 of this approach is that the DLL must run long enough to perform the
31807 attach operation. It may be useful for instance to insert a time wasting
31808 loop in the code of the DLL to meet this criterion.
31812 @item Launch the main program @file{main.exe}.
31818 @item Use the Windows @i{Task Manager} to find the process ID. Let's say
31819 that the process PID for @file{main.exe} is 208.
31827 @item Attach to the running process to be debugged.
31833 @item Load the process debugging information.
31836 (gdb) symbol-file main.exe
31839 @item Break somewhere in the DLL.
31842 (gdb) break ada_dll
31845 @item Continue process execution.
31854 This last step will resume the process execution, and stop at
31855 the breakpoint we have set. From there you can use the standard
31856 approach to debug a program as described in
31857 (@pxref{Running and Debugging Ada Programs}).
31859 @node Setting Stack Size from gnatlink
31860 @section Setting Stack Size from @command{gnatlink}
31863 It is possible to specify the program stack size at link time. On modern
31864 versions of Windows, starting with XP, this is mostly useful to set the size of
31865 the main stack (environment task). The other task stacks are set with pragma
31866 Storage_Size or with the @command{gnatbind -d} command.
31868 Since older versions of Windows (2000, NT4, etc.) do not allow setting the
31869 reserve size of individual tasks, the link-time stack size applies to all
31870 tasks, and pragma Storage_Size has no effect.
31871 In particular, Stack Overflow checks are made against this
31872 link-time specified size.
31874 This setting can be done with
31875 @command{gnatlink} using either:
31879 @item using @option{-Xlinker} linker option
31882 $ gnatlink hello -Xlinker --stack=0x10000,0x1000
31885 This sets the stack reserve size to 0x10000 bytes and the stack commit
31886 size to 0x1000 bytes.
31888 @item using @option{-Wl} linker option
31891 $ gnatlink hello -Wl,--stack=0x1000000
31894 This sets the stack reserve size to 0x1000000 bytes. Note that with
31895 @option{-Wl} option it is not possible to set the stack commit size
31896 because the coma is a separator for this option.
31900 @node Setting Heap Size from gnatlink
31901 @section Setting Heap Size from @command{gnatlink}
31904 Under Windows systems, it is possible to specify the program heap size from
31905 @command{gnatlink} using either:
31909 @item using @option{-Xlinker} linker option
31912 $ gnatlink hello -Xlinker --heap=0x10000,0x1000
31915 This sets the heap reserve size to 0x10000 bytes and the heap commit
31916 size to 0x1000 bytes.
31918 @item using @option{-Wl} linker option
31921 $ gnatlink hello -Wl,--heap=0x1000000
31924 This sets the heap reserve size to 0x1000000 bytes. Note that with
31925 @option{-Wl} option it is not possible to set the heap commit size
31926 because the coma is a separator for this option.
31930 @node Mac OS Topics
31931 @appendix Mac OS Topics
31935 This chapter describes topics that are specific to Apple's OS X
31939 * Codesigning the Debugger::
31942 @node Codesigning the Debugger
31943 @section Codesigning the Debugger
31946 The Darwin Kernel requires the debugger to have special permissions
31947 before it is allowed to control other processes. These permissions
31948 are granted by codesigning the GDB executable. Without these
31949 permissions, the debugger will report error messages such as:
31952 Starting program: /x/y/foo
31953 Unable to find Mach task port for process-id 28885: (os/kern) failure (0x5).
31954 (please check gdb is codesigned - see taskgated(8))
31957 Codesigning requires a certificate. The following procedure explains
31961 @item Start the Keychain Access application (in
31962 /Applications/Utilities/Keychain Access.app)
31964 @item Select the Keychain Access -> Certificate Assistant ->
31965 Create a Certificate... menu
31970 @item Choose a name for the new certificate (this procedure will use
31971 "gdb-cert" as an example)
31973 @item Set "Identity Type" to "Self Signed Root"
31975 @item Set "Certificate Type" to "Code Signing"
31977 @item Activate the "Let me override defaults" option
31981 @item Click several times on "Continue" until the "Specify a Location
31982 For The Certificate" screen appears, then set "Keychain" to "System"
31984 @item Click on "Continue" until the certificate is created
31986 @item Finally, in the view, double-click on the new certificate,
31987 and set "When using this certificate" to "Always Trust"
31989 @item Exit the Keychain Access application and restart the computer
31990 (this is unfortunately required)
31994 Once a certificate has been created, the debugger can be codesigned
31995 as follow. In a Terminal, run the following command...
31998 codesign -f -s "gdb-cert" <gnat_install_prefix>/bin/gdb
32001 ... where "gdb-cert" should be replaced by the actual certificate
32002 name chosen above, and <gnat_install_prefix> should be replaced by
32003 the location where you installed GNAT.
32005 @c **********************************
32006 @c * GNU Free Documentation License *
32007 @c **********************************
32009 @c GNU Free Documentation License
32017 @c Put table of contents at end, otherwise it precedes the "title page" in
32018 @c the .txt version
32019 @c Edit the pdf file to move the contents to the beginning, after the title