1 \input texinfo @c -*-texinfo-*-
4 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
6 @c GNAT DOCUMENTATION o
10 @c Copyright (C) 1992-2014, Free Software Foundation, Inc. o
12 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
14 @setfilename gnat_ugn.info
17 Copyright @copyright{} 1995-2014 Free Software Foundation,
20 Permission is granted to copy, distribute and/or modify this document
21 under the terms of the GNU Free Documentation License, Version 1.3 or
22 any later version published by the Free Software Foundation; with no
23 Invariant Sections, with no Front-Cover Texts and with no Back-Cover
24 Texts. A copy of the license is included in the section entitled
25 ``GNU Free Documentation License''.
28 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
30 @c GNAT_UGN Style Guide
32 @c 1. Always put a @noindent on the line before the first paragraph
33 @c after any of these commands:
45 @c 2. DO NOT use @example. Use @smallexample instead.
46 @c a) DO NOT use highlighting commands (@b{}, @i{}) inside an @smallexample
47 @c context. These can interfere with the readability of the texi
48 @c source file. Instead, use one of the following annotated
49 @c @smallexample commands, and preprocess the texi file with the
50 @c ada2texi tool (which generates appropriate highlighting):
51 @c @smallexample @c ada
52 @c @smallexample @c adanocomment
53 @c @smallexample @c projectfile
54 @c b) The "@c ada" markup will result in boldface for reserved words
55 @c and italics for comments
56 @c c) The "@c adanocomment" markup will result only in boldface for
57 @c reserved words (comments are left alone)
58 @c d) The "@c projectfile" markup is like "@c ada" except that the set
59 @c of reserved words include the new reserved words for project files
61 @c 3. Each @chapter, @section, @subsection, @subsubsection, etc.
62 @c command must be preceded by two empty lines
64 @c 4. The @item command should be on a line of its own if it is in an
65 @c @itemize or @enumerate command.
67 @c 5. When talking about ALI files use "ALI" (all uppercase), not "Ali"
70 @c 6. DO NOT put trailing spaces at the end of a line. Such spaces will
71 @c cause the document build to fail.
73 @c 7. DO NOT use @cartouche for examples that are longer than around 10 lines.
74 @c This command inhibits page breaks, so long examples in a @cartouche can
75 @c lead to large, ugly patches of empty space on a page.
77 @c NOTE: This file should be submitted to xgnatugn with either the vms flag
78 @c or the unw flag set. The unw flag covers topics for both Unix and
81 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
84 @c This flag is used where the text refers to conditions that exist when the
85 @c text was entered into the document but which may change over time.
86 @c Update the setting for the flag, and (if necessary) the text surrounding,
87 @c the references to the flag, on future doc revisions:
88 @c search for @value{NOW}.
100 @set TITLESUFFIX for OpenVMS
105 @c The ARG is an optional argument. To be used for macro arguments in
106 @c their documentation (@defmac).
108 @r{[}@var{\varname\}@r{]}@c
110 @c Status as of November 2009:
111 @c Unfortunately texi2pdf and texi2html treat the trailing "@c"
112 @c differently, and faulty output is produced by one or the other
113 @c depending on whether the "@c" is present or absent.
114 @c As a result, the @ovar macro is not used, and all invocations
115 @c of the @ovar macro have been expanded inline.
118 @settitle @value{EDITION} User's Guide @value{TITLESUFFIX}
119 @dircategory GNU Ada tools
121 * @value{EDITION} User's Guide: (gnat_ugn). @value{PLATFORM}
124 @include gcc-common.texi
126 @setchapternewpage odd
131 @title @value{EDITION} User's Guide
135 @titlefont{@i{@value{PLATFORM}}}
141 @subtitle GNAT, The GNU Ada Development Environment
146 @vskip 0pt plus 1filll
153 @node Top, About This Guide, (dir), (dir)
154 @top @value{EDITION} User's Guide
157 @value{EDITION} User's Guide @value{PLATFORM}
160 GNAT, The GNU Ada Development Environment@*
161 GCC version @value{version-GCC}@*
168 * Getting Started with GNAT::
169 * The GNAT Compilation Model::
170 * Compiling with gcc::
171 * Binding with gnatbind::
172 * Linking with gnatlink::
173 * The GNAT Make Program gnatmake::
174 * Improving Performance::
175 * Renaming Files with gnatchop::
176 * Configuration Pragmas::
177 * Handling Arbitrary File Naming Conventions with gnatname::
178 * GNAT Project Manager::
179 * Tools Supporting Project Files::
180 * The Cross-Referencing Tools gnatxref and gnatfind::
182 * The GNAT Pretty-Printer gnatpp::
184 * The Ada-to-XML converter gnat2xml::
186 * The GNAT Metrics Tool gnatmetric::
188 * File Name Krunching with gnatkr::
189 * Preprocessing with gnatprep::
190 * The GNAT Library Browser gnatls::
191 * Cleaning Up with gnatclean::
193 * GNAT and Libraries::
194 * Using the GNU make Utility::
196 * Memory Management Issues::
197 * Stack Related Facilities::
199 * Verifying Properties with gnatcheck::
200 * Creating Sample Bodies with gnatstub::
201 * Creating Unit Tests with gnattest::
203 * Performing Dimensionality Analysis in GNAT::
204 * Generating Ada Bindings for C and C++ headers::
205 * Other Utility Programs::
207 * Code Coverage and Profiling::
209 * Running and Debugging Ada Programs::
211 * Compatibility with HP Ada::
213 * Platform-Specific Information for the Run-Time Libraries::
214 * Example of Binder Output File::
215 * Elaboration Order Handling in GNAT::
216 * Overflow Check Handling in GNAT::
217 * Conditional Compilation::
219 * Compatibility and Porting Guide::
220 * Microsoft Windows Topics::
222 * GNU Free Documentation License::
227 @node About This Guide
228 @unnumbered About This Guide
232 This guide describes the use of @value{EDITION},
233 a compiler and software development toolset for the full Ada
234 programming language, implemented on OpenVMS for HP's Alpha and
235 Integrity server (I64) platforms.
238 This guide describes the use of @value{EDITION},
239 a compiler and software development
240 toolset for the full Ada programming language.
242 It documents the features of the compiler and tools, and explains
243 how to use them to build Ada applications.
245 @value{EDITION} implements Ada 95, Ada 2005 and Ada 2012, and it may also be
246 invoked in Ada 83 compatibility mode.
247 By default, @value{EDITION} assumes Ada 2012, but you can override with a
248 compiler switch (@pxref{Compiling Different Versions of Ada})
249 to explicitly specify the language version.
250 Throughout this manual, references to ``Ada'' without a year suffix
251 apply to all Ada 95/2005/2012 versions of the language.
254 For ease of exposition, ``@value{EDITION}'' will be referred to simply as
255 ``GNAT'' in the remainder of this document.
260 * What This Guide Contains::
261 * What You Should Know before Reading This Guide::
262 * Related Information::
266 @node What This Guide Contains
267 @unnumberedsec What This Guide Contains
270 This guide contains the following chapters:
274 @ref{Getting Started with GNAT}, describes how to get started compiling
275 and running Ada programs with the GNAT Ada programming environment.
277 @ref{The GNAT Compilation Model}, describes the compilation model used
281 @ref{Compiling with gcc}, describes how to compile
282 Ada programs with @command{gcc}, the Ada compiler.
285 @ref{Binding with gnatbind}, describes how to
286 perform binding of Ada programs with @code{gnatbind}, the GNAT binding
290 @ref{Linking with gnatlink},
291 describes @command{gnatlink}, a
292 program that provides for linking using the GNAT run-time library to
293 construct a program. @command{gnatlink} can also incorporate foreign language
294 object units into the executable.
297 @ref{The GNAT Make Program gnatmake}, describes @command{gnatmake}, a
298 utility that automatically determines the set of sources
299 needed by an Ada compilation unit, and executes the necessary compilations
303 @ref{Improving Performance}, shows various techniques for making your
304 Ada program run faster or take less space and describes the effect of
305 the compiler's optimization switch.
308 the @command{gnatelim} tool and
310 unused subprogram/data elimination.
313 @ref{Renaming Files with gnatchop}, describes
314 @code{gnatchop}, a utility that allows you to preprocess a file that
315 contains Ada source code, and split it into one or more new files, one
316 for each compilation unit.
319 @ref{Configuration Pragmas}, describes the configuration pragmas
323 @ref{Handling Arbitrary File Naming Conventions with gnatname},
324 shows how to override the default GNAT file naming conventions,
325 either for an individual unit or globally.
328 @ref{GNAT Project Manager}, describes how to use project files
329 to organize large projects.
332 @ref{The Cross-Referencing Tools gnatxref and gnatfind}, discusses
333 @code{gnatxref} and @code{gnatfind}, two tools that provide an easy
334 way to navigate through sources.
338 @ref{The GNAT Pretty-Printer gnatpp}, shows how to produce a reformatted
339 version of an Ada source file with control over casing, indentation,
340 comment placement, and other elements of program presentation style.
346 @ref{The Ada-to-XML converter gnat2xml}, shows how to convert Ada
347 source code into XML.
353 @ref{The GNAT Metrics Tool gnatmetric}, shows how to compute various
354 metrics for an Ada source file, such as the number of types and subprograms,
355 and assorted complexity measures.
359 @ref{File Name Krunching with gnatkr}, describes the @code{gnatkr}
360 file name krunching utility, used to handle shortened
361 file names on operating systems with a limit on the length of names.
364 @ref{Preprocessing with gnatprep}, describes @code{gnatprep}, a
365 preprocessor utility that allows a single source file to be used to
366 generate multiple or parameterized source files by means of macro
370 @ref{The GNAT Library Browser gnatls}, describes @code{gnatls}, a
371 utility that displays information about compiled units, including dependences
372 on the corresponding sources files, and consistency of compilations.
375 @ref{Cleaning Up with gnatclean}, describes @code{gnatclean}, a utility
376 to delete files that are produced by the compiler, binder and linker.
380 @ref{GNAT and Libraries}, describes the process of creating and using
381 Libraries with GNAT. It also describes how to recompile the GNAT run-time
385 @ref{Using the GNU make Utility}, describes some techniques for using
386 the GNAT toolset in Makefiles.
390 @ref{Memory Management Issues}, describes some useful predefined storage pools
391 and in particular the GNAT Debug Pool facility, which helps detect incorrect
395 It also describes @command{gnatmem}, a utility that monitors dynamic
396 allocation and deallocation and helps detect ``memory leaks''.
401 @ref{Stack Related Facilities}, describes some useful tools associated with
402 stack checking and analysis.
406 @ref{Verifying Properties with gnatcheck}, discusses @code{gnatcheck},
407 a utility that checks Ada code against a set of rules.
410 @ref{Creating Sample Bodies with gnatstub}, discusses @code{gnatstub},
411 a utility that generates empty but compilable bodies for library units.
416 @ref{Creating Unit Tests with gnattest}, discusses @code{gnattest},
417 a utility that generates unit testing templates for library units.
421 @ref{Performing Dimensionality Analysis in GNAT}, describes the Ada 2012
422 facilities used in GNAT to declare dimensioned objects, and to verify that
423 uses of these objects are consistent with their given physical dimensions
424 (so that meters cannot be assigned to kilograms, and so on).
427 @ref{Generating Ada Bindings for C and C++ headers}, describes how to
428 generate automatically Ada bindings from C and C++ headers.
431 @ref{Other Utility Programs}, discusses several other GNAT utilities,
432 including @code{gnathtml}.
436 @ref{Code Coverage and Profiling}, describes how to perform a structural
437 coverage and profile the execution of Ada programs.
441 @ref{Running and Debugging Ada Programs}, describes how to run and debug
446 @ref{Compatibility with HP Ada}, details the compatibility of GNAT with
447 HP Ada 83 @footnote{``HP Ada'' refers to the legacy product originally
448 developed by Digital Equipment Corporation and currently supported by HP.}
449 for OpenVMS Alpha. This product was formerly known as DEC Ada,
452 historical compatibility reasons, the relevant libraries still use the
457 @ref{Platform-Specific Information for the Run-Time Libraries},
458 describes the various run-time
459 libraries supported by GNAT on various platforms and explains how to
460 choose a particular library.
463 @ref{Example of Binder Output File}, shows the source code for the binder
464 output file for a sample program.
467 @ref{Elaboration Order Handling in GNAT}, describes how GNAT helps
468 you deal with elaboration order issues.
471 @ref{Overflow Check Handling in GNAT}, describes how GNAT helps
472 you deal with arithmetic overflow issues.
475 @ref{Conditional Compilation}, describes how to model conditional compilation,
476 both with Ada in general and with GNAT facilities in particular.
479 @ref{Inline Assembler}, shows how to use the inline assembly facility
483 @ref{Compatibility and Porting Guide}, contains sections on compatibility
484 of GNAT with other Ada development environments (including Ada 83 systems),
485 to assist in porting code from those environments.
489 @ref{Microsoft Windows Topics}, presents information relevant to the
490 Microsoft Windows platform.
493 @ref{Mac OS Topics}, presents information relevant to Apple's OS X
498 @c *************************************************
499 @node What You Should Know before Reading This Guide
500 @c *************************************************
501 @unnumberedsec What You Should Know before Reading This Guide
503 @cindex Ada 95 Language Reference Manual
504 @cindex Ada 2005 Language Reference Manual
506 This guide assumes a basic familiarity with the Ada 95 language, as
507 described in the International Standard ANSI/ISO/IEC-8652:1995, January
509 It does not require knowledge of the new features introduced by Ada 2005,
510 (officially known as ISO/IEC 8652:1995 with Technical Corrigendum 1
512 Both reference manuals are included in the GNAT documentation
515 @node Related Information
516 @unnumberedsec Related Information
519 For further information about related tools, refer to the following
524 @xref{Top, GNAT Reference Manual, About This Guide, gnat_rm, GNAT
525 Reference Manual}, which contains all reference material for the GNAT
526 implementation of Ada.
530 @cite{Using the GNAT Programming Studio}, which describes the GPS
531 Integrated Development Environment.
534 @cite{GNAT Programming Studio Tutorial}, which introduces the
535 main GPS features through examples.
539 @cite{Ada 95 Reference Manual}, which contains reference
540 material for the Ada 95 programming language.
543 @cite{Ada 2005 Reference Manual}, which contains reference
544 material for the Ada 2005 programming language.
547 @xref{Top,, Debugging with GDB, gdb, Debugging with GDB},
549 in the GNU:[DOCS] directory,
551 for all details on the use of the GNU source-level debugger.
554 @xref{Top,, The extensible self-documenting text editor, emacs,
557 located in the GNU:[DOCS] directory if the EMACS kit is installed,
559 for full information on the extensible editor and programming
566 @unnumberedsec Conventions
568 @cindex Typographical conventions
571 Following are examples of the typographical and graphic conventions used
576 @code{Functions}, @command{utility program names}, @code{standard names},
580 @option{Option flags}
583 @file{File names}, @samp{button names}, and @samp{field names}.
586 @code{Variables}, @env{environment variables}, and @var{metasyntactic
593 @r{[}optional information or parameters@r{]}
596 Examples are described by text
598 and then shown this way.
603 Commands that are entered by the user are preceded in this manual by the
604 characters @w{``@code{$ }''} (dollar sign followed by space). If your system
605 uses this sequence as a prompt, then the commands will appear exactly as
606 you see them in the manual. If your system uses some other prompt, then
607 the command will appear with the @code{$} replaced by whatever prompt
608 character you are using.
611 Full file names are shown with the ``@code{/}'' character
612 as the directory separator; e.g., @file{parent-dir/subdir/myfile.adb}.
613 If you are using GNAT on a Windows platform, please note that
614 the ``@code{\}'' character should be used instead.
617 @c ****************************
618 @node Getting Started with GNAT
619 @chapter Getting Started with GNAT
622 This chapter describes some simple ways of using GNAT to build
623 executable Ada programs.
625 @ref{Running GNAT}, through @ref{Using the gnatmake Utility},
626 show how to use the command line environment.
627 @ref{Introduction to GPS}, provides a brief
628 introduction to the GNAT Programming Studio, a visually-oriented
629 Integrated Development Environment for GNAT.
630 GPS offers a graphical ``look and feel'', support for development in
631 other programming languages, comprehensive browsing features, and
632 many other capabilities.
633 For information on GPS please refer to
634 @cite{Using the GNAT Programming Studio}.
639 * Running a Simple Ada Program::
640 * Running a Program with Multiple Units::
641 * Using the gnatmake Utility::
643 * Editing with Emacs::
646 * Introduction to GPS::
651 @section Running GNAT
654 Three steps are needed to create an executable file from an Ada source
659 The source file(s) must be compiled.
661 The file(s) must be bound using the GNAT binder.
663 All appropriate object files must be linked to produce an executable.
667 All three steps are most commonly handled by using the @command{gnatmake}
668 utility program that, given the name of the main program, automatically
669 performs the necessary compilation, binding and linking steps.
671 @node Running a Simple Ada Program
672 @section Running a Simple Ada Program
675 Any text editor may be used to prepare an Ada program.
677 used, the optional Ada mode may be helpful in laying out the program.)
679 program text is a normal text file. We will assume in our initial
680 example that you have used your editor to prepare the following
681 standard format text file:
685 with Ada.Text_IO; use Ada.Text_IO;
688 Put_Line ("Hello WORLD!");
694 This file should be named @file{hello.adb}.
695 With the normal default file naming conventions, GNAT requires
697 contain a single compilation unit whose file name is the
699 with periods replaced by hyphens; the
700 extension is @file{ads} for a
701 spec and @file{adb} for a body.
702 You can override this default file naming convention by use of the
703 special pragma @code{Source_File_Name} (@pxref{Using Other File Names}).
704 Alternatively, if you want to rename your files according to this default
705 convention, which is probably more convenient if you will be using GNAT
706 for all your compilations, then the @code{gnatchop} utility
707 can be used to generate correctly-named source files
708 (@pxref{Renaming Files with gnatchop}).
710 You can compile the program using the following command (@code{$} is used
711 as the command prompt in the examples in this document):
718 @command{gcc} is the command used to run the compiler. This compiler is
719 capable of compiling programs in several languages, including Ada and
720 C. It assumes that you have given it an Ada program if the file extension is
721 either @file{.ads} or @file{.adb}, and it will then call
722 the GNAT compiler to compile the specified file.
725 The @option{-c} switch is required. It tells @command{gcc} to only do a
726 compilation. (For C programs, @command{gcc} can also do linking, but this
727 capability is not used directly for Ada programs, so the @option{-c}
728 switch must always be present.)
731 This compile command generates a file
732 @file{hello.o}, which is the object
733 file corresponding to your Ada program. It also generates
734 an ``Ada Library Information'' file @file{hello.ali},
735 which contains additional information used to check
736 that an Ada program is consistent.
737 To build an executable file,
738 use @code{gnatbind} to bind the program
739 and @command{gnatlink} to link it. The
740 argument to both @code{gnatbind} and @command{gnatlink} is the name of the
741 @file{ALI} file, but the default extension of @file{.ali} can
742 be omitted. This means that in the most common case, the argument
743 is simply the name of the main program:
751 A simpler method of carrying out these steps is to use
753 a master program that invokes all the required
754 compilation, binding and linking tools in the correct order. In particular,
755 @command{gnatmake} automatically recompiles any sources that have been
756 modified since they were last compiled, or sources that depend
757 on such modified sources, so that ``version skew'' is avoided.
758 @cindex Version skew (avoided by @command{gnatmake})
765 The result is an executable program called @file{hello}, which can be
773 assuming that the current directory is on the search path
774 for executable programs.
777 and, if all has gone well, you will see
784 appear in response to this command.
786 @c ****************************************
787 @node Running a Program with Multiple Units
788 @section Running a Program with Multiple Units
791 Consider a slightly more complicated example that has three files: a
792 main program, and the spec and body of a package:
802 with Ada.Text_IO; use Ada.Text_IO;
803 package body Greetings is
806 Put_Line ("Hello WORLD!");
811 Put_Line ("Goodbye WORLD!");
828 Following the one-unit-per-file rule, place this program in the
829 following three separate files:
833 spec of package @code{Greetings}
836 body of package @code{Greetings}
843 To build an executable version of
844 this program, we could use four separate steps to compile, bind, and link
845 the program, as follows:
849 $ gcc -c greetings.adb
855 Note that there is no required order of compilation when using GNAT.
856 In particular it is perfectly fine to compile the main program first.
857 Also, it is not necessary to compile package specs in the case where
858 there is an accompanying body; you only need to compile the body. If you want
859 to submit these files to the compiler for semantic checking and not code
860 generation, then use the
861 @option{-gnatc} switch:
864 $ gcc -c greetings.ads -gnatc
868 Although the compilation can be done in separate steps as in the
869 above example, in practice it is almost always more convenient
870 to use the @command{gnatmake} tool. All you need to know in this case
871 is the name of the main program's source file. The effect of the above four
872 commands can be achieved with a single one:
879 In the next section we discuss the advantages of using @command{gnatmake} in
882 @c *****************************
883 @node Using the gnatmake Utility
884 @section Using the @command{gnatmake} Utility
887 If you work on a program by compiling single components at a time using
888 @command{gcc}, you typically keep track of the units you modify. In order to
889 build a consistent system, you compile not only these units, but also any
890 units that depend on the units you have modified.
891 For example, in the preceding case,
892 if you edit @file{gmain.adb}, you only need to recompile that file. But if
893 you edit @file{greetings.ads}, you must recompile both
894 @file{greetings.adb} and @file{gmain.adb}, because both files contain
895 units that depend on @file{greetings.ads}.
897 @code{gnatbind} will warn you if you forget one of these compilation
898 steps, so that it is impossible to generate an inconsistent program as a
899 result of forgetting to do a compilation. Nevertheless it is tedious and
900 error-prone to keep track of dependencies among units.
901 One approach to handle the dependency-bookkeeping is to use a
902 makefile. However, makefiles present maintenance problems of their own:
903 if the dependencies change as you change the program, you must make
904 sure that the makefile is kept up-to-date manually, which is also an
907 The @command{gnatmake} utility takes care of these details automatically.
908 Invoke it using either one of the following forms:
912 $ gnatmake ^gmain^GMAIN^
916 The argument is the name of the file containing the main program;
917 you may omit the extension. @command{gnatmake}
918 examines the environment, automatically recompiles any files that need
919 recompiling, and binds and links the resulting set of object files,
920 generating the executable file, @file{^gmain^GMAIN.EXE^}.
921 In a large program, it
922 can be extremely helpful to use @command{gnatmake}, because working out by hand
923 what needs to be recompiled can be difficult.
925 Note that @command{gnatmake}
926 takes into account all the Ada rules that
927 establish dependencies among units. These include dependencies that result
928 from inlining subprogram bodies, and from
929 generic instantiation. Unlike some other
930 Ada make tools, @command{gnatmake} does not rely on the dependencies that were
931 found by the compiler on a previous compilation, which may possibly
932 be wrong when sources change. @command{gnatmake} determines the exact set of
933 dependencies from scratch each time it is run.
936 @node Editing with Emacs
937 @section Editing with Emacs
941 Emacs is an extensible self-documenting text editor that is available in a
942 separate VMSINSTAL kit.
944 Invoke Emacs by typing @kbd{Emacs} at the command prompt. To get started,
945 click on the Emacs Help menu and run the Emacs Tutorial.
946 In a character cell terminal, Emacs help is invoked with @kbd{Ctrl-h} (also
947 written as @kbd{C-h}), and the tutorial by @kbd{C-h t}.
949 Documentation on Emacs and other tools is available in Emacs under the
950 pull-down menu button: @code{Help - Info}. After selecting @code{Info},
951 use the middle mouse button to select a topic (e.g.@: Emacs).
953 In a character cell terminal, do @kbd{C-h i} to invoke info, and then @kbd{m}
954 (stands for menu) followed by the menu item desired, as in @kbd{m Emacs}, to
955 get to the Emacs manual.
956 Help on Emacs is also available by typing @kbd{HELP EMACS} at the DCL command
959 The tutorial is highly recommended in order to learn the intricacies of Emacs,
960 which is sufficiently extensible to provide for a complete programming
961 environment and shell for the sophisticated user.
965 @node Introduction to GPS
966 @section Introduction to GPS
967 @cindex GPS (GNAT Programming Studio)
968 @cindex GNAT Programming Studio (GPS)
970 Although the command line interface (@command{gnatmake}, etc.) alone
971 is sufficient, a graphical Interactive Development
972 Environment can make it easier for you to compose, navigate, and debug
973 programs. This section describes the main features of GPS
974 (``GNAT Programming Studio''), the GNAT graphical IDE.
975 You will see how to use GPS to build and debug an executable, and
976 you will also learn some of the basics of the GNAT ``project'' facility.
978 GPS enables you to do much more than is presented here;
979 e.g., you can produce a call graph, interface to a third-party
980 Version Control System, and inspect the generated assembly language
982 Indeed, GPS also supports languages other than Ada.
983 Such additional information, and an explanation of all of the GPS menu
984 items. may be found in the on-line help, which includes
985 a user's guide and a tutorial (these are also accessible from the GNAT
989 * Building a New Program with GPS::
990 * Simple Debugging with GPS::
993 @node Building a New Program with GPS
994 @subsection Building a New Program with GPS
996 GPS invokes the GNAT compilation tools using information
997 contained in a @emph{project} (also known as a @emph{project file}):
998 a collection of properties such
999 as source directories, identities of main subprograms, tool switches, etc.,
1000 and their associated values.
1001 See @ref{GNAT Project Manager} for details.
1002 In order to run GPS, you will need to either create a new project
1003 or else open an existing one.
1005 This section will explain how you can use GPS to create a project,
1006 to associate Ada source files with a project, and to build and run
1010 @item @emph{Creating a project}
1012 Invoke GPS, either from the command line or the platform's IDE.
1013 After it starts, GPS will display a ``Welcome'' screen with three
1018 @code{Start with default project in directory}
1021 @code{Create new project with wizard}
1024 @code{Open existing project}
1028 Select @code{Create new project with wizard} and press @code{OK}.
1029 A new window will appear. In the text box labeled with
1030 @code{Enter the name of the project to create}, type @file{sample}
1031 as the project name.
1032 In the next box, browse to choose the directory in which you
1033 would like to create the project file.
1034 After selecting an appropriate directory, press @code{Forward}.
1036 A window will appear with the title
1037 @code{Version Control System Configuration}.
1038 Simply press @code{Forward}.
1040 A window will appear with the title
1041 @code{Please select the source directories for this project}.
1042 The directory that you specified for the project file will be selected
1043 by default as the one to use for sources; simply press @code{Forward}.
1045 A window will appear with the title
1046 @code{Please select the build directory for this project}.
1047 The directory that you specified for the project file will be selected
1048 by default for object files and executables;
1049 simply press @code{Forward}.
1051 A window will appear with the title
1052 @code{Please select the main units for this project}.
1053 You will supply this information later, after creating the source file.
1054 Simply press @code{Forward} for now.
1056 A window will appear with the title
1057 @code{Please select the switches to build the project}.
1058 Press @code{Apply}. This will create a project file named
1059 @file{sample.prj} in the directory that you had specified.
1061 @item @emph{Creating and saving the source file}
1063 After you create the new project, a GPS window will appear, which is
1064 partitioned into two main sections:
1068 A @emph{Workspace area}, initially greyed out, which you will use for
1069 creating and editing source files
1072 Directly below, a @emph{Messages area}, which initially displays a
1073 ``Welcome'' message.
1074 (If the Messages area is not visible, drag its border upward to expand it.)
1078 Select @code{File} on the menu bar, and then the @code{New} command.
1079 The Workspace area will become white, and you can now
1080 enter the source program explicitly.
1081 Type the following text
1083 @smallexample @c ada
1085 with Ada.Text_IO; use Ada.Text_IO;
1088 Put_Line("Hello from GPS!");
1094 Select @code{File}, then @code{Save As}, and enter the source file name
1096 The file will be saved in the same directory you specified as the
1097 location of the default project file.
1099 @item @emph{Updating the project file}
1101 You need to add the new source file to the project.
1103 the @code{Project} menu and then @code{Edit project properties}.
1104 Click the @code{Main files} tab on the left, and then the
1106 Choose @file{hello.adb} from the list, and press @code{Open}.
1107 The project settings window will reflect this action.
1110 @item @emph{Building and running the program}
1112 In the main GPS window, now choose the @code{Build} menu, then @code{Make},
1113 and select @file{hello.adb}.
1114 The Messages window will display the resulting invocations of @command{gcc},
1115 @command{gnatbind}, and @command{gnatlink}
1116 (reflecting the default switch settings from the
1117 project file that you created) and then a ``successful compilation/build''
1120 To run the program, choose the @code{Build} menu, then @code{Run}, and
1121 select @command{hello}.
1122 An @emph{Arguments Selection} window will appear.
1123 There are no command line arguments, so just click @code{OK}.
1125 The Messages window will now display the program's output (the string
1126 @code{Hello from GPS}), and at the bottom of the GPS window a status
1127 update is displayed (@code{Run: hello}).
1128 Close the GPS window (or select @code{File}, then @code{Exit}) to
1129 terminate this GPS session.
1132 @node Simple Debugging with GPS
1133 @subsection Simple Debugging with GPS
1135 This section illustrates basic debugging techniques (setting breakpoints,
1136 examining/modifying variables, single stepping).
1139 @item @emph{Opening a project}
1141 Start GPS and select @code{Open existing project}; browse to
1142 specify the project file @file{sample.prj} that you had created in the
1145 @item @emph{Creating a source file}
1147 Select @code{File}, then @code{New}, and type in the following program:
1149 @smallexample @c ada
1151 with Ada.Text_IO; use Ada.Text_IO;
1152 procedure Example is
1153 Line : String (1..80);
1156 Put_Line("Type a line of text at each prompt; an empty line to exit");
1160 Put_Line (Line (1..N) );
1168 Select @code{File}, then @code{Save as}, and enter the file name
1171 @item @emph{Updating the project file}
1173 Add @code{Example} as a new main unit for the project:
1176 Select @code{Project}, then @code{Edit Project Properties}.
1179 Select the @code{Main files} tab, click @code{Add}, then
1180 select the file @file{example.adb} from the list, and
1182 You will see the file name appear in the list of main units
1188 @item @emph{Building/running the executable}
1190 To build the executable
1191 select @code{Build}, then @code{Make}, and then choose @file{example.adb}.
1193 Run the program to see its effect (in the Messages area).
1194 Each line that you enter is displayed; an empty line will
1195 cause the loop to exit and the program to terminate.
1197 @item @emph{Debugging the program}
1199 Note that the @option{-g} switches to @command{gcc} and @command{gnatlink},
1200 which are required for debugging, are on by default when you create
1202 Thus unless you intentionally remove these settings, you will be able
1203 to debug any program that you develop using GPS.
1206 @item @emph{Initializing}
1208 Select @code{Debug}, then @code{Initialize}, then @file{example}
1210 @item @emph{Setting a breakpoint}
1212 After performing the initialization step, you will observe a small
1213 icon to the right of each line number.
1214 This serves as a toggle for breakpoints; clicking the icon will
1215 set a breakpoint at the corresponding line (the icon will change to
1216 a red circle with an ``x''), and clicking it again
1217 will remove the breakpoint / reset the icon.
1219 For purposes of this example, set a breakpoint at line 10 (the
1220 statement @code{Put_Line@ (Line@ (1..N));}
1222 @item @emph{Starting program execution}
1224 Select @code{Debug}, then @code{Run}. When the
1225 @code{Program Arguments} window appears, click @code{OK}.
1226 A console window will appear; enter some line of text,
1227 e.g.@: @code{abcde}, at the prompt.
1228 The program will pause execution when it gets to the
1229 breakpoint, and the corresponding line is highlighted.
1231 @item @emph{Examining a variable}
1233 Move the mouse over one of the occurrences of the variable @code{N}.
1234 You will see the value (5) displayed, in ``tool tip'' fashion.
1235 Right click on @code{N}, select @code{Debug}, then select @code{Display N}.
1236 You will see information about @code{N} appear in the @code{Debugger Data}
1237 pane, showing the value as 5.
1239 @item @emph{Assigning a new value to a variable}
1241 Right click on the @code{N} in the @code{Debugger Data} pane, and
1242 select @code{Set value of N}.
1243 When the input window appears, enter the value @code{4} and click
1245 This value does not automatically appear in the @code{Debugger Data}
1246 pane; to see it, right click again on the @code{N} in the
1247 @code{Debugger Data} pane and select @code{Update value}.
1248 The new value, 4, will appear in red.
1250 @item @emph{Single stepping}
1252 Select @code{Debug}, then @code{Next}.
1253 This will cause the next statement to be executed, in this case the
1254 call of @code{Put_Line} with the string slice.
1255 Notice in the console window that the displayed string is simply
1256 @code{abcd} and not @code{abcde} which you had entered.
1257 This is because the upper bound of the slice is now 4 rather than 5.
1259 @item @emph{Removing a breakpoint}
1261 Toggle the breakpoint icon at line 10.
1263 @item @emph{Resuming execution from a breakpoint}
1265 Select @code{Debug}, then @code{Continue}.
1266 The program will reach the next iteration of the loop, and
1267 wait for input after displaying the prompt.
1268 This time, just hit the @kbd{Enter} key.
1269 The value of @code{N} will be 0, and the program will terminate.
1270 The console window will disappear.
1275 @node The GNAT Compilation Model
1276 @chapter The GNAT Compilation Model
1277 @cindex GNAT compilation model
1278 @cindex Compilation model
1281 * Source Representation::
1282 * Foreign Language Representation::
1283 * File Naming Rules::
1284 * Using Other File Names::
1285 * Alternative File Naming Schemes::
1286 * Generating Object Files::
1287 * Source Dependencies::
1288 * The Ada Library Information Files::
1289 * Binding an Ada Program::
1290 * Mixed Language Programming::
1292 * Building Mixed Ada & C++ Programs::
1293 * Comparison between GNAT and C/C++ Compilation Models::
1295 * Comparison between GNAT and Conventional Ada Library Models::
1297 * Placement of temporary files::
1302 This chapter describes the compilation model used by GNAT. Although
1303 similar to that used by other languages, such as C and C++, this model
1304 is substantially different from the traditional Ada compilation models,
1305 which are based on a library. The model is initially described without
1306 reference to the library-based model. If you have not previously used an
1307 Ada compiler, you need only read the first part of this chapter. The
1308 last section describes and discusses the differences between the GNAT
1309 model and the traditional Ada compiler models. If you have used other
1310 Ada compilers, this section will help you to understand those
1311 differences, and the advantages of the GNAT model.
1313 @node Source Representation
1314 @section Source Representation
1318 Ada source programs are represented in standard text files, using
1319 Latin-1 coding. Latin-1 is an 8-bit code that includes the familiar
1320 7-bit ASCII set, plus additional characters used for
1321 representing foreign languages (@pxref{Foreign Language Representation}
1322 for support of non-USA character sets). The format effector characters
1323 are represented using their standard ASCII encodings, as follows:
1328 Vertical tab, @code{16#0B#}
1332 Horizontal tab, @code{16#09#}
1336 Carriage return, @code{16#0D#}
1340 Line feed, @code{16#0A#}
1344 Form feed, @code{16#0C#}
1348 Source files are in standard text file format. In addition, GNAT will
1349 recognize a wide variety of stream formats, in which the end of
1350 physical lines is marked by any of the following sequences:
1351 @code{LF}, @code{CR}, @code{CR-LF}, or @code{LF-CR}. This is useful
1352 in accommodating files that are imported from other operating systems.
1354 @cindex End of source file
1355 @cindex Source file, end
1357 The end of a source file is normally represented by the physical end of
1358 file. However, the control character @code{16#1A#} (@code{SUB}) is also
1359 recognized as signalling the end of the source file. Again, this is
1360 provided for compatibility with other operating systems where this
1361 code is used to represent the end of file.
1363 Each file contains a single Ada compilation unit, including any pragmas
1364 associated with the unit. For example, this means you must place a
1365 package declaration (a package @dfn{spec}) and the corresponding body in
1366 separate files. An Ada @dfn{compilation} (which is a sequence of
1367 compilation units) is represented using a sequence of files. Similarly,
1368 you will place each subunit or child unit in a separate file.
1370 @node Foreign Language Representation
1371 @section Foreign Language Representation
1374 GNAT supports the standard character sets defined in Ada as well as
1375 several other non-standard character sets for use in localized versions
1376 of the compiler (@pxref{Character Set Control}).
1379 * Other 8-Bit Codes::
1380 * Wide Character Encodings::
1388 The basic character set is Latin-1. This character set is defined by ISO
1389 standard 8859, part 1. The lower half (character codes @code{16#00#}
1390 @dots{} @code{16#7F#)} is identical to standard ASCII coding, but the upper
1391 half is used to represent additional characters. These include extended letters
1392 used by European languages, such as French accents, the vowels with umlauts
1393 used in German, and the extra letter A-ring used in Swedish.
1395 @findex Ada.Characters.Latin_1
1396 For a complete list of Latin-1 codes and their encodings, see the source
1397 file of library unit @code{Ada.Characters.Latin_1} in file
1398 @file{a-chlat1.ads}.
1399 You may use any of these extended characters freely in character or
1400 string literals. In addition, the extended characters that represent
1401 letters can be used in identifiers.
1403 @node Other 8-Bit Codes
1404 @subsection Other 8-Bit Codes
1407 GNAT also supports several other 8-bit coding schemes:
1410 @item ISO 8859-2 (Latin-2)
1413 Latin-2 letters allowed in identifiers, with uppercase and lowercase
1416 @item ISO 8859-3 (Latin-3)
1419 Latin-3 letters allowed in identifiers, with uppercase and lowercase
1422 @item ISO 8859-4 (Latin-4)
1425 Latin-4 letters allowed in identifiers, with uppercase and lowercase
1428 @item ISO 8859-5 (Cyrillic)
1431 ISO 8859-5 letters (Cyrillic) allowed in identifiers, with uppercase and
1432 lowercase equivalence.
1434 @item ISO 8859-15 (Latin-9)
1437 ISO 8859-15 (Latin-9) letters allowed in identifiers, with uppercase and
1438 lowercase equivalence
1440 @item IBM PC (code page 437)
1441 @cindex code page 437
1442 This code page is the normal default for PCs in the U.S. It corresponds
1443 to the original IBM PC character set. This set has some, but not all, of
1444 the extended Latin-1 letters, but these letters do not have the same
1445 encoding as Latin-1. In this mode, these letters are allowed in
1446 identifiers with uppercase and lowercase equivalence.
1448 @item IBM PC (code page 850)
1449 @cindex code page 850
1450 This code page is a modification of 437 extended to include all the
1451 Latin-1 letters, but still not with the usual Latin-1 encoding. In this
1452 mode, all these letters are allowed in identifiers with uppercase and
1453 lowercase equivalence.
1455 @item Full Upper 8-bit
1456 Any character in the range 80-FF allowed in identifiers, and all are
1457 considered distinct. In other words, there are no uppercase and lowercase
1458 equivalences in this range. This is useful in conjunction with
1459 certain encoding schemes used for some foreign character sets (e.g.,
1460 the typical method of representing Chinese characters on the PC).
1463 No upper-half characters in the range 80-FF are allowed in identifiers.
1464 This gives Ada 83 compatibility for identifier names.
1468 For precise data on the encodings permitted, and the uppercase and lowercase
1469 equivalences that are recognized, see the file @file{csets.adb} in
1470 the GNAT compiler sources. You will need to obtain a full source release
1471 of GNAT to obtain this file.
1473 @node Wide Character Encodings
1474 @subsection Wide Character Encodings
1477 GNAT allows wide character codes to appear in character and string
1478 literals, and also optionally in identifiers, by means of the following
1479 possible encoding schemes:
1484 In this encoding, a wide character is represented by the following five
1492 Where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal
1493 characters (using uppercase letters) of the wide character code. For
1494 example, ESC A345 is used to represent the wide character with code
1496 This scheme is compatible with use of the full Wide_Character set.
1498 @item Upper-Half Coding
1499 @cindex Upper-Half Coding
1500 The wide character with encoding @code{16#abcd#} where the upper bit is on
1501 (in other words, ``a'' is in the range 8-F) is represented as two bytes,
1502 @code{16#ab#} and @code{16#cd#}. The second byte cannot be a format control
1503 character, but is not required to be in the upper half. This method can
1504 be also used for shift-JIS or EUC, where the internal coding matches the
1507 @item Shift JIS Coding
1508 @cindex Shift JIS Coding
1509 A wide character is represented by a two-character sequence,
1511 @code{16#cd#}, with the restrictions described for upper-half encoding as
1512 described above. The internal character code is the corresponding JIS
1513 character according to the standard algorithm for Shift-JIS
1514 conversion. Only characters defined in the JIS code set table can be
1515 used with this encoding method.
1519 A wide character is represented by a two-character sequence
1521 @code{16#cd#}, with both characters being in the upper half. The internal
1522 character code is the corresponding JIS character according to the EUC
1523 encoding algorithm. Only characters defined in the JIS code set table
1524 can be used with this encoding method.
1527 A wide character is represented using
1528 UCS Transformation Format 8 (UTF-8) as defined in Annex R of ISO
1529 10646-1/Am.2. Depending on the character value, the representation
1530 is a one, two, or three byte sequence:
1535 16#0000#-16#007f#: 2#0@var{xxxxxxx}#
1536 16#0080#-16#07ff#: 2#110@var{xxxxx}# 2#10@var{xxxxxx}#
1537 16#0800#-16#ffff#: 2#1110@var{xxxx}# 2#10@var{xxxxxx}# 2#10@var{xxxxxx}#
1542 where the @var{xxx} bits correspond to the left-padded bits of the
1543 16-bit character value. Note that all lower half ASCII characters
1544 are represented as ASCII bytes and all upper half characters and
1545 other wide characters are represented as sequences of upper-half
1546 (The full UTF-8 scheme allows for encoding 31-bit characters as
1547 6-byte sequences, but in this implementation, all UTF-8 sequences
1548 of four or more bytes length will be treated as illegal).
1549 @item Brackets Coding
1550 In this encoding, a wide character is represented by the following eight
1558 Where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal
1559 characters (using uppercase letters) of the wide character code. For
1560 example, [``A345''] is used to represent the wide character with code
1561 @code{16#A345#}. It is also possible (though not required) to use the
1562 Brackets coding for upper half characters. For example, the code
1563 @code{16#A3#} can be represented as @code{[``A3'']}.
1565 This scheme is compatible with use of the full Wide_Character set,
1566 and is also the method used for wide character encoding in the standard
1567 ACVC (Ada Compiler Validation Capability) test suite distributions.
1572 Note: Some of these coding schemes do not permit the full use of the
1573 Ada character set. For example, neither Shift JIS, nor EUC allow the
1574 use of the upper half of the Latin-1 set.
1576 @node File Naming Rules
1577 @section File Naming Rules
1580 The default file name is determined by the name of the unit that the
1581 file contains. The name is formed by taking the full expanded name of
1582 the unit and replacing the separating dots with hyphens and using
1583 ^lowercase^uppercase^ for all letters.
1585 An exception arises if the file name generated by the above rules starts
1586 with one of the characters
1588 @samp{A}, @samp{G}, @samp{I}, or @samp{S},
1591 @samp{a}, @samp{g}, @samp{i}, or @samp{s},
1593 and the second character is a
1594 minus. In this case, the character ^tilde^dollar sign^ is used in place
1595 of the minus. The reason for this special rule is to avoid clashes with
1596 the standard names for child units of the packages System, Ada,
1597 Interfaces, and GNAT, which use the prefixes
1599 @samp{S-}, @samp{A-}, @samp{I-}, and @samp{G-},
1602 @samp{s-}, @samp{a-}, @samp{i-}, and @samp{g-},
1606 The file extension is @file{.ads} for a spec and
1607 @file{.adb} for a body. The following list shows some
1608 examples of these rules.
1615 @item arith_functions.ads
1616 Arith_Functions (package spec)
1617 @item arith_functions.adb
1618 Arith_Functions (package body)
1620 Func.Spec (child package spec)
1622 Func.Spec (child package body)
1624 Sub (subunit of Main)
1625 @item ^a~bad.adb^A$BAD.ADB^
1626 A.Bad (child package body)
1630 Following these rules can result in excessively long
1631 file names if corresponding
1632 unit names are long (for example, if child units or subunits are
1633 heavily nested). An option is available to shorten such long file names
1634 (called file name ``krunching''). This may be particularly useful when
1635 programs being developed with GNAT are to be used on operating systems
1636 with limited file name lengths. @xref{Using gnatkr}.
1638 Of course, no file shortening algorithm can guarantee uniqueness over
1639 all possible unit names; if file name krunching is used, it is your
1640 responsibility to ensure no name clashes occur. Alternatively you
1641 can specify the exact file names that you want used, as described
1642 in the next section. Finally, if your Ada programs are migrating from a
1643 compiler with a different naming convention, you can use the gnatchop
1644 utility to produce source files that follow the GNAT naming conventions.
1645 (For details @pxref{Renaming Files with gnatchop}.)
1647 Note: in the case of @code{Windows NT/XP} or @code{OpenVMS} operating
1648 systems, case is not significant. So for example on @code{Windows XP}
1649 if the canonical name is @code{main-sub.adb}, you can use the file name
1650 @code{Main-Sub.adb} instead. However, case is significant for other
1651 operating systems, so for example, if you want to use other than
1652 canonically cased file names on a Unix system, you need to follow
1653 the procedures described in the next section.
1655 @node Using Other File Names
1656 @section Using Other File Names
1660 In the previous section, we have described the default rules used by
1661 GNAT to determine the file name in which a given unit resides. It is
1662 often convenient to follow these default rules, and if you follow them,
1663 the compiler knows without being explicitly told where to find all
1666 However, in some cases, particularly when a program is imported from
1667 another Ada compiler environment, it may be more convenient for the
1668 programmer to specify which file names contain which units. GNAT allows
1669 arbitrary file names to be used by means of the Source_File_Name pragma.
1670 The form of this pragma is as shown in the following examples:
1671 @cindex Source_File_Name pragma
1673 @smallexample @c ada
1675 pragma Source_File_Name (My_Utilities.Stacks,
1676 Spec_File_Name => "myutilst_a.ada");
1677 pragma Source_File_name (My_Utilities.Stacks,
1678 Body_File_Name => "myutilst.ada");
1683 As shown in this example, the first argument for the pragma is the unit
1684 name (in this example a child unit). The second argument has the form
1685 of a named association. The identifier
1686 indicates whether the file name is for a spec or a body;
1687 the file name itself is given by a string literal.
1689 The source file name pragma is a configuration pragma, which means that
1690 normally it will be placed in the @file{gnat.adc}
1691 file used to hold configuration
1692 pragmas that apply to a complete compilation environment.
1693 For more details on how the @file{gnat.adc} file is created and used
1694 see @ref{Handling of Configuration Pragmas}.
1695 @cindex @file{gnat.adc}
1698 GNAT allows completely arbitrary file names to be specified using the
1699 source file name pragma. However, if the file name specified has an
1700 extension other than @file{.ads} or @file{.adb} it is necessary to use
1701 a special syntax when compiling the file. The name in this case must be
1702 preceded by the special sequence @option{-x} followed by a space and the name
1703 of the language, here @code{ada}, as in:
1706 $ gcc -c -x ada peculiar_file_name.sim
1711 @command{gnatmake} handles non-standard file names in the usual manner (the
1712 non-standard file name for the main program is simply used as the
1713 argument to gnatmake). Note that if the extension is also non-standard,
1714 then it must be included in the @command{gnatmake} command, it may not
1717 @node Alternative File Naming Schemes
1718 @section Alternative File Naming Schemes
1719 @cindex File naming schemes, alternative
1722 In the previous section, we described the use of the @code{Source_File_Name}
1723 pragma to allow arbitrary names to be assigned to individual source files.
1724 However, this approach requires one pragma for each file, and especially in
1725 large systems can result in very long @file{gnat.adc} files, and also create
1726 a maintenance problem.
1728 GNAT also provides a facility for specifying systematic file naming schemes
1729 other than the standard default naming scheme previously described. An
1730 alternative scheme for naming is specified by the use of
1731 @code{Source_File_Name} pragmas having the following format:
1732 @cindex Source_File_Name pragma
1734 @smallexample @c ada
1735 pragma Source_File_Name (
1736 Spec_File_Name => FILE_NAME_PATTERN
1737 @r{[},Casing => CASING_SPEC@r{]}
1738 @r{[},Dot_Replacement => STRING_LITERAL@r{]});
1740 pragma Source_File_Name (
1741 Body_File_Name => FILE_NAME_PATTERN
1742 @r{[},Casing => CASING_SPEC@r{]}
1743 @r{[},Dot_Replacement => STRING_LITERAL@r{]});
1745 pragma Source_File_Name (
1746 Subunit_File_Name => FILE_NAME_PATTERN
1747 @r{[},Casing => CASING_SPEC@r{]}
1748 @r{[},Dot_Replacement => STRING_LITERAL@r{]});
1750 FILE_NAME_PATTERN ::= STRING_LITERAL
1751 CASING_SPEC ::= Lowercase | Uppercase | Mixedcase
1755 The @code{FILE_NAME_PATTERN} string shows how the file name is constructed.
1756 It contains a single asterisk character, and the unit name is substituted
1757 systematically for this asterisk. The optional parameter
1758 @code{Casing} indicates
1759 whether the unit name is to be all upper-case letters, all lower-case letters,
1760 or mixed-case. If no
1761 @code{Casing} parameter is used, then the default is all
1762 ^lower-case^upper-case^.
1764 The optional @code{Dot_Replacement} string is used to replace any periods
1765 that occur in subunit or child unit names. If no @code{Dot_Replacement}
1766 argument is used then separating dots appear unchanged in the resulting
1768 Although the above syntax indicates that the
1769 @code{Casing} argument must appear
1770 before the @code{Dot_Replacement} argument, but it
1771 is also permissible to write these arguments in the opposite order.
1773 As indicated, it is possible to specify different naming schemes for
1774 bodies, specs, and subunits. Quite often the rule for subunits is the
1775 same as the rule for bodies, in which case, there is no need to give
1776 a separate @code{Subunit_File_Name} rule, and in this case the
1777 @code{Body_File_name} rule is used for subunits as well.
1779 The separate rule for subunits can also be used to implement the rather
1780 unusual case of a compilation environment (e.g.@: a single directory) which
1781 contains a subunit and a child unit with the same unit name. Although
1782 both units cannot appear in the same partition, the Ada Reference Manual
1783 allows (but does not require) the possibility of the two units coexisting
1784 in the same environment.
1786 The file name translation works in the following steps:
1791 If there is a specific @code{Source_File_Name} pragma for the given unit,
1792 then this is always used, and any general pattern rules are ignored.
1795 If there is a pattern type @code{Source_File_Name} pragma that applies to
1796 the unit, then the resulting file name will be used if the file exists. If
1797 more than one pattern matches, the latest one will be tried first, and the
1798 first attempt resulting in a reference to a file that exists will be used.
1801 If no pattern type @code{Source_File_Name} pragma that applies to the unit
1802 for which the corresponding file exists, then the standard GNAT default
1803 naming rules are used.
1808 As an example of the use of this mechanism, consider a commonly used scheme
1809 in which file names are all lower case, with separating periods copied
1810 unchanged to the resulting file name, and specs end with @file{.1.ada}, and
1811 bodies end with @file{.2.ada}. GNAT will follow this scheme if the following
1814 @smallexample @c ada
1815 pragma Source_File_Name
1816 (Spec_File_Name => "*.1.ada");
1817 pragma Source_File_Name
1818 (Body_File_Name => "*.2.ada");
1822 The default GNAT scheme is actually implemented by providing the following
1823 default pragmas internally:
1825 @smallexample @c ada
1826 pragma Source_File_Name
1827 (Spec_File_Name => "*.ads", Dot_Replacement => "-");
1828 pragma Source_File_Name
1829 (Body_File_Name => "*.adb", Dot_Replacement => "-");
1833 Our final example implements a scheme typically used with one of the
1834 Ada 83 compilers, where the separator character for subunits was ``__''
1835 (two underscores), specs were identified by adding @file{_.ADA}, bodies
1836 by adding @file{.ADA}, and subunits by
1837 adding @file{.SEP}. All file names were
1838 upper case. Child units were not present of course since this was an
1839 Ada 83 compiler, but it seems reasonable to extend this scheme to use
1840 the same double underscore separator for child units.
1842 @smallexample @c ada
1843 pragma Source_File_Name
1844 (Spec_File_Name => "*_.ADA",
1845 Dot_Replacement => "__",
1846 Casing = Uppercase);
1847 pragma Source_File_Name
1848 (Body_File_Name => "*.ADA",
1849 Dot_Replacement => "__",
1850 Casing = Uppercase);
1851 pragma Source_File_Name
1852 (Subunit_File_Name => "*.SEP",
1853 Dot_Replacement => "__",
1854 Casing = Uppercase);
1857 @node Generating Object Files
1858 @section Generating Object Files
1861 An Ada program consists of a set of source files, and the first step in
1862 compiling the program is to generate the corresponding object files.
1863 These are generated by compiling a subset of these source files.
1864 The files you need to compile are the following:
1868 If a package spec has no body, compile the package spec to produce the
1869 object file for the package.
1872 If a package has both a spec and a body, compile the body to produce the
1873 object file for the package. The source file for the package spec need
1874 not be compiled in this case because there is only one object file, which
1875 contains the code for both the spec and body of the package.
1878 For a subprogram, compile the subprogram body to produce the object file
1879 for the subprogram. The spec, if one is present, is as usual in a
1880 separate file, and need not be compiled.
1884 In the case of subunits, only compile the parent unit. A single object
1885 file is generated for the entire subunit tree, which includes all the
1889 Compile child units independently of their parent units
1890 (though, of course, the spec of all the ancestor unit must be present in order
1891 to compile a child unit).
1895 Compile generic units in the same manner as any other units. The object
1896 files in this case are small dummy files that contain at most the
1897 flag used for elaboration checking. This is because GNAT always handles generic
1898 instantiation by means of macro expansion. However, it is still necessary to
1899 compile generic units, for dependency checking and elaboration purposes.
1903 The preceding rules describe the set of files that must be compiled to
1904 generate the object files for a program. Each object file has the same
1905 name as the corresponding source file, except that the extension is
1908 You may wish to compile other files for the purpose of checking their
1909 syntactic and semantic correctness. For example, in the case where a
1910 package has a separate spec and body, you would not normally compile the
1911 spec. However, it is convenient in practice to compile the spec to make
1912 sure it is error-free before compiling clients of this spec, because such
1913 compilations will fail if there is an error in the spec.
1915 GNAT provides an option for compiling such files purely for the
1916 purposes of checking correctness; such compilations are not required as
1917 part of the process of building a program. To compile a file in this
1918 checking mode, use the @option{-gnatc} switch.
1920 @node Source Dependencies
1921 @section Source Dependencies
1924 A given object file clearly depends on the source file which is compiled
1925 to produce it. Here we are using @dfn{depends} in the sense of a typical
1926 @code{make} utility; in other words, an object file depends on a source
1927 file if changes to the source file require the object file to be
1929 In addition to this basic dependency, a given object may depend on
1930 additional source files as follows:
1934 If a file being compiled @code{with}'s a unit @var{X}, the object file
1935 depends on the file containing the spec of unit @var{X}. This includes
1936 files that are @code{with}'ed implicitly either because they are parents
1937 of @code{with}'ed child units or they are run-time units required by the
1938 language constructs used in a particular unit.
1941 If a file being compiled instantiates a library level generic unit, the
1942 object file depends on both the spec and body files for this generic
1946 If a file being compiled instantiates a generic unit defined within a
1947 package, the object file depends on the body file for the package as
1948 well as the spec file.
1952 @cindex @option{-gnatn} switch
1953 If a file being compiled contains a call to a subprogram for which
1954 pragma @code{Inline} applies and inlining is activated with the
1955 @option{-gnatn} switch, the object file depends on the file containing the
1956 body of this subprogram as well as on the file containing the spec. Note
1957 that for inlining to actually occur as a result of the use of this switch,
1958 it is necessary to compile in optimizing mode.
1960 @cindex @option{-gnatN} switch
1961 The use of @option{-gnatN} activates inlining optimization
1962 that is performed by the front end of the compiler. This inlining does
1963 not require that the code generation be optimized. Like @option{-gnatn},
1964 the use of this switch generates additional dependencies.
1966 When using a gcc-based back end (in practice this means using any version
1967 of GNAT other than the JGNAT, .NET or GNAAMP versions), then the use of
1968 @option{-gnatN} is deprecated, and the use of @option{-gnatn} is preferred.
1969 Historically front end inlining was more extensive than the gcc back end
1970 inlining, but that is no longer the case.
1973 If an object file @file{O} depends on the proper body of a subunit through
1974 inlining or instantiation, it depends on the parent unit of the subunit.
1975 This means that any modification of the parent unit or one of its subunits
1976 affects the compilation of @file{O}.
1979 The object file for a parent unit depends on all its subunit body files.
1982 The previous two rules meant that for purposes of computing dependencies and
1983 recompilation, a body and all its subunits are treated as an indivisible whole.
1986 These rules are applied transitively: if unit @code{A} @code{with}'s
1987 unit @code{B}, whose elaboration calls an inlined procedure in package
1988 @code{C}, the object file for unit @code{A} will depend on the body of
1989 @code{C}, in file @file{c.adb}.
1991 The set of dependent files described by these rules includes all the
1992 files on which the unit is semantically dependent, as dictated by the
1993 Ada language standard. However, it is a superset of what the
1994 standard describes, because it includes generic, inline, and subunit
1997 An object file must be recreated by recompiling the corresponding source
1998 file if any of the source files on which it depends are modified. For
1999 example, if the @code{make} utility is used to control compilation,
2000 the rule for an Ada object file must mention all the source files on
2001 which the object file depends, according to the above definition.
2002 The determination of the necessary
2003 recompilations is done automatically when one uses @command{gnatmake}.
2006 @node The Ada Library Information Files
2007 @section The Ada Library Information Files
2008 @cindex Ada Library Information files
2009 @cindex @file{ALI} files
2012 Each compilation actually generates two output files. The first of these
2013 is the normal object file that has a @file{.o} extension. The second is a
2014 text file containing full dependency information. It has the same
2015 name as the source file, but an @file{.ali} extension.
2016 This file is known as the Ada Library Information (@file{ALI}) file.
2017 The following information is contained in the @file{ALI} file.
2021 Version information (indicates which version of GNAT was used to compile
2022 the unit(s) in question)
2025 Main program information (including priority and time slice settings,
2026 as well as the wide character encoding used during compilation).
2029 List of arguments used in the @command{gcc} command for the compilation
2032 Attributes of the unit, including configuration pragmas used, an indication
2033 of whether the compilation was successful, exception model used etc.
2036 A list of relevant restrictions applying to the unit (used for consistency)
2040 Categorization information (e.g.@: use of pragma @code{Pure}).
2043 Information on all @code{with}'ed units, including presence of
2044 @code{Elaborate} or @code{Elaborate_All} pragmas.
2047 Information from any @code{Linker_Options} pragmas used in the unit
2050 Information on the use of @code{Body_Version} or @code{Version}
2051 attributes in the unit.
2054 Dependency information. This is a list of files, together with
2055 time stamp and checksum information. These are files on which
2056 the unit depends in the sense that recompilation is required
2057 if any of these units are modified.
2060 Cross-reference data. Contains information on all entities referenced
2061 in the unit. Used by tools like @code{gnatxref} and @code{gnatfind} to
2062 provide cross-reference information.
2067 For a full detailed description of the format of the @file{ALI} file,
2068 see the source of the body of unit @code{Lib.Writ}, contained in file
2069 @file{lib-writ.adb} in the GNAT compiler sources.
2071 @node Binding an Ada Program
2072 @section Binding an Ada Program
2075 When using languages such as C and C++, once the source files have been
2076 compiled the only remaining step in building an executable program
2077 is linking the object modules together. This means that it is possible to
2078 link an inconsistent version of a program, in which two units have
2079 included different versions of the same header.
2081 The rules of Ada do not permit such an inconsistent program to be built.
2082 For example, if two clients have different versions of the same package,
2083 it is illegal to build a program containing these two clients.
2084 These rules are enforced by the GNAT binder, which also determines an
2085 elaboration order consistent with the Ada rules.
2087 The GNAT binder is run after all the object files for a program have
2088 been created. It is given the name of the main program unit, and from
2089 this it determines the set of units required by the program, by reading the
2090 corresponding ALI files. It generates error messages if the program is
2091 inconsistent or if no valid order of elaboration exists.
2093 If no errors are detected, the binder produces a main program, in Ada by
2094 default, that contains calls to the elaboration procedures of those
2095 compilation unit that require them, followed by
2096 a call to the main program. This Ada program is compiled to generate the
2097 object file for the main program. The name of
2098 the Ada file is @file{b~@var{xxx}.adb} (with the corresponding spec
2099 @file{b~@var{xxx}.ads}) where @var{xxx} is the name of the
2102 Finally, the linker is used to build the resulting executable program,
2103 using the object from the main program from the bind step as well as the
2104 object files for the Ada units of the program.
2106 @node Mixed Language Programming
2107 @section Mixed Language Programming
2108 @cindex Mixed Language Programming
2111 This section describes how to develop a mixed-language program,
2112 specifically one that comprises units in both Ada and C.
2115 * Interfacing to C::
2116 * Calling Conventions::
2119 @node Interfacing to C
2120 @subsection Interfacing to C
2122 Interfacing Ada with a foreign language such as C involves using
2123 compiler directives to import and/or export entity definitions in each
2124 language---using @code{extern} statements in C, for instance, and the
2125 @code{Import}, @code{Export}, and @code{Convention} pragmas in Ada.
2126 A full treatment of these topics is provided in Appendix B, section 1
2127 of the Ada Reference Manual.
2129 There are two ways to build a program using GNAT that contains some Ada
2130 sources and some foreign language sources, depending on whether or not
2131 the main subprogram is written in Ada. Here is a source example with
2132 the main subprogram in Ada:
2138 void print_num (int num)
2140 printf ("num is %d.\n", num);
2146 /* num_from_Ada is declared in my_main.adb */
2147 extern int num_from_Ada;
2151 return num_from_Ada;
2155 @smallexample @c ada
2157 procedure My_Main is
2159 -- Declare then export an Integer entity called num_from_Ada
2160 My_Num : Integer := 10;
2161 pragma Export (C, My_Num, "num_from_Ada");
2163 -- Declare an Ada function spec for Get_Num, then use
2164 -- C function get_num for the implementation.
2165 function Get_Num return Integer;
2166 pragma Import (C, Get_Num, "get_num");
2168 -- Declare an Ada procedure spec for Print_Num, then use
2169 -- C function print_num for the implementation.
2170 procedure Print_Num (Num : Integer);
2171 pragma Import (C, Print_Num, "print_num");
2174 Print_Num (Get_Num);
2180 To build this example, first compile the foreign language files to
2181 generate object files:
2183 ^gcc -c file1.c^gcc -c FILE1.C^
2184 ^gcc -c file2.c^gcc -c FILE2.C^
2188 Then, compile the Ada units to produce a set of object files and ALI
2191 gnatmake ^-c^/ACTIONS=COMPILE^ my_main.adb
2195 Run the Ada binder on the Ada main program:
2197 gnatbind my_main.ali
2201 Link the Ada main program, the Ada objects and the other language
2204 gnatlink my_main.ali file1.o file2.o
2208 The last three steps can be grouped in a single command:
2210 gnatmake my_main.adb -largs file1.o file2.o
2213 @cindex Binder output file
2215 If the main program is in a language other than Ada, then you may have
2216 more than one entry point into the Ada subsystem. You must use a special
2217 binder option to generate callable routines that initialize and
2218 finalize the Ada units (@pxref{Binding with Non-Ada Main Programs}).
2219 Calls to the initialization and finalization routines must be inserted
2220 in the main program, or some other appropriate point in the code. The
2221 call to initialize the Ada units must occur before the first Ada
2222 subprogram is called, and the call to finalize the Ada units must occur
2223 after the last Ada subprogram returns. The binder will place the
2224 initialization and finalization subprograms into the
2225 @file{b~@var{xxx}.adb} file where they can be accessed by your C
2226 sources. To illustrate, we have the following example:
2230 extern void adainit (void);
2231 extern void adafinal (void);
2232 extern int add (int, int);
2233 extern int sub (int, int);
2235 int main (int argc, char *argv[])
2241 /* Should print "21 + 7 = 28" */
2242 printf ("%d + %d = %d\n", a, b, add (a, b));
2243 /* Should print "21 - 7 = 14" */
2244 printf ("%d - %d = %d\n", a, b, sub (a, b));
2250 @smallexample @c ada
2253 function Add (A, B : Integer) return Integer;
2254 pragma Export (C, Add, "add");
2258 package body Unit1 is
2259 function Add (A, B : Integer) return Integer is
2267 function Sub (A, B : Integer) return Integer;
2268 pragma Export (C, Sub, "sub");
2272 package body Unit2 is
2273 function Sub (A, B : Integer) return Integer is
2282 The build procedure for this application is similar to the last
2283 example's. First, compile the foreign language files to generate object
2286 ^gcc -c main.c^gcc -c main.c^
2290 Next, compile the Ada units to produce a set of object files and ALI
2293 gnatmake ^-c^/ACTIONS=COMPILE^ unit1.adb
2294 gnatmake ^-c^/ACTIONS=COMPILE^ unit2.adb
2298 Run the Ada binder on every generated ALI file. Make sure to use the
2299 @option{-n} option to specify a foreign main program:
2301 gnatbind ^-n^/NOMAIN^ unit1.ali unit2.ali
2305 Link the Ada main program, the Ada objects and the foreign language
2306 objects. You need only list the last ALI file here:
2308 gnatlink unit2.ali main.o -o exec_file
2311 This procedure yields a binary executable called @file{exec_file}.
2315 Depending on the circumstances (for example when your non-Ada main object
2316 does not provide symbol @code{main}), you may also need to instruct the
2317 GNAT linker not to include the standard startup objects by passing the
2318 @option{^-nostartfiles^/NOSTART_FILES^} switch to @command{gnatlink}.
2320 @node Calling Conventions
2321 @subsection Calling Conventions
2322 @cindex Foreign Languages
2323 @cindex Calling Conventions
2324 GNAT follows standard calling sequence conventions and will thus interface
2325 to any other language that also follows these conventions. The following
2326 Convention identifiers are recognized by GNAT:
2329 @cindex Interfacing to Ada
2330 @cindex Other Ada compilers
2331 @cindex Convention Ada
2333 This indicates that the standard Ada calling sequence will be
2334 used and all Ada data items may be passed without any limitations in the
2335 case where GNAT is used to generate both the caller and callee. It is also
2336 possible to mix GNAT generated code and code generated by another Ada
2337 compiler. In this case, the data types should be restricted to simple
2338 cases, including primitive types. Whether complex data types can be passed
2339 depends on the situation. Probably it is safe to pass simple arrays, such
2340 as arrays of integers or floats. Records may or may not work, depending
2341 on whether both compilers lay them out identically. Complex structures
2342 involving variant records, access parameters, tasks, or protected types,
2343 are unlikely to be able to be passed.
2345 Note that in the case of GNAT running
2346 on a platform that supports HP Ada 83, a higher degree of compatibility
2347 can be guaranteed, and in particular records are laid out in an identical
2348 manner in the two compilers. Note also that if output from two different
2349 compilers is mixed, the program is responsible for dealing with elaboration
2350 issues. Probably the safest approach is to write the main program in the
2351 version of Ada other than GNAT, so that it takes care of its own elaboration
2352 requirements, and then call the GNAT-generated adainit procedure to ensure
2353 elaboration of the GNAT components. Consult the documentation of the other
2354 Ada compiler for further details on elaboration.
2356 However, it is not possible to mix the tasking run time of GNAT and
2357 HP Ada 83, All the tasking operations must either be entirely within
2358 GNAT compiled sections of the program, or entirely within HP Ada 83
2359 compiled sections of the program.
2361 @cindex Interfacing to Assembly
2362 @cindex Convention Assembler
2364 Specifies assembler as the convention. In practice this has the
2365 same effect as convention Ada (but is not equivalent in the sense of being
2366 considered the same convention).
2368 @cindex Convention Asm
2371 Equivalent to Assembler.
2373 @cindex Interfacing to COBOL
2374 @cindex Convention COBOL
2377 Data will be passed according to the conventions described
2378 in section B.4 of the Ada Reference Manual.
2381 @cindex Interfacing to C
2382 @cindex Convention C
2384 Data will be passed according to the conventions described
2385 in section B.3 of the Ada Reference Manual.
2387 A note on interfacing to a C ``varargs'' function:
2388 @findex C varargs function
2389 @cindex Interfacing to C varargs function
2390 @cindex varargs function interfaces
2394 In C, @code{varargs} allows a function to take a variable number of
2395 arguments. There is no direct equivalent in this to Ada. One
2396 approach that can be used is to create a C wrapper for each
2397 different profile and then interface to this C wrapper. For
2398 example, to print an @code{int} value using @code{printf},
2399 create a C function @code{printfi} that takes two arguments, a
2400 pointer to a string and an int, and calls @code{printf}.
2401 Then in the Ada program, use pragma @code{Import} to
2402 interface to @code{printfi}.
2405 It may work on some platforms to directly interface to
2406 a @code{varargs} function by providing a specific Ada profile
2407 for a particular call. However, this does not work on
2408 all platforms, since there is no guarantee that the
2409 calling sequence for a two argument normal C function
2410 is the same as for calling a @code{varargs} C function with
2411 the same two arguments.
2414 @cindex Convention Default
2419 @cindex Convention External
2426 @cindex Interfacing to C++
2427 @cindex Convention C++
2428 @item C_Plus_Plus (or CPP)
2429 This stands for C++. For most purposes this is identical to C.
2430 See the separate description of the specialized GNAT pragmas relating to
2431 C++ interfacing for further details.
2435 @cindex Interfacing to Fortran
2436 @cindex Convention Fortran
2438 Data will be passed according to the conventions described
2439 in section B.5 of the Ada Reference Manual.
2442 This applies to an intrinsic operation, as defined in the Ada
2443 Reference Manual. If a pragma Import (Intrinsic) applies to a subprogram,
2444 this means that the body of the subprogram is provided by the compiler itself,
2445 usually by means of an efficient code sequence, and that the user does not
2446 supply an explicit body for it. In an application program, the pragma may
2447 be applied to the following sets of names:
2451 Rotate_Left, Rotate_Right, Shift_Left, Shift_Right,
2452 Shift_Right_Arithmetic. The corresponding subprogram declaration must have
2453 two formal parameters. The
2454 first one must be a signed integer type or a modular type with a binary
2455 modulus, and the second parameter must be of type Natural.
2456 The return type must be the same as the type of the first argument. The size
2457 of this type can only be 8, 16, 32, or 64.
2460 Binary arithmetic operators: ``+'', ``-'', ``*'', ``/''
2461 The corresponding operator declaration must have parameters and result type
2462 that have the same root numeric type (for example, all three are long_float
2463 types). This simplifies the definition of operations that use type checking
2464 to perform dimensional checks:
2466 @smallexample @c ada
2467 type Distance is new Long_Float;
2468 type Time is new Long_Float;
2469 type Velocity is new Long_Float;
2470 function "/" (D : Distance; T : Time)
2472 pragma Import (Intrinsic, "/");
2476 This common idiom is often programmed with a generic definition and an
2477 explicit body. The pragma makes it simpler to introduce such declarations.
2478 It incurs no overhead in compilation time or code size, because it is
2479 implemented as a single machine instruction.
2482 General subprogram entities, to bind an Ada subprogram declaration to
2483 a compiler builtin by name with back-ends where such interfaces are
2484 available. A typical example is the set of ``__builtin'' functions
2485 exposed by the GCC back-end, as in the following example:
2487 @smallexample @c ada
2488 function builtin_sqrt (F : Float) return Float;
2489 pragma Import (Intrinsic, builtin_sqrt, "__builtin_sqrtf");
2492 Most of the GCC builtins are accessible this way, and as for other
2493 import conventions (e.g. C), it is the user's responsibility to ensure
2494 that the Ada subprogram profile matches the underlying builtin
2502 @cindex Convention Stdcall
2504 This is relevant only to Windows XP/2000/NT implementations of GNAT,
2505 and specifies that the @code{Stdcall} calling sequence will be used,
2506 as defined by the NT API. Nevertheless, to ease building
2507 cross-platform bindings this convention will be handled as a @code{C} calling
2508 convention on non-Windows platforms.
2511 @cindex Convention DLL
2513 This is equivalent to @code{Stdcall}.
2516 @cindex Convention Win32
2518 This is equivalent to @code{Stdcall}.
2522 @cindex Convention Stubbed
2524 This is a special convention that indicates that the compiler
2525 should provide a stub body that raises @code{Program_Error}.
2529 GNAT additionally provides a useful pragma @code{Convention_Identifier}
2530 that can be used to parameterize conventions and allow additional synonyms
2531 to be specified. For example if you have legacy code in which the convention
2532 identifier Fortran77 was used for Fortran, you can use the configuration
2535 @smallexample @c ada
2536 pragma Convention_Identifier (Fortran77, Fortran);
2540 And from now on the identifier Fortran77 may be used as a convention
2541 identifier (for example in an @code{Import} pragma) with the same
2545 @node Building Mixed Ada & C++ Programs
2546 @section Building Mixed Ada and C++ Programs
2549 A programmer inexperienced with mixed-language development may find that
2550 building an application containing both Ada and C++ code can be a
2551 challenge. This section gives a few
2552 hints that should make this task easier. The first section addresses
2553 the differences between interfacing with C and interfacing with C++.
2555 looks into the delicate problem of linking the complete application from
2556 its Ada and C++ parts. The last section gives some hints on how the GNAT
2557 run-time library can be adapted in order to allow inter-language dispatching
2558 with a new C++ compiler.
2561 * Interfacing to C++::
2562 * Linking a Mixed C++ & Ada Program::
2563 * A Simple Example::
2564 * Interfacing with C++ constructors::
2565 * Interfacing with C++ at the Class Level::
2568 @node Interfacing to C++
2569 @subsection Interfacing to C++
2572 GNAT supports interfacing with the G++ compiler (or any C++ compiler
2573 generating code that is compatible with the G++ Application Binary
2574 Interface ---see http://www.codesourcery.com/archives/cxx-abi).
2577 Interfacing can be done at 3 levels: simple data, subprograms, and
2578 classes. In the first two cases, GNAT offers a specific @code{Convention
2579 C_Plus_Plus} (or @code{CPP}) that behaves exactly like @code{Convention C}.
2580 Usually, C++ mangles the names of subprograms. To generate proper mangled
2581 names automatically, see @ref{Generating Ada Bindings for C and C++ headers}).
2582 This problem can also be addressed manually in two ways:
2586 by modifying the C++ code in order to force a C convention using
2587 the @code{extern "C"} syntax.
2590 by figuring out the mangled name (using e.g. @command{nm}) and using it as the
2591 Link_Name argument of the pragma import.
2595 Interfacing at the class level can be achieved by using the GNAT specific
2596 pragmas such as @code{CPP_Constructor}. @xref{Interfacing to C++,,,
2597 gnat_rm, GNAT Reference Manual}, for additional information.
2599 @node Linking a Mixed C++ & Ada Program
2600 @subsection Linking a Mixed C++ & Ada Program
2603 Usually the linker of the C++ development system must be used to link
2604 mixed applications because most C++ systems will resolve elaboration
2605 issues (such as calling constructors on global class instances)
2606 transparently during the link phase. GNAT has been adapted to ease the
2607 use of a foreign linker for the last phase. Three cases can be
2612 Using GNAT and G++ (GNU C++ compiler) from the same GCC installation:
2613 The C++ linker can simply be called by using the C++ specific driver
2616 Note that if the C++ code uses inline functions, you will need to
2617 compile your C++ code with the @code{-fkeep-inline-functions} switch in
2618 order to provide an existing function implementation that the Ada code can
2622 $ g++ -c -fkeep-inline-functions file1.C
2623 $ g++ -c -fkeep-inline-functions file2.C
2624 $ gnatmake ada_unit -largs file1.o file2.o --LINK=g++
2628 Using GNAT and G++ from two different GCC installations: If both
2629 compilers are on the @env{PATH}, the previous method may be used. It is
2630 important to note that environment variables such as
2631 @env{C_INCLUDE_PATH}, @env{GCC_EXEC_PREFIX}, @env{BINUTILS_ROOT}, and
2632 @env{GCC_ROOT} will affect both compilers
2633 at the same time and may make one of the two compilers operate
2634 improperly if set during invocation of the wrong compiler. It is also
2635 very important that the linker uses the proper @file{libgcc.a} GCC
2636 library -- that is, the one from the C++ compiler installation. The
2637 implicit link command as suggested in the @command{gnatmake} command
2638 from the former example can be replaced by an explicit link command with
2639 the full-verbosity option in order to verify which library is used:
2642 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=c++
2644 If there is a problem due to interfering environment variables, it can
2645 be worked around by using an intermediate script. The following example
2646 shows the proper script to use when GNAT has not been installed at its
2647 default location and g++ has been installed at its default location:
2655 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=./my_script
2659 Using a non-GNU C++ compiler: The commands previously described can be
2660 used to insure that the C++ linker is used. Nonetheless, you need to add
2661 a few more parameters to the link command line, depending on the exception
2664 If the @code{setjmp/longjmp} exception mechanism is used, only the paths
2665 to the libgcc libraries are required:
2670 CC $* `gcc -print-file-name=libgcc.a` `gcc -print-file-name=libgcc_eh.a`
2671 $ gnatlink ada_unit file1.o file2.o --LINK=./my_script
2674 Where CC is the name of the non-GNU C++ compiler.
2676 If the @code{zero cost} exception mechanism is used, and the platform
2677 supports automatic registration of exception tables (e.g.@: Solaris),
2678 paths to more objects are required:
2683 CC `gcc -print-file-name=crtbegin.o` $* \
2684 `gcc -print-file-name=libgcc.a` `gcc -print-file-name=libgcc_eh.a` \
2685 `gcc -print-file-name=crtend.o`
2686 $ gnatlink ada_unit file1.o file2.o --LINK=./my_script
2689 If the @code{zero cost} exception mechanism is used, and the platform
2690 doesn't support automatic registration of exception tables (e.g.@: HP-UX
2691 or AIX), the simple approach described above will not work and
2692 a pre-linking phase using GNAT will be necessary.
2696 Another alternative is to use the @command{gprbuild} multi-language builder
2697 which has a large knowledge base and knows how to link Ada and C++ code
2698 together automatically in most cases.
2700 @node A Simple Example
2701 @subsection A Simple Example
2703 The following example, provided as part of the GNAT examples, shows how
2704 to achieve procedural interfacing between Ada and C++ in both
2705 directions. The C++ class A has two methods. The first method is exported
2706 to Ada by the means of an extern C wrapper function. The second method
2707 calls an Ada subprogram. On the Ada side, The C++ calls are modelled by
2708 a limited record with a layout comparable to the C++ class. The Ada
2709 subprogram, in turn, calls the C++ method. So, starting from the C++
2710 main program, the process passes back and forth between the two
2714 Here are the compilation commands:
2716 $ gnatmake -c simple_cpp_interface
2719 $ gnatbind -n simple_cpp_interface
2720 $ gnatlink simple_cpp_interface -o cpp_main --LINK=g++
2721 -lstdc++ ex7.o cpp_main.o
2725 Here are the corresponding sources:
2733 void adainit (void);
2734 void adafinal (void);
2735 void method1 (A *t);
2757 class A : public Origin @{
2759 void method1 (void);
2760 void method2 (int v);
2770 extern "C" @{ void ada_method2 (A *t, int v);@}
2772 void A::method1 (void)
2775 printf ("in A::method1, a_value = %d \n",a_value);
2779 void A::method2 (int v)
2781 ada_method2 (this, v);
2782 printf ("in A::method2, a_value = %d \n",a_value);
2789 printf ("in A::A, a_value = %d \n",a_value);
2793 @smallexample @c ada
2795 package body Simple_Cpp_Interface is
2797 procedure Ada_Method2 (This : in out A; V : Integer) is
2803 end Simple_Cpp_Interface;
2806 package Simple_Cpp_Interface is
2809 Vptr : System.Address;
2813 pragma Convention (C, A);
2815 procedure Method1 (This : in out A);
2816 pragma Import (C, Method1);
2818 procedure Ada_Method2 (This : in out A; V : Integer);
2819 pragma Export (C, Ada_Method2);
2821 end Simple_Cpp_Interface;
2824 @node Interfacing with C++ constructors
2825 @subsection Interfacing with C++ constructors
2828 In order to interface with C++ constructors GNAT provides the
2829 @code{pragma CPP_Constructor} (@xref{Interfacing to C++,,,
2830 gnat_rm, GNAT Reference Manual}, for additional information).
2831 In this section we present some common uses of C++ constructors
2832 in mixed-languages programs in GNAT.
2834 Let us assume that we need to interface with the following
2842 @b{virtual} int Get_Value ();
2843 Root(); // Default constructor
2844 Root(int v); // 1st non-default constructor
2845 Root(int v, int w); // 2nd non-default constructor
2849 For this purpose we can write the following package spec (further
2850 information on how to build this spec is available in
2851 @ref{Interfacing with C++ at the Class Level} and
2852 @ref{Generating Ada Bindings for C and C++ headers}).
2854 @smallexample @c ada
2855 with Interfaces.C; use Interfaces.C;
2857 type Root is tagged limited record
2861 pragma Import (CPP, Root);
2863 function Get_Value (Obj : Root) return int;
2864 pragma Import (CPP, Get_Value);
2866 function Constructor return Root;
2867 pragma Cpp_Constructor (Constructor, "_ZN4RootC1Ev");
2869 function Constructor (v : Integer) return Root;
2870 pragma Cpp_Constructor (Constructor, "_ZN4RootC1Ei");
2872 function Constructor (v, w : Integer) return Root;
2873 pragma Cpp_Constructor (Constructor, "_ZN4RootC1Eii");
2877 On the Ada side the constructor is represented by a function (whose
2878 name is arbitrary) that returns the classwide type corresponding to
2879 the imported C++ class. Although the constructor is described as a
2880 function, it is typically a procedure with an extra implicit argument
2881 (the object being initialized) at the implementation level. GNAT
2882 issues the appropriate call, whatever it is, to get the object
2883 properly initialized.
2885 Constructors can only appear in the following contexts:
2889 On the right side of an initialization of an object of type @var{T}.
2891 On the right side of an initialization of a record component of type @var{T}.
2893 In an Ada 2005 limited aggregate.
2895 In an Ada 2005 nested limited aggregate.
2897 In an Ada 2005 limited aggregate that initializes an object built in
2898 place by an extended return statement.
2902 In a declaration of an object whose type is a class imported from C++,
2903 either the default C++ constructor is implicitly called by GNAT, or
2904 else the required C++ constructor must be explicitly called in the
2905 expression that initializes the object. For example:
2907 @smallexample @c ada
2909 Obj2 : Root := Constructor;
2910 Obj3 : Root := Constructor (v => 10);
2911 Obj4 : Root := Constructor (30, 40);
2914 The first two declarations are equivalent: in both cases the default C++
2915 constructor is invoked (in the former case the call to the constructor is
2916 implicit, and in the latter case the call is explicit in the object
2917 declaration). @code{Obj3} is initialized by the C++ non-default constructor
2918 that takes an integer argument, and @code{Obj4} is initialized by the
2919 non-default C++ constructor that takes two integers.
2921 Let us derive the imported C++ class in the Ada side. For example:
2923 @smallexample @c ada
2924 type DT is new Root with record
2925 C_Value : Natural := 2009;
2929 In this case the components DT inherited from the C++ side must be
2930 initialized by a C++ constructor, and the additional Ada components
2931 of type DT are initialized by GNAT. The initialization of such an
2932 object is done either by default, or by means of a function returning
2933 an aggregate of type DT, or by means of an extension aggregate.
2935 @smallexample @c ada
2937 Obj6 : DT := Function_Returning_DT (50);
2938 Obj7 : DT := (Constructor (30,40) with C_Value => 50);
2941 The declaration of @code{Obj5} invokes the default constructors: the
2942 C++ default constructor of the parent type takes care of the initialization
2943 of the components inherited from Root, and GNAT takes care of the default
2944 initialization of the additional Ada components of type DT (that is,
2945 @code{C_Value} is initialized to value 2009). The order of invocation of
2946 the constructors is consistent with the order of elaboration required by
2947 Ada and C++. That is, the constructor of the parent type is always called
2948 before the constructor of the derived type.
2950 Let us now consider a record that has components whose type is imported
2951 from C++. For example:
2953 @smallexample @c ada
2954 type Rec1 is limited record
2955 Data1 : Root := Constructor (10);
2956 Value : Natural := 1000;
2959 type Rec2 (D : Integer := 20) is limited record
2961 Data2 : Root := Constructor (D, 30);
2965 The initialization of an object of type @code{Rec2} will call the
2966 non-default C++ constructors specified for the imported components.
2969 @smallexample @c ada
2973 Using Ada 2005 we can use limited aggregates to initialize an object
2974 invoking C++ constructors that differ from those specified in the type
2975 declarations. For example:
2977 @smallexample @c ada
2978 Obj9 : Rec2 := (Rec => (Data1 => Constructor (15, 16),
2983 The above declaration uses an Ada 2005 limited aggregate to
2984 initialize @code{Obj9}, and the C++ constructor that has two integer
2985 arguments is invoked to initialize the @code{Data1} component instead
2986 of the constructor specified in the declaration of type @code{Rec1}. In
2987 Ada 2005 the box in the aggregate indicates that unspecified components
2988 are initialized using the expression (if any) available in the component
2989 declaration. That is, in this case discriminant @code{D} is initialized
2990 to value @code{20}, @code{Value} is initialized to value 1000, and the
2991 non-default C++ constructor that handles two integers takes care of
2992 initializing component @code{Data2} with values @code{20,30}.
2994 In Ada 2005 we can use the extended return statement to build the Ada
2995 equivalent to C++ non-default constructors. For example:
2997 @smallexample @c ada
2998 function Constructor (V : Integer) return Rec2 is
3000 return Obj : Rec2 := (Rec => (Data1 => Constructor (V, 20),
3003 -- Further actions required for construction of
3004 -- objects of type Rec2
3010 In this example the extended return statement construct is used to
3011 build in place the returned object whose components are initialized
3012 by means of a limited aggregate. Any further action associated with
3013 the constructor can be placed inside the construct.
3015 @node Interfacing with C++ at the Class Level
3016 @subsection Interfacing with C++ at the Class Level
3018 In this section we demonstrate the GNAT features for interfacing with
3019 C++ by means of an example making use of Ada 2005 abstract interface
3020 types. This example consists of a classification of animals; classes
3021 have been used to model our main classification of animals, and
3022 interfaces provide support for the management of secondary
3023 classifications. We first demonstrate a case in which the types and
3024 constructors are defined on the C++ side and imported from the Ada
3025 side, and latter the reverse case.
3027 The root of our derivation will be the @code{Animal} class, with a
3028 single private attribute (the @code{Age} of the animal) and two public
3029 primitives to set and get the value of this attribute.
3034 @b{virtual} void Set_Age (int New_Age);
3035 @b{virtual} int Age ();
3041 Abstract interface types are defined in C++ by means of classes with pure
3042 virtual functions and no data members. In our example we will use two
3043 interfaces that provide support for the common management of @code{Carnivore}
3044 and @code{Domestic} animals:
3047 @b{class} Carnivore @{
3049 @b{virtual} int Number_Of_Teeth () = 0;
3052 @b{class} Domestic @{
3054 @b{virtual void} Set_Owner (char* Name) = 0;
3058 Using these declarations, we can now say that a @code{Dog} is an animal that is
3059 both Carnivore and Domestic, that is:
3062 @b{class} Dog : Animal, Carnivore, Domestic @{
3064 @b{virtual} int Number_Of_Teeth ();
3065 @b{virtual} void Set_Owner (char* Name);
3067 Dog(); // Constructor
3074 In the following examples we will assume that the previous declarations are
3075 located in a file named @code{animals.h}. The following package demonstrates
3076 how to import these C++ declarations from the Ada side:
3078 @smallexample @c ada
3079 with Interfaces.C.Strings; use Interfaces.C.Strings;
3081 type Carnivore is interface;
3082 pragma Convention (C_Plus_Plus, Carnivore);
3083 function Number_Of_Teeth (X : Carnivore)
3084 return Natural is abstract;
3086 type Domestic is interface;
3087 pragma Convention (C_Plus_Plus, Set_Owner);
3089 (X : in out Domestic;
3090 Name : Chars_Ptr) is abstract;
3092 type Animal is tagged record
3095 pragma Import (C_Plus_Plus, Animal);
3097 procedure Set_Age (X : in out Animal; Age : Integer);
3098 pragma Import (C_Plus_Plus, Set_Age);
3100 function Age (X : Animal) return Integer;
3101 pragma Import (C_Plus_Plus, Age);
3103 type Dog is new Animal and Carnivore and Domestic with record
3104 Tooth_Count : Natural;
3105 Owner : String (1 .. 30);
3107 pragma Import (C_Plus_Plus, Dog);
3109 function Number_Of_Teeth (A : Dog) return Integer;
3110 pragma Import (C_Plus_Plus, Number_Of_Teeth);
3112 procedure Set_Owner (A : in out Dog; Name : Chars_Ptr);
3113 pragma Import (C_Plus_Plus, Set_Owner);
3115 function New_Dog return Dog;
3116 pragma CPP_Constructor (New_Dog);
3117 pragma Import (CPP, New_Dog, "_ZN3DogC2Ev");
3121 Thanks to the compatibility between GNAT run-time structures and the C++ ABI,
3122 interfacing with these C++ classes is easy. The only requirement is that all
3123 the primitives and components must be declared exactly in the same order in
3126 Regarding the abstract interfaces, we must indicate to the GNAT compiler by
3127 means of a @code{pragma Convention (C_Plus_Plus)}, the convention used to pass
3128 the arguments to the called primitives will be the same as for C++. For the
3129 imported classes we use @code{pragma Import} with convention @code{C_Plus_Plus}
3130 to indicate that they have been defined on the C++ side; this is required
3131 because the dispatch table associated with these tagged types will be built
3132 in the C++ side and therefore will not contain the predefined Ada primitives
3133 which Ada would otherwise expect.
3135 As the reader can see there is no need to indicate the C++ mangled names
3136 associated with each subprogram because it is assumed that all the calls to
3137 these primitives will be dispatching calls. The only exception is the
3138 constructor, which must be registered with the compiler by means of
3139 @code{pragma CPP_Constructor} and needs to provide its associated C++
3140 mangled name because the Ada compiler generates direct calls to it.
3142 With the above packages we can now declare objects of type Dog on the Ada side
3143 and dispatch calls to the corresponding subprograms on the C++ side. We can
3144 also extend the tagged type Dog with further fields and primitives, and
3145 override some of its C++ primitives on the Ada side. For example, here we have
3146 a type derivation defined on the Ada side that inherits all the dispatching
3147 primitives of the ancestor from the C++ side.
3150 @b{with} Animals; @b{use} Animals;
3151 @b{package} Vaccinated_Animals @b{is}
3152 @b{type} Vaccinated_Dog @b{is new} Dog @b{with null record};
3153 @b{function} Vaccination_Expired (A : Vaccinated_Dog) @b{return} Boolean;
3154 @b{end} Vaccinated_Animals;
3157 It is important to note that, because of the ABI compatibility, the programmer
3158 does not need to add any further information to indicate either the object
3159 layout or the dispatch table entry associated with each dispatching operation.
3161 Now let us define all the types and constructors on the Ada side and export
3162 them to C++, using the same hierarchy of our previous example:
3164 @smallexample @c ada
3165 with Interfaces.C.Strings;
3166 use Interfaces.C.Strings;
3168 type Carnivore is interface;
3169 pragma Convention (C_Plus_Plus, Carnivore);
3170 function Number_Of_Teeth (X : Carnivore)
3171 return Natural is abstract;
3173 type Domestic is interface;
3174 pragma Convention (C_Plus_Plus, Set_Owner);
3176 (X : in out Domestic;
3177 Name : Chars_Ptr) is abstract;
3179 type Animal is tagged record
3182 pragma Convention (C_Plus_Plus, Animal);
3184 procedure Set_Age (X : in out Animal; Age : Integer);
3185 pragma Export (C_Plus_Plus, Set_Age);
3187 function Age (X : Animal) return Integer;
3188 pragma Export (C_Plus_Plus, Age);
3190 type Dog is new Animal and Carnivore and Domestic with record
3191 Tooth_Count : Natural;
3192 Owner : String (1 .. 30);
3194 pragma Convention (C_Plus_Plus, Dog);
3196 function Number_Of_Teeth (A : Dog) return Integer;
3197 pragma Export (C_Plus_Plus, Number_Of_Teeth);
3199 procedure Set_Owner (A : in out Dog; Name : Chars_Ptr);
3200 pragma Export (C_Plus_Plus, Set_Owner);
3202 function New_Dog return Dog'Class;
3203 pragma Export (C_Plus_Plus, New_Dog);
3207 Compared with our previous example the only difference is the use of
3208 @code{pragma Export} to indicate to the GNAT compiler that the primitives will
3209 be available to C++. Thanks to the ABI compatibility, on the C++ side there is
3210 nothing else to be done; as explained above, the only requirement is that all
3211 the primitives and components are declared in exactly the same order.
3213 For completeness, let us see a brief C++ main program that uses the
3214 declarations available in @code{animals.h} (presented in our first example) to
3215 import and use the declarations from the Ada side, properly initializing and
3216 finalizing the Ada run-time system along the way:
3219 @b{#include} "animals.h"
3220 @b{#include} <iostream>
3221 @b{using namespace} std;
3223 void Check_Carnivore (Carnivore *obj) @{@dots{}@}
3224 void Check_Domestic (Domestic *obj) @{@dots{}@}
3225 void Check_Animal (Animal *obj) @{@dots{}@}
3226 void Check_Dog (Dog *obj) @{@dots{}@}
3229 void adainit (void);
3230 void adafinal (void);
3236 Dog *obj = new_dog(); // Ada constructor
3237 Check_Carnivore (obj); // Check secondary DT
3238 Check_Domestic (obj); // Check secondary DT
3239 Check_Animal (obj); // Check primary DT
3240 Check_Dog (obj); // Check primary DT
3245 adainit (); test(); adafinal ();
3250 @node Comparison between GNAT and C/C++ Compilation Models
3251 @section Comparison between GNAT and C/C++ Compilation Models
3254 The GNAT model of compilation is close to the C and C++ models. You can
3255 think of Ada specs as corresponding to header files in C. As in C, you
3256 don't need to compile specs; they are compiled when they are used. The
3257 Ada @code{with} is similar in effect to the @code{#include} of a C
3260 One notable difference is that, in Ada, you may compile specs separately
3261 to check them for semantic and syntactic accuracy. This is not always
3262 possible with C headers because they are fragments of programs that have
3263 less specific syntactic or semantic rules.
3265 The other major difference is the requirement for running the binder,
3266 which performs two important functions. First, it checks for
3267 consistency. In C or C++, the only defense against assembling
3268 inconsistent programs lies outside the compiler, in a makefile, for
3269 example. The binder satisfies the Ada requirement that it be impossible
3270 to construct an inconsistent program when the compiler is used in normal
3273 @cindex Elaboration order control
3274 The other important function of the binder is to deal with elaboration
3275 issues. There are also elaboration issues in C++ that are handled
3276 automatically. This automatic handling has the advantage of being
3277 simpler to use, but the C++ programmer has no control over elaboration.
3278 Where @code{gnatbind} might complain there was no valid order of
3279 elaboration, a C++ compiler would simply construct a program that
3280 malfunctioned at run time.
3283 @node Comparison between GNAT and Conventional Ada Library Models
3284 @section Comparison between GNAT and Conventional Ada Library Models
3287 This section is intended for Ada programmers who have
3288 used an Ada compiler implementing the traditional Ada library
3289 model, as described in the Ada Reference Manual.
3291 @cindex GNAT library
3292 In GNAT, there is no ``library'' in the normal sense. Instead, the set of
3293 source files themselves acts as the library. Compiling Ada programs does
3294 not generate any centralized information, but rather an object file and
3295 a ALI file, which are of interest only to the binder and linker.
3296 In a traditional system, the compiler reads information not only from
3297 the source file being compiled, but also from the centralized library.
3298 This means that the effect of a compilation depends on what has been
3299 previously compiled. In particular:
3303 When a unit is @code{with}'ed, the unit seen by the compiler corresponds
3304 to the version of the unit most recently compiled into the library.
3307 Inlining is effective only if the necessary body has already been
3308 compiled into the library.
3311 Compiling a unit may obsolete other units in the library.
3315 In GNAT, compiling one unit never affects the compilation of any other
3316 units because the compiler reads only source files. Only changes to source
3317 files can affect the results of a compilation. In particular:
3321 When a unit is @code{with}'ed, the unit seen by the compiler corresponds
3322 to the source version of the unit that is currently accessible to the
3327 Inlining requires the appropriate source files for the package or
3328 subprogram bodies to be available to the compiler. Inlining is always
3329 effective, independent of the order in which units are complied.
3332 Compiling a unit never affects any other compilations. The editing of
3333 sources may cause previous compilations to be out of date if they
3334 depended on the source file being modified.
3338 The most important result of these differences is that order of compilation
3339 is never significant in GNAT. There is no situation in which one is
3340 required to do one compilation before another. What shows up as order of
3341 compilation requirements in the traditional Ada library becomes, in
3342 GNAT, simple source dependencies; in other words, there is only a set
3343 of rules saying what source files must be present when a file is
3347 @node Placement of temporary files
3348 @section Placement of temporary files
3349 @cindex Temporary files (user control over placement)
3352 GNAT creates temporary files in the directory designated by the environment
3353 variable @env{TMPDIR}.
3354 (See the HP @emph{C RTL Reference Manual} on the function @code{getenv()}
3355 for detailed information on how environment variables are resolved.
3356 For most users the easiest way to make use of this feature is to simply
3357 define @env{TMPDIR} as a job level logical name).
3358 For example, if you wish to use a Ramdisk (assuming DECRAM is installed)
3359 for compiler temporary files, then you can include something like the
3360 following command in your @file{LOGIN.COM} file:
3363 $ define/job TMPDIR "/disk$scratchram/000000/temp/"
3367 If @env{TMPDIR} is not defined, then GNAT uses the directory designated by
3368 @env{TMP}; if @env{TMP} is not defined, then GNAT uses the directory
3369 designated by @env{TEMP}.
3370 If none of these environment variables are defined then GNAT uses the
3371 directory designated by the logical name @code{SYS$SCRATCH:}
3372 (by default the user's home directory). If all else fails
3373 GNAT uses the current directory for temporary files.
3376 @c *************************
3377 @node Compiling with gcc
3378 @chapter Compiling with @command{gcc}
3381 This chapter discusses how to compile Ada programs using the @command{gcc}
3382 command. It also describes the set of switches
3383 that can be used to control the behavior of the compiler.
3385 * Compiling Programs::
3386 * Switches for gcc::
3387 * Search Paths and the Run-Time Library (RTL)::
3388 * Order of Compilation Issues::
3392 @node Compiling Programs
3393 @section Compiling Programs
3396 The first step in creating an executable program is to compile the units
3397 of the program using the @command{gcc} command. You must compile the
3402 the body file (@file{.adb}) for a library level subprogram or generic
3406 the spec file (@file{.ads}) for a library level package or generic
3407 package that has no body
3410 the body file (@file{.adb}) for a library level package
3411 or generic package that has a body
3416 You need @emph{not} compile the following files
3421 the spec of a library unit which has a body
3428 because they are compiled as part of compiling related units. GNAT
3430 when the corresponding body is compiled, and subunits when the parent is
3433 @cindex cannot generate code
3434 If you attempt to compile any of these files, you will get one of the
3435 following error messages (where @var{fff} is the name of the file you
3439 cannot generate code for file @var{fff} (package spec)
3440 to check package spec, use -gnatc
3442 cannot generate code for file @var{fff} (missing subunits)
3443 to check parent unit, use -gnatc
3445 cannot generate code for file @var{fff} (subprogram spec)
3446 to check subprogram spec, use -gnatc
3448 cannot generate code for file @var{fff} (subunit)
3449 to check subunit, use -gnatc
3453 As indicated by the above error messages, if you want to submit
3454 one of these files to the compiler to check for correct semantics
3455 without generating code, then use the @option{-gnatc} switch.
3457 The basic command for compiling a file containing an Ada unit is
3460 @c $ gcc -c @ovar{switches} @file{file name}
3461 @c Expanding @ovar macro inline (explanation in macro def comments)
3462 $ gcc -c @r{[}@var{switches}@r{]} @file{file name}
3466 where @var{file name} is the name of the Ada file (usually
3468 @file{.ads} for a spec or @file{.adb} for a body).
3471 @option{-c} switch to tell @command{gcc} to compile, but not link, the file.
3473 The result of a successful compilation is an object file, which has the
3474 same name as the source file but an extension of @file{.o} and an Ada
3475 Library Information (ALI) file, which also has the same name as the
3476 source file, but with @file{.ali} as the extension. GNAT creates these
3477 two output files in the current directory, but you may specify a source
3478 file in any directory using an absolute or relative path specification
3479 containing the directory information.
3482 @command{gcc} is actually a driver program that looks at the extensions of
3483 the file arguments and loads the appropriate compiler. For example, the
3484 GNU C compiler is @file{cc1}, and the Ada compiler is @file{gnat1}.
3485 These programs are in directories known to the driver program (in some
3486 configurations via environment variables you set), but need not be in
3487 your path. The @command{gcc} driver also calls the assembler and any other
3488 utilities needed to complete the generation of the required object
3491 It is possible to supply several file names on the same @command{gcc}
3492 command. This causes @command{gcc} to call the appropriate compiler for
3493 each file. For example, the following command lists two separate
3494 files to be compiled:
3497 $ gcc -c x.adb y.adb
3501 calls @code{gnat1} (the Ada compiler) twice to compile @file{x.adb} and
3503 The compiler generates two object files @file{x.o} and @file{y.o}
3504 and the two ALI files @file{x.ali} and @file{y.ali}.
3505 Any switches apply to all the files ^listed,^listed.^
3507 @node Switches for gcc
3508 @section Switches for @command{gcc}
3511 The @command{gcc} command accepts switches that control the
3512 compilation process. These switches are fully described in this section.
3513 First we briefly list all the switches, in alphabetical order, then we
3514 describe the switches in more detail in functionally grouped sections.
3516 More switches exist for GCC than those documented here, especially
3517 for specific targets. However, their use is not recommended as
3518 they may change code generation in ways that are incompatible with
3519 the Ada run-time library, or can cause inconsistencies between
3523 * Output and Error Message Control::
3524 * Warning Message Control::
3525 * Debugging and Assertion Control::
3526 * Validity Checking::
3529 * Using gcc for Syntax Checking::
3530 * Using gcc for Semantic Checking::
3531 * Compiling Different Versions of Ada::
3532 * Character Set Control::
3533 * File Naming Control::
3534 * Subprogram Inlining Control::
3535 * Auxiliary Output Control::
3536 * Debugging Control::
3537 * Exception Handling Control::
3538 * Units to Sources Mapping Files::
3539 * Integrated Preprocessing::
3540 * Code Generation Control::
3549 @cindex @option{-b} (@command{gcc})
3550 @item -b @var{target}
3551 Compile your program to run on @var{target}, which is the name of a
3552 system configuration. You must have a GNAT cross-compiler built if
3553 @var{target} is not the same as your host system.
3556 @cindex @option{-B} (@command{gcc})
3557 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
3558 from @var{dir} instead of the default location. Only use this switch
3559 when multiple versions of the GNAT compiler are available.
3560 @xref{Directory Options,, Options for Directory Search, gcc, Using the
3561 GNU Compiler Collection (GCC)}, for further details. You would normally
3562 use the @option{-b} or @option{-V} switch instead.
3565 @cindex @option{-c} (@command{gcc})
3566 Compile. Always use this switch when compiling Ada programs.
3568 Note: for some other languages when using @command{gcc}, notably in
3569 the case of C and C++, it is possible to use
3570 use @command{gcc} without a @option{-c} switch to
3571 compile and link in one step. In the case of GNAT, you
3572 cannot use this approach, because the binder must be run
3573 and @command{gcc} cannot be used to run the GNAT binder.
3576 @item -fcallgraph-info@r{[}=su,da@r{]}
3577 @cindex @option{-fcallgraph-info} (@command{gcc})
3578 Makes the compiler output callgraph information for the program, on a
3579 per-file basis. The information is generated in the VCG format. It can
3580 be decorated with additional, per-node and/or per-edge information, if a
3581 list of comma-separated markers is additionally specified. When the
3582 @var{su} marker is specified, the callgraph is decorated with stack usage information; it is equivalent to @option{-fstack-usage}. When the @var{da}
3583 marker is specified, the callgraph is decorated with information about
3584 dynamically allocated objects.
3587 @cindex @option{-fdump-scos} (@command{gcc})
3588 Generates SCO (Source Coverage Obligation) information in the ALI file.
3589 This information is used by advanced coverage tools. See unit @file{SCOs}
3590 in the compiler sources for details in files @file{scos.ads} and
3594 @cindex @option{-fdump-xref} (@command{gcc})
3595 Generates cross reference information in GLI files for C and C++ sources.
3596 The GLI files have the same syntax as the ALI files for Ada, and can be used
3597 for source navigation in IDEs and on the command line using e.g. gnatxref
3598 and the @option{--ext=gli} switch.
3600 @item -flto@r{[}=n@r{]}
3601 @cindex @option{-flto} (@command{gcc})
3602 Enables Link Time Optimization. This switch must be used in conjunction
3603 with the traditional @option{-Ox} switches and instructs the compiler to
3604 defer most optimizations until the link stage. The advantage of this
3605 approach is that the compiler can do a whole-program analysis and choose
3606 the best interprocedural optimization strategy based on a complete view
3607 of the program, instead of a fragmentary view with the usual approach.
3608 This can also speed up the compilation of huge programs and reduce the
3609 size of the final executable, compared with a per-unit compilation with
3610 full inlining across modules enabled with the @option{-gnatn2} switch.
3611 The drawback of this approach is that it may require much more memory.
3612 The switch, as well as the accompanying @option{-Ox} switches, must be
3613 specified both for the compilation and the link phases.
3614 If the @var{n} parameter is specified, the optimization and final code
3615 generation at link time are executed using @var{n} parallel jobs by
3616 means of an installed @command{make} program.
3619 @cindex @option{-fno-inline} (@command{gcc})
3620 Suppresses all inlining, even if other optimization or inlining
3621 switches are set. This includes suppression of inlining that
3622 results from the use of the pragma @code{Inline_Always}.
3623 Any occurrences of pragma @code{Inline} or @code{Inline_Always}
3624 are ignored, and @option{-gnatn} and @option{-gnatN} have no
3625 effects if this switch is present. Note that inlining can also
3626 be suppressed on a finer-grained basis with pragma @code{No_Inline}.
3628 @item -fno-inline-functions
3629 @cindex @option{-fno-inline-functions} (@command{gcc})
3630 Suppresses automatic inlining of subprograms, which is enabled
3631 if @option{-O3} is used.
3633 @item -fno-inline-small-functions
3634 @cindex @option{-fno-inline-small-functions} (@command{gcc})
3635 Suppresses automatic inlining of small subprograms, which is enabled
3636 if @option{-O2} is used.
3638 @item -fno-inline-functions-called-once
3639 @cindex @option{-fno-inline-functions-called-once} (@command{gcc})
3640 Suppresses inlining of subprograms local to the unit and called once
3641 from within it, which is enabled if @option{-O1} is used.
3644 @cindex @option{-fno-ivopts} (@command{gcc})
3645 Suppresses high-level loop induction variable optimizations, which are
3646 enabled if @option{-O1} is used. These optimizations are generally
3647 profitable but, for some specific cases of loops with numerous uses
3648 of the iteration variable that follow a common pattern, they may end
3649 up destroying the regularity that could be exploited at a lower level
3650 and thus producing inferior code.
3652 @item -fno-strict-aliasing
3653 @cindex @option{-fno-strict-aliasing} (@command{gcc})
3654 Causes the compiler to avoid assumptions regarding non-aliasing
3655 of objects of different types. See
3656 @ref{Optimization and Strict Aliasing} for details.
3659 @cindex @option{-fstack-check} (@command{gcc})
3660 Activates stack checking.
3661 See @ref{Stack Overflow Checking} for details.
3664 @cindex @option{-fstack-usage} (@command{gcc})
3665 Makes the compiler output stack usage information for the program, on a
3666 per-subprogram basis. See @ref{Static Stack Usage Analysis} for details.
3669 @cindex @option{^-g^/DEBUG^} (@command{gcc})
3670 Generate debugging information. This information is stored in the object
3671 file and copied from there to the final executable file by the linker,
3672 where it can be read by the debugger. You must use the
3673 @option{^-g^/DEBUG^} switch if you plan on using the debugger.
3676 @cindex @option{-gnat83} (@command{gcc})
3677 Enforce Ada 83 restrictions.
3680 @cindex @option{-gnat95} (@command{gcc})
3681 Enforce Ada 95 restrictions.
3684 @cindex @option{-gnat05} (@command{gcc})
3685 Allow full Ada 2005 features.
3688 @cindex @option{-gnat2005} (@command{gcc})
3689 Allow full Ada 2005 features (same as @option{-gnat05})
3692 @cindex @option{-gnat12} (@command{gcc})
3695 @cindex @option{-gnat2012} (@command{gcc})
3696 Allow full Ada 2012 features (same as @option{-gnat12})
3699 @cindex @option{-gnata} (@command{gcc})
3700 Assertions enabled. @code{Pragma Assert} and @code{pragma Debug} to be
3701 activated. Note that these pragmas can also be controlled using the
3702 configuration pragmas @code{Assertion_Policy} and @code{Debug_Policy}.
3703 It also activates pragmas @code{Check}, @code{Precondition}, and
3704 @code{Postcondition}. Note that these pragmas can also be controlled
3705 using the configuration pragma @code{Check_Policy}. In Ada 2012, it
3706 also activates all assertions defined in the RM as aspects: preconditions,
3707 postconditions, type invariants and (sub)type predicates. In all Ada modes,
3708 corresponding pragmas for type invariants and (sub)type predicates are
3712 @cindex @option{-gnatA} (@command{gcc})
3713 Avoid processing @file{gnat.adc}. If a @file{gnat.adc} file is present,
3717 @cindex @option{-gnatb} (@command{gcc})
3718 Generate brief messages to @file{stderr} even if verbose mode set.
3721 @cindex @option{-gnatB} (@command{gcc})
3722 Assume no invalid (bad) values except for 'Valid attribute use
3723 (@pxref{Validity Checking}).
3726 @cindex @option{-gnatc} (@command{gcc})
3727 Check syntax and semantics only (no code generation attempted). When the
3728 compiler is invoked by @command{gnatmake}, if the switch @option{-gnatc} is
3729 only given to the compiler (after @option{-cargs} or in package Compiler of
3730 the project file, @command{gnatmake} will fail because it will not find the
3731 object file after compilation. If @command{gnatmake} is called with
3732 @option{-gnatc} as a builder switch (before @option{-cargs} or in package
3733 Builder of the project file) then @command{gnatmake} will not fail because
3734 it will not look for the object files after compilation, and it will not try
3735 to build and link. This switch may not be given if a previous @code{-gnatR}
3736 switch has been given, since @code{-gnatR} requires that the code generator
3737 be called to complete determination of representation information.
3740 @cindex @option{-gnatC} (@command{gcc})
3741 Generate CodePeer intermediate format (no code generation attempted).
3742 This switch will generate an intermediate representation suitable for
3743 use by CodePeer (@file{.scil} files). This switch is not compatible with
3744 code generation (it will, among other things, disable some switches such
3745 as -gnatn, and enable others such as -gnata).
3748 @cindex @option{-gnatd} (@command{gcc})
3749 Specify debug options for the compiler. The string of characters after
3750 the @option{-gnatd} specify the specific debug options. The possible
3751 characters are 0-9, a-z, A-Z, optionally preceded by a dot. See
3752 compiler source file @file{debug.adb} for details of the implemented
3753 debug options. Certain debug options are relevant to applications
3754 programmers, and these are documented at appropriate points in this
3759 @cindex @option{-gnatD[nn]} (@command{gcc})
3762 @item /XDEBUG /LXDEBUG=nnn
3764 Create expanded source files for source level debugging. This switch
3765 also suppress generation of cross-reference information
3766 (see @option{-gnatx}). Note that this switch is not allowed if a previous
3767 -gnatR switch has been given, since these two switches are not compatible.
3769 @item ^-gnateA^/ALIASING_CHECK^
3770 @cindex @option{-gnateA} (@command{gcc})
3771 Check that there is no aliasing between two parameters of the same subprogram.
3773 @item -gnatec=@var{path}
3774 @cindex @option{-gnatec} (@command{gcc})
3775 Specify a configuration pragma file
3777 (the equal sign is optional)
3779 (@pxref{The Configuration Pragmas Files}).
3782 @cindex @option{-gnateC} (@command{gcc})
3783 Generate CodePeer messages in a compiler-like format. This switch is only
3784 effective if @option{-gnatcC} is also specified and requires an installation
3787 @item ^-gnated^/DISABLE_ATOMIC_SYNCHRONIZATION^
3788 @cindex @option{-gnated} (@command{gcc})
3789 Disable atomic synchronization
3791 @item ^-gnateD^/DATA_PREPROCESSING=^symbol@r{[}=@var{value}@r{]}
3792 @cindex @option{-gnateD} (@command{gcc})
3793 Defines a symbol, associated with @var{value}, for preprocessing.
3794 (@pxref{Integrated Preprocessing}).
3797 @cindex @option{-gnateE} (@command{gcc})
3798 Generate extra information in exception messages. In particular, display
3799 extra column information and the value and range associated with index and
3800 range check failures, and extra column information for access checks.
3801 In cases where the compiler is able to determine at compile time that
3802 a check will fail, it gives a warning, and the extra information is not
3803 produced at run time.
3806 @cindex @option{-gnatef} (@command{gcc})
3807 Display full source path name in brief error messages.
3810 @cindex @option{-gnateF} (@command{gcc})
3811 Check for overflow on all floating-point operations, including those
3812 for unconstrained predefined types. See description of pragma
3813 @code{Check_Float_Overflow} in GNAT RM.
3816 @cindex @option{-gnateG} (@command{gcc})
3817 Save result of preprocessing in a text file.
3819 @item -gnatei@var{nnn}
3820 @cindex @option{-gnatei} (@command{gcc})
3821 Set maximum number of instantiations during compilation of a single unit to
3822 @var{nnn}. This may be useful in increasing the default maximum of 8000 for
3823 the rare case when a single unit legitimately exceeds this limit.
3825 @item -gnateI@var{nnn}
3826 @cindex @option{-gnateI} (@command{gcc})
3827 Indicates that the source is a multi-unit source and that the index of the
3828 unit to compile is @var{nnn}. @var{nnn} needs to be a positive number and need
3829 to be a valid index in the multi-unit source.
3832 @cindex @option{-gnatel} (@command{gcc})
3833 This switch can be used with the static elaboration model to issue info
3835 where implicit @code{pragma Elaborate} and @code{pragma Elaborate_All}
3836 are generated. This is useful in diagnosing elaboration circularities
3837 caused by these implicit pragmas when using the static elaboration
3838 model. See See the section in this guide on elaboration checking for
3839 further details. These messages are not generated by default, and are
3840 intended only for temporary use when debugging circularity problems.
3843 @cindex @option{-gnatel} (@command{gcc})
3844 This switch turns off the info messages about implicit elaboration pragmas.
3846 @item -gnatem=@var{path}
3847 @cindex @option{-gnatem} (@command{gcc})
3848 Specify a mapping file
3850 (the equal sign is optional)
3852 (@pxref{Units to Sources Mapping Files}).
3854 @item -gnatep=@var{file}
3855 @cindex @option{-gnatep} (@command{gcc})
3856 Specify a preprocessing data file
3858 (the equal sign is optional)
3860 (@pxref{Integrated Preprocessing}).
3863 @cindex @option{-gnateP} (@command{gcc})
3864 Turn categorization dependency errors into warnings.
3865 Ada requires that units that WITH one another have compatible categories, for
3866 example a Pure unit cannot WITH a Preelaborate unit. If this switch is used,
3867 these errors become warnings (which can be ignored, or suppressed in the usual
3868 manner). This can be useful in some specialized circumstances such as the
3869 temporary use of special test software.
3872 @cindex @option{-gnateS} (@command{gcc})
3873 Synonym of @option{-fdump-scos}, kept for backwards compatibility.
3875 @item -gnatet=@var{path}
3876 @cindex @option{-gnatet=file} (@command{gcc})
3877 Generate target dependent information. The format of the output file is
3878 described in the section about switch @option{-gnateT}.
3880 @item -gnateT=@var{path}
3881 @cindex @option{-gnateT} (@command{gcc})
3882 Read target dependent information, such as endianness or sizes and alignments
3883 of base type. If this switch is passed, the default target dependent
3884 information of the compiler is replaced by the one read from the input file.
3885 This is used by tools other than the compiler, e.g. to do
3886 semantic analysis of programs that will run on some other target than
3887 the machine on which the tool is run.
3889 The following target dependent values should be defined,
3890 where @code{Nat} denotes a natural integer value, @code{Pos} denotes a
3891 positive integer value, and fields marked with a question mark are
3892 boolean fields, where a value of 0 is False, and a value of 1 is True:
3895 Bits_BE : Nat; -- Bits stored big-endian?
3896 Bits_Per_Unit : Pos; -- Bits in a storage unit
3897 Bits_Per_Word : Pos; -- Bits in a word
3898 Bytes_BE : Nat; -- Bytes stored big-endian?
3899 Char_Size : Pos; -- Standard.Character'Size
3900 Double_Float_Alignment : Nat; -- Alignment of double float
3901 Double_Scalar_Alignment : Nat; -- Alignment of double length scalar
3902 Double_Size : Pos; -- Standard.Long_Float'Size
3903 Float_Size : Pos; -- Standard.Float'Size
3904 Float_Words_BE : Nat; -- Float words stored big-endian?
3905 Int_Size : Pos; -- Standard.Integer'Size
3906 Long_Double_Size : Pos; -- Standard.Long_Long_Float'Size
3907 Long_Long_Size : Pos; -- Standard.Long_Long_Integer'Size
3908 Long_Size : Pos; -- Standard.Long_Integer'Size
3909 Maximum_Alignment : Pos; -- Maximum permitted alignment
3910 Max_Unaligned_Field : Pos; -- Maximum size for unaligned bit field
3911 Pointer_Size : Pos; -- System.Address'Size
3912 Short_Enums : Nat; -- Short foreign convention enums?
3913 Short_Size : Pos; -- Standard.Short_Integer'Size
3914 Strict_Alignment : Nat; -- Strict alignment?
3915 System_Allocator_Alignment : Nat; -- Alignment for malloc calls
3916 Wchar_T_Size : Pos; -- Interfaces.C.wchar_t'Size
3917 Words_BE : Nat; -- Words stored big-endian?
3920 The format of the input file is as follows. First come the values of
3921 the variables defined above, with one line per value:
3927 where @code{name} is the name of the parameter, spelled out in full,
3928 and cased as in the above list, and @code{value} is an unsigned decimal
3929 integer. Two or more blanks separates the name from the value.
3931 All the variables must be present, in alphabetical order (i.e. the
3932 same order as the list above).
3934 Then there is a blank line to separate the two parts of the file. Then
3935 come the lines showing the floating-point types to be registered, with
3936 one line per registered mode:
3939 name digs float_rep size alignment
3942 where @code{name} is the string name of the type (which can have
3943 single spaces embedded in the name (e.g. long double), @code{digs} is
3944 the number of digits for the floating-point type, @code{float_rep} is
3945 the float representation (I/V/A for IEEE-754-Binary, Vax_Native,
3946 AAMP), @code{size} is the size in bits, @code{alignment} is the
3947 alignment in bits. The name is followed by at least two blanks, fields
3948 are separated by at least one blank, and a LF character immediately
3949 follows the alignment field.
3951 Here is an example of a target parameterization file:
3959 Double_Float_Alignment 0
3960 Double_Scalar_Alignment 0
3965 Long_Double_Size 128
3968 Maximum_Alignment 16
3969 Max_Unaligned_Field 64
3973 System_Allocator_Alignment 16
3979 long double 18 I 80 128
3984 @cindex @option{-gnateu} (@command{gcc})
3985 Ignore unrecognized validity, warning, and style switches that
3986 appear after this switch is given. This may be useful when
3987 compiling sources developed on a later version of the compiler
3988 with an earlier version. Of course the earlier version must
3989 support this switch.
3991 @item ^-gnateV^/PARAMETER_VALIDITY_CHECK^
3992 @cindex @option{-gnateV} (@command{gcc})
3993 Check validity of subprogram parameters.
3995 @item ^-gnateY^/IGNORE_SUPPRESS_SYLE_CHECK_PRAGMAS^
3996 @cindex @option{-gnateY} (@command{gcc})
3997 Ignore all STYLE_CHECKS pragmas. Full legality checks
3998 are still carried out, but the pragmas have no effect
3999 on what style checks are active. This allows all style
4000 checking options to be controlled from the command line.
4003 @cindex @option{-gnatE} (@command{gcc})
4004 Full dynamic elaboration checks.
4007 @cindex @option{-gnatf} (@command{gcc})
4008 Full errors. Multiple errors per line, all undefined references, do not
4009 attempt to suppress cascaded errors.
4012 @cindex @option{-gnatF} (@command{gcc})
4013 Externals names are folded to all uppercase.
4015 @item ^-gnatg^/GNAT_INTERNAL^
4016 @cindex @option{^-gnatg^/GNAT_INTERNAL^} (@command{gcc})
4017 Internal GNAT implementation mode. This should not be used for
4018 applications programs, it is intended only for use by the compiler
4019 and its run-time library. For documentation, see the GNAT sources.
4020 Note that @option{^-gnatg^/GNAT_INTERNAL^} implies
4021 @option{^-gnatw.ge^/WARNINGS=GNAT,ERRORS^} and
4022 @option{^-gnatyg^/STYLE_CHECKS=GNAT^}
4023 so that all standard warnings and all standard style options are turned on.
4024 All warnings and style messages are treated as errors.
4028 @cindex @option{-gnatG[nn]} (@command{gcc})
4031 @item /EXPAND_SOURCE, /LEXPAND_SOURCE=nnn
4033 List generated expanded code in source form.
4035 @item ^-gnath^/HELP^
4036 @cindex @option{^-gnath^/HELP^} (@command{gcc})
4037 Output usage information. The output is written to @file{stdout}.
4039 @item ^-gnati^/IDENTIFIER_CHARACTER_SET=^@var{c}
4040 @cindex @option{^-gnati^/IDENTIFIER_CHARACTER_SET^} (@command{gcc})
4041 Identifier character set
4043 (@var{c}=1/2/3/4/8/9/p/f/n/w).
4045 For details of the possible selections for @var{c},
4046 see @ref{Character Set Control}.
4048 @item ^-gnatI^/IGNORE_REP_CLAUSES^
4049 @cindex @option{^-gnatI^IGNORE_REP_CLAUSES^} (@command{gcc})
4050 Ignore representation clauses. When this switch is used,
4051 representation clauses are treated as comments. This is useful
4052 when initially porting code where you want to ignore rep clause
4053 problems, and also for compiling foreign code (particularly
4054 for use with ASIS). The representation clauses that are ignored
4055 are: enumeration_representation_clause, record_representation_clause,
4056 and attribute_definition_clause for the following attributes:
4057 Address, Alignment, Bit_Order, Component_Size, Machine_Radix,
4058 Object_Size, Size, Small, Stream_Size, and Value_Size.
4059 Note that this option should be used only for compiling -- the
4060 code is likely to malfunction at run time.
4063 @cindex @option{-gnatjnn} (@command{gcc})
4064 Reformat error messages to fit on nn character lines
4066 @item -gnatk=@var{n}
4067 @cindex @option{-gnatk} (@command{gcc})
4068 Limit file names to @var{n} (1-999) characters ^(@code{k} = krunch)^^.
4071 @cindex @option{-gnatl} (@command{gcc})
4072 Output full source listing with embedded error messages.
4075 @cindex @option{-gnatL} (@command{gcc})
4076 Used in conjunction with -gnatG or -gnatD to intersperse original
4077 source lines (as comment lines with line numbers) in the expanded
4080 @item -gnatm=@var{n}
4081 @cindex @option{-gnatm} (@command{gcc})
4082 Limit number of detected error or warning messages to @var{n}
4083 where @var{n} is in the range 1..999999. The default setting if
4084 no switch is given is 9999. If the number of warnings reaches this
4085 limit, then a message is output and further warnings are suppressed,
4086 but the compilation is continued. If the number of error messages
4087 reaches this limit, then a message is output and the compilation
4088 is abandoned. The equal sign here is optional. A value of zero
4089 means that no limit applies.
4092 @cindex @option{-gnatn} (@command{gcc})
4093 Activate inlining for subprograms for which pragma @code{Inline} is
4094 specified. This inlining is performed by the GCC back-end. An optional
4095 digit sets the inlining level: 1 for moderate inlining across modules
4096 or 2 for full inlining across modules. If no inlining level is specified,
4097 the compiler will pick it based on the optimization level.
4100 @cindex @option{-gnatN} (@command{gcc})
4101 Activate front end inlining for subprograms for which
4102 pragma @code{Inline} is specified. This inlining is performed
4103 by the front end and will be visible in the
4104 @option{-gnatG} output.
4106 When using a gcc-based back end (in practice this means using any version
4107 of GNAT other than the JGNAT, .NET or GNAAMP versions), then the use of
4108 @option{-gnatN} is deprecated, and the use of @option{-gnatn} is preferred.
4109 Historically front end inlining was more extensive than the gcc back end
4110 inlining, but that is no longer the case.
4113 @cindex @option{-gnato??} (@command{gcc})
4114 Set default mode for handling generation of code to avoid intermediate
4115 arithmetic overflow. Here `@code{??}' is two digits, a
4116 single digit, or nothing. Each digit is one of the digits `@code{1}'
4121 all intermediate overflows checked against base type (@code{STRICT})
4123 minimize intermediate overflows (@code{MINIMIZED})
4125 eliminate intermediate overflows (@code{ELIMINATED})
4128 If only one digit appears then it applies to all
4129 cases; if two digits are given, then the first applies outside
4130 assertions, and the second within assertions.
4132 If no digits follow the @option{-gnato}, then it is equivalent to
4133 @option{^-gnato11^/OVERFLOW_CHECKS=11^},
4134 causing all intermediate overflows to be handled in strict mode.
4136 This switch also causes arithmetic overflow checking to be performed
4137 (as though pragma @code{Unsuppress (Overflow_Mode)} has been specified.
4139 The default if no option @option{-gnato} is given is that overflow handling
4140 is in @code{STRICT} mode (computations done using the base type), and that
4141 overflow checking is suppressed.
4143 Note that division by zero is a separate check that is not
4144 controlled by this switch (division by zero checking is on by default).
4146 See also @ref{Specifying the Desired Mode}.
4149 @cindex @option{-gnatp} (@command{gcc})
4150 Suppress all checks. See @ref{Run-Time Checks} for details. This switch
4151 has no effect if cancelled by a subsequent @option{-gnat-p} switch.
4154 @cindex @option{-gnat-p} (@command{gcc})
4155 Cancel effect of previous @option{-gnatp} switch.
4158 @cindex @option{-gnatP} (@command{gcc})
4159 Enable polling. This is required on some systems (notably Windows NT) to
4160 obtain asynchronous abort and asynchronous transfer of control capability.
4161 @xref{Pragma Polling,,, gnat_rm, GNAT Reference Manual}, for full
4165 @cindex @option{-gnatq} (@command{gcc})
4166 Don't quit. Try semantics, even if parse errors.
4169 @cindex @option{-gnatQ} (@command{gcc})
4170 Don't quit. Generate @file{ALI} and tree files even if illegalities.
4173 @cindex @option{-gnatr} (@command{gcc})
4174 Treat pragma Restrictions as Restriction_Warnings.
4176 @item ^-gnatR@r{[}0@r{/}1@r{/}2@r{/}3@r{[}s@r{]]}^/REPRESENTATION_INFO^
4177 @cindex @option{-gnatR} (@command{gcc})
4178 Output representation information for declared types and objects.
4179 Note that this switch is not allowed if a previous @code{-gnatD} switch has
4180 been given, since these two switches are not compatible. It is also not allowed
4181 if a previous @code{-gnatc} switch has been given, since we must be generating
4182 code to be able to determine representation information.
4184 @item ^-gnatRm[s]^/REPRESENTATION_INFO^
4185 Output convention and parameter passing mechanisms for all subprograms.
4186 This form is also incompatible with the use of @code{-gnatc}.
4189 @cindex @option{-gnats} (@command{gcc})
4193 @cindex @option{-gnatS} (@command{gcc})
4194 Print package Standard.
4197 @cindex @option{-gnatt} (@command{gcc})
4198 Generate tree output file.
4200 @item ^-gnatT^/TABLE_MULTIPLIER=^@var{nnn}
4201 @cindex @option{^-gnatT^/TABLE_MULTIPLIER^} (@command{gcc})
4202 All compiler tables start at @var{nnn} times usual starting size.
4205 @cindex @option{-gnatu} (@command{gcc})
4206 List units for this compilation.
4209 @cindex @option{-gnatU} (@command{gcc})
4210 Tag all error messages with the unique string ``error:''
4213 @cindex @option{-gnatv} (@command{gcc})
4214 Verbose mode. Full error output with source lines to @file{stdout}.
4217 @cindex @option{-gnatV} (@command{gcc})
4218 Control level of validity checking (@pxref{Validity Checking}).
4220 @item ^-gnatw@var{xxx}^/WARNINGS=(@var{option}@r{[},@dots{}@r{]})^
4221 @cindex @option{^-gnatw^/WARNINGS^} (@command{gcc})
4223 ^@var{xxx} is a string of option letters that^the list of options^ denotes
4224 the exact warnings that
4225 are enabled or disabled (@pxref{Warning Message Control}).
4227 @item ^-gnatW^/WIDE_CHARACTER_ENCODING=^@var{e}
4228 @cindex @option{^-gnatW^/WIDE_CHARACTER_ENCODING^} (@command{gcc})
4229 Wide character encoding method
4231 (@var{e}=n/h/u/s/e/8).
4234 (@var{e}=@code{BRACKETS, NONE, HEX, UPPER, SHIFT_JIS, EUC, UTF8})
4238 @cindex @option{-gnatx} (@command{gcc})
4239 Suppress generation of cross-reference information.
4242 @cindex @option{-gnatX} (@command{gcc})
4243 Enable GNAT implementation extensions and latest Ada version.
4245 @item ^-gnaty^/STYLE_CHECKS=(option,option@dots{})^
4246 @cindex @option{^-gnaty^/STYLE_CHECKS^} (@command{gcc})
4247 Enable built-in style checks (@pxref{Style Checking}).
4249 @item ^-gnatz^/DISTRIBUTION_STUBS=^@var{m}
4250 @cindex @option{^-gnatz^/DISTRIBUTION_STUBS^} (@command{gcc})
4251 Distribution stub generation and compilation
4253 (@var{m}=r/c for receiver/caller stubs).
4256 (@var{m}=@code{RECEIVER} or @code{CALLER} to specify the type of stubs
4257 to be generated and compiled).
4260 @item ^-I^/SEARCH=^@var{dir}
4261 @cindex @option{^-I^/SEARCH^} (@command{gcc})
4263 Direct GNAT to search the @var{dir} directory for source files needed by
4264 the current compilation
4265 (@pxref{Search Paths and the Run-Time Library (RTL)}).
4267 @item ^-I-^/NOCURRENT_DIRECTORY^
4268 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gcc})
4270 Except for the source file named in the command line, do not look for source
4271 files in the directory containing the source file named in the command line
4272 (@pxref{Search Paths and the Run-Time Library (RTL)}).
4276 @cindex @option{-mbig-switch} (@command{gcc})
4277 @cindex @code{case} statement (effect of @option{-mbig-switch} option)
4278 This standard gcc switch causes the compiler to use larger offsets in its
4279 jump table representation for @code{case} statements.
4280 This may result in less efficient code, but is sometimes necessary
4281 (for example on HP-UX targets)
4282 @cindex HP-UX and @option{-mbig-switch} option
4283 in order to compile large and/or nested @code{case} statements.
4286 @cindex @option{-o} (@command{gcc})
4287 This switch is used in @command{gcc} to redirect the generated object file
4288 and its associated ALI file. Beware of this switch with GNAT, because it may
4289 cause the object file and ALI file to have different names which in turn
4290 may confuse the binder and the linker.
4294 @cindex @option{-nostdinc} (@command{gcc})
4295 Inhibit the search of the default location for the GNAT Run Time
4296 Library (RTL) source files.
4299 @cindex @option{-nostdlib} (@command{gcc})
4300 Inhibit the search of the default location for the GNAT Run Time
4301 Library (RTL) ALI files.
4305 @c Expanding @ovar macro inline (explanation in macro def comments)
4306 @item -O@r{[}@var{n}@r{]}
4307 @cindex @option{-O} (@command{gcc})
4308 @var{n} controls the optimization level.
4312 No optimization, the default setting if no @option{-O} appears
4315 Normal optimization, the default if you specify @option{-O} without
4316 an operand. A good compromise between code quality and compilation
4320 Extensive optimization, may improve execution time, possibly at the cost of
4321 substantially increased compilation time.
4324 Same as @option{-O2}, and also includes inline expansion for small subprograms
4328 Optimize space usage
4332 See also @ref{Optimization Levels}.
4337 @cindex @option{/NOOPTIMIZE} (@code{GNAT COMPILE})
4338 Equivalent to @option{/OPTIMIZE=NONE}.
4339 This is the default behavior in the absence of an @option{/OPTIMIZE}
4342 @item /OPTIMIZE@r{[}=(keyword@r{[},@dots{}@r{]})@r{]}
4343 @cindex @option{/OPTIMIZE} (@code{GNAT COMPILE})
4344 Selects the level of optimization for your program. The supported
4345 keywords are as follows:
4348 Perform most optimizations, including those that
4350 This is the default if the @option{/OPTIMIZE} qualifier is supplied
4351 without keyword options.
4354 Do not do any optimizations. Same as @code{/NOOPTIMIZE}.
4357 Perform some optimizations, but omit ones that are costly.
4360 Same as @code{SOME}.
4363 Full optimization as in @option{/OPTIMIZE=ALL}, and also attempts
4364 automatic inlining of small subprograms within a unit
4367 Try to unroll loops. This keyword may be specified together with
4368 any keyword above other than @code{NONE}. Loop unrolling
4369 usually, but not always, improves the performance of programs.
4372 Optimize space usage
4376 See also @ref{Optimization Levels}.
4380 @item -pass-exit-codes
4381 @cindex @option{-pass-exit-codes} (@command{gcc})
4382 Catch exit codes from the compiler and use the most meaningful as
4386 @item --RTS=@var{rts-path}
4387 @cindex @option{--RTS} (@command{gcc})
4388 Specifies the default location of the runtime library. Same meaning as the
4389 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
4392 @cindex @option{^-S^/ASM^} (@command{gcc})
4393 ^Used in place of @option{-c} to^Used to^
4394 cause the assembler source file to be
4395 generated, using @file{^.s^.S^} as the extension,
4396 instead of the object file.
4397 This may be useful if you need to examine the generated assembly code.
4399 @item ^-fverbose-asm^/VERBOSE_ASM^
4400 @cindex @option{^-fverbose-asm^/VERBOSE_ASM^} (@command{gcc})
4401 ^Used in conjunction with @option{-S}^Used in place of @option{/ASM}^
4402 to cause the generated assembly code file to be annotated with variable
4403 names, making it significantly easier to follow.
4406 @cindex @option{^-v^/VERBOSE^} (@command{gcc})
4407 Show commands generated by the @command{gcc} driver. Normally used only for
4408 debugging purposes or if you need to be sure what version of the
4409 compiler you are executing.
4413 @cindex @option{-V} (@command{gcc})
4414 Execute @var{ver} version of the compiler. This is the @command{gcc}
4415 version, not the GNAT version.
4418 @item ^-w^/NO_BACK_END_WARNINGS^
4419 @cindex @option{-w} (@command{gcc})
4420 Turn off warnings generated by the back end of the compiler. Use of
4421 this switch also causes the default for front end warnings to be set
4422 to suppress (as though @option{-gnatws} had appeared at the start of
4428 @c Combining qualifiers does not work on VMS
4429 You may combine a sequence of GNAT switches into a single switch. For
4430 example, the combined switch
4432 @cindex Combining GNAT switches
4438 is equivalent to specifying the following sequence of switches:
4441 -gnato -gnatf -gnati3
4446 The following restrictions apply to the combination of switches
4451 The switch @option{-gnatc} if combined with other switches must come
4452 first in the string.
4455 The switch @option{-gnats} if combined with other switches must come
4456 first in the string.
4460 ^^@option{/DISTRIBUTION_STUBS=},^
4461 @option{-gnatzc} and @option{-gnatzr} may not be combined with any other
4462 switches, and only one of them may appear in the command line.
4465 The switch @option{-gnat-p} may not be combined with any other switch.
4469 Once a ``y'' appears in the string (that is a use of the @option{-gnaty}
4470 switch), then all further characters in the switch are interpreted
4471 as style modifiers (see description of @option{-gnaty}).
4474 Once a ``d'' appears in the string (that is a use of the @option{-gnatd}
4475 switch), then all further characters in the switch are interpreted
4476 as debug flags (see description of @option{-gnatd}).
4479 Once a ``w'' appears in the string (that is a use of the @option{-gnatw}
4480 switch), then all further characters in the switch are interpreted
4481 as warning mode modifiers (see description of @option{-gnatw}).
4484 Once a ``V'' appears in the string (that is a use of the @option{-gnatV}
4485 switch), then all further characters in the switch are interpreted
4486 as validity checking options (@pxref{Validity Checking}).
4489 Option ``em'', ``ec'', ``ep'', ``l='' and ``R'' must be the last options in
4490 a combined list of options.
4494 @node Output and Error Message Control
4495 @subsection Output and Error Message Control
4499 The standard default format for error messages is called ``brief format''.
4500 Brief format messages are written to @file{stderr} (the standard error
4501 file) and have the following form:
4504 e.adb:3:04: Incorrect spelling of keyword "function"
4505 e.adb:4:20: ";" should be "is"
4509 The first integer after the file name is the line number in the file,
4510 and the second integer is the column number within the line.
4512 @code{GPS} can parse the error messages
4513 and point to the referenced character.
4515 The following switches provide control over the error message
4521 @cindex @option{-gnatv} (@command{gcc})
4524 The v stands for verbose.
4526 The effect of this setting is to write long-format error
4527 messages to @file{stdout} (the standard output file.
4528 The same program compiled with the
4529 @option{-gnatv} switch would generate:
4533 3. funcion X (Q : Integer)
4535 >>> Incorrect spelling of keyword "function"
4538 >>> ";" should be "is"
4543 The vertical bar indicates the location of the error, and the @samp{>>>}
4544 prefix can be used to search for error messages. When this switch is
4545 used the only source lines output are those with errors.
4548 @cindex @option{-gnatl} (@command{gcc})
4550 The @code{l} stands for list.
4552 This switch causes a full listing of
4553 the file to be generated. In the case where a body is
4554 compiled, the corresponding spec is also listed, along
4555 with any subunits. Typical output from compiling a package
4556 body @file{p.adb} might look like:
4558 @smallexample @c ada
4562 1. package body p is
4564 3. procedure a is separate;
4575 2. pragma Elaborate_Body
4599 When you specify the @option{-gnatv} or @option{-gnatl} switches and
4600 standard output is redirected, a brief summary is written to
4601 @file{stderr} (standard error) giving the number of error messages and
4602 warning messages generated.
4604 @item ^-gnatl^/OUTPUT_FILE^=file
4605 @cindex @option{^-gnatl^/OUTPUT_FILE^=fname} (@command{gcc})
4606 This has the same effect as @option{-gnatl} except that the output is
4607 written to a file instead of to standard output. If the given name
4608 @file{fname} does not start with a period, then it is the full name
4609 of the file to be written. If @file{fname} is an extension, it is
4610 appended to the name of the file being compiled. For example, if
4611 file @file{xyz.adb} is compiled with @option{^-gnatl^/OUTPUT_FILE^=.lst},
4612 then the output is written to file ^xyz.adb.lst^xyz.adb_lst^.
4615 @cindex @option{-gnatU} (@command{gcc})
4616 This switch forces all error messages to be preceded by the unique
4617 string ``error:''. This means that error messages take a few more
4618 characters in space, but allows easy searching for and identification
4622 @cindex @option{-gnatb} (@command{gcc})
4624 The @code{b} stands for brief.
4626 This switch causes GNAT to generate the
4627 brief format error messages to @file{stderr} (the standard error
4628 file) as well as the verbose
4629 format message or full listing (which as usual is written to
4630 @file{stdout} (the standard output file).
4632 @item -gnatm=@var{n}
4633 @cindex @option{-gnatm} (@command{gcc})
4635 The @code{m} stands for maximum.
4637 @var{n} is a decimal integer in the
4638 range of 1 to 999999 and limits the number of error or warning
4639 messages to be generated. For example, using
4640 @option{-gnatm2} might yield
4643 e.adb:3:04: Incorrect spelling of keyword "function"
4644 e.adb:5:35: missing ".."
4645 fatal error: maximum number of errors detected
4646 compilation abandoned
4650 The default setting if
4651 no switch is given is 9999. If the number of warnings reaches this
4652 limit, then a message is output and further warnings are suppressed,
4653 but the compilation is continued. If the number of error messages
4654 reaches this limit, then a message is output and the compilation
4655 is abandoned. A value of zero means that no limit applies.
4658 Note that the equal sign is optional, so the switches
4659 @option{-gnatm2} and @option{-gnatm=2} are equivalent.
4662 @cindex @option{-gnatf} (@command{gcc})
4663 @cindex Error messages, suppressing
4665 The @code{f} stands for full.
4667 Normally, the compiler suppresses error messages that are likely to be
4668 redundant. This switch causes all error
4669 messages to be generated. In particular, in the case of
4670 references to undefined variables. If a given variable is referenced
4671 several times, the normal format of messages is
4673 e.adb:7:07: "V" is undefined (more references follow)
4677 where the parenthetical comment warns that there are additional
4678 references to the variable @code{V}. Compiling the same program with the
4679 @option{-gnatf} switch yields
4682 e.adb:7:07: "V" is undefined
4683 e.adb:8:07: "V" is undefined
4684 e.adb:8:12: "V" is undefined
4685 e.adb:8:16: "V" is undefined
4686 e.adb:9:07: "V" is undefined
4687 e.adb:9:12: "V" is undefined
4691 The @option{-gnatf} switch also generates additional information for
4692 some error messages. Some examples are:
4696 Details on possibly non-portable unchecked conversion
4698 List possible interpretations for ambiguous calls
4700 Additional details on incorrect parameters
4704 @cindex @option{-gnatjnn} (@command{gcc})
4705 In normal operation mode (or if @option{-gnatj0} is used), then error messages
4706 with continuation lines are treated as though the continuation lines were
4707 separate messages (and so a warning with two continuation lines counts as
4708 three warnings, and is listed as three separate messages).
4710 If the @option{-gnatjnn} switch is used with a positive value for nn, then
4711 messages are output in a different manner. A message and all its continuation
4712 lines are treated as a unit, and count as only one warning or message in the
4713 statistics totals. Furthermore, the message is reformatted so that no line
4714 is longer than nn characters.
4717 @cindex @option{-gnatq} (@command{gcc})
4719 The @code{q} stands for quit (really ``don't quit'').
4721 In normal operation mode, the compiler first parses the program and
4722 determines if there are any syntax errors. If there are, appropriate
4723 error messages are generated and compilation is immediately terminated.
4725 GNAT to continue with semantic analysis even if syntax errors have been
4726 found. This may enable the detection of more errors in a single run. On
4727 the other hand, the semantic analyzer is more likely to encounter some
4728 internal fatal error when given a syntactically invalid tree.
4731 @cindex @option{-gnatQ} (@command{gcc})
4732 In normal operation mode, the @file{ALI} file is not generated if any
4733 illegalities are detected in the program. The use of @option{-gnatQ} forces
4734 generation of the @file{ALI} file. This file is marked as being in
4735 error, so it cannot be used for binding purposes, but it does contain
4736 reasonably complete cross-reference information, and thus may be useful
4737 for use by tools (e.g., semantic browsing tools or integrated development
4738 environments) that are driven from the @file{ALI} file. This switch
4739 implies @option{-gnatq}, since the semantic phase must be run to get a
4740 meaningful ALI file.
4742 In addition, if @option{-gnatt} is also specified, then the tree file is
4743 generated even if there are illegalities. It may be useful in this case
4744 to also specify @option{-gnatq} to ensure that full semantic processing
4745 occurs. The resulting tree file can be processed by ASIS, for the purpose
4746 of providing partial information about illegal units, but if the error
4747 causes the tree to be badly malformed, then ASIS may crash during the
4750 When @option{-gnatQ} is used and the generated @file{ALI} file is marked as
4751 being in error, @command{gnatmake} will attempt to recompile the source when it
4752 finds such an @file{ALI} file, including with switch @option{-gnatc}.
4754 Note that @option{-gnatQ} has no effect if @option{-gnats} is specified,
4755 since ALI files are never generated if @option{-gnats} is set.
4759 @node Warning Message Control
4760 @subsection Warning Message Control
4761 @cindex Warning messages
4763 In addition to error messages, which correspond to illegalities as defined
4764 in the Ada Reference Manual, the compiler detects two kinds of warning
4767 First, the compiler considers some constructs suspicious and generates a
4768 warning message to alert you to a possible error. Second, if the
4769 compiler detects a situation that is sure to raise an exception at
4770 run time, it generates a warning message. The following shows an example
4771 of warning messages:
4773 e.adb:4:24: warning: creation of object may raise Storage_Error
4774 e.adb:10:17: warning: static value out of range
4775 e.adb:10:17: warning: "Constraint_Error" will be raised at run time
4779 GNAT considers a large number of situations as appropriate
4780 for the generation of warning messages. As always, warnings are not
4781 definite indications of errors. For example, if you do an out-of-range
4782 assignment with the deliberate intention of raising a
4783 @code{Constraint_Error} exception, then the warning that may be
4784 issued does not indicate an error. Some of the situations for which GNAT
4785 issues warnings (at least some of the time) are given in the following
4786 list. This list is not complete, and new warnings are often added to
4787 subsequent versions of GNAT. The list is intended to give a general idea
4788 of the kinds of warnings that are generated.
4792 Possible infinitely recursive calls
4795 Out-of-range values being assigned
4798 Possible order of elaboration problems
4801 Assertions (pragma Assert) that are sure to fail
4807 Address clauses with possibly unaligned values, or where an attempt is
4808 made to overlay a smaller variable with a larger one.
4811 Fixed-point type declarations with a null range
4814 Direct_IO or Sequential_IO instantiated with a type that has access values
4817 Variables that are never assigned a value
4820 Variables that are referenced before being initialized
4823 Task entries with no corresponding @code{accept} statement
4826 Duplicate accepts for the same task entry in a @code{select}
4829 Objects that take too much storage
4832 Unchecked conversion between types of differing sizes
4835 Missing @code{return} statement along some execution path in a function
4838 Incorrect (unrecognized) pragmas
4841 Incorrect external names
4844 Allocation from empty storage pool
4847 Potentially blocking operation in protected type
4850 Suspicious parenthesization of expressions
4853 Mismatching bounds in an aggregate
4856 Attempt to return local value by reference
4859 Premature instantiation of a generic body
4862 Attempt to pack aliased components
4865 Out of bounds array subscripts
4868 Wrong length on string assignment
4871 Violations of style rules if style checking is enabled
4874 Unused @code{with} clauses
4877 @code{Bit_Order} usage that does not have any effect
4880 @code{Standard.Duration} used to resolve universal fixed expression
4883 Dereference of possibly null value
4886 Declaration that is likely to cause storage error
4889 Internal GNAT unit @code{with}'ed by application unit
4892 Values known to be out of range at compile time
4895 Unreferenced or unmodified variables. Note that a special
4896 exemption applies to variables which contain any of the substrings
4897 @code{DISCARD, DUMMY, IGNORE, JUNK, UNUSED}, in any casing. Such variables
4898 are considered likely to be intentionally used in a situation where
4899 otherwise a warning would be given, so warnings of this kind are
4900 always suppressed for such variables.
4903 Address overlays that could clobber memory
4906 Unexpected initialization when address clause present
4909 Bad alignment for address clause
4912 Useless type conversions
4915 Redundant assignment statements and other redundant constructs
4918 Useless exception handlers
4921 Accidental hiding of name by child unit
4924 Access before elaboration detected at compile time
4927 A range in a @code{for} loop that is known to be null or might be null
4932 The following section lists compiler switches that are available
4933 to control the handling of warning messages. It is also possible
4934 to exercise much finer control over what warnings are issued and
4935 suppressed using the GNAT pragma Warnings, @xref{Pragma Warnings,,,
4936 gnat_rm, GNAT Reference manual}.
4941 @emph{Activate most optional warnings.}
4942 @cindex @option{-gnatwa} (@command{gcc})
4943 This switch activates most optional warning messages. See the remaining list
4944 in this section for details on optional warning messages that can be
4945 individually controlled. The warnings that are not turned on by this
4947 @option{-gnatwd} (implicit dereferencing),
4948 @option{-gnatwh} (hiding),
4949 @option{-gnatw.d} (tag warnings with -gnatw switch)
4950 @option{-gnatw.h} (holes (gaps) in record layouts)
4951 @option{-gnatw.i} (overlapping actuals),
4952 @option{-gnatw.k} (redefinition of names in standard),
4953 @option{-gnatwl} (elaboration warnings),
4954 @option{-gnatw.l} (inherited aspects),
4955 @option{-gnatw.o} (warn on values set by out parameters ignored),
4956 @option{-gnatwt} (tracking of deleted conditional code)
4957 and @option{-gnatw.u} (unordered enumeration),
4958 All other optional warnings are turned on.
4961 @emph{Suppress all optional errors.}
4962 @cindex @option{-gnatwA} (@command{gcc})
4963 This switch suppresses all optional warning messages, see remaining list
4964 in this section for details on optional warning messages that can be
4965 individually controlled. Note that unlike switch @option{-gnatws}, the
4966 use of switch @option{-gnatwA} does not suppress warnings that are
4967 normally given unconditionally and cannot be individually controlled
4968 (for example, the warning about a missing exit path in a function).
4969 Also, again unlike switch @option{-gnatws}, warnings suppressed by
4970 the use of switch @option{-gnatwA} can be individually turned back
4971 on. For example the use of switch @option{-gnatwA} followed by
4972 switch @option{-gnatwd} will suppress all optional warnings except
4973 the warnings for implicit dereferencing.
4976 @emph{Activate warnings on failing assertions.}
4977 @cindex @option{-gnatw.a} (@command{gcc})
4978 @cindex Assert failures
4979 This switch activates warnings for assertions where the compiler can tell at
4980 compile time that the assertion will fail. Note that this warning is given
4981 even if assertions are disabled. The default is that such warnings are
4985 @emph{Suppress warnings on failing assertions.}
4986 @cindex @option{-gnatw.A} (@command{gcc})
4987 @cindex Assert failures
4988 This switch suppresses warnings for assertions where the compiler can tell at
4989 compile time that the assertion will fail.
4992 @emph{Activate warnings on bad fixed values.}
4993 @cindex @option{-gnatwb} (@command{gcc})
4994 @cindex Bad fixed values
4995 @cindex Fixed-point Small value
4997 This switch activates warnings for static fixed-point expressions whose
4998 value is not an exact multiple of Small. Such values are implementation
4999 dependent, since an implementation is free to choose either of the multiples
5000 that surround the value. GNAT always chooses the closer one, but this is not
5001 required behavior, and it is better to specify a value that is an exact
5002 multiple, ensuring predictable execution. The default is that such warnings
5006 @emph{Suppress warnings on bad fixed values.}
5007 @cindex @option{-gnatwB} (@command{gcc})
5008 This switch suppresses warnings for static fixed-point expressions whose
5009 value is not an exact multiple of Small.
5012 @emph{Activate warnings on biased representation.}
5013 @cindex @option{-gnatw.b} (@command{gcc})
5014 @cindex Biased representation
5015 This switch activates warnings when a size clause, value size clause, component
5016 clause, or component size clause forces the use of biased representation for an
5017 integer type (e.g. representing a range of 10..11 in a single bit by using 0/1
5018 to represent 10/11). The default is that such warnings are generated.
5021 @emph{Suppress warnings on biased representation.}
5022 @cindex @option{-gnatwB} (@command{gcc})
5023 This switch suppresses warnings for representation clauses that force the use
5024 of biased representation.
5027 @emph{Activate warnings on conditionals.}
5028 @cindex @option{-gnatwc} (@command{gcc})
5029 @cindex Conditionals, constant
5030 This switch activates warnings for conditional expressions used in
5031 tests that are known to be True or False at compile time. The default
5032 is that such warnings are not generated.
5033 Note that this warning does
5034 not get issued for the use of boolean variables or constants whose
5035 values are known at compile time, since this is a standard technique
5036 for conditional compilation in Ada, and this would generate too many
5037 false positive warnings.
5039 This warning option also activates a special test for comparisons using
5040 the operators ``>='' and`` <=''.
5041 If the compiler can tell that only the equality condition is possible,
5042 then it will warn that the ``>'' or ``<'' part of the test
5043 is useless and that the operator could be replaced by ``=''.
5044 An example would be comparing a @code{Natural} variable <= 0.
5046 This warning option also generates warnings if
5047 one or both tests is optimized away in a membership test for integer
5048 values if the result can be determined at compile time. Range tests on
5049 enumeration types are not included, since it is common for such tests
5050 to include an end point.
5052 This warning can also be turned on using @option{-gnatwa}.
5055 @emph{Suppress warnings on conditionals.}
5056 @cindex @option{-gnatwC} (@command{gcc})
5057 This switch suppresses warnings for conditional expressions used in
5058 tests that are known to be True or False at compile time.
5061 @emph{Activate warnings on missing component clauses.}
5062 @cindex @option{-gnatw.c} (@command{gcc})
5063 @cindex Component clause, missing
5064 This switch activates warnings for record components where a record
5065 representation clause is present and has component clauses for the
5066 majority, but not all, of the components. A warning is given for each
5067 component for which no component clause is present.
5069 This warning can also be turned on using @option{-gnatwa}.
5072 @emph{Suppress warnings on missing component clauses.}
5073 @cindex @option{-gnatwC} (@command{gcc})
5074 This switch suppresses warnings for record components that are
5075 missing a component clause in the situation described above.
5078 @emph{Activate warnings on implicit dereferencing.}
5079 @cindex @option{-gnatwd} (@command{gcc})
5080 If this switch is set, then the use of a prefix of an access type
5081 in an indexed component, slice, or selected component without an
5082 explicit @code{.all} will generate a warning. With this warning
5083 enabled, access checks occur only at points where an explicit
5084 @code{.all} appears in the source code (assuming no warnings are
5085 generated as a result of this switch). The default is that such
5086 warnings are not generated.
5087 Note that @option{-gnatwa} does not affect the setting of
5088 this warning option.
5091 @emph{Suppress warnings on implicit dereferencing.}
5092 @cindex @option{-gnatwD} (@command{gcc})
5093 @cindex Implicit dereferencing
5094 @cindex Dereferencing, implicit
5095 This switch suppresses warnings for implicit dereferences in
5096 indexed components, slices, and selected components.
5099 @emph{Activate tagging of warning and info messages.}
5100 @cindex @option{-gnatw.d} (@command{gcc})
5101 If this switch is set, then warning messages are tagged, with one of the
5107 Used to tag warnings controlled by the switch @option{-gnatwx} where x
5111 Used to tag warnings controlled by the switch @option{-gnatw.x} where x
5115 Used to tag elaboration information (info) messages generated when the
5116 static model of elaboration is used and the @option{-gnatel} switch is set.
5118 @item [restriction warning]
5119 Used to tag warning messages for restriction violations, activated by use
5120 of the pragma @option{Restriction_Warnings}.
5122 @item [warning-as-error]
5123 Used to tag warning messages that have been converted to error messages by
5124 use of the pragma Warning_As_Error. Note that such warnings are prefixed by
5125 the string "error: " rather than "warning: ".
5127 @item [enabled by default]
5128 Used to tag all other warnings that are always given by default, unless
5129 warnings are completely suppressed using pragma @option{Warnings(Off)} or
5130 the switch @option{-gnatws}.
5135 @emph{Deactivate tagging of warning and info messages messages.}
5136 @cindex @option{-gnatw.d} (@command{gcc})
5137 If this switch is set, then warning messages return to the default
5138 mode in which warnings and info messages are not tagged as described above for
5142 @emph{Treat warnings and style checks as errors.}
5143 @cindex @option{-gnatwe} (@command{gcc})
5144 @cindex Warnings, treat as error
5145 This switch causes warning messages and style check messages to be
5147 The warning string still appears, but the warning messages are counted
5148 as errors, and prevent the generation of an object file. Note that this
5149 is the only -gnatw switch that affects the handling of style check messages.
5152 @emph{Activate every optional warning}
5153 @cindex @option{-gnatw.e} (@command{gcc})
5154 @cindex Warnings, activate every optional warning
5155 This switch activates all optional warnings, including those which
5156 are not activated by @code{-gnatwa}. The use of this switch is not
5157 recommended for normal use. If you turn this switch on, it is almost
5158 certain that you will get large numbers of useless warnings. The
5159 warnings that are excluded from @code{-gnatwa} are typically highly
5160 specialized warnings that are suitable for use only in code that has
5161 been specifically designed according to specialized coding rules.
5164 @emph{Activate warnings on unreferenced formals.}
5165 @cindex @option{-gnatwf} (@command{gcc})
5166 @cindex Formals, unreferenced
5167 This switch causes a warning to be generated if a formal parameter
5168 is not referenced in the body of the subprogram. This warning can
5169 also be turned on using @option{-gnatwa} or @option{-gnatwu}. The
5170 default is that these warnings are not generated.
5173 @emph{Suppress warnings on unreferenced formals.}
5174 @cindex @option{-gnatwF} (@command{gcc})
5175 This switch suppresses warnings for unreferenced formal
5176 parameters. Note that the
5177 combination @option{-gnatwu} followed by @option{-gnatwF} has the
5178 effect of warning on unreferenced entities other than subprogram
5182 @emph{Activate warnings on unrecognized pragmas.}
5183 @cindex @option{-gnatwg} (@command{gcc})
5184 @cindex Pragmas, unrecognized
5185 This switch causes a warning to be generated if an unrecognized
5186 pragma is encountered. Apart from issuing this warning, the
5187 pragma is ignored and has no effect. This warning can
5188 also be turned on using @option{-gnatwa}. The default
5189 is that such warnings are issued (satisfying the Ada Reference
5190 Manual requirement that such warnings appear).
5193 @emph{Suppress warnings on unrecognized pragmas.}
5194 @cindex @option{-gnatwG} (@command{gcc})
5195 This switch suppresses warnings for unrecognized pragmas.
5198 @emph{Warnings used for GNAT sources}
5199 @cindex @option{-gnatw.g} (@command{gcc})
5200 This switch sets the warning categories that are used by the standard
5201 GNAT style. Currently this is equivalent to
5202 @option{-gnatwAao.sI.C.V.X}
5203 but more warnings may be added in the future without advanced notice.
5206 @emph{Activate warnings on hiding.}
5207 @cindex @option{-gnatwh} (@command{gcc})
5208 @cindex Hiding of Declarations
5209 This switch activates warnings on hiding declarations.
5210 A declaration is considered hiding
5211 if it is for a non-overloadable entity, and it declares an entity with the
5212 same name as some other entity that is directly or use-visible. The default
5213 is that such warnings are not generated.
5214 Note that @option{-gnatwa} does not affect the setting of this warning option.
5217 @emph{Suppress warnings on hiding.}
5218 @cindex @option{-gnatwH} (@command{gcc})
5219 This switch suppresses warnings on hiding declarations.
5222 @emph{Activate warnings on holes/gaps in records.}
5223 @cindex @option{-gnatw.h} (@command{gcc})
5224 @cindex Record Representation (gaps)
5225 This switch activates warnings on component clauses in record
5226 representation clauses that leave holes (gaps) in the record layout.
5227 If this warning option is active, then record representation clauses
5228 should specify a contiguous layout, adding unused fill fields if needed.
5229 Note that @option{-gnatwa} does not affect the setting of this warning option.
5232 @emph{Suppress warnings on holes/gaps in records.}
5233 @cindex @option{-gnatw.H} (@command{gcc})
5234 This switch suppresses warnings on component clauses in record
5235 representation clauses that leave holes (haps) in the record layout.
5238 @emph{Activate warnings on implementation units.}
5239 @cindex @option{-gnatwi} (@command{gcc})
5240 This switch activates warnings for a @code{with} of an internal GNAT
5241 implementation unit, defined as any unit from the @code{Ada},
5242 @code{Interfaces}, @code{GNAT},
5243 ^^@code{DEC},^ or @code{System}
5244 hierarchies that is not
5245 documented in either the Ada Reference Manual or the GNAT
5246 Programmer's Reference Manual. Such units are intended only
5247 for internal implementation purposes and should not be @code{with}'ed
5248 by user programs. The default is that such warnings are generated
5249 This warning can also be turned on using @option{-gnatwa}.
5252 @emph{Disable warnings on implementation units.}
5253 @cindex @option{-gnatwI} (@command{gcc})
5254 This switch disables warnings for a @code{with} of an internal GNAT
5255 implementation unit.
5258 @emph{Activate warnings on overlapping actuals.}
5259 @cindex @option{-gnatw.i} (@command{gcc})
5260 This switch enables a warning on statically detectable overlapping actuals in
5261 a subprogram call, when one of the actuals is an in-out parameter, and the
5262 types of the actuals are not by-copy types. The warning is off by default,
5263 and is not included under -gnatwa.
5266 @emph{Disable warnings on overlapping actuals.}
5267 @cindex @option{-gnatw.I} (@command{gcc})
5268 This switch disables warnings on overlapping actuals in a call..
5271 @emph{Activate warnings on obsolescent features (Annex J).}
5272 @cindex @option{-gnatwj} (@command{gcc})
5273 @cindex Features, obsolescent
5274 @cindex Obsolescent features
5275 If this warning option is activated, then warnings are generated for
5276 calls to subprograms marked with @code{pragma Obsolescent} and
5277 for use of features in Annex J of the Ada Reference Manual. In the
5278 case of Annex J, not all features are flagged. In particular use
5279 of the renamed packages (like @code{Text_IO}) and use of package
5280 @code{ASCII} are not flagged, since these are very common and
5281 would generate many annoying positive warnings. The default is that
5282 such warnings are not generated. This warning is also turned on by
5283 the use of @option{-gnatwa}.
5285 In addition to the above cases, warnings are also generated for
5286 GNAT features that have been provided in past versions but which
5287 have been superseded (typically by features in the new Ada standard).
5288 For example, @code{pragma Ravenscar} will be flagged since its
5289 function is replaced by @code{pragma Profile(Ravenscar)}, and
5290 @code{pragma Interface_Name} will be flagged since its function
5291 is replaced by @code{pragma Import}.
5293 Note that this warning option functions differently from the
5294 restriction @code{No_Obsolescent_Features} in two respects.
5295 First, the restriction applies only to annex J features.
5296 Second, the restriction does flag uses of package @code{ASCII}.
5299 @emph{Suppress warnings on obsolescent features (Annex J).}
5300 @cindex @option{-gnatwJ} (@command{gcc})
5301 This switch disables warnings on use of obsolescent features.
5304 @emph{Activate warnings on variables that could be constants.}
5305 @cindex @option{-gnatwk} (@command{gcc})
5306 This switch activates warnings for variables that are initialized but
5307 never modified, and then could be declared constants. The default is that
5308 such warnings are not given.
5309 This warning can also be turned on using @option{-gnatwa}.
5312 @emph{Suppress warnings on variables that could be constants.}
5313 @cindex @option{-gnatwK} (@command{gcc})
5314 This switch disables warnings on variables that could be declared constants.
5317 @emph{Activate warnings on redefinition of names in standard.}
5318 @cindex @option{-gnatw.k} (@command{gcc})
5319 This switch activates warnings for declarations that declare a name that
5320 is defined in package Standard. Such declarations can be confusing,
5321 especially since the names in package Standard continue to be directly
5322 visible, meaning that use visibiliy on such redeclared names does not
5323 work as expected. Names of discriminants and components in records are
5324 not included in this check.
5325 This warning is not part of the warnings activated by @option{-gnatwa}.
5326 It must be explicitly activated.
5329 @emph{Suppress warnings on variables that could be constants.}
5330 @cindex @option{-gnatwK} (@command{gcc})
5331 This switch activates warnings for declarations that declare a name that
5332 is defined in package Standard.
5335 @emph{Activate warnings for elaboration pragmas.}
5336 @cindex @option{-gnatwl} (@command{gcc})
5337 @cindex Elaboration, warnings
5338 This switch activates warnings on missing
5339 for possible elaboration problems, including suspicious use
5340 of @code{Elaborate} pragmas, when using the static elaboration model, and
5341 possible situations that may raise @code{Program_Error} when using the
5342 dynamic elaboration model.
5343 See the section in this guide on elaboration checking for further details.
5344 The default is that such warnings
5346 This warning is not automatically turned on by the use of @option{-gnatwa}.
5349 @emph{Suppress warnings for elaboration pragmas.}
5350 @cindex @option{-gnatwL} (@command{gcc})
5351 This switch suppresses warnings for possible elaboration problems.
5354 @emph{List inherited aspects.}
5355 @cindex @option{-gnatw.l} (@command{gcc})
5356 This switch causes the compiler to list inherited invariants,
5357 preconditions, and postconditions from Type_Invariant'Class, Invariant'Class,
5358 Pre'Class, and Post'Class aspects. Also list inherited subtype predicates.
5359 These messages are not automatically turned on by the use of @option{-gnatwa}.
5362 @emph{Suppress listing of inherited aspects.}
5363 @cindex @option{-gnatw.L} (@command{gcc})
5364 This switch suppresses listing of inherited aspects.
5367 @emph{Activate warnings on modified but unreferenced variables.}
5368 @cindex @option{-gnatwm} (@command{gcc})
5369 This switch activates warnings for variables that are assigned (using
5370 an initialization value or with one or more assignment statements) but
5371 whose value is never read. The warning is suppressed for volatile
5372 variables and also for variables that are renamings of other variables
5373 or for which an address clause is given.
5374 This warning can also be turned on using @option{-gnatwa}.
5375 The default is that these warnings are not given.
5378 @emph{Disable warnings on modified but unreferenced variables.}
5379 @cindex @option{-gnatwM} (@command{gcc})
5380 This switch disables warnings for variables that are assigned or
5381 initialized, but never read.
5384 @emph{Activate warnings on suspicious modulus values.}
5385 @cindex @option{-gnatw.m} (@command{gcc})
5386 This switch activates warnings for modulus values that seem suspicious.
5387 The cases caught are where the size is the same as the modulus (e.g.
5388 a modulus of 7 with a size of 7 bits), and modulus values of 32 or 64
5389 with no size clause. The guess in both cases is that 2**x was intended
5390 rather than x. In addition expressions of the form 2*x for small x
5391 generate a warning (the almost certainly accurate guess being that
5392 2**x was intended). The default is that these warnings are given.
5395 @emph{Disable warnings on suspicious modulus values.}
5396 @cindex @option{-gnatw.M} (@command{gcc})
5397 This switch disables warnings for suspicious modulus values.
5400 @emph{Set normal warnings mode.}
5401 @cindex @option{-gnatwn} (@command{gcc})
5402 This switch sets normal warning mode, in which enabled warnings are
5403 issued and treated as warnings rather than errors. This is the default
5404 mode. the switch @option{-gnatwn} can be used to cancel the effect of
5405 an explicit @option{-gnatws} or
5406 @option{-gnatwe}. It also cancels the effect of the
5407 implicit @option{-gnatwe} that is activated by the
5408 use of @option{-gnatg}.
5411 @emph{Activate warnings on atomic synchronization.}
5412 @cindex @option{-gnatw.n} (@command{gcc})
5413 @cindex Atomic Synchronization, warnings
5414 This switch actives warnings when an access to an atomic variable
5415 requires the generation of atomic synchronization code. These
5416 warnings are off by default and this warning is not included
5420 @emph{Suppress warnings on atomic synchronization.}
5421 @cindex @option{-gnatw.n} (@command{gcc})
5422 @cindex Atomic Synchronization, warnings
5423 This switch suppresses warnings when an access to an atomic variable
5424 requires the generation of atomic synchronization code.
5427 @emph{Activate warnings on address clause overlays.}
5428 @cindex @option{-gnatwo} (@command{gcc})
5429 @cindex Address Clauses, warnings
5430 This switch activates warnings for possibly unintended initialization
5431 effects of defining address clauses that cause one variable to overlap
5432 another. The default is that such warnings are generated.
5433 This warning can also be turned on using @option{-gnatwa}.
5436 @emph{Suppress warnings on address clause overlays.}
5437 @cindex @option{-gnatwO} (@command{gcc})
5438 This switch suppresses warnings on possibly unintended initialization
5439 effects of defining address clauses that cause one variable to overlap
5443 @emph{Activate warnings on modified but unreferenced out parameters.}
5444 @cindex @option{-gnatw.o} (@command{gcc})
5445 This switch activates warnings for variables that are modified by using
5446 them as actuals for a call to a procedure with an out mode formal, where
5447 the resulting assigned value is never read. It is applicable in the case
5448 where there is more than one out mode formal. If there is only one out
5449 mode formal, the warning is issued by default (controlled by -gnatwu).
5450 The warning is suppressed for volatile
5451 variables and also for variables that are renamings of other variables
5452 or for which an address clause is given.
5453 The default is that these warnings are not given. Note that this warning
5454 is not included in -gnatwa, it must be activated explicitly.
5457 @emph{Disable warnings on modified but unreferenced out parameters.}
5458 @cindex @option{-gnatw.O} (@command{gcc})
5459 This switch suppresses warnings for variables that are modified by using
5460 them as actuals for a call to a procedure with an out mode formal, where
5461 the resulting assigned value is never read.
5464 @emph{Activate warnings on ineffective pragma Inlines.}
5465 @cindex @option{-gnatwp} (@command{gcc})
5466 @cindex Inlining, warnings
5467 This switch activates warnings for failure of front end inlining
5468 (activated by @option{-gnatN}) to inline a particular call. There are
5469 many reasons for not being able to inline a call, including most
5470 commonly that the call is too complex to inline. The default is
5471 that such warnings are not given.
5472 This warning can also be turned on using @option{-gnatwa}.
5473 Warnings on ineffective inlining by the gcc back-end can be activated
5474 separately, using the gcc switch -Winline.
5477 @emph{Suppress warnings on ineffective pragma Inlines.}
5478 @cindex @option{-gnatwP} (@command{gcc})
5479 This switch suppresses warnings on ineffective pragma Inlines. If the
5480 inlining mechanism cannot inline a call, it will simply ignore the
5484 @emph{Activate warnings on parameter ordering.}
5485 @cindex @option{-gnatw.p} (@command{gcc})
5486 @cindex Parameter order, warnings
5487 This switch activates warnings for cases of suspicious parameter
5488 ordering when the list of arguments are all simple identifiers that
5489 match the names of the formals, but are in a different order. The
5490 warning is suppressed if any use of named parameter notation is used,
5491 so this is the appropriate way to suppress a false positive (and
5492 serves to emphasize that the "misordering" is deliberate). The
5494 that such warnings are not given.
5495 This warning can also be turned on using @option{-gnatwa}.
5498 @emph{Suppress warnings on parameter ordering.}
5499 @cindex @option{-gnatw.P} (@command{gcc})
5500 This switch suppresses warnings on cases of suspicious parameter
5504 @emph{Activate warnings on questionable missing parentheses.}
5505 @cindex @option{-gnatwq} (@command{gcc})
5506 @cindex Parentheses, warnings
5507 This switch activates warnings for cases where parentheses are not used and
5508 the result is potential ambiguity from a readers point of view. For example
5509 (not a > b) when a and b are modular means ((not a) > b) and very likely the
5510 programmer intended (not (a > b)). Similarly (-x mod 5) means (-(x mod 5)) and
5511 quite likely ((-x) mod 5) was intended. In such situations it seems best to
5512 follow the rule of always parenthesizing to make the association clear, and
5513 this warning switch warns if such parentheses are not present. The default
5514 is that these warnings are given.
5515 This warning can also be turned on using @option{-gnatwa}.
5518 @emph{Suppress warnings on questionable missing parentheses.}
5519 @cindex @option{-gnatwQ} (@command{gcc})
5520 This switch suppresses warnings for cases where the association is not
5521 clear and the use of parentheses is preferred.
5524 @emph{Activate warnings on redundant constructs.}
5525 @cindex @option{-gnatwr} (@command{gcc})
5526 This switch activates warnings for redundant constructs. The following
5527 is the current list of constructs regarded as redundant:
5531 Assignment of an item to itself.
5533 Type conversion that converts an expression to its own type.
5535 Use of the attribute @code{Base} where @code{typ'Base} is the same
5538 Use of pragma @code{Pack} when all components are placed by a record
5539 representation clause.
5541 Exception handler containing only a reraise statement (raise with no
5542 operand) which has no effect.
5544 Use of the operator abs on an operand that is known at compile time
5547 Comparison of boolean expressions to an explicit True value.
5550 This warning can also be turned on using @option{-gnatwa}.
5551 The default is that warnings for redundant constructs are not given.
5554 @emph{Suppress warnings on redundant constructs.}
5555 @cindex @option{-gnatwR} (@command{gcc})
5556 This switch suppresses warnings for redundant constructs.
5559 @emph{Activate warnings for object renaming function.}
5560 @cindex @option{-gnatw.r} (@command{gcc})
5561 This switch activates warnings for an object renaming that renames a
5562 function call, which is equivalent to a constant declaration (as
5563 opposed to renaming the function itself). The default is that these
5564 warnings are given. This warning can also be turned on using
5568 @emph{Suppress warnings for object renaming function.}
5569 @cindex @option{-gnatwT} (@command{gcc})
5570 This switch suppresses warnings for object renaming function.
5573 @emph{Suppress all warnings.}
5574 @cindex @option{-gnatws} (@command{gcc})
5575 This switch completely suppresses the
5576 output of all warning messages from the GNAT front end, including
5577 both warnings that can be controlled by switches described in this
5578 section, and those that are normally given unconditionally. The
5579 effect of this suppress action can only be cancelled by a subsequent
5580 use of the switch @option{-gnatwn}.
5582 Note that switch @option{-gnatws} does not suppress
5583 warnings from the @command{gcc} back end.
5584 To suppress these back end warnings as well, use the switch @option{-w}
5585 in addition to @option{-gnatws}. Also this switch has no effect on the
5586 handling of style check messages.
5589 @emph{Activate warnings on overridden size clauses.}
5590 @cindex @option{-gnatw.s} (@command{gcc})
5591 @cindex Record Representation (component sizes)
5592 This switch activates warnings on component clauses in record
5593 representation clauses where the length given overrides that
5594 specified by an explicit size clause for the component type. A
5595 warning is similarly given in the array case if a specified
5596 component size overrides an explicit size clause for the array
5598 Note that @option{-gnatwa} does not affect the setting of this warning option.
5601 @emph{Suppress warnings on overridden size clauses.}
5602 @cindex @option{-gnatw.S} (@command{gcc})
5603 This switch suppresses warnings on component clauses in record
5604 representation clauses that override size clauses, and similar
5605 warnings when an array component size overrides a size clause.
5608 @emph{Activate warnings for tracking of deleted conditional code.}
5609 @cindex @option{-gnatwt} (@command{gcc})
5610 @cindex Deactivated code, warnings
5611 @cindex Deleted code, warnings
5612 This switch activates warnings for tracking of code in conditionals (IF and
5613 CASE statements) that is detected to be dead code which cannot be executed, and
5614 which is removed by the front end. This warning is off by default, and is not
5615 turned on by @option{-gnatwa}, it has to be turned on explicitly. This may be
5616 useful for detecting deactivated code in certified applications.
5619 @emph{Suppress warnings for tracking of deleted conditional code.}
5620 @cindex @option{-gnatwT} (@command{gcc})
5621 This switch suppresses warnings for tracking of deleted conditional code.
5624 @emph{Activate warnings on suspicious contracts.}
5625 @cindex @option{-gnatw.t} (@command{gcc})
5626 This switch activates warnings on suspicious postconditions (whether a
5627 pragma @code{Postcondition} or a @code{Post} aspect in Ada 2012)
5628 and suspicious contract cases (pragma @code{Contract_Cases}). A
5629 function postcondition or contract case is suspicious when no postcondition
5630 or contract case for this function mentions the result of the function.
5631 A procedure postcondition or contract case is suspicious when it only
5632 refers to the pre-state of the procedure, because in that case it should
5633 rather be expressed as a precondition. The default is that such warnings
5634 are not generated. This warning can also be turned on using @option{-gnatwa}.
5637 @emph{Suppress warnings on suspicious contracts.}
5638 @cindex @option{-gnatw.T} (@command{gcc})
5639 This switch suppresses warnings on suspicious postconditions.
5642 @emph{Activate warnings on unused entities.}
5643 @cindex @option{-gnatwu} (@command{gcc})
5644 This switch activates warnings to be generated for entities that
5645 are declared but not referenced, and for units that are @code{with}'ed
5647 referenced. In the case of packages, a warning is also generated if
5648 no entities in the package are referenced. This means that if a with'ed
5649 package is referenced but the only references are in @code{use}
5650 clauses or @code{renames}
5651 declarations, a warning is still generated. A warning is also generated
5652 for a generic package that is @code{with}'ed but never instantiated.
5653 In the case where a package or subprogram body is compiled, and there
5654 is a @code{with} on the corresponding spec
5655 that is only referenced in the body,
5656 a warning is also generated, noting that the
5657 @code{with} can be moved to the body. The default is that
5658 such warnings are not generated.
5659 This switch also activates warnings on unreferenced formals
5660 (it includes the effect of @option{-gnatwf}).
5661 This warning can also be turned on using @option{-gnatwa}.
5664 @emph{Suppress warnings on unused entities.}
5665 @cindex @option{-gnatwU} (@command{gcc})
5666 This switch suppresses warnings for unused entities and packages.
5667 It also turns off warnings on unreferenced formals (and thus includes
5668 the effect of @option{-gnatwF}).
5671 @emph{Activate warnings on unordered enumeration types.}
5672 @cindex @option{-gnatw.u} (@command{gcc})
5673 This switch causes enumeration types to be considered as conceptually
5674 unordered, unless an explicit pragma @code{Ordered} is given for the type.
5675 The effect is to generate warnings in clients that use explicit comparisons
5676 or subranges, since these constructs both treat objects of the type as
5677 ordered. (A @emph{client} is defined as a unit that is other than the unit in
5678 which the type is declared, or its body or subunits.) Please refer to
5679 the description of pragma @code{Ordered} in the
5680 @cite{@value{EDITION} Reference Manual} for further details.
5681 The default is that such warnings are not generated.
5682 This warning is not automatically turned on by the use of @option{-gnatwa}.
5685 @emph{Deactivate warnings on unordered enumeration types.}
5686 @cindex @option{-gnatw.U} (@command{gcc})
5687 This switch causes all enumeration types to be considered as ordered, so
5688 that no warnings are given for comparisons or subranges for any type.
5691 @emph{Activate warnings on unassigned variables.}
5692 @cindex @option{-gnatwv} (@command{gcc})
5693 @cindex Unassigned variable warnings
5694 This switch activates warnings for access to variables which
5695 may not be properly initialized. The default is that
5696 such warnings are generated.
5697 This warning can also be turned on using @option{-gnatwa}.
5700 @emph{Suppress warnings on unassigned variables.}
5701 @cindex @option{-gnatwV} (@command{gcc})
5702 This switch suppresses warnings for access to variables which
5703 may not be properly initialized.
5704 For variables of a composite type, the warning can also be suppressed in
5705 Ada 2005 by using a default initialization with a box. For example, if
5706 Table is an array of records whose components are only partially uninitialized,
5707 then the following code:
5709 @smallexample @c ada
5710 Tab : Table := (others => <>);
5713 will suppress warnings on subsequent statements that access components
5717 @emph{Activate info messages for non-default bit order.}
5718 @cindex @option{-gnatw.v} (@command{gcc})
5719 @cindex bit order warnings
5720 This switch activates messages (labeled "info", they are not warnings,
5721 just informational messages) about the effects of non-default bit-order
5722 on records to which a component clause is applied. The effect of specifying
5723 non-default bit ordering is a bit subtle (and changed with Ada 2005), so
5724 these messages, which are given by default, are useful in understanding the
5725 exact consequences of using this feature. These messages
5726 can also be turned on using @option{-gnatwa}
5729 @emph{Suppress info messages for non-default bit order.}
5730 @cindex @option{-gnatw.V} (@command{gcc})
5731 This switch suppresses information messages for the effects of specifying
5732 non-default bit order on record components with component clauses.
5735 @emph{Activate warnings on wrong low bound assumption.}
5736 @cindex @option{-gnatww} (@command{gcc})
5737 @cindex String indexing warnings
5738 This switch activates warnings for indexing an unconstrained string parameter
5739 with a literal or S'Length. This is a case where the code is assuming that the
5740 low bound is one, which is in general not true (for example when a slice is
5741 passed). The default is that such warnings are generated.
5742 This warning can also be turned on using @option{-gnatwa}.
5745 @emph{Suppress warnings on wrong low bound assumption.}
5746 @cindex @option{-gnatwW} (@command{gcc})
5747 This switch suppresses warnings for indexing an unconstrained string parameter
5748 with a literal or S'Length. Note that this warning can also be suppressed
5749 in a particular case by adding an
5750 assertion that the lower bound is 1,
5751 as shown in the following example.
5753 @smallexample @c ada
5754 procedure K (S : String) is
5755 pragma Assert (S'First = 1);
5760 @emph{Activate warnings on Warnings Off pragmas}
5761 @cindex @option{-gnatw.w} (@command{gcc})
5762 @cindex Warnings Off control
5763 This switch activates warnings for use of @code{pragma Warnings (Off, entity)}
5764 where either the pragma is entirely useless (because it suppresses no
5765 warnings), or it could be replaced by @code{pragma Unreferenced} or
5766 @code{pragma Unmodified}. The default is that these warnings are not given.
5767 Note that this warning is not included in -gnatwa, it must be
5768 activated explicitly. Also activates warnings for the case of
5769 Warnings (Off, String), where either there is no matching
5770 Warnings (On, String), or the Warnings (Off) did not suppress any warning.
5773 @emph{Suppress warnings on unnecessary Warnings Off pragmas}
5774 @cindex @option{-gnatw.W} (@command{gcc})
5775 This switch suppresses warnings for use of @code{pragma Warnings (Off, ...)}.
5778 @emph{Activate warnings on Export/Import pragmas.}
5779 @cindex @option{-gnatwx} (@command{gcc})
5780 @cindex Export/Import pragma warnings
5781 This switch activates warnings on Export/Import pragmas when
5782 the compiler detects a possible conflict between the Ada and
5783 foreign language calling sequences. For example, the use of
5784 default parameters in a convention C procedure is dubious
5785 because the C compiler cannot supply the proper default, so
5786 a warning is issued. The default is that such warnings are
5788 This warning can also be turned on using @option{-gnatwa}.
5791 @emph{Suppress warnings on Export/Import pragmas.}
5792 @cindex @option{-gnatwX} (@command{gcc})
5793 This switch suppresses warnings on Export/Import pragmas.
5794 The sense of this is that you are telling the compiler that
5795 you know what you are doing in writing the pragma, and it
5796 should not complain at you.
5799 @emph{Activate warnings for No_Exception_Propagation mode.}
5800 @cindex @option{-gnatwm} (@command{gcc})
5801 This switch activates warnings for exception usage when pragma Restrictions
5802 (No_Exception_Propagation) is in effect. Warnings are given for implicit or
5803 explicit exception raises which are not covered by a local handler, and for
5804 exception handlers which do not cover a local raise. The default is that these
5805 warnings are not given.
5808 @emph{Disable warnings for No_Exception_Propagation mode.}
5809 This switch disables warnings for exception usage when pragma Restrictions
5810 (No_Exception_Propagation) is in effect.
5813 @emph{Activate warnings for Ada compatibility issues.}
5814 @cindex @option{-gnatwy} (@command{gcc})
5815 @cindex Ada compatibility issues warnings
5816 For the most part, newer versions of Ada are upwards compatible
5817 with older versions. For example, Ada 2005 programs will almost
5818 always work when compiled as Ada 2012.
5819 However there are some exceptions (for example the fact that
5820 @code{some} is now a reserved word in Ada 2012). This
5821 switch activates several warnings to help in identifying
5822 and correcting such incompatibilities. The default is that
5823 these warnings are generated. Note that at one point Ada 2005
5824 was called Ada 0Y, hence the choice of character.
5825 This warning can also be turned on using @option{-gnatwa}.
5828 @emph{Disable warnings for Ada compatibility issues.}
5829 @cindex @option{-gnatwY} (@command{gcc})
5830 @cindex Ada compatibility issues warnings
5831 This switch suppresses the warnings intended to help in identifying
5832 incompatibilities between Ada language versions.
5835 @emph{Activate information messages for why package spec needs body}
5836 @cindex @option{-gnatw.y} (@command{gcc})
5837 @cindex Package spec needing body
5838 There are a number of cases in which a package spec needs a body.
5839 For example, the use of pragma Elaborate_Body, or the declaration
5840 of a procedure specification requiring a completion. This switch
5841 causes information messages to be output showing why a package
5842 specification requires a body. This can be useful in the case of
5843 a large package specification which is unexpectedly requiring a
5844 body. The default is that such information messages are not output.
5847 @emph{Disable information messages for why package spec needs body}
5848 @cindex @option{-gnatw.Y} (@command{gcc})
5849 @cindex No information messages for why package spec needs body
5850 This switch suppresses the output of information messages showing why
5851 a package specification needs a body.
5854 @emph{Activate warnings on unchecked conversions.}
5855 @cindex @option{-gnatwz} (@command{gcc})
5856 @cindex Unchecked_Conversion warnings
5857 This switch activates warnings for unchecked conversions
5858 where the types are known at compile time to have different
5860 is that such warnings are generated. Warnings are also
5861 generated for subprogram pointers with different conventions,
5862 and, on VMS only, for data pointers with different conventions.
5863 This warning can also be turned on using @option{-gnatwa}.
5866 @emph{Suppress warnings on unchecked conversions.}
5867 @cindex @option{-gnatwZ} (@command{gcc})
5868 This switch suppresses warnings for unchecked conversions
5869 where the types are known at compile time to have different
5870 sizes or conventions.
5872 @item ^-Wunused^WARNINGS=UNUSED^
5873 @cindex @option{-Wunused}
5874 The warnings controlled by the @option{-gnatw} switch are generated by
5875 the front end of the compiler. The @option{GCC} back end can provide
5876 additional warnings and they are controlled by the @option{-W} switch.
5877 For example, @option{^-Wunused^WARNINGS=UNUSED^} activates back end
5878 warnings for entities that are declared but not referenced.
5880 @item ^-Wuninitialized^WARNINGS=UNINITIALIZED^
5881 @cindex @option{-Wuninitialized}
5882 Similarly, @option{^-Wuninitialized^WARNINGS=UNINITIALIZED^} activates
5883 the back end warning for uninitialized variables. This switch must be
5884 used in conjunction with an optimization level greater than zero.
5886 @item -Wstack-usage=@var{len}
5887 @cindex @option{-Wstack-usage}
5888 Warn if the stack usage of a subprogram might be larger than @var{len} bytes.
5889 See @ref{Static Stack Usage Analysis} for details.
5891 @item ^-Wall^/ALL_BACK_END_WARNINGS^
5892 @cindex @option{-Wall}
5893 This switch enables most warnings from the @option{GCC} back end.
5894 The code generator detects a number of warning situations that are missed
5895 by the @option{GNAT} front end, and this switch can be used to activate them.
5896 The use of this switch also sets the default front end warning mode to
5897 @option{-gnatwa}, that is, most front end warnings activated as well.
5899 @item ^-w^/NO_BACK_END_WARNINGS^
5901 Conversely, this switch suppresses warnings from the @option{GCC} back end.
5902 The use of this switch also sets the default front end warning mode to
5903 @option{-gnatws}, that is, front end warnings suppressed as well.
5906 @cindex @option{-Werror}
5907 This switch causes warnings from the @option{GCC} back end to be treated as
5908 errors. The warning string still appears, but the warning messages are
5909 counted as errors, and prevent the generation of an object file.
5915 A string of warning parameters can be used in the same parameter. For example:
5922 will turn on all optional warnings except for unrecognized pragma warnings,
5923 and also specify that warnings should be treated as errors.
5926 When no switch @option{^-gnatw^/WARNINGS^} is used, this is equivalent to:
5969 @node Debugging and Assertion Control
5970 @subsection Debugging and Assertion Control
5974 @cindex @option{-gnata} (@command{gcc})
5980 The pragmas @code{Assert} and @code{Debug} normally have no effect and
5981 are ignored. This switch, where @samp{a} stands for assert, causes
5982 @code{Assert} and @code{Debug} pragmas to be activated.
5984 The pragmas have the form:
5988 @b{pragma} Assert (@var{Boolean-expression} @r{[},
5989 @var{static-string-expression}@r{]})
5990 @b{pragma} Debug (@var{procedure call})
5995 The @code{Assert} pragma causes @var{Boolean-expression} to be tested.
5996 If the result is @code{True}, the pragma has no effect (other than
5997 possible side effects from evaluating the expression). If the result is
5998 @code{False}, the exception @code{Assert_Failure} declared in the package
5999 @code{System.Assertions} is
6000 raised (passing @var{static-string-expression}, if present, as the
6001 message associated with the exception). If no string expression is
6002 given the default is a string giving the file name and line number
6005 The @code{Debug} pragma causes @var{procedure} to be called. Note that
6006 @code{pragma Debug} may appear within a declaration sequence, allowing
6007 debugging procedures to be called between declarations.
6010 @item /DEBUG@r{[}=debug-level@r{]}
6012 Specifies how much debugging information is to be included in
6013 the resulting object file where 'debug-level' is one of the following:
6016 Include both debugger symbol records and traceback
6018 This is the default setting.
6020 Include both debugger symbol records and traceback in
6023 Excludes both debugger symbol records and traceback
6024 the object file. Same as /NODEBUG.
6026 Includes only debugger symbol records in the object
6027 file. Note that this doesn't include traceback information.
6032 @node Validity Checking
6033 @subsection Validity Checking
6034 @findex Validity Checking
6037 The Ada Reference Manual defines the concept of invalid values (see
6038 RM 13.9.1). The primary source of invalid values is uninitialized
6039 variables. A scalar variable that is left uninitialized may contain
6040 an invalid value; the concept of invalid does not apply to access or
6043 It is an error to read an invalid value, but the RM does not require
6044 run-time checks to detect such errors, except for some minimal
6045 checking to prevent erroneous execution (i.e. unpredictable
6046 behavior). This corresponds to the @option{-gnatVd} switch below,
6047 which is the default. For example, by default, if the expression of a
6048 case statement is invalid, it will raise Constraint_Error rather than
6049 causing a wild jump, and if an array index on the left-hand side of an
6050 assignment is invalid, it will raise Constraint_Error rather than
6051 overwriting an arbitrary memory location.
6053 The @option{-gnatVa} may be used to enable additional validity checks,
6054 which are not required by the RM. These checks are often very
6055 expensive (which is why the RM does not require them). These checks
6056 are useful in tracking down uninitialized variables, but they are
6057 not usually recommended for production builds.
6059 The other @option{-gnatV^@var{x}^^} switches below allow finer-grained
6060 control; you can enable whichever validity checks you desire. However,
6061 for most debugging purposes, @option{-gnatVa} is sufficient, and the
6062 default @option{-gnatVd} (i.e. standard Ada behavior) is usually
6063 sufficient for non-debugging use.
6065 The @option{-gnatB} switch tells the compiler to assume that all
6066 values are valid (that is, within their declared subtype range)
6067 except in the context of a use of the Valid attribute. This means
6068 the compiler can generate more efficient code, since the range
6069 of values is better known at compile time. However, an uninitialized
6070 variable can cause wild jumps and memory corruption in this mode.
6072 The @option{-gnatV^@var{x}^^} switch allows control over the validity
6073 checking mode as described below.
6075 The @code{x} argument is a string of letters that
6076 indicate validity checks that are performed or not performed in addition
6077 to the default checks required by Ada as described above.
6080 The options allowed for this qualifier
6081 indicate validity checks that are performed or not performed in addition
6082 to the default checks required by Ada as described above.
6088 @emph{All validity checks.}
6089 @cindex @option{-gnatVa} (@command{gcc})
6090 All validity checks are turned on.
6092 That is, @option{-gnatVa} is
6093 equivalent to @option{gnatVcdfimorst}.
6097 @emph{Validity checks for copies.}
6098 @cindex @option{-gnatVc} (@command{gcc})
6099 The right hand side of assignments, and the initializing values of
6100 object declarations are validity checked.
6103 @emph{Default (RM) validity checks.}
6104 @cindex @option{-gnatVd} (@command{gcc})
6105 Some validity checks are done by default following normal Ada semantics
6107 A check is done in case statements that the expression is within the range
6108 of the subtype. If it is not, Constraint_Error is raised.
6109 For assignments to array components, a check is done that the expression used
6110 as index is within the range. If it is not, Constraint_Error is raised.
6111 Both these validity checks may be turned off using switch @option{-gnatVD}.
6112 They are turned on by default. If @option{-gnatVD} is specified, a subsequent
6113 switch @option{-gnatVd} will leave the checks turned on.
6114 Switch @option{-gnatVD} should be used only if you are sure that all such
6115 expressions have valid values. If you use this switch and invalid values
6116 are present, then the program is erroneous, and wild jumps or memory
6117 overwriting may occur.
6120 @emph{Validity checks for elementary components.}
6121 @cindex @option{-gnatVe} (@command{gcc})
6122 In the absence of this switch, assignments to record or array components are
6123 not validity checked, even if validity checks for assignments generally
6124 (@option{-gnatVc}) are turned on. In Ada, assignment of composite values do not
6125 require valid data, but assignment of individual components does. So for
6126 example, there is a difference between copying the elements of an array with a
6127 slice assignment, compared to assigning element by element in a loop. This
6128 switch allows you to turn off validity checking for components, even when they
6129 are assigned component by component.
6132 @emph{Validity checks for floating-point values.}
6133 @cindex @option{-gnatVf} (@command{gcc})
6134 In the absence of this switch, validity checking occurs only for discrete
6135 values. If @option{-gnatVf} is specified, then validity checking also applies
6136 for floating-point values, and NaNs and infinities are considered invalid,
6137 as well as out of range values for constrained types. Note that this means
6138 that standard IEEE infinity mode is not allowed. The exact contexts
6139 in which floating-point values are checked depends on the setting of other
6140 options. For example,
6141 @option{^-gnatVif^VALIDITY_CHECKING=(IN_PARAMS,FLOATS)^} or
6142 @option{^-gnatVfi^VALIDITY_CHECKING=(FLOATS,IN_PARAMS)^}
6143 (the order does not matter) specifies that floating-point parameters of mode
6144 @code{in} should be validity checked.
6147 @emph{Validity checks for @code{in} mode parameters}
6148 @cindex @option{-gnatVi} (@command{gcc})
6149 Arguments for parameters of mode @code{in} are validity checked in function
6150 and procedure calls at the point of call.
6153 @emph{Validity checks for @code{in out} mode parameters.}
6154 @cindex @option{-gnatVm} (@command{gcc})
6155 Arguments for parameters of mode @code{in out} are validity checked in
6156 procedure calls at the point of call. The @code{'m'} here stands for
6157 modify, since this concerns parameters that can be modified by the call.
6158 Note that there is no specific option to test @code{out} parameters,
6159 but any reference within the subprogram will be tested in the usual
6160 manner, and if an invalid value is copied back, any reference to it
6161 will be subject to validity checking.
6164 @emph{No validity checks.}
6165 @cindex @option{-gnatVn} (@command{gcc})
6166 This switch turns off all validity checking, including the default checking
6167 for case statements and left hand side subscripts. Note that the use of
6168 the switch @option{-gnatp} suppresses all run-time checks, including
6169 validity checks, and thus implies @option{-gnatVn}. When this switch
6170 is used, it cancels any other @option{-gnatV} previously issued.
6173 @emph{Validity checks for operator and attribute operands.}
6174 @cindex @option{-gnatVo} (@command{gcc})
6175 Arguments for predefined operators and attributes are validity checked.
6176 This includes all operators in package @code{Standard},
6177 the shift operators defined as intrinsic in package @code{Interfaces}
6178 and operands for attributes such as @code{Pos}. Checks are also made
6179 on individual component values for composite comparisons, and on the
6180 expressions in type conversions and qualified expressions. Checks are
6181 also made on explicit ranges using @samp{..} (e.g.@: slices, loops etc).
6184 @emph{Validity checks for parameters.}
6185 @cindex @option{-gnatVp} (@command{gcc})
6186 This controls the treatment of parameters within a subprogram (as opposed
6187 to @option{-gnatVi} and @option{-gnatVm} which control validity testing
6188 of parameters on a call. If either of these call options is used, then
6189 normally an assumption is made within a subprogram that the input arguments
6190 have been validity checking at the point of call, and do not need checking
6191 again within a subprogram). If @option{-gnatVp} is set, then this assumption
6192 is not made, and parameters are not assumed to be valid, so their validity
6193 will be checked (or rechecked) within the subprogram.
6196 @emph{Validity checks for function returns.}
6197 @cindex @option{-gnatVr} (@command{gcc})
6198 The expression in @code{return} statements in functions is validity
6202 @emph{Validity checks for subscripts.}
6203 @cindex @option{-gnatVs} (@command{gcc})
6204 All subscripts expressions are checked for validity, whether they appear
6205 on the right side or left side (in default mode only left side subscripts
6206 are validity checked).
6209 @emph{Validity checks for tests.}
6210 @cindex @option{-gnatVt} (@command{gcc})
6211 Expressions used as conditions in @code{if}, @code{while} or @code{exit}
6212 statements are checked, as well as guard expressions in entry calls.
6217 The @option{-gnatV} switch may be followed by
6218 ^a string of letters^a list of options^
6219 to turn on a series of validity checking options.
6221 @option{^-gnatVcr^/VALIDITY_CHECKING=(COPIES, RETURNS)^}
6222 specifies that in addition to the default validity checking, copies and
6223 function return expressions are to be validity checked.
6224 In order to make it easier
6225 to specify the desired combination of effects,
6227 the upper case letters @code{CDFIMORST} may
6228 be used to turn off the corresponding lower case option.
6231 the prefix @code{NO} on an option turns off the corresponding validity
6234 @item @code{NOCOPIES}
6235 @item @code{NODEFAULT}
6236 @item @code{NOFLOATS}
6237 @item @code{NOIN_PARAMS}
6238 @item @code{NOMOD_PARAMS}
6239 @item @code{NOOPERANDS}
6240 @item @code{NORETURNS}
6241 @item @code{NOSUBSCRIPTS}
6242 @item @code{NOTESTS}
6246 @option{^-gnatVaM^/VALIDITY_CHECKING=(ALL, NOMOD_PARAMS)^}
6247 turns on all validity checking options except for
6248 checking of @code{@b{in out}} procedure arguments.
6250 The specification of additional validity checking generates extra code (and
6251 in the case of @option{-gnatVa} the code expansion can be substantial).
6252 However, these additional checks can be very useful in detecting
6253 uninitialized variables, incorrect use of unchecked conversion, and other
6254 errors leading to invalid values. The use of pragma @code{Initialize_Scalars}
6255 is useful in conjunction with the extra validity checking, since this
6256 ensures that wherever possible uninitialized variables have invalid values.
6258 See also the pragma @code{Validity_Checks} which allows modification of
6259 the validity checking mode at the program source level, and also allows for
6260 temporary disabling of validity checks.
6262 @node Style Checking
6263 @subsection Style Checking
6264 @findex Style checking
6267 The @option{-gnaty^x^(option,option,@dots{})^} switch
6268 @cindex @option{-gnaty} (@command{gcc})
6269 causes the compiler to
6270 enforce specified style rules. A limited set of style rules has been used
6271 in writing the GNAT sources themselves. This switch allows user programs
6272 to activate all or some of these checks. If the source program fails a
6273 specified style check, an appropriate message is given, preceded by
6274 the character sequence ``(style)''. This message does not prevent
6275 successful compilation (unless the @option{-gnatwe} switch is used).
6277 Note that this is by no means intended to be a general facility for
6278 checking arbitrary coding standards. It is simply an embedding of the
6279 style rules we have chosen for the GNAT sources. If you are starting
6280 a project which does not have established style standards, you may
6281 find it useful to adopt the entire set of GNAT coding standards, or
6282 some subset of them.
6284 If you already have an established set of coding
6285 standards, then the selected style checking options may
6286 indeed correspond to choices you have made, but for general checking
6287 of an existing set of coding rules, you should look to the gnatcheck
6288 tool, which is designed for that purpose.
6292 @code{(option,option,@dots{})} is a sequence of keywords
6295 The string @var{x} is a sequence of letters or digits
6297 indicating the particular style
6298 checks to be performed. The following checks are defined:
6303 @emph{Specify indentation level.}
6304 If a digit from 1-9 appears
6305 ^in the string after @option{-gnaty}^as an option for /STYLE_CHECKS^
6306 then proper indentation is checked, with the digit indicating the
6307 indentation level required. A value of zero turns off this style check.
6308 The general style of required indentation is as specified by
6309 the examples in the Ada Reference Manual. Full line comments must be
6310 aligned with the @code{--} starting on a column that is a multiple of
6311 the alignment level, or they may be aligned the same way as the following
6312 non-blank line (this is useful when full line comments appear in the middle
6313 of a statement, or they may be aligned with the source line on the previous
6317 @emph{Check attribute casing.}
6318 Attribute names, including the case of keywords such as @code{digits}
6319 used as attributes names, must be written in mixed case, that is, the
6320 initial letter and any letter following an underscore must be uppercase.
6321 All other letters must be lowercase.
6323 @item ^A^ARRAY_INDEXES^
6324 @emph{Use of array index numbers in array attributes.}
6325 When using the array attributes First, Last, Range,
6326 or Length, the index number must be omitted for one-dimensional arrays
6327 and is required for multi-dimensional arrays.
6330 @emph{Blanks not allowed at statement end.}
6331 Trailing blanks are not allowed at the end of statements. The purpose of this
6332 rule, together with h (no horizontal tabs), is to enforce a canonical format
6333 for the use of blanks to separate source tokens.
6335 @item ^B^BOOLEAN_OPERATORS^
6336 @emph{Check Boolean operators.}
6337 The use of AND/OR operators is not permitted except in the cases of modular
6338 operands, array operands, and simple stand-alone boolean variables or
6339 boolean constants. In all other cases @code{and then}/@code{or else} are
6343 @emph{Check comments, double space.}
6344 Comments must meet the following set of rules:
6349 The ``@code{--}'' that starts the column must either start in column one,
6350 or else at least one blank must precede this sequence.
6353 Comments that follow other tokens on a line must have at least one blank
6354 following the ``@code{--}'' at the start of the comment.
6357 Full line comments must have at least two blanks following the
6358 ``@code{--}'' that starts the comment, with the following exceptions.
6361 A line consisting only of the ``@code{--}'' characters, possibly preceded
6362 by blanks is permitted.
6365 A comment starting with ``@code{--x}'' where @code{x} is a special character
6367 This allows proper processing of the output generated by specialized tools
6368 including @command{gnatprep} (where ``@code{--!}'' is used) and the SPARK
6370 language (where ``@code{--#}'' is used). For the purposes of this rule, a
6371 special character is defined as being in one of the ASCII ranges
6372 @code{16#21#@dots{}16#2F#} or @code{16#3A#@dots{}16#3F#}.
6373 Note that this usage is not permitted
6374 in GNAT implementation units (i.e., when @option{-gnatg} is used).
6377 A line consisting entirely of minus signs, possibly preceded by blanks, is
6378 permitted. This allows the construction of box comments where lines of minus
6379 signs are used to form the top and bottom of the box.
6382 A comment that starts and ends with ``@code{--}'' is permitted as long as at
6383 least one blank follows the initial ``@code{--}''. Together with the preceding
6384 rule, this allows the construction of box comments, as shown in the following
6387 ---------------------------
6388 -- This is a box comment --
6389 -- with two text lines. --
6390 ---------------------------
6395 @emph{Check comments, single space.}
6396 This is identical to @code{^c^COMMENTS^} except that only one space
6397 is required following the @code{--} of a comment instead of two.
6399 @item ^d^DOS_LINE_ENDINGS^
6400 @emph{Check no DOS line terminators present.}
6401 All lines must be terminated by a single ASCII.LF
6402 character (in particular the DOS line terminator sequence CR/LF is not
6406 @emph{Check end/exit labels.}
6407 Optional labels on @code{end} statements ending subprograms and on
6408 @code{exit} statements exiting named loops, are required to be present.
6411 @emph{No form feeds or vertical tabs.}
6412 Neither form feeds nor vertical tab characters are permitted
6416 @emph{GNAT style mode.}
6417 The set of style check switches is set to match that used by the GNAT sources.
6418 This may be useful when developing code that is eventually intended to be
6419 incorporated into GNAT. Currently this is equivalent to @option{-gnatwydISux})
6420 but additional style switches may be added to this set in the future without
6424 @emph{No horizontal tabs.}
6425 Horizontal tab characters are not permitted in the source text.
6426 Together with the b (no blanks at end of line) check, this
6427 enforces a canonical form for the use of blanks to separate
6431 @emph{Check if-then layout.}
6432 The keyword @code{then} must appear either on the same
6433 line as corresponding @code{if}, or on a line on its own, lined
6434 up under the @code{if}.
6437 @emph{check mode IN keywords.}
6438 Mode @code{in} (the default mode) is not
6439 allowed to be given explicitly. @code{in out} is fine,
6440 but not @code{in} on its own.
6443 @emph{Check keyword casing.}
6444 All keywords must be in lower case (with the exception of keywords
6445 such as @code{digits} used as attribute names to which this check
6449 @emph{Check layout.}
6450 Layout of statement and declaration constructs must follow the
6451 recommendations in the Ada Reference Manual, as indicated by the
6452 form of the syntax rules. For example an @code{else} keyword must
6453 be lined up with the corresponding @code{if} keyword.
6455 There are two respects in which the style rule enforced by this check
6456 option are more liberal than those in the Ada Reference Manual. First
6457 in the case of record declarations, it is permissible to put the
6458 @code{record} keyword on the same line as the @code{type} keyword, and
6459 then the @code{end} in @code{end record} must line up under @code{type}.
6460 This is also permitted when the type declaration is split on two lines.
6461 For example, any of the following three layouts is acceptable:
6463 @smallexample @c ada
6486 Second, in the case of a block statement, a permitted alternative
6487 is to put the block label on the same line as the @code{declare} or
6488 @code{begin} keyword, and then line the @code{end} keyword up under
6489 the block label. For example both the following are permitted:
6491 @smallexample @c ada
6509 The same alternative format is allowed for loops. For example, both of
6510 the following are permitted:
6512 @smallexample @c ada
6514 Clear : while J < 10 loop
6525 @item ^Lnnn^MAX_NESTING=nnn^
6526 @emph{Set maximum nesting level.}
6527 The maximum level of nesting of constructs (including subprograms, loops,
6528 blocks, packages, and conditionals) may not exceed the given value
6529 @option{nnn}. A value of zero disconnects this style check.
6531 @item ^m^LINE_LENGTH^
6532 @emph{Check maximum line length.}
6533 The length of source lines must not exceed 79 characters, including
6534 any trailing blanks. The value of 79 allows convenient display on an
6535 80 character wide device or window, allowing for possible special
6536 treatment of 80 character lines. Note that this count is of
6537 characters in the source text. This means that a tab character counts
6538 as one character in this count and a wide character sequence counts as
6539 a single character (however many bytes are needed in the encoding).
6541 @item ^Mnnn^MAX_LENGTH=nnn^
6542 @emph{Set maximum line length.}
6543 The length of lines must not exceed the
6544 given value @option{nnn}. The maximum value that can be specified is 32767.
6545 If neither style option for setting the line length is used, then the
6546 default is 255. This also controls the maximum length of lexical elements,
6547 where the only restriction is that they must fit on a single line.
6549 @item ^n^STANDARD_CASING^
6550 @emph{Check casing of entities in Standard.}
6551 Any identifier from Standard must be cased
6552 to match the presentation in the Ada Reference Manual (for example,
6553 @code{Integer} and @code{ASCII.NUL}).
6556 @emph{Turn off all style checks.}
6557 All style check options are turned off.
6559 @item ^o^ORDERED_SUBPROGRAMS^
6560 @emph{Check order of subprogram bodies.}
6561 All subprogram bodies in a given scope
6562 (e.g.@: a package body) must be in alphabetical order. The ordering
6563 rule uses normal Ada rules for comparing strings, ignoring casing
6564 of letters, except that if there is a trailing numeric suffix, then
6565 the value of this suffix is used in the ordering (e.g.@: Junk2 comes
6568 @item ^O^OVERRIDING_INDICATORS^
6569 @emph{Check that overriding subprograms are explicitly marked as such.}
6570 The declaration of a primitive operation of a type extension that overrides
6571 an inherited operation must carry an overriding indicator.
6574 @emph{Check pragma casing.}
6575 Pragma names must be written in mixed case, that is, the
6576 initial letter and any letter following an underscore must be uppercase.
6577 All other letters must be lowercase. An exception is that SPARK_Mode is
6578 allowed as an alternative for Spark_Mode.
6580 @item ^r^REFERENCES^
6581 @emph{Check references.}
6582 All identifier references must be cased in the same way as the
6583 corresponding declaration. No specific casing style is imposed on
6584 identifiers. The only requirement is for consistency of references
6588 @emph{Check separate specs.}
6589 Separate declarations (``specs'') are required for subprograms (a
6590 body is not allowed to serve as its own declaration). The only
6591 exception is that parameterless library level procedures are
6592 not required to have a separate declaration. This exception covers
6593 the most frequent form of main program procedures.
6595 @item ^S^STATEMENTS_AFTER_THEN_ELSE^
6596 @emph{Check no statements after @code{then}/@code{else}.}
6597 No statements are allowed
6598 on the same line as a @code{then} or @code{else} keyword following the
6599 keyword in an @code{if} statement. @code{or else} and @code{and then} are not
6600 affected, and a special exception allows a pragma to appear after @code{else}.
6603 @emph{Check token spacing.}
6604 The following token spacing rules are enforced:
6609 The keywords @code{abs} and @code{not} must be followed by a space.
6612 The token @code{=>} must be surrounded by spaces.
6615 The token @code{<>} must be preceded by a space or a left parenthesis.
6618 Binary operators other than @code{**} must be surrounded by spaces.
6619 There is no restriction on the layout of the @code{**} binary operator.
6622 Colon must be surrounded by spaces.
6625 Colon-equal (assignment, initialization) must be surrounded by spaces.
6628 Comma must be the first non-blank character on the line, or be
6629 immediately preceded by a non-blank character, and must be followed
6633 If the token preceding a left parenthesis ends with a letter or digit, then
6634 a space must separate the two tokens.
6637 if the token following a right parenthesis starts with a letter or digit, then
6638 a space must separate the two tokens.
6641 A right parenthesis must either be the first non-blank character on
6642 a line, or it must be preceded by a non-blank character.
6645 A semicolon must not be preceded by a space, and must not be followed by
6646 a non-blank character.
6649 A unary plus or minus may not be followed by a space.
6652 A vertical bar must be surrounded by spaces.
6656 Exactly one blank (and no other white space) must appear between
6657 a @code{not} token and a following @code{in} token.
6659 @item ^u^UNNECESSARY_BLANK_LINES^
6660 @emph{Check unnecessary blank lines.}
6661 Unnecessary blank lines are not allowed. A blank line is considered
6662 unnecessary if it appears at the end of the file, or if more than
6663 one blank line occurs in sequence.
6665 @item ^x^XTRA_PARENS^
6666 @emph{Check extra parentheses.}
6667 Unnecessary extra level of parentheses (C-style) are not allowed
6668 around conditions in @code{if} statements, @code{while} statements and
6669 @code{exit} statements.
6671 @item ^y^ALL_BUILTIN^
6672 @emph{Set all standard style check options}
6673 This is equivalent to @code{gnaty3aAbcefhiklmnprst}, that is all checking
6674 options enabled with the exception of @option{-gnatyB}, @option{-gnatyd},
6675 @option{-gnatyI}, @option{-gnatyLnnn}, @option{-gnatyo}, @option{-gnatyO},
6676 @option{-gnatyS}, @option{-gnatyu}, and @option{-gnatyx}.
6680 @emph{Remove style check options}
6681 This causes any subsequent options in the string to act as canceling the
6682 corresponding style check option. To cancel maximum nesting level control,
6683 use @option{L} parameter witout any integer value after that, because any
6684 digit following @option{-} in the parameter string of the @option{-gnaty}
6685 option will be threated as canceling indentation check. The same is true
6686 for @option{M} parameter. @option{y} and @option{N} parameters are not
6687 allowed after @option{-}.
6690 This causes any subsequent options in the string to enable the corresponding
6691 style check option. That is, it cancels the effect of a previous ^-^REMOVE^,
6697 @emph{Removing style check options}
6698 If the name of a style check is preceded by @option{NO} then the corresponding
6699 style check is turned off. For example @option{NOCOMMENTS} turns off style
6700 checking for comments.
6705 In the above rules, appearing in column one is always permitted, that is,
6706 counts as meeting either a requirement for a required preceding space,
6707 or as meeting a requirement for no preceding space.
6709 Appearing at the end of a line is also always permitted, that is, counts
6710 as meeting either a requirement for a following space, or as meeting
6711 a requirement for no following space.
6714 If any of these style rules is violated, a message is generated giving
6715 details on the violation. The initial characters of such messages are
6716 always ``@code{(style)}''. Note that these messages are treated as warning
6717 messages, so they normally do not prevent the generation of an object
6718 file. The @option{-gnatwe} switch can be used to treat warning messages,
6719 including style messages, as fatal errors.
6723 @option{-gnaty} on its own (that is not
6724 followed by any letters or digits) is equivalent
6725 to the use of @option{-gnatyy} as described above, that is all
6726 built-in standard style check options are enabled.
6730 /STYLE_CHECKS=ALL_BUILTIN enables all checking options with
6731 the exception of ORDERED_SUBPROGRAMS, UNNECESSARY_BLANK_LINES,
6732 XTRA_PARENS, and DOS_LINE_ENDINGS. In addition
6742 clears any previously set style checks.
6744 @node Run-Time Checks
6745 @subsection Run-Time Checks
6746 @cindex Division by zero
6747 @cindex Access before elaboration
6748 @cindex Checks, division by zero
6749 @cindex Checks, access before elaboration
6750 @cindex Checks, stack overflow checking
6753 By default, the following checks are suppressed: integer overflow
6754 checks, stack overflow checks, and checks for access before
6755 elaboration on subprogram calls. All other checks, including range
6756 checks and array bounds checks, are turned on by default. The
6757 following @command{gcc} switches refine this default behavior.
6762 @cindex @option{-gnatp} (@command{gcc})
6763 @cindex Suppressing checks
6764 @cindex Checks, suppressing
6766 This switch causes the unit to be compiled
6767 as though @code{pragma Suppress (All_checks)}
6768 had been present in the source. Validity checks are also eliminated (in
6769 other words @option{-gnatp} also implies @option{-gnatVn}.
6770 Use this switch to improve the performance
6771 of the code at the expense of safety in the presence of invalid data or
6774 Note that when checks are suppressed, the compiler is allowed, but not
6775 required, to omit the checking code. If the run-time cost of the
6776 checking code is zero or near-zero, the compiler will generate it even
6777 if checks are suppressed. In particular, if the compiler can prove
6778 that a certain check will necessarily fail, it will generate code to
6779 do an unconditional ``raise'', even if checks are suppressed. The
6780 compiler warns in this case. Another case in which checks may not be
6781 eliminated is when they are embedded in certain run time routines such
6782 as math library routines.
6784 Of course, run-time checks are omitted whenever the compiler can prove
6785 that they will not fail, whether or not checks are suppressed.
6787 Note that if you suppress a check that would have failed, program
6788 execution is erroneous, which means the behavior is totally
6789 unpredictable. The program might crash, or print wrong answers, or
6790 do anything else. It might even do exactly what you wanted it to do
6791 (and then it might start failing mysteriously next week or next
6792 year). The compiler will generate code based on the assumption that
6793 the condition being checked is true, which can result in disaster if
6794 that assumption is wrong.
6796 The checks subject to suppression include all the checks defined by
6797 the Ada standard, the additional implementation defined checks
6798 @code{Alignment_Check}, @code{Atomic_Synchronization}, and
6799 @code{Validity_Check}, as well as any checks introduced using
6800 @code{pragma Check_Name}.
6802 The @option{-gnatp} switch has no effect if a subsequent
6803 @option{-gnat-p} switch appears.
6806 @cindex @option{-gnat-p} (@command{gcc})
6807 @cindex Suppressing checks
6808 @cindex Checks, suppressing
6810 This switch cancels the effect of a previous @option{gnatp} switch.
6813 @cindex @option{-gnato??} (@command{gcc})
6814 @cindex Overflow checks
6815 @cindex Overflow mode
6816 @cindex Check, overflow
6817 This switch controls the mode used for computing intermediate
6818 arithmetic integer operations, and also enables overflow checking.
6819 For a full description of overflow mode and checking control, see
6820 the ``Overflow Check Handling in GNAT'' appendix in this
6823 Overflow checks are always enabled by this switch. The argument
6824 controls the mode, using the codes
6828 In STRICT mode, intermediate operations are always done using the
6829 base type, and overflow checking ensures that the result is within
6830 the base type range.
6833 In MINIMIZED mode, overflows in intermediate operations are avoided
6834 where possible by using a larger integer type for the computation
6835 (typically @code{Long_Long_Integer}). Overflow checking ensures that
6836 the result fits in this larger integer type.
6838 @item 3 = ELIMINATED
6839 In ELIMINATED mode, overflows in intermediate operations are avoided
6840 by using multi-precision arithmetic. In this case, overflow checking
6841 has no effect on intermediate operations (since overflow is impossible).
6844 If two digits are present after @option{-gnato} then the first digit
6845 sets the mode for expressions outside assertions, and the second digit
6846 sets the mode for expressions within assertions. Here assertions is used
6847 in the technical sense (which includes for example precondition and
6848 postcondition expressions).
6850 If one digit is present, the corresponding mode is applicable to both
6851 expressions within and outside assertion expressions.
6853 If no digits are present, the default is to enable overflow checks
6854 and set STRICT mode for both kinds of expressions. This is compatible
6855 with the use of @option{-gnato} in previous versions of GNAT.
6857 @findex Machine_Overflows
6858 Note that the @option{-gnato??} switch does not affect the code generated
6859 for any floating-point operations; it applies only to integer semantics.
6860 For floating-point, @value{EDITION} has the @code{Machine_Overflows}
6861 attribute set to @code{False} and the normal mode of operation is to
6862 generate IEEE NaN and infinite values on overflow or invalid operations
6863 (such as dividing 0.0 by 0.0).
6865 The reason that we distinguish overflow checking from other kinds of
6866 range constraint checking is that a failure of an overflow check, unlike
6867 for example the failure of a range check, can result in an incorrect
6868 value, but cannot cause random memory destruction (like an out of range
6869 subscript), or a wild jump (from an out of range case value). Overflow
6870 checking is also quite expensive in time and space, since in general it
6871 requires the use of double length arithmetic.
6873 Note again that the default is @option{^-gnato00^/OVERFLOW_CHECKS=00^},
6874 so overflow checking is not performed in default mode. This means that out of
6875 the box, with the default settings, @value{EDITION} does not do all the checks
6876 expected from the language description in the Ada Reference Manual.
6877 If you want all constraint checks to be performed, as described in this Manual,
6878 then you must explicitly use the @option{-gnato??}
6879 switch either on the @command{gnatmake} or @command{gcc} command.
6882 @cindex @option{-gnatE} (@command{gcc})
6883 @cindex Elaboration checks
6884 @cindex Check, elaboration
6885 Enables dynamic checks for access-before-elaboration
6886 on subprogram calls and generic instantiations.
6887 Note that @option{-gnatE} is not necessary for safety, because in the
6888 default mode, GNAT ensures statically that the checks would not fail.
6889 For full details of the effect and use of this switch,
6890 @xref{Compiling with gcc}.
6893 @cindex @option{-fstack-check} (@command{gcc})
6894 @cindex Stack Overflow Checking
6895 @cindex Checks, stack overflow checking
6896 Activates stack overflow checking. For full details of the effect and use of
6897 this switch see @ref{Stack Overflow Checking}.
6902 The setting of these switches only controls the default setting of the
6903 checks. You may modify them using either @code{Suppress} (to remove
6904 checks) or @code{Unsuppress} (to add back suppressed checks) pragmas in
6907 @node Using gcc for Syntax Checking
6908 @subsection Using @command{gcc} for Syntax Checking
6911 @cindex @option{-gnats} (@command{gcc})
6915 The @code{s} stands for ``syntax''.
6918 Run GNAT in syntax checking only mode. For
6919 example, the command
6922 $ gcc -c -gnats x.adb
6926 compiles file @file{x.adb} in syntax-check-only mode. You can check a
6927 series of files in a single command
6929 , and can use wild cards to specify such a group of files.
6930 Note that you must specify the @option{-c} (compile
6931 only) flag in addition to the @option{-gnats} flag.
6934 You may use other switches in conjunction with @option{-gnats}. In
6935 particular, @option{-gnatl} and @option{-gnatv} are useful to control the
6936 format of any generated error messages.
6938 When the source file is empty or contains only empty lines and/or comments,
6939 the output is a warning:
6942 $ gcc -c -gnats -x ada toto.txt
6943 toto.txt:1:01: warning: empty file, contains no compilation units
6947 Otherwise, the output is simply the error messages, if any. No object file or
6948 ALI file is generated by a syntax-only compilation. Also, no units other
6949 than the one specified are accessed. For example, if a unit @code{X}
6950 @code{with}'s a unit @code{Y}, compiling unit @code{X} in syntax
6951 check only mode does not access the source file containing unit
6954 @cindex Multiple units, syntax checking
6955 Normally, GNAT allows only a single unit in a source file. However, this
6956 restriction does not apply in syntax-check-only mode, and it is possible
6957 to check a file containing multiple compilation units concatenated
6958 together. This is primarily used by the @code{gnatchop} utility
6959 (@pxref{Renaming Files with gnatchop}).
6962 @node Using gcc for Semantic Checking
6963 @subsection Using @command{gcc} for Semantic Checking
6966 @cindex @option{-gnatc} (@command{gcc})
6970 The @code{c} stands for ``check''.
6972 Causes the compiler to operate in semantic check mode,
6973 with full checking for all illegalities specified in the
6974 Ada Reference Manual, but without generation of any object code
6975 (no object file is generated).
6977 Because dependent files must be accessed, you must follow the GNAT
6978 semantic restrictions on file structuring to operate in this mode:
6982 The needed source files must be accessible
6983 (@pxref{Search Paths and the Run-Time Library (RTL)}).
6986 Each file must contain only one compilation unit.
6989 The file name and unit name must match (@pxref{File Naming Rules}).
6992 The output consists of error messages as appropriate. No object file is
6993 generated. An @file{ALI} file is generated for use in the context of
6994 cross-reference tools, but this file is marked as not being suitable
6995 for binding (since no object file is generated).
6996 The checking corresponds exactly to the notion of
6997 legality in the Ada Reference Manual.
6999 Any unit can be compiled in semantics-checking-only mode, including
7000 units that would not normally be compiled (subunits,
7001 and specifications where a separate body is present).
7004 @node Compiling Different Versions of Ada
7005 @subsection Compiling Different Versions of Ada
7008 The switches described in this section allow you to explicitly specify
7009 the version of the Ada language that your programs are written in.
7010 The default mode is Ada 2012,
7011 but you can also specify Ada 95, Ada 2005 mode, or
7012 indicate Ada 83 compatibility mode.
7015 @cindex Compatibility with Ada 83
7017 @item -gnat83 (Ada 83 Compatibility Mode)
7018 @cindex @option{-gnat83} (@command{gcc})
7019 @cindex ACVC, Ada 83 tests
7023 Although GNAT is primarily an Ada 95 / Ada 2005 compiler, this switch
7024 specifies that the program is to be compiled in Ada 83 mode. With
7025 @option{-gnat83}, GNAT rejects most post-Ada 83 extensions and applies Ada 83
7026 semantics where this can be done easily.
7027 It is not possible to guarantee this switch does a perfect
7028 job; some subtle tests, such as are
7029 found in earlier ACVC tests (and that have been removed from the ACATS suite
7030 for Ada 95), might not compile correctly.
7031 Nevertheless, this switch may be useful in some circumstances, for example
7032 where, due to contractual reasons, existing code needs to be maintained
7033 using only Ada 83 features.
7035 With few exceptions (most notably the need to use @code{<>} on
7036 @cindex Generic formal parameters
7037 unconstrained generic formal parameters, the use of the new Ada 95 / Ada 2005
7038 reserved words, and the use of packages
7039 with optional bodies), it is not necessary to specify the
7040 @option{-gnat83} switch when compiling Ada 83 programs, because, with rare
7041 exceptions, Ada 95 and Ada 2005 are upwardly compatible with Ada 83. Thus
7042 a correct Ada 83 program is usually also a correct program
7043 in these later versions of the language standard.
7044 For further information, please refer to @ref{Compatibility and Porting Guide}.
7046 @item -gnat95 (Ada 95 mode)
7047 @cindex @option{-gnat95} (@command{gcc})
7051 This switch directs the compiler to implement the Ada 95 version of the
7053 Since Ada 95 is almost completely upwards
7054 compatible with Ada 83, Ada 83 programs may generally be compiled using
7055 this switch (see the description of the @option{-gnat83} switch for further
7056 information about Ada 83 mode).
7057 If an Ada 2005 program is compiled in Ada 95 mode,
7058 uses of the new Ada 2005 features will cause error
7059 messages or warnings.
7061 This switch also can be used to cancel the effect of a previous
7062 @option{-gnat83}, @option{-gnat05/2005}, or @option{-gnat12/2012}
7063 switch earlier in the command line.
7065 @item -gnat05 or -gnat2005 (Ada 2005 mode)
7066 @cindex @option{-gnat05} (@command{gcc})
7067 @cindex @option{-gnat2005} (@command{gcc})
7068 @cindex Ada 2005 mode
7071 This switch directs the compiler to implement the Ada 2005 version of the
7072 language, as documented in the official Ada standards document.
7073 Since Ada 2005 is almost completely upwards
7074 compatible with Ada 95 (and thus also with Ada 83), Ada 83 and Ada 95 programs
7075 may generally be compiled using this switch (see the description of the
7076 @option{-gnat83} and @option{-gnat95} switches for further
7079 @item -gnat12 or -gnat2012 (Ada 2012 mode)
7080 @cindex @option{-gnat12} (@command{gcc})
7081 @cindex @option{-gnat2012} (@command{gcc})
7082 @cindex Ada 2012 mode
7085 This switch directs the compiler to implement the Ada 2012 version of the
7086 language (also the default).
7087 Since Ada 2012 is almost completely upwards
7088 compatible with Ada 2005 (and thus also with Ada 83, and Ada 95),
7089 Ada 83 and Ada 95 programs
7090 may generally be compiled using this switch (see the description of the
7091 @option{-gnat83}, @option{-gnat95}, and @option{-gnat05/2005} switches
7092 for further information).
7094 @item -gnatX (Enable GNAT Extensions)
7095 @cindex @option{-gnatX} (@command{gcc})
7096 @cindex Ada language extensions
7097 @cindex GNAT extensions
7100 This switch directs the compiler to implement the latest version of the
7101 language (currently Ada 2012) and also to enable certain GNAT implementation
7102 extensions that are not part of any Ada standard. For a full list of these
7103 extensions, see the GNAT reference manual.
7107 @node Character Set Control
7108 @subsection Character Set Control
7110 @item ^-gnati^/IDENTIFIER_CHARACTER_SET=^@var{c}
7111 @cindex @option{^-gnati^/IDENTIFIER_CHARACTER_SET^} (@command{gcc})
7114 Normally GNAT recognizes the Latin-1 character set in source program
7115 identifiers, as described in the Ada Reference Manual.
7117 GNAT to recognize alternate character sets in identifiers. @var{c} is a
7118 single character ^^or word^ indicating the character set, as follows:
7122 ISO 8859-1 (Latin-1) identifiers
7125 ISO 8859-2 (Latin-2) letters allowed in identifiers
7128 ISO 8859-3 (Latin-3) letters allowed in identifiers
7131 ISO 8859-4 (Latin-4) letters allowed in identifiers
7134 ISO 8859-5 (Cyrillic) letters allowed in identifiers
7137 ISO 8859-15 (Latin-9) letters allowed in identifiers
7140 IBM PC letters (code page 437) allowed in identifiers
7143 IBM PC letters (code page 850) allowed in identifiers
7145 @item ^f^FULL_UPPER^
7146 Full upper-half codes allowed in identifiers
7149 No upper-half codes allowed in identifiers
7152 Wide-character codes (that is, codes greater than 255)
7153 allowed in identifiers
7156 @xref{Foreign Language Representation}, for full details on the
7157 implementation of these character sets.
7159 @item ^-gnatW^/WIDE_CHARACTER_ENCODING=^@var{e}
7160 @cindex @option{^-gnatW^/WIDE_CHARACTER_ENCODING^} (@command{gcc})
7161 Specify the method of encoding for wide characters.
7162 @var{e} is one of the following:
7167 Hex encoding (brackets coding also recognized)
7170 Upper half encoding (brackets encoding also recognized)
7173 Shift/JIS encoding (brackets encoding also recognized)
7176 EUC encoding (brackets encoding also recognized)
7179 UTF-8 encoding (brackets encoding also recognized)
7182 Brackets encoding only (default value)
7184 For full details on these encoding
7185 methods see @ref{Wide Character Encodings}.
7186 Note that brackets coding is always accepted, even if one of the other
7187 options is specified, so for example @option{-gnatW8} specifies that both
7188 brackets and UTF-8 encodings will be recognized. The units that are
7189 with'ed directly or indirectly will be scanned using the specified
7190 representation scheme, and so if one of the non-brackets scheme is
7191 used, it must be used consistently throughout the program. However,
7192 since brackets encoding is always recognized, it may be conveniently
7193 used in standard libraries, allowing these libraries to be used with
7194 any of the available coding schemes.
7196 Note that brackets encoding only applies to program text. Within comments,
7197 brackets are considered to be normal graphic characters, and bracket sequences
7198 are never recognized as wide characters.
7200 If no @option{-gnatW?} parameter is present, then the default
7201 representation is normally Brackets encoding only. However, if the
7202 first three characters of the file are 16#EF# 16#BB# 16#BF# (the standard
7203 byte order mark or BOM for UTF-8), then these three characters are
7204 skipped and the default representation for the file is set to UTF-8.
7206 Note that the wide character representation that is specified (explicitly
7207 or by default) for the main program also acts as the default encoding used
7208 for Wide_Text_IO files if not specifically overridden by a WCEM form
7213 When no @option{-gnatW?} is specified, then characters (other than wide
7214 characters represented using brackets notation) are treated as 8-bit
7215 Latin-1 codes. The codes recognized are the Latin-1 graphic characters,
7216 and ASCII format effectors (CR, LF, HT, VT). Other lower half control
7217 characters in the range 16#00#..16#1F# are not accepted in program text
7218 or in comments. Upper half control characters (16#80#..16#9F#) are rejected
7219 in program text, but allowed and ignored in comments. Note in particular
7220 that the Next Line (NEL) character whose encoding is 16#85# is not recognized
7221 as an end of line in this default mode. If your source program contains
7222 instances of the NEL character used as a line terminator,
7223 you must use UTF-8 encoding for the whole
7224 source program. In default mode, all lines must be ended by a standard
7225 end of line sequence (CR, CR/LF, or LF).
7227 Note that the convention of simply accepting all upper half characters in
7228 comments means that programs that use standard ASCII for program text, but
7229 UTF-8 encoding for comments are accepted in default mode, providing that the
7230 comments are ended by an appropriate (CR, or CR/LF, or LF) line terminator.
7231 This is a common mode for many programs with foreign language comments.
7233 @node File Naming Control
7234 @subsection File Naming Control
7237 @item ^-gnatk^/FILE_NAME_MAX_LENGTH=^@var{n}
7238 @cindex @option{-gnatk} (@command{gcc})
7239 Activates file name ``krunching''. @var{n}, a decimal integer in the range
7240 1-999, indicates the maximum allowable length of a file name (not
7241 including the @file{.ads} or @file{.adb} extension). The default is not
7242 to enable file name krunching.
7244 For the source file naming rules, @xref{File Naming Rules}.
7247 @node Subprogram Inlining Control
7248 @subsection Subprogram Inlining Control
7253 @cindex @option{-gnatn} (@command{gcc})
7255 The @code{n} here is intended to suggest the first syllable of the
7258 GNAT recognizes and processes @code{Inline} pragmas. However, for the
7259 inlining to actually occur, optimization must be enabled and, in order
7260 to enable inlining of subprograms specified by pragma @code{Inline},
7261 you must also specify this switch.
7262 In the absence of this switch, GNAT does not attempt
7263 inlining and does not need to access the bodies of
7264 subprograms for which @code{pragma Inline} is specified if they are not
7265 in the current unit.
7267 You can optionally specify the inlining level: 1 for moderate inlining across
7268 modules, which is a good compromise between compilation times and performances
7269 at run time, or 2 for full inlining across modules, which may bring about
7270 longer compilation times. If no inlining level is specified, the compiler will
7271 pick it based on the optimization level: 1 for @option{-O1}, @option{-O2} or
7272 @option{-Os} and 2 for @option{-O3}.
7274 If you specify this switch the compiler will access these bodies,
7275 creating an extra source dependency for the resulting object file, and
7276 where possible, the call will be inlined.
7277 For further details on when inlining is possible
7278 see @ref{Inlining of Subprograms}.
7281 @cindex @option{-gnatN} (@command{gcc})
7282 This switch activates front-end inlining which also
7283 generates additional dependencies.
7285 When using a gcc-based back end (in practice this means using any version
7286 of GNAT other than the JGNAT, .NET or GNAAMP versions), then the use of
7287 @option{-gnatN} is deprecated, and the use of @option{-gnatn} is preferred.
7288 Historically front end inlining was more extensive than the gcc back end
7289 inlining, but that is no longer the case.
7292 @node Auxiliary Output Control
7293 @subsection Auxiliary Output Control
7297 @cindex @option{-gnatt} (@command{gcc})
7298 @cindex Writing internal trees
7299 @cindex Internal trees, writing to file
7300 Causes GNAT to write the internal tree for a unit to a file (with the
7301 extension @file{.adt}.
7302 This not normally required, but is used by separate analysis tools.
7304 these tools do the necessary compilations automatically, so you should
7305 not have to specify this switch in normal operation.
7306 Note that the combination of switches @option{-gnatct}
7307 generates a tree in the form required by ASIS applications.
7310 @cindex @option{-gnatu} (@command{gcc})
7311 Print a list of units required by this compilation on @file{stdout}.
7312 The listing includes all units on which the unit being compiled depends
7313 either directly or indirectly.
7316 @item -pass-exit-codes
7317 @cindex @option{-pass-exit-codes} (@command{gcc})
7318 If this switch is not used, the exit code returned by @command{gcc} when
7319 compiling multiple files indicates whether all source files have
7320 been successfully used to generate object files or not.
7322 When @option{-pass-exit-codes} is used, @command{gcc} exits with an extended
7323 exit status and allows an integrated development environment to better
7324 react to a compilation failure. Those exit status are:
7328 There was an error in at least one source file.
7330 At least one source file did not generate an object file.
7332 The compiler died unexpectedly (internal error for example).
7334 An object file has been generated for every source file.
7339 @node Debugging Control
7340 @subsection Debugging Control
7344 @cindex Debugging options
7347 @cindex @option{-gnatd} (@command{gcc})
7348 Activate internal debugging switches. @var{x} is a letter or digit, or
7349 string of letters or digits, which specifies the type of debugging
7350 outputs desired. Normally these are used only for internal development
7351 or system debugging purposes. You can find full documentation for these
7352 switches in the body of the @code{Debug} unit in the compiler source
7353 file @file{debug.adb}.
7357 @cindex @option{-gnatG} (@command{gcc})
7358 This switch causes the compiler to generate auxiliary output containing
7359 a pseudo-source listing of the generated expanded code. Like most Ada
7360 compilers, GNAT works by first transforming the high level Ada code into
7361 lower level constructs. For example, tasking operations are transformed
7362 into calls to the tasking run-time routines. A unique capability of GNAT
7363 is to list this expanded code in a form very close to normal Ada source.
7364 This is very useful in understanding the implications of various Ada
7365 usage on the efficiency of the generated code. There are many cases in
7366 Ada (e.g.@: the use of controlled types), where simple Ada statements can
7367 generate a lot of run-time code. By using @option{-gnatG} you can identify
7368 these cases, and consider whether it may be desirable to modify the coding
7369 approach to improve efficiency.
7371 The optional parameter @code{nn} if present after -gnatG specifies an
7372 alternative maximum line length that overrides the normal default of 72.
7373 This value is in the range 40-999999, values less than 40 being silently
7374 reset to 40. The equal sign is optional.
7376 The format of the output is very similar to standard Ada source, and is
7377 easily understood by an Ada programmer. The following special syntactic
7378 additions correspond to low level features used in the generated code that
7379 do not have any exact analogies in pure Ada source form. The following
7380 is a partial list of these special constructions. See the spec
7381 of package @code{Sprint} in file @file{sprint.ads} for a full list.
7383 If the switch @option{-gnatL} is used in conjunction with
7384 @cindex @option{-gnatL} (@command{gcc})
7385 @option{-gnatG}, then the original source lines are interspersed
7386 in the expanded source (as comment lines with the original line number).
7389 @item new @var{xxx} @r{[}storage_pool = @var{yyy}@r{]}
7390 Shows the storage pool being used for an allocator.
7392 @item at end @var{procedure-name};
7393 Shows the finalization (cleanup) procedure for a scope.
7395 @item (if @var{expr} then @var{expr} else @var{expr})
7396 Conditional expression equivalent to the @code{x?y:z} construction in C.
7398 @item @var{target}^^^(@var{source})
7399 A conversion with floating-point truncation instead of rounding.
7401 @item @var{target}?(@var{source})
7402 A conversion that bypasses normal Ada semantic checking. In particular
7403 enumeration types and fixed-point types are treated simply as integers.
7405 @item @var{target}?^^^(@var{source})
7406 Combines the above two cases.
7408 @item @var{x} #/ @var{y}
7409 @itemx @var{x} #mod @var{y}
7410 @itemx @var{x} #* @var{y}
7411 @itemx @var{x} #rem @var{y}
7412 A division or multiplication of fixed-point values which are treated as
7413 integers without any kind of scaling.
7415 @item free @var{expr} @r{[}storage_pool = @var{xxx}@r{]}
7416 Shows the storage pool associated with a @code{free} statement.
7418 @item [subtype or type declaration]
7419 Used to list an equivalent declaration for an internally generated
7420 type that is referenced elsewhere in the listing.
7422 @c @item freeze @var{type-name} @ovar{actions}
7423 @c Expanding @ovar macro inline (explanation in macro def comments)
7424 @item freeze @var{type-name} @r{[}@var{actions}@r{]}
7425 Shows the point at which @var{type-name} is frozen, with possible
7426 associated actions to be performed at the freeze point.
7428 @item reference @var{itype}
7429 Reference (and hence definition) to internal type @var{itype}.
7431 @item @var{function-name}! (@var{arg}, @var{arg}, @var{arg})
7432 Intrinsic function call.
7434 @item @var{label-name} : label
7435 Declaration of label @var{labelname}.
7437 @item #$ @var{subprogram-name}
7438 An implicit call to a run-time support routine
7439 (to meet the requirement of H.3.1(9) in a
7442 @item @var{expr} && @var{expr} && @var{expr} @dots{} && @var{expr}
7443 A multiple concatenation (same effect as @var{expr} & @var{expr} &
7444 @var{expr}, but handled more efficiently).
7446 @item [constraint_error]
7447 Raise the @code{Constraint_Error} exception.
7449 @item @var{expression}'reference
7450 A pointer to the result of evaluating @var{expression}.
7452 @item @var{target-type}!(@var{source-expression})
7453 An unchecked conversion of @var{source-expression} to @var{target-type}.
7455 @item [@var{numerator}/@var{denominator}]
7456 Used to represent internal real literals (that) have no exact
7457 representation in base 2-16 (for example, the result of compile time
7458 evaluation of the expression 1.0/27.0).
7462 @cindex @option{-gnatD} (@command{gcc})
7463 When used in conjunction with @option{-gnatG}, this switch causes
7464 the expanded source, as described above for
7465 @option{-gnatG} to be written to files with names
7466 @file{^xxx.dg^XXX_DG^}, where @file{xxx} is the normal file name,
7467 instead of to the standard output file. For
7468 example, if the source file name is @file{hello.adb}, then a file
7469 @file{^hello.adb.dg^HELLO.ADB_DG^} will be written. The debugging
7470 information generated by the @command{gcc} @option{^-g^/DEBUG^} switch
7471 will refer to the generated @file{^xxx.dg^XXX_DG^} file. This allows
7472 you to do source level debugging using the generated code which is
7473 sometimes useful for complex code, for example to find out exactly
7474 which part of a complex construction raised an exception. This switch
7475 also suppress generation of cross-reference information (see
7476 @option{-gnatx}) since otherwise the cross-reference information
7477 would refer to the @file{^.dg^.DG^} file, which would cause
7478 confusion since this is not the original source file.
7480 Note that @option{-gnatD} actually implies @option{-gnatG}
7481 automatically, so it is not necessary to give both options.
7482 In other words @option{-gnatD} is equivalent to @option{-gnatDG}).
7484 If the switch @option{-gnatL} is used in conjunction with
7485 @cindex @option{-gnatL} (@command{gcc})
7486 @option{-gnatDG}, then the original source lines are interspersed
7487 in the expanded source (as comment lines with the original line number).
7489 The optional parameter @code{nn} if present after -gnatD specifies an
7490 alternative maximum line length that overrides the normal default of 72.
7491 This value is in the range 40-999999, values less than 40 being silently
7492 reset to 40. The equal sign is optional.
7495 @cindex @option{-gnatr} (@command{gcc})
7496 @cindex pragma Restrictions
7497 This switch causes pragma Restrictions to be treated as Restriction_Warnings
7498 so that violation of restrictions causes warnings rather than illegalities.
7499 This is useful during the development process when new restrictions are added
7500 or investigated. The switch also causes pragma Profile to be treated as
7501 Profile_Warnings, and pragma Restricted_Run_Time and pragma Ravenscar set
7502 restriction warnings rather than restrictions.
7505 @item -gnatR@r{[}0@r{|}1@r{|}2@r{|}3@r{[}s@r{]]}
7506 @cindex @option{-gnatR} (@command{gcc})
7507 This switch controls output from the compiler of a listing showing
7508 representation information for declared types and objects. For
7509 @option{-gnatR0}, no information is output (equivalent to omitting
7510 the @option{-gnatR} switch). For @option{-gnatR1} (which is the default,
7511 so @option{-gnatR} with no parameter has the same effect), size and alignment
7512 information is listed for declared array and record types. For
7513 @option{-gnatR2}, size and alignment information is listed for all
7514 declared types and objects. The @code{Linker_Section} is also listed for any
7515 entity for which the @code{Linker_Section} is set explicitly or implicitly (the
7516 latter case occurs for objects of a type for which a @code{Linker_Section}
7519 Finally @option{-gnatR3} includes symbolic
7520 expressions for values that are computed at run time for
7521 variant records. These symbolic expressions have a mostly obvious
7522 format with #n being used to represent the value of the n'th
7523 discriminant. See source files @file{repinfo.ads/adb} in the
7524 @code{GNAT} sources for full details on the format of @option{-gnatR3}
7525 output. If the switch is followed by an s (e.g.@: @option{-gnatR2s}), then
7526 the output is to a file with the name @file{^file.rep^file_REP^} where
7527 file is the name of the corresponding source file.
7530 This form of the switch controls output of subprogram conventions
7531 and parameter passing mechanisms for all subprograms. A following
7532 @code{s} means output to a file as described above.
7535 @item /REPRESENTATION_INFO
7536 @cindex @option{/REPRESENTATION_INFO} (@command{gcc})
7537 This qualifier controls output from the compiler of a listing showing
7538 representation information for declared types and objects. For
7539 @option{/REPRESENTATION_INFO=NONE}, no information is output
7540 (equivalent to omitting the @option{/REPRESENTATION_INFO} qualifier).
7541 @option{/REPRESENTATION_INFO} without option is equivalent to
7542 @option{/REPRESENTATION_INFO=ARRAYS}.
7543 For @option{/REPRESENTATION_INFO=ARRAYS}, size and alignment
7544 information is listed for declared array and record types. For
7545 @option{/REPRESENTATION_INFO=OBJECTS}, size and alignment information
7546 is listed for all expression information for values that are computed
7547 at run time for variant records. These symbolic expressions have a mostly
7548 obvious format with #n being used to represent the value of the n'th
7549 discriminant. See source files @file{REPINFO.ADS/ADB} in the
7550 @code{GNAT} sources for full details on the format of
7551 @option{/REPRESENTATION_INFO=SYMBOLIC} output.
7552 If _FILE is added at the end of an option
7553 (e.g.@: @option{/REPRESENTATION_INFO=ARRAYS_FILE}),
7554 then the output is to a file with the name @file{file_REP} where
7555 file is the name of the corresponding source file.
7557 @item /REPRESENTATION_INFO=MECHANISMS
7558 This qualifier form controls output of subprogram conventions
7559 and parameter passing mechanisms for all subprograms. It is
7560 possible to append _FILE as described above to cause information
7561 to be written to a file.
7564 Note that it is possible for record components to have zero size. In
7565 this case, the component clause uses an obvious extension of permitted
7566 Ada syntax, for example @code{at 0 range 0 .. -1}.
7568 Representation information requires that code be generated (since it is the
7569 code generator that lays out complex data structures). If an attempt is made
7570 to output representation information when no code is generated, for example
7571 when a subunit is compiled on its own, then no information can be generated
7572 and the compiler outputs a message to this effect.
7575 @cindex @option{-gnatS} (@command{gcc})
7576 The use of the switch @option{-gnatS} for an
7577 Ada compilation will cause the compiler to output a
7578 representation of package Standard in a form very
7579 close to standard Ada. It is not quite possible to
7580 do this entirely in standard Ada (since new
7581 numeric base types cannot be created in standard
7582 Ada), but the output is easily
7583 readable to any Ada programmer, and is useful to
7584 determine the characteristics of target dependent
7585 types in package Standard.
7588 @cindex @option{-gnatx} (@command{gcc})
7589 Normally the compiler generates full cross-referencing information in
7590 the @file{ALI} file. This information is used by a number of tools,
7591 including @code{gnatfind} and @code{gnatxref}. The @option{-gnatx} switch
7592 suppresses this information. This saves some space and may slightly
7593 speed up compilation, but means that these tools cannot be used.
7596 @node Exception Handling Control
7597 @subsection Exception Handling Control
7600 GNAT uses two methods for handling exceptions at run-time. The
7601 @code{setjmp/longjmp} method saves the context when entering
7602 a frame with an exception handler. Then when an exception is
7603 raised, the context can be restored immediately, without the
7604 need for tracing stack frames. This method provides very fast
7605 exception propagation, but introduces significant overhead for
7606 the use of exception handlers, even if no exception is raised.
7608 The other approach is called ``zero cost'' exception handling.
7609 With this method, the compiler builds static tables to describe
7610 the exception ranges. No dynamic code is required when entering
7611 a frame containing an exception handler. When an exception is
7612 raised, the tables are used to control a back trace of the
7613 subprogram invocation stack to locate the required exception
7614 handler. This method has considerably poorer performance for
7615 the propagation of exceptions, but there is no overhead for
7616 exception handlers if no exception is raised. Note that in this
7617 mode and in the context of mixed Ada and C/C++ programming,
7618 to propagate an exception through a C/C++ code, the C/C++ code
7619 must be compiled with the @option{-funwind-tables} GCC's
7622 The following switches may be used to control which of the
7623 two exception handling methods is used.
7629 @cindex @option{--RTS=sjlj} (@command{gnatmake})
7630 This switch causes the setjmp/longjmp run-time (when available) to be used
7631 for exception handling. If the default
7632 mechanism for the target is zero cost exceptions, then
7633 this switch can be used to modify this default, and must be
7634 used for all units in the partition.
7635 This option is rarely used. One case in which it may be
7636 advantageous is if you have an application where exception
7637 raising is common and the overall performance of the
7638 application is improved by favoring exception propagation.
7641 @cindex @option{--RTS=zcx} (@command{gnatmake})
7642 @cindex Zero Cost Exceptions
7643 This switch causes the zero cost approach to be used
7644 for exception handling. If this is the default mechanism for the
7645 target (see below), then this switch is unneeded. If the default
7646 mechanism for the target is setjmp/longjmp exceptions, then
7647 this switch can be used to modify this default, and must be
7648 used for all units in the partition.
7649 This option can only be used if the zero cost approach
7650 is available for the target in use, otherwise it will generate an error.
7654 The same option @option{--RTS} must be used both for @command{gcc}
7655 and @command{gnatbind}. Passing this option to @command{gnatmake}
7656 (@pxref{Switches for gnatmake}) will ensure the required consistency
7657 through the compilation and binding steps.
7659 @node Units to Sources Mapping Files
7660 @subsection Units to Sources Mapping Files
7664 @item -gnatem=@var{path}
7665 @cindex @option{-gnatem} (@command{gcc})
7666 A mapping file is a way to communicate to the compiler two mappings:
7667 from unit names to file names (without any directory information) and from
7668 file names to path names (with full directory information). These mappings
7669 are used by the compiler to short-circuit the path search.
7671 The use of mapping files is not required for correct operation of the
7672 compiler, but mapping files can improve efficiency, particularly when
7673 sources are read over a slow network connection. In normal operation,
7674 you need not be concerned with the format or use of mapping files,
7675 and the @option{-gnatem} switch is not a switch that you would use
7676 explicitly. It is intended primarily for use by automatic tools such as
7677 @command{gnatmake} running under the project file facility. The
7678 description here of the format of mapping files is provided
7679 for completeness and for possible use by other tools.
7681 A mapping file is a sequence of sets of three lines. In each set, the
7682 first line is the unit name, in lower case, with @code{%s} appended
7683 for specs and @code{%b} appended for bodies; the second line is the
7684 file name; and the third line is the path name.
7690 /gnat/project1/sources/main.2.ada
7693 When the switch @option{-gnatem} is specified, the compiler will
7694 create in memory the two mappings from the specified file. If there is
7695 any problem (nonexistent file, truncated file or duplicate entries),
7696 no mapping will be created.
7698 Several @option{-gnatem} switches may be specified; however, only the
7699 last one on the command line will be taken into account.
7701 When using a project file, @command{gnatmake} creates a temporary
7702 mapping file and communicates it to the compiler using this switch.
7706 @node Integrated Preprocessing
7707 @subsection Integrated Preprocessing
7710 GNAT sources may be preprocessed immediately before compilation.
7711 In this case, the actual
7712 text of the source is not the text of the source file, but is derived from it
7713 through a process called preprocessing. Integrated preprocessing is specified
7714 through switches @option{-gnatep} and/or @option{-gnateD}. @option{-gnatep}
7715 indicates, through a text file, the preprocessing data to be used.
7716 @option{-gnateD} specifies or modifies the values of preprocessing symbol.
7717 Note that integrated preprocessing applies only to Ada source files, it is
7718 not available for configuration pragma files.
7721 Note that when integrated preprocessing is used, the output from the
7722 preprocessor is not written to any external file. Instead it is passed
7723 internally to the compiler. If you need to preserve the result of
7724 preprocessing in a file, then you should use @command{gnatprep}
7725 to perform the desired preprocessing in stand-alone mode.
7728 It is recommended that @command{gnatmake} switch ^-s^/SWITCH_CHECK^ should be
7729 used when Integrated Preprocessing is used. The reason is that preprocessing
7730 with another Preprocessing Data file without changing the sources will
7731 not trigger recompilation without this switch.
7734 Note that @command{gnatmake} switch ^-m^/MINIMAL_RECOMPILATION^ will almost
7735 always trigger recompilation for sources that are preprocessed,
7736 because @command{gnatmake} cannot compute the checksum of the source after
7740 The actual preprocessing function is described in details in section
7741 @ref{Preprocessing with gnatprep}. This section only describes how integrated
7742 preprocessing is triggered and parameterized.
7746 @item -gnatep=@var{file}
7747 @cindex @option{-gnatep} (@command{gcc})
7748 This switch indicates to the compiler the file name (without directory
7749 information) of the preprocessor data file to use. The preprocessor data file
7750 should be found in the source directories. Note that when the compiler is
7751 called by a builder such as (@command{gnatmake} with a project
7752 file, if the object directory is not also a source directory, the builder needs
7753 to be called with @option{-x}.
7756 A preprocessing data file is a text file with significant lines indicating
7757 how should be preprocessed either a specific source or all sources not
7758 mentioned in other lines. A significant line is a nonempty, non-comment line.
7759 Comments are similar to Ada comments.
7762 Each significant line starts with either a literal string or the character '*'.
7763 A literal string is the file name (without directory information) of the source
7764 to preprocess. A character '*' indicates the preprocessing for all the sources
7765 that are not specified explicitly on other lines (order of the lines is not
7766 significant). It is an error to have two lines with the same file name or two
7767 lines starting with the character '*'.
7770 After the file name or the character '*', another optional literal string
7771 indicating the file name of the definition file to be used for preprocessing
7772 (@pxref{Form of Definitions File}). The definition files are found by the
7773 compiler in one of the source directories. In some cases, when compiling
7774 a source in a directory other than the current directory, if the definition
7775 file is in the current directory, it may be necessary to add the current
7776 directory as a source directory through switch ^-I.^/SEARCH=[]^, otherwise
7777 the compiler would not find the definition file.
7780 Then, optionally, ^switches^switches^ similar to those of @code{gnatprep} may
7781 be found. Those ^switches^switches^ are:
7786 Causes both preprocessor lines and the lines deleted by
7787 preprocessing to be replaced by blank lines, preserving the line number.
7788 This ^switch^switch^ is always implied; however, if specified after @option{-c}
7789 it cancels the effect of @option{-c}.
7792 Causes both preprocessor lines and the lines deleted
7793 by preprocessing to be retained as comments marked
7794 with the special string ``@code{--! }''.
7796 @item -Dsymbol=value
7797 Define or redefine a symbol, associated with value. A symbol is an Ada
7798 identifier, or an Ada reserved word, with the exception of @code{if},
7799 @code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}.
7800 @code{value} is either a literal string, an Ada identifier or any Ada reserved
7801 word. A symbol declared with this ^switch^switch^ replaces a symbol with the
7802 same name defined in a definition file.
7805 Causes a sorted list of symbol names and values to be
7806 listed on the standard output file.
7809 Causes undefined symbols to be treated as having the value @code{FALSE}
7811 of a preprocessor test. In the absence of this option, an undefined symbol in
7812 a @code{#if} or @code{#elsif} test will be treated as an error.
7817 Examples of valid lines in a preprocessor data file:
7820 "toto.adb" "prep.def" -u
7821 -- preprocess "toto.adb", using definition file "prep.def",
7822 -- undefined symbol are False.
7825 -- preprocess all other sources without a definition file;
7826 -- suppressed lined are commented; symbol VERSION has the value V101.
7828 "titi.adb" "prep2.def" -s
7829 -- preprocess "titi.adb", using definition file "prep2.def";
7830 -- list all symbols with their values.
7833 @item ^-gnateD^/DATA_PREPROCESSING=^symbol@r{[}=value@r{]}
7834 @cindex @option{-gnateD} (@command{gcc})
7835 Define or redefine a preprocessing symbol, associated with value. If no value
7836 is given on the command line, then the value of the symbol is @code{True}.
7837 A symbol is an identifier, following normal Ada (case-insensitive)
7838 rules for its syntax, and value is either an arbitrary string between double
7839 quotes or any sequence (including an empty sequence) of characters from the
7840 set (letters, digits, period, underline).
7841 Ada reserved words may be used as symbols, with the exceptions of @code{if},
7842 @code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}.
7851 -gnateDFoo=\"Foo-Bar\"
7856 A symbol declared with this ^switch^switch^ on the command line replaces a
7857 symbol with the same name either in a definition file or specified with a
7858 ^switch^switch^ -D in the preprocessor data file.
7861 This switch is similar to switch @option{^-D^/ASSOCIATE^} of @code{gnatprep}.
7864 When integrated preprocessing is performed and the preprocessor modifies
7865 the source text, write the result of this preprocessing into a file
7866 <source>^.prep^_prep^.
7870 @node Code Generation Control
7871 @subsection Code Generation Control
7875 The GCC technology provides a wide range of target dependent
7876 @option{-m} switches for controlling
7877 details of code generation with respect to different versions of
7878 architectures. This includes variations in instruction sets (e.g.@:
7879 different members of the power pc family), and different requirements
7880 for optimal arrangement of instructions (e.g.@: different members of
7881 the x86 family). The list of available @option{-m} switches may be
7882 found in the GCC documentation.
7884 Use of these @option{-m} switches may in some cases result in improved
7887 The @value{EDITION} technology is tested and qualified without any
7888 @option{-m} switches,
7889 so generally the most reliable approach is to avoid the use of these
7890 switches. However, we generally expect most of these switches to work
7891 successfully with @value{EDITION}, and many customers have reported successful
7892 use of these options.
7894 Our general advice is to avoid the use of @option{-m} switches unless
7895 special needs lead to requirements in this area. In particular,
7896 there is no point in using @option{-m} switches to improve performance
7897 unless you actually see a performance improvement.
7901 @subsection Return Codes
7902 @cindex Return Codes
7903 @cindex @option{/RETURN_CODES=VMS}
7906 On VMS, GNAT compiled programs return POSIX-style codes by default,
7907 e.g.@: @option{/RETURN_CODES=POSIX}.
7909 To enable VMS style return codes, use GNAT BIND and LINK with the option
7910 @option{/RETURN_CODES=VMS}. For example:
7913 GNAT BIND MYMAIN.ALI /RETURN_CODES=VMS
7914 GNAT LINK MYMAIN.ALI /RETURN_CODES=VMS
7918 Programs built with /RETURN_CODES=VMS are suitable to be called in
7919 VMS DCL scripts. Programs compiled with the default /RETURN_CODES=POSIX
7920 are suitable for spawning with appropriate GNAT RTL routines.
7924 @node Search Paths and the Run-Time Library (RTL)
7925 @section Search Paths and the Run-Time Library (RTL)
7928 With the GNAT source-based library system, the compiler must be able to
7929 find source files for units that are needed by the unit being compiled.
7930 Search paths are used to guide this process.
7932 The compiler compiles one source file whose name must be given
7933 explicitly on the command line. In other words, no searching is done
7934 for this file. To find all other source files that are needed (the most
7935 common being the specs of units), the compiler examines the following
7936 directories, in the following order:
7940 The directory containing the source file of the main unit being compiled
7941 (the file name on the command line).
7944 Each directory named by an @option{^-I^/SOURCE_SEARCH^} switch given on the
7945 @command{gcc} command line, in the order given.
7948 @findex ADA_PRJ_INCLUDE_FILE
7949 Each of the directories listed in the text file whose name is given
7950 by the @env{ADA_PRJ_INCLUDE_FILE} ^environment variable^logical name^.
7953 @env{ADA_PRJ_INCLUDE_FILE} is normally set by gnatmake or by the ^gnat^GNAT^
7954 driver when project files are used. It should not normally be set
7958 @findex ADA_INCLUDE_PATH
7959 Each of the directories listed in the value of the
7960 @env{ADA_INCLUDE_PATH} ^environment variable^logical name^.
7962 Construct this value
7963 exactly as the @env{PATH} environment variable: a list of directory
7964 names separated by colons (semicolons when working with the NT version).
7967 Normally, define this value as a logical name containing a comma separated
7968 list of directory names.
7970 This variable can also be defined by means of an environment string
7971 (an argument to the HP C exec* set of functions).
7975 DEFINE ANOTHER_PATH FOO:[BAG]
7976 DEFINE ADA_INCLUDE_PATH ANOTHER_PATH,FOO:[BAM],FOO:[BAR]
7979 By default, the path includes GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB]
7980 first, followed by the standard Ada
7981 libraries in GNU:[LIB.OPENVMS7_x.2_8_x.ADAINCLUDE].
7982 If this is not redefined, the user will obtain the HP Ada 83 IO packages
7983 (Text_IO, Sequential_IO, etc)
7984 instead of the standard Ada packages. Thus, in order to get the standard Ada
7985 packages by default, ADA_INCLUDE_PATH must be redefined.
7989 The content of the @file{ada_source_path} file which is part of the GNAT
7990 installation tree and is used to store standard libraries such as the
7991 GNAT Run Time Library (RTL) source files.
7993 @ref{Installing a library}
7998 Specifying the switch @option{^-I-^/NOCURRENT_DIRECTORY^}
7999 inhibits the use of the directory
8000 containing the source file named in the command line. You can still
8001 have this directory on your search path, but in this case it must be
8002 explicitly requested with a @option{^-I^/SOURCE_SEARCH^} switch.
8004 Specifying the switch @option{-nostdinc}
8005 inhibits the search of the default location for the GNAT Run Time
8006 Library (RTL) source files.
8008 The compiler outputs its object files and ALI files in the current
8011 Caution: The object file can be redirected with the @option{-o} switch;
8012 however, @command{gcc} and @code{gnat1} have not been coordinated on this
8013 so the @file{ALI} file will not go to the right place. Therefore, you should
8014 avoid using the @option{-o} switch.
8018 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
8019 children make up the GNAT RTL, together with the simple @code{System.IO}
8020 package used in the @code{"Hello World"} example. The sources for these units
8021 are needed by the compiler and are kept together in one directory. Not
8022 all of the bodies are needed, but all of the sources are kept together
8023 anyway. In a normal installation, you need not specify these directory
8024 names when compiling or binding. Either the environment variables or
8025 the built-in defaults cause these files to be found.
8027 In addition to the language-defined hierarchies (@code{System}, @code{Ada} and
8028 @code{Interfaces}), the GNAT distribution provides a fourth hierarchy,
8029 consisting of child units of @code{GNAT}. This is a collection of generally
8030 useful types, subprograms, etc. @xref{Top, GNAT Reference Manual, About
8031 This Guid, gnat_rm, GNAT Reference Manual}, for further details.
8033 Besides simplifying access to the RTL, a major use of search paths is
8034 in compiling sources from multiple directories. This can make
8035 development environments much more flexible.
8037 @node Order of Compilation Issues
8038 @section Order of Compilation Issues
8041 If, in our earlier example, there was a spec for the @code{hello}
8042 procedure, it would be contained in the file @file{hello.ads}; yet this
8043 file would not have to be explicitly compiled. This is the result of the
8044 model we chose to implement library management. Some of the consequences
8045 of this model are as follows:
8049 There is no point in compiling specs (except for package
8050 specs with no bodies) because these are compiled as needed by clients. If
8051 you attempt a useless compilation, you will receive an error message.
8052 It is also useless to compile subunits because they are compiled as needed
8056 There are no order of compilation requirements: performing a
8057 compilation never obsoletes anything. The only way you can obsolete
8058 something and require recompilations is to modify one of the
8059 source files on which it depends.
8062 There is no library as such, apart from the ALI files
8063 (@pxref{The Ada Library Information Files}, for information on the format
8064 of these files). For now we find it convenient to create separate ALI files,
8065 but eventually the information therein may be incorporated into the object
8069 When you compile a unit, the source files for the specs of all units
8070 that it @code{with}'s, all its subunits, and the bodies of any generics it
8071 instantiates must be available (reachable by the search-paths mechanism
8072 described above), or you will receive a fatal error message.
8079 The following are some typical Ada compilation command line examples:
8082 @item $ gcc -c xyz.adb
8083 Compile body in file @file{xyz.adb} with all default options.
8086 @item $ gcc -c -O2 -gnata xyz-def.adb
8089 @item $ GNAT COMPILE /OPTIMIZE=ALL -gnata xyz-def.adb
8092 Compile the child unit package in file @file{xyz-def.adb} with extensive
8093 optimizations, and pragma @code{Assert}/@code{Debug} statements
8096 @item $ gcc -c -gnatc abc-def.adb
8097 Compile the subunit in file @file{abc-def.adb} in semantic-checking-only
8101 @node Binding with gnatbind
8102 @chapter Binding with @code{gnatbind}
8106 * Running gnatbind::
8107 * Switches for gnatbind::
8108 * Command-Line Access::
8109 * Search Paths for gnatbind::
8110 * Examples of gnatbind Usage::
8114 This chapter describes the GNAT binder, @code{gnatbind}, which is used
8115 to bind compiled GNAT objects.
8117 Note: to invoke @code{gnatbind} with a project file, use the @code{gnat}
8118 driver (see @ref{The GNAT Driver and Project Files}).
8120 The @code{gnatbind} program performs four separate functions:
8124 Checks that a program is consistent, in accordance with the rules in
8125 Chapter 10 of the Ada Reference Manual. In particular, error
8126 messages are generated if a program uses inconsistent versions of a
8130 Checks that an acceptable order of elaboration exists for the program
8131 and issues an error message if it cannot find an order of elaboration
8132 that satisfies the rules in Chapter 10 of the Ada Language Manual.
8135 Generates a main program incorporating the given elaboration order.
8136 This program is a small Ada package (body and spec) that
8137 must be subsequently compiled
8138 using the GNAT compiler. The necessary compilation step is usually
8139 performed automatically by @command{gnatlink}. The two most important
8140 functions of this program
8141 are to call the elaboration routines of units in an appropriate order
8142 and to call the main program.
8145 Determines the set of object files required by the given main program.
8146 This information is output in the forms of comments in the generated program,
8147 to be read by the @command{gnatlink} utility used to link the Ada application.
8150 @node Running gnatbind
8151 @section Running @code{gnatbind}
8154 The form of the @code{gnatbind} command is
8157 @c $ gnatbind @ovar{switches} @var{mainprog}@r{[}.ali@r{]} @ovar{switches}
8158 @c Expanding @ovar macro inline (explanation in macro def comments)
8159 $ gnatbind @r{[}@var{switches}@r{]} @var{mainprog}@r{[}.ali@r{]} @r{[}@var{switches}@r{]}
8163 where @file{@var{mainprog}.adb} is the Ada file containing the main program
8164 unit body. @code{gnatbind} constructs an Ada
8165 package in two files whose names are
8166 @file{b~@var{mainprog}.ads}, and @file{b~@var{mainprog}.adb}.
8167 For example, if given the
8168 parameter @file{hello.ali}, for a main program contained in file
8169 @file{hello.adb}, the binder output files would be @file{b~hello.ads}
8170 and @file{b~hello.adb}.
8172 When doing consistency checking, the binder takes into consideration
8173 any source files it can locate. For example, if the binder determines
8174 that the given main program requires the package @code{Pack}, whose
8176 file is @file{pack.ali} and whose corresponding source spec file is
8177 @file{pack.ads}, it attempts to locate the source file @file{pack.ads}
8178 (using the same search path conventions as previously described for the
8179 @command{gcc} command). If it can locate this source file, it checks that
8181 or source checksums of the source and its references to in @file{ALI} files
8182 match. In other words, any @file{ALI} files that mentions this spec must have
8183 resulted from compiling this version of the source file (or in the case
8184 where the source checksums match, a version close enough that the
8185 difference does not matter).
8187 @cindex Source files, use by binder
8188 The effect of this consistency checking, which includes source files, is
8189 that the binder ensures that the program is consistent with the latest
8190 version of the source files that can be located at bind time. Editing a
8191 source file without compiling files that depend on the source file cause
8192 error messages to be generated by the binder.
8194 For example, suppose you have a main program @file{hello.adb} and a
8195 package @code{P}, from file @file{p.ads} and you perform the following
8200 Enter @code{gcc -c hello.adb} to compile the main program.
8203 Enter @code{gcc -c p.ads} to compile package @code{P}.
8206 Edit file @file{p.ads}.
8209 Enter @code{gnatbind hello}.
8213 At this point, the file @file{p.ali} contains an out-of-date time stamp
8214 because the file @file{p.ads} has been edited. The attempt at binding
8215 fails, and the binder generates the following error messages:
8218 error: "hello.adb" must be recompiled ("p.ads" has been modified)
8219 error: "p.ads" has been modified and must be recompiled
8223 Now both files must be recompiled as indicated, and then the bind can
8224 succeed, generating a main program. You need not normally be concerned
8225 with the contents of this file, but for reference purposes a sample
8226 binder output file is given in @ref{Example of Binder Output File}.
8228 In most normal usage, the default mode of @command{gnatbind} which is to
8229 generate the main package in Ada, as described in the previous section.
8230 In particular, this means that any Ada programmer can read and understand
8231 the generated main program. It can also be debugged just like any other
8232 Ada code provided the @option{^-g^/DEBUG^} switch is used for
8233 @command{gnatbind} and @command{gnatlink}.
8235 @node Switches for gnatbind
8236 @section Switches for @command{gnatbind}
8239 The following switches are available with @code{gnatbind}; details will
8240 be presented in subsequent sections.
8243 * Consistency-Checking Modes::
8244 * Binder Error Message Control::
8245 * Elaboration Control::
8247 * Dynamic Allocation Control::
8248 * Binding with Non-Ada Main Programs::
8249 * Binding Programs with No Main Subprogram::
8256 @cindex @option{--version} @command{gnatbind}
8257 Display Copyright and version, then exit disregarding all other options.
8260 @cindex @option{--help} @command{gnatbind}
8261 If @option{--version} was not used, display usage, then exit disregarding
8265 @cindex @option{-a} @command{gnatbind}
8266 Indicates that, if supported by the platform, the adainit procedure should
8267 be treated as an initialisation routine by the linker (a constructor). This
8268 is intended to be used by the Project Manager to automatically initialize
8269 shared Stand-Alone Libraries.
8271 @item ^-aO^/OBJECT_SEARCH^
8272 @cindex @option{^-aO^/OBJECT_SEARCH^} (@command{gnatbind})
8273 Specify directory to be searched for ALI files.
8275 @item ^-aI^/SOURCE_SEARCH^
8276 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatbind})
8277 Specify directory to be searched for source file.
8279 @item ^-A^/ALI_LIST^@r{[=}@var{filename}@r{]}
8280 @cindex @option{^-A^/ALI_LIST^} (@command{gnatbind})
8281 Output ALI list (to standard output or to the named file).
8283 @item ^-b^/REPORT_ERRORS=BRIEF^
8284 @cindex @option{^-b^/REPORT_ERRORS=BRIEF^} (@command{gnatbind})
8285 Generate brief messages to @file{stderr} even if verbose mode set.
8287 @item ^-c^/NOOUTPUT^
8288 @cindex @option{^-c^/NOOUTPUT^} (@command{gnatbind})
8289 Check only, no generation of binder output file.
8291 @item ^-d^/DEFAULT_STACK_SIZE=^@var{nn}@r{[}k@r{|}m@r{]}
8292 @cindex @option{^-d^/DEFAULT_STACK_SIZE=^@var{nn}@r{[}k@r{|}m@r{]}} (@command{gnatbind})
8293 This switch can be used to change the default task stack size value
8294 to a specified size @var{nn}, which is expressed in bytes by default, or
8295 in kilobytes when suffixed with @var{k} or in megabytes when suffixed
8297 In the absence of a @samp{@r{[}k@r{|}m@r{]}} suffix, this switch is equivalent,
8298 in effect, to completing all task specs with
8299 @smallexample @c ada
8300 pragma Storage_Size (nn);
8302 When they do not already have such a pragma.
8304 @item ^-D^/DEFAULT_SECONDARY_STACK_SIZE=^@var{nn}@r{[}k@r{|}m@r{]}
8305 @cindex @option{^-D^/DEFAULT_SECONDARY_STACK_SIZE=nnnnn^} (@command{gnatbind})
8306 This switch can be used to change the default secondary stack size value
8307 to a specified size @var{nn}, which is expressed in bytes by default, or
8308 in kilobytes when suffixed with @var{k} or in megabytes when suffixed
8311 The secondary stack is used to deal with functions that return a variable
8312 sized result, for example a function returning an unconstrained
8313 String. There are two ways in which this secondary stack is allocated.
8315 For most targets, the secondary stack is growing on demand and is allocated
8316 as a chain of blocks in the heap. The -D option is not very
8317 relevant. It only give some control over the size of the allocated
8318 blocks (whose size is the minimum of the default secondary stack size value,
8319 and the actual size needed for the current allocation request).
8321 For certain targets, notably VxWorks 653,
8322 the secondary stack is allocated by carving off a fixed ratio chunk of the
8323 primary task stack. The -D option is used to define the
8324 size of the environment task's secondary stack.
8326 @item ^-e^/ELABORATION_DEPENDENCIES^
8327 @cindex @option{^-e^/ELABORATION_DEPENDENCIES^} (@command{gnatbind})
8328 Output complete list of elaboration-order dependencies.
8330 @item ^-E^/STORE_TRACEBACKS^
8331 @cindex @option{^-E^/STORE_TRACEBACKS^} (@command{gnatbind})
8332 Store tracebacks in exception occurrences when the target supports it.
8334 @c The following may get moved to an appendix
8335 This option is currently supported on the following targets:
8336 all x86 ports, Solaris, Windows, HP-UX, AIX, PowerPC VxWorks and Alpha VxWorks.
8338 See also the packages @code{GNAT.Traceback} and
8339 @code{GNAT.Traceback.Symbolic} for more information.
8341 Note that on x86 ports, you must not use @option{-fomit-frame-pointer}
8342 @command{gcc} option.
8345 @item ^-F^/FORCE_ELABS_FLAGS^
8346 @cindex @option{^-F^/FORCE_ELABS_FLAGS^} (@command{gnatbind})
8347 Force the checks of elaboration flags. @command{gnatbind} does not normally
8348 generate checks of elaboration flags for the main executable, except when
8349 a Stand-Alone Library is used. However, there are cases when this cannot be
8350 detected by gnatbind. An example is importing an interface of a Stand-Alone
8351 Library through a pragma Import and only specifying through a linker switch
8352 this Stand-Alone Library. This switch is used to guarantee that elaboration
8353 flag checks are generated.
8356 @cindex @option{^-h^/HELP^} (@command{gnatbind})
8357 Output usage (help) information
8359 @item ^-H32^/32_MALLOC^
8360 @cindex @option{^-H32^/32_MALLOC^} (@command{gnatbind})
8361 Use 32-bit allocations for @code{__gnat_malloc} (and thus for access types).
8362 For further details see @ref{Dynamic Allocation Control}.
8364 @item ^-H64^/64_MALLOC^
8365 @cindex @option{^-H64^/64_MALLOC^} (@command{gnatbind})
8366 Use 64-bit allocations for @code{__gnat_malloc} (and thus for access types).
8367 @cindex @code{__gnat_malloc}
8368 For further details see @ref{Dynamic Allocation Control}.
8371 @cindex @option{^-I^/SEARCH^} (@command{gnatbind})
8372 Specify directory to be searched for source and ALI files.
8374 @item ^-I-^/NOCURRENT_DIRECTORY^
8375 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gnatbind})
8376 Do not look for sources in the current directory where @code{gnatbind} was
8377 invoked, and do not look for ALI files in the directory containing the
8378 ALI file named in the @code{gnatbind} command line.
8380 @item ^-l^/ORDER_OF_ELABORATION^
8381 @cindex @option{^-l^/ORDER_OF_ELABORATION^} (@command{gnatbind})
8382 Output chosen elaboration order.
8384 @item ^-L@var{xxx}^/BUILD_LIBRARY=@var{xxx}^
8385 @cindex @option{^-L^/BUILD_LIBRARY^} (@command{gnatbind})
8386 Bind the units for library building. In this case the adainit and
8387 adafinal procedures (@pxref{Binding with Non-Ada Main Programs})
8388 are renamed to ^@var{xxx}init^@var{XXX}INIT^ and
8389 ^@var{xxx}final^@var{XXX}FINAL^.
8390 Implies ^-n^/NOCOMPILE^.
8392 (@xref{GNAT and Libraries}, for more details.)
8395 On OpenVMS, these init and final procedures are exported in uppercase
8396 letters. For example if /BUILD_LIBRARY=toto is used, the exported name of
8397 the init procedure will be "TOTOINIT" and the exported name of the final
8398 procedure will be "TOTOFINAL".
8401 @item ^-Mxyz^/RENAME_MAIN=xyz^
8402 @cindex @option{^-M^/RENAME_MAIN^} (@command{gnatbind})
8403 Rename generated main program from main to xyz. This option is
8404 supported on cross environments only.
8406 @item ^-m^/ERROR_LIMIT=^@var{n}
8407 @cindex @option{^-m^/ERROR_LIMIT^} (@command{gnatbind})
8408 Limit number of detected errors or warnings to @var{n}, where @var{n} is
8409 in the range 1..999999. The default value if no switch is
8410 given is 9999. If the number of warnings reaches this limit, then a
8411 message is output and further warnings are suppressed, the bind
8412 continues in this case. If the number of errors reaches this
8413 limit, then a message is output and the bind is abandoned.
8414 A value of zero means that no limit is enforced. The equal
8418 @cindex @option{^-n^/NOMAIN^} (@command{gnatbind})
8422 @cindex @option{-nostdinc} (@command{gnatbind})
8423 Do not look for sources in the system default directory.
8426 @cindex @option{-nostdlib} (@command{gnatbind})
8427 Do not look for library files in the system default directory.
8429 @item --RTS=@var{rts-path}
8430 @cindex @option{--RTS} (@code{gnatbind})
8431 Specifies the default location of the runtime library. Same meaning as the
8432 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
8434 @item ^-o ^/OUTPUT=^@var{file}
8435 @cindex @option{^-o ^/OUTPUT^} (@command{gnatbind})
8436 Name the output file @var{file} (default is @file{b~@var{xxx}.adb}).
8437 Note that if this option is used, then linking must be done manually,
8438 gnatlink cannot be used.
8440 @item ^-O^/OBJECT_LIST^@r{[=}@var{filename}@r{]}
8441 @cindex @option{^-O^/OBJECT_LIST^} (@command{gnatbind})
8442 Output object list (to standard output or to the named file).
8444 @item ^-p^/PESSIMISTIC_ELABORATION^
8445 @cindex @option{^-p^/PESSIMISTIC_ELABORATION^} (@command{gnatbind})
8446 Pessimistic (worst-case) elaboration order
8449 @cindex @option{^-P^/CODEPEER^} (@command{gnatbind})
8450 Generate binder file suitable for CodePeer.
8453 @cindex @option{^-R^-R^} (@command{gnatbind})
8454 Output closure source list.
8456 @item ^-s^/READ_SOURCES=ALL^
8457 @cindex @option{^-s^/READ_SOURCES=ALL^} (@command{gnatbind})
8458 Require all source files to be present.
8460 @item ^-S@var{xxx}^/INITIALIZE_SCALARS=@var{xxx}^
8461 @cindex @option{^-S^/INITIALIZE_SCALARS^} (@command{gnatbind})
8462 Specifies the value to be used when detecting uninitialized scalar
8463 objects with pragma Initialize_Scalars.
8464 The @var{xxx} ^string specified with the switch^option^ may be either
8466 @item ``@option{^in^INVALID^}'' requesting an invalid value where possible
8467 @item ``@option{^lo^LOW^}'' for the lowest possible value
8468 @item ``@option{^hi^HIGH^}'' for the highest possible value
8469 @item ``@option{@var{xx}}'' for a value consisting of repeated bytes with the
8470 value @code{16#@var{xx}#} (i.e., @var{xx} is a string of two hexadecimal digits).
8473 In addition, you can specify @option{-Sev} to indicate that the value is
8474 to be set at run time. In this case, the program will look for an environment
8475 @cindex GNAT_INIT_SCALARS
8476 variable of the form @env{GNAT_INIT_SCALARS=@var{xx}}, where @var{xx} is one
8477 of @option{in/lo/hi/@var{xx}} with the same meanings as above.
8478 If no environment variable is found, or if it does not have a valid value,
8479 then the default is @option{in} (invalid values).
8483 @cindex @option{-static} (@code{gnatbind})
8484 Link against a static GNAT run time.
8487 @cindex @option{-shared} (@code{gnatbind})
8488 Link against a shared GNAT run time when available.
8491 @item ^-t^/NOTIME_STAMP_CHECK^
8492 @cindex @option{^-t^/NOTIME_STAMP_CHECK^} (@code{gnatbind})
8493 Tolerate time stamp and other consistency errors
8495 @item ^-T@var{n}^/TIME_SLICE=@var{n}^
8496 @cindex @option{^-T^/TIME_SLICE^} (@code{gnatbind})
8497 Set the time slice value to @var{n} milliseconds. If the system supports
8498 the specification of a specific time slice value, then the indicated value
8499 is used. If the system does not support specific time slice values, but
8500 does support some general notion of round-robin scheduling, then any
8501 nonzero value will activate round-robin scheduling.
8503 A value of zero is treated specially. It turns off time
8504 slicing, and in addition, indicates to the tasking run time that the
8505 semantics should match as closely as possible the Annex D
8506 requirements of the Ada RM, and in particular sets the default
8507 scheduling policy to @code{FIFO_Within_Priorities}.
8509 @item ^-u@var{n}^/DYNAMIC_STACK_USAGE=@var{n}^
8510 @cindex @option{^-u^/DYNAMIC_STACK_USAGE^} (@code{gnatbind})
8511 Enable dynamic stack usage, with @var{n} results stored and displayed
8512 at program termination. A result is generated when a task
8513 terminates. Results that can't be stored are displayed on the fly, at
8514 task termination. This option is currently not supported on Itanium
8515 platforms. (See @ref{Dynamic Stack Usage Analysis} for details.)
8517 @item ^-v^/REPORT_ERRORS=VERBOSE^
8518 @cindex @option{^-v^/REPORT_ERRORS=VERBOSE^} (@code{gnatbind})
8519 Verbose mode. Write error messages, header, summary output to
8524 @cindex @option{-w} (@code{gnatbind})
8525 Warning mode (@var{x}=s/e for suppress/treat as error)
8529 @item /WARNINGS=NORMAL
8530 @cindex @option{/WARNINGS} (@code{gnatbind})
8531 Normal warnings mode. Warnings are issued but ignored
8533 @item /WARNINGS=SUPPRESS
8534 @cindex @option{/WARNINGS} (@code{gnatbind})
8535 All warning messages are suppressed
8537 @item /WARNINGS=ERROR
8538 @cindex @option{/WARNINGS} (@code{gnatbind})
8539 Warning messages are treated as fatal errors
8542 @item ^-Wx^/WIDE_CHARACTER_ENCODING=^@var{e}
8543 @cindex @option{^-Wx^/WIDE_CHARACTER_ENCODING^} (@code{gnatbind})
8544 Override default wide character encoding for standard Text_IO files.
8546 @item ^-x^/READ_SOURCES=NONE^
8547 @cindex @option{^-x^/READ_SOURCES^} (@code{gnatbind})
8548 Exclude source files (check object consistency only).
8551 @item /READ_SOURCES=AVAILABLE
8552 @cindex @option{/READ_SOURCES} (@code{gnatbind})
8553 Default mode, in which sources are checked for consistency only if
8557 @item ^-X@var{nnn}^/RETURN_CODES=POSIX^
8558 @cindex @option{^-X@var{nnn}^/RETURN_CODES=POSIX^} (@code{gnatbind})
8559 Set default exit status value, normally 0 for POSIX compliance.
8562 @item /RETURN_CODES=VMS
8563 @cindex @option{/RETURN_CODES=VMS} (@code{gnatbind})
8564 VMS default normal successful return value is 1.
8567 @item ^-y^/ENABLE_LEAP_SECONDS^
8568 @cindex @option{^-y^/ENABLE_LEAP_SECONDS^} (@code{gnatbind})
8569 Enable leap seconds support in @code{Ada.Calendar} and its children.
8571 @item ^-z^/ZERO_MAIN^
8572 @cindex @option{^-z^/ZERO_MAIN^} (@code{gnatbind})
8578 You may obtain this listing of switches by running @code{gnatbind} with
8582 @node Consistency-Checking Modes
8583 @subsection Consistency-Checking Modes
8586 As described earlier, by default @code{gnatbind} checks
8587 that object files are consistent with one another and are consistent
8588 with any source files it can locate. The following switches control binder
8593 @item ^-s^/READ_SOURCES=ALL^
8594 @cindex @option{^-s^/READ_SOURCES=ALL^} (@code{gnatbind})
8595 Require source files to be present. In this mode, the binder must be
8596 able to locate all source files that are referenced, in order to check
8597 their consistency. In normal mode, if a source file cannot be located it
8598 is simply ignored. If you specify this switch, a missing source
8601 @item ^-Wx^/WIDE_CHARACTER_ENCODING=^@var{e}
8602 @cindex @option{^-Wx^/WIDE_CHARACTER_ENCODING^} (@code{gnatbind})
8603 Override default wide character encoding for standard Text_IO files.
8604 Normally the default wide character encoding method used for standard
8605 [Wide_[Wide_]]Text_IO files is taken from the encoding specified for
8606 the main source input (see description of switch
8607 @option{^-gnatWx^/WIDE_CHARACTER_ENCODING^} for the compiler). The
8608 use of this switch for the binder (which has the same set of
8609 possible arguments) overrides this default as specified.
8611 @item ^-x^/READ_SOURCES=NONE^
8612 @cindex @option{^-x^/READ_SOURCES=NONE^} (@code{gnatbind})
8613 Exclude source files. In this mode, the binder only checks that ALI
8614 files are consistent with one another. Source files are not accessed.
8615 The binder runs faster in this mode, and there is still a guarantee that
8616 the resulting program is self-consistent.
8617 If a source file has been edited since it was last compiled, and you
8618 specify this switch, the binder will not detect that the object
8619 file is out of date with respect to the source file. Note that this is the
8620 mode that is automatically used by @command{gnatmake} because in this
8621 case the checking against sources has already been performed by
8622 @command{gnatmake} in the course of compilation (i.e.@: before binding).
8625 @item /READ_SOURCES=AVAILABLE
8626 @cindex @code{/READ_SOURCES=AVAILABLE} (@code{gnatbind})
8627 This is the default mode in which source files are checked if they are
8628 available, and ignored if they are not available.
8632 @node Binder Error Message Control
8633 @subsection Binder Error Message Control
8636 The following switches provide control over the generation of error
8637 messages from the binder:
8641 @item ^-v^/REPORT_ERRORS=VERBOSE^
8642 @cindex @option{^-v^/REPORT_ERRORS=VERBOSE^} (@code{gnatbind})
8643 Verbose mode. In the normal mode, brief error messages are generated to
8644 @file{stderr}. If this switch is present, a header is written
8645 to @file{stdout} and any error messages are directed to @file{stdout}.
8646 All that is written to @file{stderr} is a brief summary message.
8648 @item ^-b^/REPORT_ERRORS=BRIEF^
8649 @cindex @option{^-b^/REPORT_ERRORS=BRIEF^} (@code{gnatbind})
8650 Generate brief error messages to @file{stderr} even if verbose mode is
8651 specified. This is relevant only when used with the
8652 @option{^-v^/REPORT_ERRORS=VERBOSE^} switch.
8656 @cindex @option{-m} (@code{gnatbind})
8657 Limits the number of error messages to @var{n}, a decimal integer in the
8658 range 1-999. The binder terminates immediately if this limit is reached.
8661 @cindex @option{-M} (@code{gnatbind})
8662 Renames the generated main program from @code{main} to @code{xxx}.
8663 This is useful in the case of some cross-building environments, where
8664 the actual main program is separate from the one generated
8668 @item ^-ws^/WARNINGS=SUPPRESS^
8669 @cindex @option{^-ws^/WARNINGS=SUPPRESS^} (@code{gnatbind})
8671 Suppress all warning messages.
8673 @item ^-we^/WARNINGS=ERROR^
8674 @cindex @option{^-we^/WARNINGS=ERROR^} (@code{gnatbind})
8675 Treat any warning messages as fatal errors.
8678 @item /WARNINGS=NORMAL
8679 Standard mode with warnings generated, but warnings do not get treated
8683 @item ^-t^/NOTIME_STAMP_CHECK^
8684 @cindex @option{^-t^/NOTIME_STAMP_CHECK^} (@code{gnatbind})
8685 @cindex Time stamp checks, in binder
8686 @cindex Binder consistency checks
8687 @cindex Consistency checks, in binder
8688 The binder performs a number of consistency checks including:
8692 Check that time stamps of a given source unit are consistent
8694 Check that checksums of a given source unit are consistent
8696 Check that consistent versions of @code{GNAT} were used for compilation
8698 Check consistency of configuration pragmas as required
8702 Normally failure of such checks, in accordance with the consistency
8703 requirements of the Ada Reference Manual, causes error messages to be
8704 generated which abort the binder and prevent the output of a binder
8705 file and subsequent link to obtain an executable.
8707 The @option{^-t^/NOTIME_STAMP_CHECK^} switch converts these error messages
8708 into warnings, so that
8709 binding and linking can continue to completion even in the presence of such
8710 errors. The result may be a failed link (due to missing symbols), or a
8711 non-functional executable which has undefined semantics.
8712 @emph{This means that
8713 @option{^-t^/NOTIME_STAMP_CHECK^} should be used only in unusual situations,
8717 @node Elaboration Control
8718 @subsection Elaboration Control
8721 The following switches provide additional control over the elaboration
8722 order. For full details see @ref{Elaboration Order Handling in GNAT}.
8725 @item ^-p^/PESSIMISTIC_ELABORATION^
8726 @cindex @option{^-p^/PESSIMISTIC_ELABORATION^} (@code{gnatbind})
8727 Normally the binder attempts to choose an elaboration order that is
8728 likely to minimize the likelihood of an elaboration order error resulting
8729 in raising a @code{Program_Error} exception. This switch reverses the
8730 action of the binder, and requests that it deliberately choose an order
8731 that is likely to maximize the likelihood of an elaboration error.
8732 This is useful in ensuring portability and avoiding dependence on
8733 accidental fortuitous elaboration ordering.
8735 Normally it only makes sense to use the @option{^-p^/PESSIMISTIC_ELABORATION^}
8737 elaboration checking is used (@option{-gnatE} switch used for compilation).
8738 This is because in the default static elaboration mode, all necessary
8739 @code{Elaborate} and @code{Elaborate_All} pragmas are implicitly inserted.
8740 These implicit pragmas are still respected by the binder in
8741 @option{^-p^/PESSIMISTIC_ELABORATION^} mode, so a
8742 safe elaboration order is assured.
8744 Note that @option{^-p^/PESSIMISTIC_ELABORATION^} is not intended for
8745 production use; it is more for debugging/experimental use.
8748 @node Output Control
8749 @subsection Output Control
8752 The following switches allow additional control over the output
8753 generated by the binder.
8758 @item ^-c^/NOOUTPUT^
8759 @cindex @option{^-c^/NOOUTPUT^} (@code{gnatbind})
8760 Check only. Do not generate the binder output file. In this mode the
8761 binder performs all error checks but does not generate an output file.
8763 @item ^-e^/ELABORATION_DEPENDENCIES^
8764 @cindex @option{^-e^/ELABORATION_DEPENDENCIES^} (@code{gnatbind})
8765 Output complete list of elaboration-order dependencies, showing the
8766 reason for each dependency. This output can be rather extensive but may
8767 be useful in diagnosing problems with elaboration order. The output is
8768 written to @file{stdout}.
8771 @cindex @option{^-h^/HELP^} (@code{gnatbind})
8772 Output usage information. The output is written to @file{stdout}.
8774 @item ^-K^/LINKER_OPTION_LIST^
8775 @cindex @option{^-K^/LINKER_OPTION_LIST^} (@code{gnatbind})
8776 Output linker options to @file{stdout}. Includes library search paths,
8777 contents of pragmas Ident and Linker_Options, and libraries added
8780 @item ^-l^/ORDER_OF_ELABORATION^
8781 @cindex @option{^-l^/ORDER_OF_ELABORATION^} (@code{gnatbind})
8782 Output chosen elaboration order. The output is written to @file{stdout}.
8784 @item ^-O^/OBJECT_LIST^
8785 @cindex @option{^-O^/OBJECT_LIST^} (@code{gnatbind})
8786 Output full names of all the object files that must be linked to provide
8787 the Ada component of the program. The output is written to @file{stdout}.
8788 This list includes the files explicitly supplied and referenced by the user
8789 as well as implicitly referenced run-time unit files. The latter are
8790 omitted if the corresponding units reside in shared libraries. The
8791 directory names for the run-time units depend on the system configuration.
8793 @item ^-o ^/OUTPUT=^@var{file}
8794 @cindex @option{^-o^/OUTPUT^} (@code{gnatbind})
8795 Set name of output file to @var{file} instead of the normal
8796 @file{b~@var{mainprog}.adb} default. Note that @var{file} denote the Ada
8797 binder generated body filename.
8798 Note that if this option is used, then linking must be done manually.
8799 It is not possible to use gnatlink in this case, since it cannot locate
8802 @item ^-r^/RESTRICTION_LIST^
8803 @cindex @option{^-r^/RESTRICTION_LIST^} (@code{gnatbind})
8804 Generate list of @code{pragma Restrictions} that could be applied to
8805 the current unit. This is useful for code audit purposes, and also may
8806 be used to improve code generation in some cases.
8810 @node Dynamic Allocation Control
8811 @subsection Dynamic Allocation Control
8814 The heap control switches -- @option{-H32} and @option{-H64} --
8815 determine whether dynamic allocation uses 32-bit or 64-bit memory.
8816 They only affect compiler-generated allocations via @code{__gnat_malloc};
8817 explicit calls to @code{malloc} and related functions from the C
8818 run-time library are unaffected.
8822 Allocate memory on 32-bit heap
8825 Allocate memory on 64-bit heap. This is the default
8826 unless explicitly overridden by a @code{'Size} clause on the access type.
8831 See also @ref{Access types and 32/64-bit allocation}.
8835 These switches are only effective on VMS platforms.
8839 @node Binding with Non-Ada Main Programs
8840 @subsection Binding with Non-Ada Main Programs
8843 In our description so far we have assumed that the main
8844 program is in Ada, and that the task of the binder is to generate a
8845 corresponding function @code{main} that invokes this Ada main
8846 program. GNAT also supports the building of executable programs where
8847 the main program is not in Ada, but some of the called routines are
8848 written in Ada and compiled using GNAT (@pxref{Mixed Language Programming}).
8849 The following switch is used in this situation:
8853 @cindex @option{^-n^/NOMAIN^} (@code{gnatbind})
8854 No main program. The main program is not in Ada.
8858 In this case, most of the functions of the binder are still required,
8859 but instead of generating a main program, the binder generates a file
8860 containing the following callable routines:
8865 You must call this routine to initialize the Ada part of the program by
8866 calling the necessary elaboration routines. A call to @code{adainit} is
8867 required before the first call to an Ada subprogram.
8869 Note that it is assumed that the basic execution environment must be setup
8870 to be appropriate for Ada execution at the point where the first Ada
8871 subprogram is called. In particular, if the Ada code will do any
8872 floating-point operations, then the FPU must be setup in an appropriate
8873 manner. For the case of the x86, for example, full precision mode is
8874 required. The procedure GNAT.Float_Control.Reset may be used to ensure
8875 that the FPU is in the right state.
8879 You must call this routine to perform any library-level finalization
8880 required by the Ada subprograms. A call to @code{adafinal} is required
8881 after the last call to an Ada subprogram, and before the program
8886 If the @option{^-n^/NOMAIN^} switch
8887 @cindex @option{^-n^/NOMAIN^} (@command{gnatbind})
8888 @cindex Binder, multiple input files
8889 is given, more than one ALI file may appear on
8890 the command line for @code{gnatbind}. The normal @dfn{closure}
8891 calculation is performed for each of the specified units. Calculating
8892 the closure means finding out the set of units involved by tracing
8893 @code{with} references. The reason it is necessary to be able to
8894 specify more than one ALI file is that a given program may invoke two or
8895 more quite separate groups of Ada units.
8897 The binder takes the name of its output file from the last specified ALI
8898 file, unless overridden by the use of the @option{^-o file^/OUTPUT=file^}.
8899 @cindex @option{^-o^/OUTPUT^} (@command{gnatbind})
8900 The output is an Ada unit in source form that can be compiled with GNAT.
8901 This compilation occurs automatically as part of the @command{gnatlink}
8904 Currently the GNAT run time requires a FPU using 80 bits mode
8905 precision. Under targets where this is not the default it is required to
8906 call GNAT.Float_Control.Reset before using floating point numbers (this
8907 include float computation, float input and output) in the Ada code. A
8908 side effect is that this could be the wrong mode for the foreign code
8909 where floating point computation could be broken after this call.
8911 @node Binding Programs with No Main Subprogram
8912 @subsection Binding Programs with No Main Subprogram
8915 It is possible to have an Ada program which does not have a main
8916 subprogram. This program will call the elaboration routines of all the
8917 packages, then the finalization routines.
8919 The following switch is used to bind programs organized in this manner:
8922 @item ^-z^/ZERO_MAIN^
8923 @cindex @option{^-z^/ZERO_MAIN^} (@code{gnatbind})
8924 Normally the binder checks that the unit name given on the command line
8925 corresponds to a suitable main subprogram. When this switch is used,
8926 a list of ALI files can be given, and the execution of the program
8927 consists of elaboration of these units in an appropriate order. Note
8928 that the default wide character encoding method for standard Text_IO
8929 files is always set to Brackets if this switch is set (you can use
8931 @option{^-Wx^WIDE_CHARACTER_ENCODING^} to override this default).
8934 @node Command-Line Access
8935 @section Command-Line Access
8938 The package @code{Ada.Command_Line} provides access to the command-line
8939 arguments and program name. In order for this interface to operate
8940 correctly, the two variables
8952 are declared in one of the GNAT library routines. These variables must
8953 be set from the actual @code{argc} and @code{argv} values passed to the
8954 main program. With no @option{^n^/NOMAIN^} present, @code{gnatbind}
8955 generates the C main program to automatically set these variables.
8956 If the @option{^n^/NOMAIN^} switch is used, there is no automatic way to
8957 set these variables. If they are not set, the procedures in
8958 @code{Ada.Command_Line} will not be available, and any attempt to use
8959 them will raise @code{Constraint_Error}. If command line access is
8960 required, your main program must set @code{gnat_argc} and
8961 @code{gnat_argv} from the @code{argc} and @code{argv} values passed to
8964 @node Search Paths for gnatbind
8965 @section Search Paths for @code{gnatbind}
8968 The binder takes the name of an ALI file as its argument and needs to
8969 locate source files as well as other ALI files to verify object consistency.
8971 For source files, it follows exactly the same search rules as @command{gcc}
8972 (@pxref{Search Paths and the Run-Time Library (RTL)}). For ALI files the
8973 directories searched are:
8977 The directory containing the ALI file named in the command line, unless
8978 the switch @option{^-I-^/NOCURRENT_DIRECTORY^} is specified.
8981 All directories specified by @option{^-I^/SEARCH^}
8982 switches on the @code{gnatbind}
8983 command line, in the order given.
8986 @findex ADA_PRJ_OBJECTS_FILE
8987 Each of the directories listed in the text file whose name is given
8988 by the @env{ADA_PRJ_OBJECTS_FILE} ^environment variable^logical name^.
8991 @env{ADA_PRJ_OBJECTS_FILE} is normally set by gnatmake or by the ^gnat^GNAT^
8992 driver when project files are used. It should not normally be set
8996 @findex ADA_OBJECTS_PATH
8997 Each of the directories listed in the value of the
8998 @env{ADA_OBJECTS_PATH} ^environment variable^logical name^.
9000 Construct this value
9001 exactly as the @env{PATH} environment variable: a list of directory
9002 names separated by colons (semicolons when working with the NT version
9006 Normally, define this value as a logical name containing a comma separated
9007 list of directory names.
9009 This variable can also be defined by means of an environment string
9010 (an argument to the HP C exec* set of functions).
9014 DEFINE ANOTHER_PATH FOO:[BAG]
9015 DEFINE ADA_OBJECTS_PATH ANOTHER_PATH,FOO:[BAM],FOO:[BAR]
9018 By default, the path includes GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB]
9019 first, followed by the standard Ada
9020 libraries in GNU:[LIB.OPENVMS7_x.2_8_x.ADALIB].
9021 If this is not redefined, the user will obtain the HP Ada 83 IO packages
9022 (Text_IO, Sequential_IO, etc)
9023 instead of the standard Ada packages. Thus, in order to get the standard Ada
9024 packages by default, ADA_OBJECTS_PATH must be redefined.
9028 The content of the @file{ada_object_path} file which is part of the GNAT
9029 installation tree and is used to store standard libraries such as the
9030 GNAT Run Time Library (RTL) unless the switch @option{-nostdlib} is
9033 @ref{Installing a library}
9038 In the binder the switch @option{^-I^/SEARCH^}
9039 @cindex @option{^-I^/SEARCH^} (@command{gnatbind})
9040 is used to specify both source and
9041 library file paths. Use @option{^-aI^/SOURCE_SEARCH^}
9042 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatbind})
9043 instead if you want to specify
9044 source paths only, and @option{^-aO^/LIBRARY_SEARCH^}
9045 @cindex @option{^-aO^/LIBRARY_SEARCH^} (@command{gnatbind})
9046 if you want to specify library paths
9047 only. This means that for the binder
9048 @option{^-I^/SEARCH=^}@var{dir} is equivalent to
9049 @option{^-aI^/SOURCE_SEARCH=^}@var{dir}
9050 @option{^-aO^/OBJECT_SEARCH=^}@var{dir}.
9051 The binder generates the bind file (a C language source file) in the
9052 current working directory.
9058 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
9059 children make up the GNAT Run-Time Library, together with the package
9060 GNAT and its children, which contain a set of useful additional
9061 library functions provided by GNAT. The sources for these units are
9062 needed by the compiler and are kept together in one directory. The ALI
9063 files and object files generated by compiling the RTL are needed by the
9064 binder and the linker and are kept together in one directory, typically
9065 different from the directory containing the sources. In a normal
9066 installation, you need not specify these directory names when compiling
9067 or binding. Either the environment variables or the built-in defaults
9068 cause these files to be found.
9070 Besides simplifying access to the RTL, a major use of search paths is
9071 in compiling sources from multiple directories. This can make
9072 development environments much more flexible.
9074 @node Examples of gnatbind Usage
9075 @section Examples of @code{gnatbind} Usage
9078 This section contains a number of examples of using the GNAT binding
9079 utility @code{gnatbind}.
9082 @item gnatbind hello
9083 The main program @code{Hello} (source program in @file{hello.adb}) is
9084 bound using the standard switch settings. The generated main program is
9085 @file{b~hello.adb}. This is the normal, default use of the binder.
9088 @item gnatbind hello -o mainprog.adb
9091 @item gnatbind HELLO.ALI /OUTPUT=Mainprog.ADB
9093 The main program @code{Hello} (source program in @file{hello.adb}) is
9094 bound using the standard switch settings. The generated main program is
9095 @file{mainprog.adb} with the associated spec in
9096 @file{mainprog.ads}. Note that you must specify the body here not the
9097 spec. Note that if this option is used, then linking must be done manually,
9098 since gnatlink will not be able to find the generated file.
9101 @c ------------------------------------
9102 @node Linking with gnatlink
9103 @chapter Linking with @command{gnatlink}
9104 @c ------------------------------------
9108 This chapter discusses @command{gnatlink}, a tool that links
9109 an Ada program and builds an executable file. This utility
9110 invokes the system linker ^(via the @command{gcc} command)^^
9111 with a correct list of object files and library references.
9112 @command{gnatlink} automatically determines the list of files and
9113 references for the Ada part of a program. It uses the binder file
9114 generated by the @command{gnatbind} to determine this list.
9116 Note: to invoke @code{gnatlink} with a project file, use the @code{gnat}
9117 driver (see @ref{The GNAT Driver and Project Files}).
9120 * Running gnatlink::
9121 * Switches for gnatlink::
9124 @node Running gnatlink
9125 @section Running @command{gnatlink}
9128 The form of the @command{gnatlink} command is
9131 @c $ gnatlink @ovar{switches} @var{mainprog}@r{[}.ali@r{]}
9132 @c @ovar{non-Ada objects} @ovar{linker options}
9133 @c Expanding @ovar macro inline (explanation in macro def comments)
9134 $ gnatlink @r{[}@var{switches}@r{]} @var{mainprog}@r{[}.ali@r{]}
9135 @r{[}@var{non-Ada objects}@r{]} @r{[}@var{linker options}@r{]}
9140 The arguments of @command{gnatlink} (switches, main @file{ALI} file,
9142 or linker options) may be in any order, provided that no non-Ada object may
9143 be mistaken for a main @file{ALI} file.
9144 Any file name @file{F} without the @file{.ali}
9145 extension will be taken as the main @file{ALI} file if a file exists
9146 whose name is the concatenation of @file{F} and @file{.ali}.
9149 @file{@var{mainprog}.ali} references the ALI file of the main program.
9150 The @file{.ali} extension of this file can be omitted. From this
9151 reference, @command{gnatlink} locates the corresponding binder file
9152 @file{b~@var{mainprog}.adb} and, using the information in this file along
9153 with the list of non-Ada objects and linker options, constructs a
9154 linker command file to create the executable.
9156 The arguments other than the @command{gnatlink} switches and the main
9157 @file{ALI} file are passed to the linker uninterpreted.
9158 They typically include the names of
9159 object files for units written in other languages than Ada and any library
9160 references required to resolve references in any of these foreign language
9161 units, or in @code{Import} pragmas in any Ada units.
9163 @var{linker options} is an optional list of linker specific
9165 The default linker called by gnatlink is @command{gcc} which in
9166 turn calls the appropriate system linker.
9168 One useful option for the linker is @option{-s}: it reduces the size of the
9169 executable by removing all symbol table and relocation information from the
9172 Standard options for the linker such as @option{-lmy_lib} or
9173 @option{-Ldir} can be added as is.
9174 For options that are not recognized by
9175 @command{gcc} as linker options, use the @command{gcc} switches
9176 @option{-Xlinker} or @option{-Wl,}.
9178 Refer to the GCC documentation for
9181 Here is an example showing how to generate a linker map:
9184 $ ^gnatlink my_prog -Wl,-Map,MAPFILE^GNAT LINK my_prog.ali /MAP^
9187 Using @var{linker options} it is possible to set the program stack and
9190 See @ref{Setting Stack Size from gnatlink} and
9191 @ref{Setting Heap Size from gnatlink}.
9194 @command{gnatlink} determines the list of objects required by the Ada
9195 program and prepends them to the list of objects passed to the linker.
9196 @command{gnatlink} also gathers any arguments set by the use of
9197 @code{pragma Linker_Options} and adds them to the list of arguments
9198 presented to the linker.
9201 @command{gnatlink} accepts the following types of extra files on the command
9202 line: objects (@file{.OBJ}), libraries (@file{.OLB}), sharable images
9203 (@file{.EXE}), and options files (@file{.OPT}). These are recognized and
9204 handled according to their extension.
9207 @node Switches for gnatlink
9208 @section Switches for @command{gnatlink}
9211 The following switches are available with the @command{gnatlink} utility:
9217 @cindex @option{--version} @command{gnatlink}
9218 Display Copyright and version, then exit disregarding all other options.
9221 @cindex @option{--help} @command{gnatlink}
9222 If @option{--version} was not used, display usage, then exit disregarding
9225 @item ^-f^/FORCE_OBJECT_FILE_LIST^
9226 @cindex Command line length
9227 @cindex @option{^-f^/FORCE_OBJECT_FILE_LIST^} (@command{gnatlink})
9228 On some targets, the command line length is limited, and @command{gnatlink}
9229 will generate a separate file for the linker if the list of object files
9231 The @option{^-f^/FORCE_OBJECT_FILE_LIST^} switch forces this file
9232 to be generated even if
9233 the limit is not exceeded. This is useful in some cases to deal with
9234 special situations where the command line length is exceeded.
9237 @cindex Debugging information, including
9238 @cindex @option{^-g^/DEBUG^} (@command{gnatlink})
9239 The option to include debugging information causes the Ada bind file (in
9240 other words, @file{b~@var{mainprog}.adb}) to be compiled with
9241 @option{^-g^/DEBUG^}.
9242 In addition, the binder does not delete the @file{b~@var{mainprog}.adb},
9243 @file{b~@var{mainprog}.o} and @file{b~@var{mainprog}.ali} files.
9244 Without @option{^-g^/DEBUG^}, the binder removes these files by
9245 default. The same procedure apply if a C bind file was generated using
9246 @option{^-C^/BIND_FILE=C^} @code{gnatbind} option, in this case the filenames
9247 are @file{b_@var{mainprog}.c} and @file{b_@var{mainprog}.o}.
9249 @item ^-n^/NOCOMPILE^
9250 @cindex @option{^-n^/NOCOMPILE^} (@command{gnatlink})
9251 Do not compile the file generated by the binder. This may be used when
9252 a link is rerun with different options, but there is no need to recompile
9256 @cindex @option{^-v^/VERBOSE^} (@command{gnatlink})
9257 Causes additional information to be output, including a full list of the
9258 included object files. This switch option is most useful when you want
9259 to see what set of object files are being used in the link step.
9261 @item ^-v -v^/VERBOSE/VERBOSE^
9262 @cindex @option{^-v -v^/VERBOSE/VERBOSE^} (@command{gnatlink})
9263 Very verbose mode. Requests that the compiler operate in verbose mode when
9264 it compiles the binder file, and that the system linker run in verbose mode.
9266 @item ^-o ^/EXECUTABLE=^@var{exec-name}
9267 @cindex @option{^-o^/EXECUTABLE^} (@command{gnatlink})
9268 @var{exec-name} specifies an alternate name for the generated
9269 executable program. If this switch is omitted, the executable has the same
9270 name as the main unit. For example, @code{gnatlink try.ali} creates
9271 an executable called @file{^try^TRY.EXE^}.
9274 @item -b @var{target}
9275 @cindex @option{-b} (@command{gnatlink})
9276 Compile your program to run on @var{target}, which is the name of a
9277 system configuration. You must have a GNAT cross-compiler built if
9278 @var{target} is not the same as your host system.
9281 @cindex @option{-B} (@command{gnatlink})
9282 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
9283 from @var{dir} instead of the default location. Only use this switch
9284 when multiple versions of the GNAT compiler are available.
9285 @xref{Directory Options,,, gcc, The GNU Compiler Collection},
9286 for further details. You would normally use the @option{-b} or
9287 @option{-V} switch instead.
9290 When linking an executable, create a map file. The name of the map file
9291 has the same name as the executable with extension ".map".
9294 When linking an executable, create a map file. The name of the map file is
9297 @item --GCC=@var{compiler_name}
9298 @cindex @option{--GCC=compiler_name} (@command{gnatlink})
9299 Program used for compiling the binder file. The default is
9300 @command{gcc}. You need to use quotes around @var{compiler_name} if
9301 @code{compiler_name} contains spaces or other separator characters.
9302 As an example @option{--GCC="foo -x -y"} will instruct @command{gnatlink} to
9303 use @code{foo -x -y} as your compiler. Note that switch @option{-c} is always
9304 inserted after your command name. Thus in the above example the compiler
9305 command that will be used by @command{gnatlink} will be @code{foo -c -x -y}.
9306 A limitation of this syntax is that the name and path name of the executable
9307 itself must not include any embedded spaces. If the compiler executable is
9308 different from the default one (gcc or <prefix>-gcc), then the back-end
9309 switches in the ALI file are not used to compile the binder generated source.
9310 For example, this is the case with @option{--GCC="foo -x -y"}. But the back end
9311 switches will be used for @option{--GCC="gcc -gnatv"}. If several
9312 @option{--GCC=compiler_name} are used, only the last @var{compiler_name}
9313 is taken into account. However, all the additional switches are also taken
9315 @option{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
9316 @option{--GCC="bar -x -y -z -t"}.
9318 @item --LINK=@var{name}
9319 @cindex @option{--LINK=} (@command{gnatlink})
9320 @var{name} is the name of the linker to be invoked. This is especially
9321 useful in mixed language programs since languages such as C++ require
9322 their own linker to be used. When this switch is omitted, the default
9323 name for the linker is @command{gcc}. When this switch is used, the
9324 specified linker is called instead of @command{gcc} with exactly the same
9325 parameters that would have been passed to @command{gcc} so if the desired
9326 linker requires different parameters it is necessary to use a wrapper
9327 script that massages the parameters before invoking the real linker. It
9328 may be useful to control the exact invocation by using the verbose
9334 @item /DEBUG=TRACEBACK
9335 @cindex @code{/DEBUG=TRACEBACK} (@command{gnatlink})
9336 This qualifier causes sufficient information to be included in the
9337 executable file to allow a traceback, but does not include the full
9338 symbol information needed by the debugger.
9340 @item /IDENTIFICATION="<string>"
9341 @code{"<string>"} specifies the string to be stored in the image file
9342 identification field in the image header.
9343 It overrides any pragma @code{Ident} specified string.
9345 @item /NOINHIBIT-EXEC
9346 Generate the executable file even if there are linker warnings.
9348 @item /NOSTART_FILES
9349 Don't link in the object file containing the ``main'' transfer address.
9350 Used when linking with a foreign language main program compiled with an
9354 Prefer linking with object libraries over sharable images, even without
9360 @node The GNAT Make Program gnatmake
9361 @chapter The GNAT Make Program @command{gnatmake}
9365 * Running gnatmake::
9366 * Switches for gnatmake::
9367 * Mode Switches for gnatmake::
9368 * Notes on the Command Line::
9369 * How gnatmake Works::
9370 * Examples of gnatmake Usage::
9373 A typical development cycle when working on an Ada program consists of
9374 the following steps:
9378 Edit some sources to fix bugs.
9384 Compile all sources affected.
9394 The third step can be tricky, because not only do the modified files
9395 @cindex Dependency rules
9396 have to be compiled, but any files depending on these files must also be
9397 recompiled. The dependency rules in Ada can be quite complex, especially
9398 in the presence of overloading, @code{use} clauses, generics and inlined
9401 @command{gnatmake} automatically takes care of the third and fourth steps
9402 of this process. It determines which sources need to be compiled,
9403 compiles them, and binds and links the resulting object files.
9405 Unlike some other Ada make programs, the dependencies are always
9406 accurately recomputed from the new sources. The source based approach of
9407 the GNAT compilation model makes this possible. This means that if
9408 changes to the source program cause corresponding changes in
9409 dependencies, they will always be tracked exactly correctly by
9412 @node Running gnatmake
9413 @section Running @command{gnatmake}
9416 The usual form of the @command{gnatmake} command is
9419 @c $ gnatmake @ovar{switches} @var{file_name}
9420 @c @ovar{file_names} @ovar{mode_switches}
9421 @c Expanding @ovar macro inline (explanation in macro def comments)
9422 $ gnatmake @r{[}@var{switches}@r{]} @var{file_name}
9423 @r{[}@var{file_names}@r{]} @r{[}@var{mode_switches}@r{]}
9427 The only required argument is one @var{file_name}, which specifies
9428 a compilation unit that is a main program. Several @var{file_names} can be
9429 specified: this will result in several executables being built.
9430 If @code{switches} are present, they can be placed before the first
9431 @var{file_name}, between @var{file_names} or after the last @var{file_name}.
9432 If @var{mode_switches} are present, they must always be placed after
9433 the last @var{file_name} and all @code{switches}.
9435 If you are using standard file extensions (@file{.adb} and @file{.ads}), then the
9436 extension may be omitted from the @var{file_name} arguments. However, if
9437 you are using non-standard extensions, then it is required that the
9438 extension be given. A relative or absolute directory path can be
9439 specified in a @var{file_name}, in which case, the input source file will
9440 be searched for in the specified directory only. Otherwise, the input
9441 source file will first be searched in the directory where
9442 @command{gnatmake} was invoked and if it is not found, it will be search on
9443 the source path of the compiler as described in
9444 @ref{Search Paths and the Run-Time Library (RTL)}.
9446 All @command{gnatmake} output (except when you specify
9447 @option{^-M^/DEPENDENCIES_LIST^}) is to
9448 @file{stderr}. The output produced by the
9449 @option{^-M^/DEPENDENCIES_LIST^} switch is send to
9452 @node Switches for gnatmake
9453 @section Switches for @command{gnatmake}
9456 You may specify any of the following switches to @command{gnatmake}:
9462 @cindex @option{--version} @command{gnatmake}
9463 Display Copyright and version, then exit disregarding all other options.
9466 @cindex @option{--help} @command{gnatmake}
9467 If @option{--version} was not used, display usage, then exit disregarding
9471 @item --GCC=@var{compiler_name}
9472 @cindex @option{--GCC=compiler_name} (@command{gnatmake})
9473 Program used for compiling. The default is `@command{gcc}'. You need to use
9474 quotes around @var{compiler_name} if @code{compiler_name} contains
9475 spaces or other separator characters. As an example @option{--GCC="foo -x
9476 -y"} will instruct @command{gnatmake} to use @code{foo -x -y} as your
9477 compiler. A limitation of this syntax is that the name and path name of
9478 the executable itself must not include any embedded spaces. Note that
9479 switch @option{-c} is always inserted after your command name. Thus in the
9480 above example the compiler command that will be used by @command{gnatmake}
9481 will be @code{foo -c -x -y}. If several @option{--GCC=compiler_name} are
9482 used, only the last @var{compiler_name} is taken into account. However,
9483 all the additional switches are also taken into account. Thus,
9484 @option{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
9485 @option{--GCC="bar -x -y -z -t"}.
9487 @item --GNATBIND=@var{binder_name}
9488 @cindex @option{--GNATBIND=binder_name} (@command{gnatmake})
9489 Program used for binding. The default is `@code{gnatbind}'. You need to
9490 use quotes around @var{binder_name} if @var{binder_name} contains spaces
9491 or other separator characters. As an example @option{--GNATBIND="bar -x
9492 -y"} will instruct @command{gnatmake} to use @code{bar -x -y} as your
9493 binder. Binder switches that are normally appended by @command{gnatmake}
9494 to `@code{gnatbind}' are now appended to the end of @code{bar -x -y}.
9495 A limitation of this syntax is that the name and path name of the executable
9496 itself must not include any embedded spaces.
9498 @item --GNATLINK=@var{linker_name}
9499 @cindex @option{--GNATLINK=linker_name} (@command{gnatmake})
9500 Program used for linking. The default is `@command{gnatlink}'. You need to
9501 use quotes around @var{linker_name} if @var{linker_name} contains spaces
9502 or other separator characters. As an example @option{--GNATLINK="lan -x
9503 -y"} will instruct @command{gnatmake} to use @code{lan -x -y} as your
9504 linker. Linker switches that are normally appended by @command{gnatmake} to
9505 `@command{gnatlink}' are now appended to the end of @code{lan -x -y}.
9506 A limitation of this syntax is that the name and path name of the executable
9507 itself must not include any embedded spaces.
9511 @item ^--subdirs^/SUBDIRS^=subdir
9512 Actual object directory of each project file is the subdirectory subdir of the
9513 object directory specified or defaulted in the project file.
9515 @item ^--single-compile-per-obj-dir^/SINGLE_COMPILE_PER_OBJ_DIR^
9516 Disallow simultaneous compilations in the same object directory when
9517 project files are used.
9519 @item ^--unchecked-shared-lib-imports^/UNCHECKED_SHARED_LIB_IMPORTS^
9520 By default, shared library projects are not allowed to import static library
9521 projects. When this switch is used on the command line, this restriction is
9524 @item ^--source-info=<source info file>^/SRC_INFO=source-info-file^
9525 Specify a source info file. This switch is active only when project files
9526 are used. If the source info file is specified as a relative path, then it is
9527 relative to the object directory of the main project. If the source info file
9528 does not exist, then after the Project Manager has successfully parsed and
9529 processed the project files and found the sources, it creates the source info
9530 file. If the source info file already exists and can be read successfully,
9531 then the Project Manager will get all the needed information about the sources
9532 from the source info file and will not look for them. This reduces the time
9533 to process the project files, especially when looking for sources that take a
9534 long time. If the source info file exists but cannot be parsed successfully,
9535 the Project Manager will attempt to recreate it. If the Project Manager fails
9536 to create the source info file, a message is issued, but gnatmake does not
9537 fail. @command{gnatmake} "trusts" the source info file. This means that
9538 if the source files have changed (addition, deletion, moving to a different
9539 source directory), then the source info file need to be deleted and recreated.
9542 @item --create-map-file
9543 When linking an executable, create a map file. The name of the map file
9544 has the same name as the executable with extension ".map".
9546 @item --create-map-file=mapfile
9547 When linking an executable, create a map file. The name of the map file is
9552 @item ^-a^/ALL_FILES^
9553 @cindex @option{^-a^/ALL_FILES^} (@command{gnatmake})
9554 Consider all files in the make process, even the GNAT internal system
9555 files (for example, the predefined Ada library files), as well as any
9556 locked files. Locked files are files whose ALI file is write-protected.
9558 @command{gnatmake} does not check these files,
9559 because the assumption is that the GNAT internal files are properly up
9560 to date, and also that any write protected ALI files have been properly
9561 installed. Note that if there is an installation problem, such that one
9562 of these files is not up to date, it will be properly caught by the
9564 You may have to specify this switch if you are working on GNAT
9565 itself. The switch @option{^-a^/ALL_FILES^} is also useful
9566 in conjunction with @option{^-f^/FORCE_COMPILE^}
9567 if you need to recompile an entire application,
9568 including run-time files, using special configuration pragmas,
9569 such as a @code{Normalize_Scalars} pragma.
9572 @code{gnatmake ^-a^/ALL_FILES^} compiles all GNAT
9575 @code{gcc -c -gnatpg} rather than @code{gcc -c}.
9578 the @code{/CHECKS=SUPPRESS_ALL /STYLE_CHECKS=GNAT} switch.
9581 @item ^-b^/ACTIONS=BIND^
9582 @cindex @option{^-b^/ACTIONS=BIND^} (@command{gnatmake})
9583 Bind only. Can be combined with @option{^-c^/ACTIONS=COMPILE^} to do
9584 compilation and binding, but no link.
9585 Can be combined with @option{^-l^/ACTIONS=LINK^}
9586 to do binding and linking. When not combined with
9587 @option{^-c^/ACTIONS=COMPILE^}
9588 all the units in the closure of the main program must have been previously
9589 compiled and must be up to date. The root unit specified by @var{file_name}
9590 may be given without extension, with the source extension or, if no GNAT
9591 Project File is specified, with the ALI file extension.
9593 @item ^-c^/ACTIONS=COMPILE^
9594 @cindex @option{^-c^/ACTIONS=COMPILE^} (@command{gnatmake})
9595 Compile only. Do not perform binding, except when @option{^-b^/ACTIONS=BIND^}
9596 is also specified. Do not perform linking, except if both
9597 @option{^-b^/ACTIONS=BIND^} and
9598 @option{^-l^/ACTIONS=LINK^} are also specified.
9599 If the root unit specified by @var{file_name} is not a main unit, this is the
9600 default. Otherwise @command{gnatmake} will attempt binding and linking
9601 unless all objects are up to date and the executable is more recent than
9605 @cindex @option{^-C^/MAPPING^} (@command{gnatmake})
9606 Use a temporary mapping file. A mapping file is a way to communicate
9607 to the compiler two mappings: from unit names to file names (without
9608 any directory information) and from file names to path names (with
9609 full directory information). A mapping file can make the compiler's
9610 file searches faster, especially if there are many source directories,
9611 or the sources are read over a slow network connection. If
9612 @option{^-P^/PROJECT_FILE^} is used, a mapping file is always used, so
9613 @option{^-C^/MAPPING^} is unnecessary; in this case the mapping file
9614 is initially populated based on the project file. If
9615 @option{^-C^/MAPPING^} is used without
9616 @option{^-P^/PROJECT_FILE^},
9617 the mapping file is initially empty. Each invocation of the compiler
9618 will add any newly accessed sources to the mapping file.
9620 @item ^-C=^/USE_MAPPING_FILE=^@var{file}
9621 @cindex @option{^-C=^/USE_MAPPING^} (@command{gnatmake})
9622 Use a specific mapping file. The file, specified as a path name (absolute or
9623 relative) by this switch, should already exist, otherwise the switch is
9624 ineffective. The specified mapping file will be communicated to the compiler.
9625 This switch is not compatible with a project file
9626 (^-P^/PROJECT_FILE=^@var{file}) or with multiple compiling processes
9627 (^-j^/PROCESSES=^nnn, when nnn is greater than 1).
9629 @item ^-d^/DISPLAY_PROGRESS^
9630 @cindex @option{^-d^/DISPLAY_PROGRESS^} (@command{gnatmake})
9631 Display progress for each source, up to date or not, as a single line
9634 completed x out of y (zz%)
9637 If the file needs to be compiled this is displayed after the invocation of
9638 the compiler. These lines are displayed even in quiet output mode.
9640 @item ^-D ^/DIRECTORY_OBJECTS=^@var{dir}
9641 @cindex @option{^-D^/DIRECTORY_OBJECTS^} (@command{gnatmake})
9642 Put all object files and ALI file in directory @var{dir}.
9643 If the @option{^-D^/DIRECTORY_OBJECTS^} switch is not used, all object files
9644 and ALI files go in the current working directory.
9646 This switch cannot be used when using a project file.
9649 @cindex @option{-eI} (@command{gnatmake})
9650 Indicates that the main source is a multi-unit source and the rank of the unit
9651 in the source file is nnn. nnn needs to be a positive number and a valid
9652 index in the source. This switch cannot be used when @command{gnatmake} is
9653 invoked for several mains.
9657 @cindex @option{-eL} (@command{gnatmake})
9658 @cindex symbolic links
9659 Follow all symbolic links when processing project files.
9660 This should be used if your project uses symbolic links for files or
9661 directories, but is not needed in other cases.
9663 @cindex naming scheme
9664 This also assumes that no directory matches the naming scheme for files (for
9665 instance that you do not have a directory called "sources.ads" when using the
9666 default GNAT naming scheme).
9668 When you do not have to use this switch (i.e.@: by default), gnatmake is able to
9669 save a lot of system calls (several per source file and object file), which
9670 can result in a significant speed up to load and manipulate a project file,
9671 especially when using source files from a remote system.
9675 @item ^-eS^/STANDARD_OUTPUT_FOR_COMMANDS^
9676 @cindex @option{^-eS^/STANDARD_OUTPUT_FOR_COMMANDS^} (@command{gnatmake})
9677 Output the commands for the compiler, the binder and the linker
9678 on ^standard output^SYS$OUTPUT^,
9679 instead of ^standard error^SYS$ERROR^.
9681 @item ^-f^/FORCE_COMPILE^
9682 @cindex @option{^-f^/FORCE_COMPILE^} (@command{gnatmake})
9683 Force recompilations. Recompile all sources, even though some object
9684 files may be up to date, but don't recompile predefined or GNAT internal
9685 files or locked files (files with a write-protected ALI file),
9686 unless the @option{^-a^/ALL_FILES^} switch is also specified.
9688 @item ^-F^/FULL_PATH_IN_BRIEF_MESSAGES^
9689 @cindex @option{^-F^/FULL_PATH_IN_BRIEF_MESSAGES^} (@command{gnatmake})
9690 When using project files, if some errors or warnings are detected during
9691 parsing and verbose mode is not in effect (no use of switch
9692 ^-v^/VERBOSE^), then error lines start with the full path name of the project
9693 file, rather than its simple file name.
9696 @cindex @option{^-g^/DEBUG^} (@command{gnatmake})
9697 Enable debugging. This switch is simply passed to the compiler and to the
9700 @item ^-i^/IN_PLACE^
9701 @cindex @option{^-i^/IN_PLACE^} (@command{gnatmake})
9702 In normal mode, @command{gnatmake} compiles all object files and ALI files
9703 into the current directory. If the @option{^-i^/IN_PLACE^} switch is used,
9704 then instead object files and ALI files that already exist are overwritten
9705 in place. This means that once a large project is organized into separate
9706 directories in the desired manner, then @command{gnatmake} will automatically
9707 maintain and update this organization. If no ALI files are found on the
9708 Ada object path (@ref{Search Paths and the Run-Time Library (RTL)}),
9709 the new object and ALI files are created in the
9710 directory containing the source being compiled. If another organization
9711 is desired, where objects and sources are kept in different directories,
9712 a useful technique is to create dummy ALI files in the desired directories.
9713 When detecting such a dummy file, @command{gnatmake} will be forced to
9714 recompile the corresponding source file, and it will be put the resulting
9715 object and ALI files in the directory where it found the dummy file.
9717 @item ^-j^/PROCESSES=^@var{n}
9718 @cindex @option{^-j^/PROCESSES^} (@command{gnatmake})
9719 @cindex Parallel make
9720 Use @var{n} processes to carry out the (re)compilations. On a multiprocessor
9721 machine compilations will occur in parallel. If @var{n} is 0, then the
9722 maximum number of parallel compilations is the number of core processors
9723 on the platform. In the event of compilation errors, messages from various
9724 compilations might get interspersed (but @command{gnatmake} will give you the
9725 full ordered list of failing compiles at the end). If this is problematic,
9726 rerun the make process with n set to 1 to get a clean list of messages.
9728 @item ^-k^/CONTINUE_ON_ERROR^
9729 @cindex @option{^-k^/CONTINUE_ON_ERROR^} (@command{gnatmake})
9730 Keep going. Continue as much as possible after a compilation error. To
9731 ease the programmer's task in case of compilation errors, the list of
9732 sources for which the compile fails is given when @command{gnatmake}
9735 If @command{gnatmake} is invoked with several @file{file_names} and with this
9736 switch, if there are compilation errors when building an executable,
9737 @command{gnatmake} will not attempt to build the following executables.
9739 @item ^-l^/ACTIONS=LINK^
9740 @cindex @option{^-l^/ACTIONS=LINK^} (@command{gnatmake})
9741 Link only. Can be combined with @option{^-b^/ACTIONS=BIND^} to binding
9742 and linking. Linking will not be performed if combined with
9743 @option{^-c^/ACTIONS=COMPILE^}
9744 but not with @option{^-b^/ACTIONS=BIND^}.
9745 When not combined with @option{^-b^/ACTIONS=BIND^}
9746 all the units in the closure of the main program must have been previously
9747 compiled and must be up to date, and the main program needs to have been bound.
9748 The root unit specified by @var{file_name}
9749 may be given without extension, with the source extension or, if no GNAT
9750 Project File is specified, with the ALI file extension.
9752 @item ^-m^/MINIMAL_RECOMPILATION^
9753 @cindex @option{^-m^/MINIMAL_RECOMPILATION^} (@command{gnatmake})
9754 Specify that the minimum necessary amount of recompilations
9755 be performed. In this mode @command{gnatmake} ignores time
9756 stamp differences when the only
9757 modifications to a source file consist in adding/removing comments,
9758 empty lines, spaces or tabs. This means that if you have changed the
9759 comments in a source file or have simply reformatted it, using this
9760 switch will tell @command{gnatmake} not to recompile files that depend on it
9761 (provided other sources on which these files depend have undergone no
9762 semantic modifications). Note that the debugging information may be
9763 out of date with respect to the sources if the @option{-m} switch causes
9764 a compilation to be switched, so the use of this switch represents a
9765 trade-off between compilation time and accurate debugging information.
9767 @item ^-M^/DEPENDENCIES_LIST^
9768 @cindex Dependencies, producing list
9769 @cindex @option{^-M^/DEPENDENCIES_LIST^} (@command{gnatmake})
9770 Check if all objects are up to date. If they are, output the object
9771 dependences to @file{stdout} in a form that can be directly exploited in
9772 a @file{Makefile}. By default, each source file is prefixed with its
9773 (relative or absolute) directory name. This name is whatever you
9774 specified in the various @option{^-aI^/SOURCE_SEARCH^}
9775 and @option{^-I^/SEARCH^} switches. If you use
9776 @code{gnatmake ^-M^/DEPENDENCIES_LIST^}
9777 @option{^-q^/QUIET^}
9778 (see below), only the source file names,
9779 without relative paths, are output. If you just specify the
9780 @option{^-M^/DEPENDENCIES_LIST^}
9781 switch, dependencies of the GNAT internal system files are omitted. This
9782 is typically what you want. If you also specify
9783 the @option{^-a^/ALL_FILES^} switch,
9784 dependencies of the GNAT internal files are also listed. Note that
9785 dependencies of the objects in external Ada libraries (see switch
9786 @option{^-aL^/SKIP_MISSING=^}@var{dir} in the following list)
9789 @item ^-n^/DO_OBJECT_CHECK^
9790 @cindex @option{^-n^/DO_OBJECT_CHECK^} (@command{gnatmake})
9791 Don't compile, bind, or link. Checks if all objects are up to date.
9792 If they are not, the full name of the first file that needs to be
9793 recompiled is printed.
9794 Repeated use of this option, followed by compiling the indicated source
9795 file, will eventually result in recompiling all required units.
9797 @item ^-o ^/EXECUTABLE=^@var{exec_name}
9798 @cindex @option{^-o^/EXECUTABLE^} (@command{gnatmake})
9799 Output executable name. The name of the final executable program will be
9800 @var{exec_name}. If the @option{^-o^/EXECUTABLE^} switch is omitted the default
9801 name for the executable will be the name of the input file in appropriate form
9802 for an executable file on the host system.
9804 This switch cannot be used when invoking @command{gnatmake} with several
9807 @item ^-p or --create-missing-dirs^/CREATE_MISSING_DIRS^
9808 @cindex @option{^-p^/CREATE_MISSING_DIRS^} (@command{gnatmake})
9809 When using project files (^-P^/PROJECT_FILE=^@var{project}), create
9810 automatically missing object directories, library directories and exec
9813 @item ^-P^/PROJECT_FILE=^@var{project}
9814 @cindex @option{^-P^/PROJECT_FILE^} (@command{gnatmake})
9815 Use project file @var{project}. Only one such switch can be used.
9816 @xref{gnatmake and Project Files}.
9819 @cindex @option{^-q^/QUIET^} (@command{gnatmake})
9820 Quiet. When this flag is not set, the commands carried out by
9821 @command{gnatmake} are displayed.
9823 @item ^-s^/SWITCH_CHECK/^
9824 @cindex @option{^-s^/SWITCH_CHECK^} (@command{gnatmake})
9825 Recompile if compiler switches have changed since last compilation.
9826 All compiler switches but -I and -o are taken into account in the
9828 orders between different ``first letter'' switches are ignored, but
9829 orders between same switches are taken into account. For example,
9830 @option{-O -O2} is different than @option{-O2 -O}, but @option{-g -O}
9831 is equivalent to @option{-O -g}.
9833 This switch is recommended when Integrated Preprocessing is used.
9836 @cindex @option{^-u^/UNIQUE^} (@command{gnatmake})
9837 Unique. Recompile at most the main files. It implies -c. Combined with
9838 -f, it is equivalent to calling the compiler directly. Note that using
9839 ^-u^/UNIQUE^ with a project file and no main has a special meaning
9840 (@pxref{Project Files and Main Subprograms}).
9842 @item ^-U^/ALL_PROJECTS^
9843 @cindex @option{^-U^/ALL_PROJECTS^} (@command{gnatmake})
9844 When used without a project file or with one or several mains on the command
9845 line, is equivalent to ^-u^/UNIQUE^. When used with a project file and no main
9846 on the command line, all sources of all project files are checked and compiled
9847 if not up to date, and libraries are rebuilt, if necessary.
9850 @cindex @option{^-v^/REASONS^} (@command{gnatmake})
9851 Verbose. Display the reason for all recompilations @command{gnatmake}
9852 decides are necessary, with the highest verbosity level.
9854 @item ^-vl^/LOW_VERBOSITY^
9855 @cindex @option{^-vl^/LOW_VERBOSITY^} (@command{gnatmake})
9856 Verbosity level Low. Display fewer lines than in verbosity Medium.
9858 @item ^-vm^/MEDIUM_VERBOSITY^
9859 @cindex @option{^-vm^/MEDIUM_VERBOSITY^} (@command{gnatmake})
9860 Verbosity level Medium. Potentially display fewer lines than in verbosity High.
9862 @item ^-vh^/HIGH_VERBOSITY^
9863 @cindex @option{^-vm^/HIGH_VERBOSITY^} (@command{gnatmake})
9864 Verbosity level High. Equivalent to ^-v^/REASONS^.
9866 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
9867 Indicate the verbosity of the parsing of GNAT project files.
9868 @xref{Switches Related to Project Files}.
9870 @item ^-x^/NON_PROJECT_UNIT_COMPILATION^
9871 @cindex @option{^-x^/NON_PROJECT_UNIT_COMPILATION^} (@command{gnatmake})
9872 Indicate that sources that are not part of any Project File may be compiled.
9873 Normally, when using Project Files, only sources that are part of a Project
9874 File may be compile. When this switch is used, a source outside of all Project
9875 Files may be compiled. The ALI file and the object file will be put in the
9876 object directory of the main Project. The compilation switches used will only
9877 be those specified on the command line. Even when
9878 @option{^-x^/NON_PROJECT_UNIT_COMPILATION^} is used, mains specified on the
9879 command line need to be sources of a project file.
9881 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
9882 Indicate that external variable @var{name} has the value @var{value}.
9883 The Project Manager will use this value for occurrences of
9884 @code{external(name)} when parsing the project file.
9885 @xref{Switches Related to Project Files}.
9888 @cindex @option{^-z^/NOMAIN^} (@command{gnatmake})
9889 No main subprogram. Bind and link the program even if the unit name
9890 given on the command line is a package name. The resulting executable
9891 will execute the elaboration routines of the package and its closure,
9892 then the finalization routines.
9897 @item @command{gcc} @asis{switches}
9899 Any uppercase or multi-character switch that is not a @command{gnatmake} switch
9900 is passed to @command{gcc} (e.g.@: @option{-O}, @option{-gnato,} etc.)
9903 Any qualifier that cannot be recognized as a qualifier for @code{GNAT MAKE}
9904 but is recognizable as a valid qualifier for @code{GNAT COMPILE} is
9905 automatically treated as a compiler switch, and passed on to all
9906 compilations that are carried out.
9911 Source and library search path switches:
9915 @item ^-aI^/SOURCE_SEARCH=^@var{dir}
9916 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatmake})
9917 When looking for source files also look in directory @var{dir}.
9918 The order in which source files search is undertaken is
9919 described in @ref{Search Paths and the Run-Time Library (RTL)}.
9921 @item ^-aL^/SKIP_MISSING=^@var{dir}
9922 @cindex @option{^-aL^/SKIP_MISSING^} (@command{gnatmake})
9923 Consider @var{dir} as being an externally provided Ada library.
9924 Instructs @command{gnatmake} to skip compilation units whose @file{.ALI}
9925 files have been located in directory @var{dir}. This allows you to have
9926 missing bodies for the units in @var{dir} and to ignore out of date bodies
9927 for the same units. You still need to specify
9928 the location of the specs for these units by using the switches
9929 @option{^-aI^/SOURCE_SEARCH=^@var{dir}}
9930 or @option{^-I^/SEARCH=^@var{dir}}.
9931 Note: this switch is provided for compatibility with previous versions
9932 of @command{gnatmake}. The easier method of causing standard libraries
9933 to be excluded from consideration is to write-protect the corresponding
9936 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
9937 @cindex @option{^-aO^/OBJECT_SEARCH^} (@command{gnatmake})
9938 When searching for library and object files, look in directory
9939 @var{dir}. The order in which library files are searched is described in
9940 @ref{Search Paths for gnatbind}.
9942 @item ^-A^/CONDITIONAL_SOURCE_SEARCH=^@var{dir}
9943 @cindex Search paths, for @command{gnatmake}
9944 @cindex @option{^-A^/CONDITIONAL_SOURCE_SEARCH^} (@command{gnatmake})
9945 Equivalent to @option{^-aL^/SKIP_MISSING=^@var{dir}
9946 ^-aI^/SOURCE_SEARCH=^@var{dir}}.
9948 @item ^-I^/SEARCH=^@var{dir}
9949 @cindex @option{^-I^/SEARCH^} (@command{gnatmake})
9950 Equivalent to @option{^-aO^/OBJECT_SEARCH=^@var{dir}
9951 ^-aI^/SOURCE_SEARCH=^@var{dir}}.
9953 @item ^-I-^/NOCURRENT_DIRECTORY^
9954 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gnatmake})
9955 @cindex Source files, suppressing search
9956 Do not look for source files in the directory containing the source
9957 file named in the command line.
9958 Do not look for ALI or object files in the directory
9959 where @command{gnatmake} was invoked.
9961 @item ^-L^/LIBRARY_SEARCH=^@var{dir}
9962 @cindex @option{^-L^/LIBRARY_SEARCH^} (@command{gnatmake})
9963 @cindex Linker libraries
9964 Add directory @var{dir} to the list of directories in which the linker
9965 will search for libraries. This is equivalent to
9966 @option{-largs ^-L^/LIBRARY_SEARCH=^}@var{dir}.
9968 Furthermore, under Windows, the sources pointed to by the libraries path
9969 set in the registry are not searched for.
9973 @cindex @option{-nostdinc} (@command{gnatmake})
9974 Do not look for source files in the system default directory.
9977 @cindex @option{-nostdlib} (@command{gnatmake})
9978 Do not look for library files in the system default directory.
9980 @item --RTS=@var{rts-path}
9981 @cindex @option{--RTS} (@command{gnatmake})
9982 Specifies the default location of the runtime library. GNAT looks for the
9984 in the following directories, and stops as soon as a valid runtime is found
9985 (@file{adainclude} or @file{ada_source_path}, and @file{adalib} or
9986 @file{ada_object_path} present):
9989 @item <current directory>/$rts_path
9991 @item <default-search-dir>/$rts_path
9993 @item <default-search-dir>/rts-$rts_path
9997 The selected path is handled like a normal RTS path.
10001 @node Mode Switches for gnatmake
10002 @section Mode Switches for @command{gnatmake}
10005 The mode switches (referred to as @code{mode_switches}) allow the
10006 inclusion of switches that are to be passed to the compiler itself, the
10007 binder or the linker. The effect of a mode switch is to cause all
10008 subsequent switches up to the end of the switch list, or up to the next
10009 mode switch, to be interpreted as switches to be passed on to the
10010 designated component of GNAT.
10014 @item -cargs @var{switches}
10015 @cindex @option{-cargs} (@command{gnatmake})
10016 Compiler switches. Here @var{switches} is a list of switches
10017 that are valid switches for @command{gcc}. They will be passed on to
10018 all compile steps performed by @command{gnatmake}.
10020 @item -bargs @var{switches}
10021 @cindex @option{-bargs} (@command{gnatmake})
10022 Binder switches. Here @var{switches} is a list of switches
10023 that are valid switches for @code{gnatbind}. They will be passed on to
10024 all bind steps performed by @command{gnatmake}.
10026 @item -largs @var{switches}
10027 @cindex @option{-largs} (@command{gnatmake})
10028 Linker switches. Here @var{switches} is a list of switches
10029 that are valid switches for @command{gnatlink}. They will be passed on to
10030 all link steps performed by @command{gnatmake}.
10032 @item -margs @var{switches}
10033 @cindex @option{-margs} (@command{gnatmake})
10034 Make switches. The switches are directly interpreted by @command{gnatmake},
10035 regardless of any previous occurrence of @option{-cargs}, @option{-bargs}
10036 or @option{-largs}.
10039 @node Notes on the Command Line
10040 @section Notes on the Command Line
10043 This section contains some additional useful notes on the operation
10044 of the @command{gnatmake} command.
10048 @cindex Recompilation, by @command{gnatmake}
10049 If @command{gnatmake} finds no ALI files, it recompiles the main program
10050 and all other units required by the main program.
10051 This means that @command{gnatmake}
10052 can be used for the initial compile, as well as during subsequent steps of
10053 the development cycle.
10056 If you enter @code{gnatmake @var{file}.adb}, where @file{@var{file}.adb}
10057 is a subunit or body of a generic unit, @command{gnatmake} recompiles
10058 @file{@var{file}.adb} (because it finds no ALI) and stops, issuing a
10062 In @command{gnatmake} the switch @option{^-I^/SEARCH^}
10063 is used to specify both source and
10064 library file paths. Use @option{^-aI^/SOURCE_SEARCH^}
10065 instead if you just want to specify
10066 source paths only and @option{^-aO^/OBJECT_SEARCH^}
10067 if you want to specify library paths
10071 @command{gnatmake} will ignore any files whose ALI file is write-protected.
10072 This may conveniently be used to exclude standard libraries from
10073 consideration and in particular it means that the use of the
10074 @option{^-f^/FORCE_COMPILE^} switch will not recompile these files
10075 unless @option{^-a^/ALL_FILES^} is also specified.
10078 @command{gnatmake} has been designed to make the use of Ada libraries
10079 particularly convenient. Assume you have an Ada library organized
10080 as follows: @i{^obj-dir^[OBJ_DIR]^} contains the objects and ALI files for
10081 of your Ada compilation units,
10082 whereas @i{^include-dir^[INCLUDE_DIR]^} contains the
10083 specs of these units, but no bodies. Then to compile a unit
10084 stored in @code{main.adb}, which uses this Ada library you would just type
10088 $ gnatmake -aI@var{include-dir} -aL@var{obj-dir} main
10091 $ gnatmake /SOURCE_SEARCH=@i{[INCLUDE_DIR]}
10092 /SKIP_MISSING=@i{[OBJ_DIR]} main
10097 Using @command{gnatmake} along with the
10098 @option{^-m (minimal recompilation)^/MINIMAL_RECOMPILATION^}
10099 switch provides a mechanism for avoiding unnecessary recompilations. Using
10101 you can update the comments/format of your
10102 source files without having to recompile everything. Note, however, that
10103 adding or deleting lines in a source files may render its debugging
10104 info obsolete. If the file in question is a spec, the impact is rather
10105 limited, as that debugging info will only be useful during the
10106 elaboration phase of your program. For bodies the impact can be more
10107 significant. In all events, your debugger will warn you if a source file
10108 is more recent than the corresponding object, and alert you to the fact
10109 that the debugging information may be out of date.
10112 @node How gnatmake Works
10113 @section How @command{gnatmake} Works
10116 Generally @command{gnatmake} automatically performs all necessary
10117 recompilations and you don't need to worry about how it works. However,
10118 it may be useful to have some basic understanding of the @command{gnatmake}
10119 approach and in particular to understand how it uses the results of
10120 previous compilations without incorrectly depending on them.
10122 First a definition: an object file is considered @dfn{up to date} if the
10123 corresponding ALI file exists and if all the source files listed in the
10124 dependency section of this ALI file have time stamps matching those in
10125 the ALI file. This means that neither the source file itself nor any
10126 files that it depends on have been modified, and hence there is no need
10127 to recompile this file.
10129 @command{gnatmake} works by first checking if the specified main unit is up
10130 to date. If so, no compilations are required for the main unit. If not,
10131 @command{gnatmake} compiles the main program to build a new ALI file that
10132 reflects the latest sources. Then the ALI file of the main unit is
10133 examined to find all the source files on which the main program depends,
10134 and @command{gnatmake} recursively applies the above procedure on all these
10137 This process ensures that @command{gnatmake} only trusts the dependencies
10138 in an existing ALI file if they are known to be correct. Otherwise it
10139 always recompiles to determine a new, guaranteed accurate set of
10140 dependencies. As a result the program is compiled ``upside down'' from what may
10141 be more familiar as the required order of compilation in some other Ada
10142 systems. In particular, clients are compiled before the units on which
10143 they depend. The ability of GNAT to compile in any order is critical in
10144 allowing an order of compilation to be chosen that guarantees that
10145 @command{gnatmake} will recompute a correct set of new dependencies if
10148 When invoking @command{gnatmake} with several @var{file_names}, if a unit is
10149 imported by several of the executables, it will be recompiled at most once.
10151 Note: when using non-standard naming conventions
10152 (@pxref{Using Other File Names}), changing through a configuration pragmas
10153 file the version of a source and invoking @command{gnatmake} to recompile may
10154 have no effect, if the previous version of the source is still accessible
10155 by @command{gnatmake}. It may be necessary to use the switch
10156 ^-f^/FORCE_COMPILE^.
10158 @node Examples of gnatmake Usage
10159 @section Examples of @command{gnatmake} Usage
10162 @item gnatmake hello.adb
10163 Compile all files necessary to bind and link the main program
10164 @file{hello.adb} (containing unit @code{Hello}) and bind and link the
10165 resulting object files to generate an executable file @file{^hello^HELLO.EXE^}.
10167 @item gnatmake main1 main2 main3
10168 Compile all files necessary to bind and link the main programs
10169 @file{main1.adb} (containing unit @code{Main1}), @file{main2.adb}
10170 (containing unit @code{Main2}) and @file{main3.adb}
10171 (containing unit @code{Main3}) and bind and link the resulting object files
10172 to generate three executable files @file{^main1^MAIN1.EXE^},
10173 @file{^main2^MAIN2.EXE^}
10174 and @file{^main3^MAIN3.EXE^}.
10177 @item gnatmake -q Main_Unit -cargs -O2 -bargs -l
10181 @item gnatmake Main_Unit /QUIET
10182 /COMPILER_QUALIFIERS /OPTIMIZE=ALL
10183 /BINDER_QUALIFIERS /ORDER_OF_ELABORATION
10185 Compile all files necessary to bind and link the main program unit
10186 @code{Main_Unit} (from file @file{main_unit.adb}). All compilations will
10187 be done with optimization level 2 and the order of elaboration will be
10188 listed by the binder. @command{gnatmake} will operate in quiet mode, not
10189 displaying commands it is executing.
10192 @c *************************
10193 @node Improving Performance
10194 @chapter Improving Performance
10195 @cindex Improving performance
10198 This chapter presents several topics related to program performance.
10199 It first describes some of the tradeoffs that need to be considered
10200 and some of the techniques for making your program run faster.
10202 @ifclear FSFEDITION
10203 the @command{gnatelim} tool and
10205 unused subprogram/data
10206 elimination feature, which can reduce the size of program executables.
10210 * Performance Considerations::
10211 * Text_IO Suggestions::
10212 @ifclear FSFEDITION
10213 * Reducing Size of Ada Executables with gnatelim::
10215 * Reducing Size of Executables with unused subprogram/data elimination::
10219 @c *****************************
10220 @node Performance Considerations
10221 @section Performance Considerations
10224 The GNAT system provides a number of options that allow a trade-off
10229 performance of the generated code
10232 speed of compilation
10235 minimization of dependences and recompilation
10238 the degree of run-time checking.
10242 The defaults (if no options are selected) aim at improving the speed
10243 of compilation and minimizing dependences, at the expense of performance
10244 of the generated code:
10251 no inlining of subprogram calls
10254 all run-time checks enabled except overflow and elaboration checks
10258 These options are suitable for most program development purposes. This
10259 chapter describes how you can modify these choices, and also provides
10260 some guidelines on debugging optimized code.
10263 * Controlling Run-Time Checks::
10264 * Use of Restrictions::
10265 * Optimization Levels::
10266 * Debugging Optimized Code::
10267 * Inlining of Subprograms::
10268 * Vectorization of loops::
10269 * Other Optimization Switches::
10270 * Optimization and Strict Aliasing::
10271 * Aliased Variables and Optimization::
10272 * Atomic Variables and Optimization::
10273 * Passive Task Optimization::
10276 * Coverage Analysis::
10280 @node Controlling Run-Time Checks
10281 @subsection Controlling Run-Time Checks
10284 By default, GNAT generates all run-time checks, except integer overflow
10285 checks, stack overflow checks, and checks for access before elaboration on
10286 subprogram calls. The latter are not required in default mode, because all
10287 necessary checking is done at compile time.
10288 @cindex @option{-gnatp} (@command{gcc})
10289 @cindex @option{-gnato} (@command{gcc})
10290 Two gnat switches, @option{-gnatp} and @option{-gnato} allow this default to
10291 be modified. @xref{Run-Time Checks}.
10293 Our experience is that the default is suitable for most development
10296 We treat integer overflow specially because these
10297 are quite expensive and in our experience are not as important as other
10298 run-time checks in the development process. Note that division by zero
10299 is not considered an overflow check, and divide by zero checks are
10300 generated where required by default.
10302 Elaboration checks are off by default, and also not needed by default, since
10303 GNAT uses a static elaboration analysis approach that avoids the need for
10304 run-time checking. This manual contains a full chapter discussing the issue
10305 of elaboration checks, and if the default is not satisfactory for your use,
10306 you should read this chapter.
10308 For validity checks, the minimal checks required by the Ada Reference
10309 Manual (for case statements and assignments to array elements) are on
10310 by default. These can be suppressed by use of the @option{-gnatVn} switch.
10311 Note that in Ada 83, there were no validity checks, so if the Ada 83 mode
10312 is acceptable (or when comparing GNAT performance with an Ada 83 compiler),
10313 it may be reasonable to routinely use @option{-gnatVn}. Validity checks
10314 are also suppressed entirely if @option{-gnatp} is used.
10316 @cindex Overflow checks
10317 @cindex Checks, overflow
10320 @cindex pragma Suppress
10321 @cindex pragma Unsuppress
10322 Note that the setting of the switches controls the default setting of
10323 the checks. They may be modified using either @code{pragma Suppress} (to
10324 remove checks) or @code{pragma Unsuppress} (to add back suppressed
10325 checks) in the program source.
10327 @node Use of Restrictions
10328 @subsection Use of Restrictions
10331 The use of pragma Restrictions allows you to control which features are
10332 permitted in your program. Apart from the obvious point that if you avoid
10333 relatively expensive features like finalization (enforceable by the use
10334 of pragma Restrictions (No_Finalization), the use of this pragma does not
10335 affect the generated code in most cases.
10337 One notable exception to this rule is that the possibility of task abort
10338 results in some distributed overhead, particularly if finalization or
10339 exception handlers are used. The reason is that certain sections of code
10340 have to be marked as non-abortable.
10342 If you use neither the @code{abort} statement, nor asynchronous transfer
10343 of control (@code{select @dots{} then abort}), then this distributed overhead
10344 is removed, which may have a general positive effect in improving
10345 overall performance. Especially code involving frequent use of tasking
10346 constructs and controlled types will show much improved performance.
10347 The relevant restrictions pragmas are
10349 @smallexample @c ada
10350 pragma Restrictions (No_Abort_Statements);
10351 pragma Restrictions (Max_Asynchronous_Select_Nesting => 0);
10355 It is recommended that these restriction pragmas be used if possible. Note
10356 that this also means that you can write code without worrying about the
10357 possibility of an immediate abort at any point.
10359 @node Optimization Levels
10360 @subsection Optimization Levels
10361 @cindex @option{^-O^/OPTIMIZE^} (@command{gcc})
10364 Without any optimization ^option,^qualifier,^
10365 the compiler's goal is to reduce the cost of
10366 compilation and to make debugging produce the expected results.
10367 Statements are independent: if you stop the program with a breakpoint between
10368 statements, you can then assign a new value to any variable or change
10369 the program counter to any other statement in the subprogram and get exactly
10370 the results you would expect from the source code.
10372 Turning on optimization makes the compiler attempt to improve the
10373 performance and/or code size at the expense of compilation time and
10374 possibly the ability to debug the program.
10376 If you use multiple
10377 ^-O options, with or without level numbers,^/OPTIMIZE qualifiers,^
10378 the last such option is the one that is effective.
10381 The default is optimization off. This results in the fastest compile
10382 times, but GNAT makes absolutely no attempt to optimize, and the
10383 generated programs are considerably larger and slower than when
10384 optimization is enabled. You can use the
10386 @option{-O} switch (the permitted forms are @option{-O0}, @option{-O1}
10387 @option{-O2}, @option{-O3}, and @option{-Os})
10390 @code{OPTIMIZE} qualifier
10392 to @command{gcc} to control the optimization level:
10395 @item ^-O0^/OPTIMIZE=NONE^
10396 No optimization (the default);
10397 generates unoptimized code but has
10398 the fastest compilation time.
10400 Note that many other compilers do fairly extensive optimization
10401 even if ``no optimization'' is specified. With gcc, it is
10402 very unusual to use ^-O0^/OPTIMIZE=NONE^ for production if
10403 execution time is of any concern, since ^-O0^/OPTIMIZE=NONE^
10404 really does mean no optimization at all. This difference between
10405 gcc and other compilers should be kept in mind when doing
10406 performance comparisons.
10408 @item ^-O1^/OPTIMIZE=SOME^
10409 Moderate optimization;
10410 optimizes reasonably well but does not
10411 degrade compilation time significantly.
10413 @item ^-O2^/OPTIMIZE=ALL^
10415 @itemx /OPTIMIZE=DEVELOPMENT
10418 generates highly optimized code and has
10419 the slowest compilation time.
10421 @item ^-O3^/OPTIMIZE=INLINING^
10422 Full optimization as in @option{-O2};
10423 also uses more aggressive automatic inlining of subprograms within a unit
10424 (@pxref{Inlining of Subprograms}) and attempts to vectorize loops.
10426 @item ^-Os^/OPTIMIZE=SPACE^
10427 Optimize space usage (code and data) of resulting program.
10431 Higher optimization levels perform more global transformations on the
10432 program and apply more expensive analysis algorithms in order to generate
10433 faster and more compact code. The price in compilation time, and the
10434 resulting improvement in execution time,
10435 both depend on the particular application and the hardware environment.
10436 You should experiment to find the best level for your application.
10438 Since the precise set of optimizations done at each level will vary from
10439 release to release (and sometime from target to target), it is best to think
10440 of the optimization settings in general terms.
10441 @xref{Optimize Options,, Options That Control Optimization, gcc, Using
10442 the GNU Compiler Collection (GCC)}, for details about
10443 ^the @option{-O} settings and a number of @option{-f} options that^how to^
10444 individually enable or disable specific optimizations.
10446 Unlike some other compilation systems, ^@command{gcc}^GNAT^ has
10447 been tested extensively at all optimization levels. There are some bugs
10448 which appear only with optimization turned on, but there have also been
10449 bugs which show up only in @emph{unoptimized} code. Selecting a lower
10450 level of optimization does not improve the reliability of the code
10451 generator, which in practice is highly reliable at all optimization
10454 Note regarding the use of @option{-O3}: The use of this optimization level
10455 is generally discouraged with GNAT, since it often results in larger
10456 executables which may run more slowly. See further discussion of this point
10457 in @ref{Inlining of Subprograms}.
10459 @node Debugging Optimized Code
10460 @subsection Debugging Optimized Code
10461 @cindex Debugging optimized code
10462 @cindex Optimization and debugging
10465 Although it is possible to do a reasonable amount of debugging at
10467 nonzero optimization levels,
10468 the higher the level the more likely that
10471 @option{/OPTIMIZE} settings other than @code{NONE},
10472 such settings will make it more likely that
10474 source-level constructs will have been eliminated by optimization.
10475 For example, if a loop is strength-reduced, the loop
10476 control variable may be completely eliminated and thus cannot be
10477 displayed in the debugger.
10478 This can only happen at @option{-O2} or @option{-O3}.
10479 Explicit temporary variables that you code might be eliminated at
10480 ^level^setting^ @option{-O1} or higher.
10482 The use of the @option{^-g^/DEBUG^} switch,
10483 @cindex @option{^-g^/DEBUG^} (@command{gcc})
10484 which is needed for source-level debugging,
10485 affects the size of the program executable on disk,
10486 and indeed the debugging information can be quite large.
10487 However, it has no effect on the generated code (and thus does not
10488 degrade performance)
10490 Since the compiler generates debugging tables for a compilation unit before
10491 it performs optimizations, the optimizing transformations may invalidate some
10492 of the debugging data. You therefore need to anticipate certain
10493 anomalous situations that may arise while debugging optimized code.
10494 These are the most common cases:
10498 @i{The ``hopping Program Counter'':} Repeated @code{step} or @code{next}
10500 the PC bouncing back and forth in the code. This may result from any of
10501 the following optimizations:
10505 @i{Common subexpression elimination:} using a single instance of code for a
10506 quantity that the source computes several times. As a result you
10507 may not be able to stop on what looks like a statement.
10510 @i{Invariant code motion:} moving an expression that does not change within a
10511 loop, to the beginning of the loop.
10514 @i{Instruction scheduling:} moving instructions so as to
10515 overlap loads and stores (typically) with other code, or in
10516 general to move computations of values closer to their uses. Often
10517 this causes you to pass an assignment statement without the assignment
10518 happening and then later bounce back to the statement when the
10519 value is actually needed. Placing a breakpoint on a line of code
10520 and then stepping over it may, therefore, not always cause all the
10521 expected side-effects.
10525 @i{The ``big leap'':} More commonly known as @emph{cross-jumping}, in which
10526 two identical pieces of code are merged and the program counter suddenly
10527 jumps to a statement that is not supposed to be executed, simply because
10528 it (and the code following) translates to the same thing as the code
10529 that @emph{was} supposed to be executed. This effect is typically seen in
10530 sequences that end in a jump, such as a @code{goto}, a @code{return}, or
10531 a @code{break} in a C @code{^switch^switch^} statement.
10534 @i{The ``roving variable'':} The symptom is an unexpected value in a variable.
10535 There are various reasons for this effect:
10539 In a subprogram prologue, a parameter may not yet have been moved to its
10543 A variable may be dead, and its register re-used. This is
10544 probably the most common cause.
10547 As mentioned above, the assignment of a value to a variable may
10551 A variable may be eliminated entirely by value propagation or
10552 other means. In this case, GCC may incorrectly generate debugging
10553 information for the variable
10557 In general, when an unexpected value appears for a local variable or parameter
10558 you should first ascertain if that value was actually computed by
10559 your program, as opposed to being incorrectly reported by the debugger.
10561 array elements in an object designated by an access value
10562 are generally less of a problem, once you have ascertained that the access
10564 Typically, this means checking variables in the preceding code and in the
10565 calling subprogram to verify that the value observed is explainable from other
10566 values (one must apply the procedure recursively to those
10567 other values); or re-running the code and stopping a little earlier
10568 (perhaps before the call) and stepping to better see how the variable obtained
10569 the value in question; or continuing to step @emph{from} the point of the
10570 strange value to see if code motion had simply moved the variable's
10575 In light of such anomalies, a recommended technique is to use @option{-O0}
10576 early in the software development cycle, when extensive debugging capabilities
10577 are most needed, and then move to @option{-O1} and later @option{-O2} as
10578 the debugger becomes less critical.
10579 Whether to use the @option{^-g^/DEBUG^} switch in the release version is
10580 a release management issue.
10582 Note that if you use @option{-g} you can then use the @command{strip} program
10583 on the resulting executable,
10584 which removes both debugging information and global symbols.
10587 @node Inlining of Subprograms
10588 @subsection Inlining of Subprograms
10591 A call to a subprogram in the current unit is inlined if all the
10592 following conditions are met:
10596 The optimization level is at least @option{-O1}.
10599 The called subprogram is suitable for inlining: It must be small enough
10600 and not contain something that @command{gcc} cannot support in inlined
10604 @cindex pragma Inline
10606 Any one of the following applies: @code{pragma Inline} is applied to the
10607 subprogram and the @option{^-gnatn^/INLINE^} switch is specified; the
10608 subprogram is local to the unit and called once from within it; the
10609 subprogram is small and optimization level @option{-O2} is specified;
10610 optimization level @option{-O3} is specified.
10614 Calls to subprograms in @code{with}'ed units are normally not inlined.
10615 To achieve actual inlining (that is, replacement of the call by the code
10616 in the body of the subprogram), the following conditions must all be true:
10620 The optimization level is at least @option{-O1}.
10623 The called subprogram is suitable for inlining: It must be small enough
10624 and not contain something that @command{gcc} cannot support in inlined
10628 The call appears in a body (not in a package spec).
10631 There is a @code{pragma Inline} for the subprogram.
10634 The @option{^-gnatn^/INLINE^} switch is used on the command line.
10637 Even if all these conditions are met, it may not be possible for
10638 the compiler to inline the call, due to the length of the body,
10639 or features in the body that make it impossible for the compiler
10640 to do the inlining.
10642 Note that specifying the @option{-gnatn} switch causes additional
10643 compilation dependencies. Consider the following:
10645 @smallexample @c ada
10665 With the default behavior (no @option{-gnatn} switch specified), the
10666 compilation of the @code{Main} procedure depends only on its own source,
10667 @file{main.adb}, and the spec of the package in file @file{r.ads}. This
10668 means that editing the body of @code{R} does not require recompiling
10671 On the other hand, the call @code{R.Q} is not inlined under these
10672 circumstances. If the @option{-gnatn} switch is present when @code{Main}
10673 is compiled, the call will be inlined if the body of @code{Q} is small
10674 enough, but now @code{Main} depends on the body of @code{R} in
10675 @file{r.adb} as well as on the spec. This means that if this body is edited,
10676 the main program must be recompiled. Note that this extra dependency
10677 occurs whether or not the call is in fact inlined by @command{gcc}.
10679 The use of front end inlining with @option{-gnatN} generates similar
10680 additional dependencies.
10682 @cindex @option{^-fno-inline^/INLINE=SUPPRESS^} (@command{gcc})
10683 Note: The @option{^-fno-inline^/INLINE=SUPPRESS^} switch
10684 can be used to prevent
10685 all inlining. This switch overrides all other conditions and ensures
10686 that no inlining occurs. The extra dependences resulting from
10687 @option{-gnatn} will still be active, even if
10688 this switch is used to suppress the resulting inlining actions.
10690 @cindex @option{-fno-inline-functions} (@command{gcc})
10691 Note: The @option{-fno-inline-functions} switch can be used to prevent
10692 automatic inlining of subprograms if @option{-O3} is used.
10694 @cindex @option{-fno-inline-small-functions} (@command{gcc})
10695 Note: The @option{-fno-inline-small-functions} switch can be used to prevent
10696 automatic inlining of small subprograms if @option{-O2} is used.
10698 @cindex @option{-fno-inline-functions-called-once} (@command{gcc})
10699 Note: The @option{-fno-inline-functions-called-once} switch
10700 can be used to prevent inlining of subprograms local to the unit
10701 and called once from within it if @option{-O1} is used.
10703 Note regarding the use of @option{-O3}: @option{-gnatn} is made up of two
10704 sub-switches @option{-gnatn1} and @option{-gnatn2} that can be directly
10705 specified in lieu of it, @option{-gnatn} being translated into one of them
10706 based on the optimization level. With @option{-O2} or below, @option{-gnatn}
10707 is equivalent to @option{-gnatn1} which activates pragma @code{Inline} with
10708 moderate inlining across modules. With @option{-O3}, @option{-gnatn} is
10709 equivalent to @option{-gnatn2} which activates pragma @code{Inline} with
10710 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
10711 effect of inlining subprograms you did not think should be inlined. We have
10712 found that the use of @option{-O3} may slow down the compilation and increase
10713 the code size by performing excessive inlining, leading to increased
10714 instruction cache pressure from the increased code size and thus minor
10715 performance improvements. So the bottom line here is that you should not
10716 automatically assume that @option{-O3} is better than @option{-O2}, and
10717 indeed you should use @option{-O3} only if tests show that it actually
10718 improves performance for your program.
10720 @node Vectorization of loops
10721 @subsection Vectorization of loops
10722 @cindex Optimization Switches
10724 You can take advantage of the auto-vectorizer present in the @command{gcc}
10725 back end to vectorize loops with GNAT. The corresponding command line switch
10726 is @option{-ftree-vectorize} but, as it is enabled by default at @option{-O3}
10727 and other aggressive optimizations helpful for vectorization also are enabled
10728 by default at this level, using @option{-O3} directly is recommended.
10730 You also need to make sure that the target architecture features a supported
10731 SIMD instruction set. For example, for the x86 architecture, you should at
10732 least specify @option{-msse2} to get significant vectorization (but you don't
10733 need to specify it for x86-64 as it is part of the base 64-bit architecture).
10734 Similarly, for the PowerPC architecture, you should specify @option{-maltivec}.
10736 The preferred loop form for vectorization is the @code{for} iteration scheme.
10737 Loops with a @code{while} iteration scheme can also be vectorized if they are
10738 very simple, but the vectorizer will quickly give up otherwise. With either
10739 iteration scheme, the flow of control must be straight, in particular no
10740 @code{exit} statement may appear in the loop body. The loop may however
10741 contain a single nested loop, if it can be vectorized when considered alone:
10743 @smallexample @c ada
10745 A : array (1..4, 1..4) of Long_Float;
10746 S : array (1..4) of Long_Float;
10750 for I in A'Range(1) loop
10751 for J in A'Range(2) loop
10752 S (I) := S (I) + A (I, J);
10759 The vectorizable operations depend on the targeted SIMD instruction set, but
10760 the adding and some of the multiplying operators are generally supported, as
10761 well as the logical operators for modular types. Note that, in the former
10762 case, enabling overflow checks, for example with @option{-gnato}, totally
10763 disables vectorization. The other checks are not supposed to have the same
10764 definitive effect, although compiling with @option{-gnatp} might well reveal
10765 cases where some checks do thwart vectorization.
10767 Type conversions may also prevent vectorization if they involve semantics that
10768 are not directly supported by the code generator or the SIMD instruction set.
10769 A typical example is direct conversion from floating-point to integer types.
10770 The solution in this case is to use the following idiom:
10772 @smallexample @c ada
10773 Integer (S'Truncation (F))
10777 if @code{S} is the subtype of floating-point object @code{F}.
10779 In most cases, the vectorizable loops are loops that iterate over arrays.
10780 All kinds of array types are supported, i.e. constrained array types with
10783 @smallexample @c ada
10784 type Array_Type is array (1 .. 4) of Long_Float;
10788 constrained array types with dynamic bounds:
10790 @smallexample @c ada
10791 type Array_Type is array (1 .. Q.N) of Long_Float;
10793 type Array_Type is array (Q.K .. 4) of Long_Float;
10795 type Array_Type is array (Q.K .. Q.N) of Long_Float;
10799 or unconstrained array types:
10801 @smallexample @c ada
10802 type Array_Type is array (Positive range <>) of Long_Float;
10806 The quality of the generated code decreases when the dynamic aspect of the
10807 array type increases, the worst code being generated for unconstrained array
10808 types. This is so because, the less information the compiler has about the
10809 bounds of the array, the more fallback code it needs to generate in order to
10810 fix things up at run time.
10812 It is possible to specify that a given loop should be subject to vectorization
10813 preferably to other optimizations by means of pragma @code{Loop_Optimize}:
10815 @smallexample @c ada
10816 pragma Loop_Optimize (Vector);
10820 placed immediately within the loop will convey the appropriate hint to the
10821 compiler for this loop.
10823 It is also possible to help the compiler generate better vectorized code
10824 for a given loop by asserting that there are no loop-carried dependencies
10825 in the loop. Consider for example the procedure:
10827 @smallexample @c ada
10828 type Arr is array (1 .. 4) of Long_Float;
10830 procedure Add (X, Y : not null access Arr; R : not null access Arr) is
10832 for I in Arr'Range loop
10833 R(I) := X(I) + Y(I);
10839 By default, the compiler cannot unconditionally vectorize the loop because
10840 assigning to a component of the array designated by R in one iteration could
10841 change the value read from the components of the arrays designated by X or Y
10842 in a later iteration. As a result, the compiler will generate two versions
10843 of the loop in the object code, one vectorized and the other not vectorized,
10844 as well as a test to select the appropriate version at run time. This can
10845 be overcome by another hint:
10847 @smallexample @c ada
10848 pragma Loop_Optimize (Ivdep);
10852 placed immediately within the loop will tell the compiler that it can safely
10853 omit the non-vectorized version of the loop as well as the run-time test.
10855 @node Other Optimization Switches
10856 @subsection Other Optimization Switches
10857 @cindex Optimization Switches
10859 Since @code{GNAT} uses the @command{gcc} back end, all the specialized
10860 @command{gcc} optimization switches are potentially usable. These switches
10861 have not been extensively tested with GNAT but can generally be expected
10862 to work. Examples of switches in this category are @option{-funroll-loops}
10863 and the various target-specific @option{-m} options (in particular, it has
10864 been observed that @option{-march=xxx} can significantly improve performance
10865 on appropriate machines). For full details of these switches, see
10866 @ref{Submodel Options,, Hardware Models and Configurations, gcc, Using
10867 the GNU Compiler Collection (GCC)}.
10869 @node Optimization and Strict Aliasing
10870 @subsection Optimization and Strict Aliasing
10872 @cindex Strict Aliasing
10873 @cindex No_Strict_Aliasing
10876 The strong typing capabilities of Ada allow an optimizer to generate
10877 efficient code in situations where other languages would be forced to
10878 make worst case assumptions preventing such optimizations. Consider
10879 the following example:
10881 @smallexample @c ada
10884 type Int1 is new Integer;
10885 type Int2 is new Integer;
10886 type Int1A is access Int1;
10887 type Int2A is access Int2;
10894 for J in Data'Range loop
10895 if Data (J) = Int1V.all then
10896 Int2V.all := Int2V.all + 1;
10905 In this example, since the variable @code{Int1V} can only access objects
10906 of type @code{Int1}, and @code{Int2V} can only access objects of type
10907 @code{Int2}, there is no possibility that the assignment to
10908 @code{Int2V.all} affects the value of @code{Int1V.all}. This means that
10909 the compiler optimizer can "know" that the value @code{Int1V.all} is constant
10910 for all iterations of the loop and avoid the extra memory reference
10911 required to dereference it each time through the loop.
10913 This kind of optimization, called strict aliasing analysis, is
10914 triggered by specifying an optimization level of @option{-O2} or
10915 higher or @option{-Os} and allows @code{GNAT} to generate more efficient code
10916 when access values are involved.
10918 However, although this optimization is always correct in terms of
10919 the formal semantics of the Ada Reference Manual, difficulties can
10920 arise if features like @code{Unchecked_Conversion} are used to break
10921 the typing system. Consider the following complete program example:
10923 @smallexample @c ada
10926 type int1 is new integer;
10927 type int2 is new integer;
10928 type a1 is access int1;
10929 type a2 is access int2;
10934 function to_a2 (Input : a1) return a2;
10937 with Unchecked_Conversion;
10939 function to_a2 (Input : a1) return a2 is
10941 new Unchecked_Conversion (a1, a2);
10943 return to_a2u (Input);
10949 with Text_IO; use Text_IO;
10951 v1 : a1 := new int1;
10952 v2 : a2 := to_a2 (v1);
10956 put_line (int1'image (v1.all));
10962 This program prints out 0 in @option{-O0} or @option{-O1}
10963 mode, but it prints out 1 in @option{-O2} mode. That's
10964 because in strict aliasing mode, the compiler can and
10965 does assume that the assignment to @code{v2.all} could not
10966 affect the value of @code{v1.all}, since different types
10969 This behavior is not a case of non-conformance with the standard, since
10970 the Ada RM specifies that an unchecked conversion where the resulting
10971 bit pattern is not a correct value of the target type can result in an
10972 abnormal value and attempting to reference an abnormal value makes the
10973 execution of a program erroneous. That's the case here since the result
10974 does not point to an object of type @code{int2}. This means that the
10975 effect is entirely unpredictable.
10977 However, although that explanation may satisfy a language
10978 lawyer, in practice an applications programmer expects an
10979 unchecked conversion involving pointers to create true
10980 aliases and the behavior of printing 1 seems plain wrong.
10981 In this case, the strict aliasing optimization is unwelcome.
10983 Indeed the compiler recognizes this possibility, and the
10984 unchecked conversion generates a warning:
10987 p2.adb:5:07: warning: possible aliasing problem with type "a2"
10988 p2.adb:5:07: warning: use -fno-strict-aliasing switch for references
10989 p2.adb:5:07: warning: or use "pragma No_Strict_Aliasing (a2);"
10993 Unfortunately the problem is recognized when compiling the body of
10994 package @code{p2}, but the actual "bad" code is generated while
10995 compiling the body of @code{m} and this latter compilation does not see
10996 the suspicious @code{Unchecked_Conversion}.
10998 As implied by the warning message, there are approaches you can use to
10999 avoid the unwanted strict aliasing optimization in a case like this.
11001 One possibility is to simply avoid the use of @option{-O2}, but
11002 that is a bit drastic, since it throws away a number of useful
11003 optimizations that do not involve strict aliasing assumptions.
11005 A less drastic approach is to compile the program using the
11006 option @option{-fno-strict-aliasing}. Actually it is only the
11007 unit containing the dereferencing of the suspicious pointer
11008 that needs to be compiled. So in this case, if we compile
11009 unit @code{m} with this switch, then we get the expected
11010 value of zero printed. Analyzing which units might need
11011 the switch can be painful, so a more reasonable approach
11012 is to compile the entire program with options @option{-O2}
11013 and @option{-fno-strict-aliasing}. If the performance is
11014 satisfactory with this combination of options, then the
11015 advantage is that the entire issue of possible "wrong"
11016 optimization due to strict aliasing is avoided.
11018 To avoid the use of compiler switches, the configuration
11019 pragma @code{No_Strict_Aliasing} with no parameters may be
11020 used to specify that for all access types, the strict
11021 aliasing optimization should be suppressed.
11023 However, these approaches are still overkill, in that they causes
11024 all manipulations of all access values to be deoptimized. A more
11025 refined approach is to concentrate attention on the specific
11026 access type identified as problematic.
11028 First, if a careful analysis of uses of the pointer shows
11029 that there are no possible problematic references, then
11030 the warning can be suppressed by bracketing the
11031 instantiation of @code{Unchecked_Conversion} to turn
11034 @smallexample @c ada
11035 pragma Warnings (Off);
11037 new Unchecked_Conversion (a1, a2);
11038 pragma Warnings (On);
11042 Of course that approach is not appropriate for this particular
11043 example, since indeed there is a problematic reference. In this
11044 case we can take one of two other approaches.
11046 The first possibility is to move the instantiation of unchecked
11047 conversion to the unit in which the type is declared. In
11048 this example, we would move the instantiation of
11049 @code{Unchecked_Conversion} from the body of package
11050 @code{p2} to the spec of package @code{p1}. Now the
11051 warning disappears. That's because any use of the
11052 access type knows there is a suspicious unchecked
11053 conversion, and the strict aliasing optimization
11054 is automatically suppressed for the type.
11056 If it is not practical to move the unchecked conversion to the same unit
11057 in which the destination access type is declared (perhaps because the
11058 source type is not visible in that unit), you may use pragma
11059 @code{No_Strict_Aliasing} for the type. This pragma must occur in the
11060 same declarative sequence as the declaration of the access type:
11062 @smallexample @c ada
11063 type a2 is access int2;
11064 pragma No_Strict_Aliasing (a2);
11068 Here again, the compiler now knows that the strict aliasing optimization
11069 should be suppressed for any reference to type @code{a2} and the
11070 expected behavior is obtained.
11072 Finally, note that although the compiler can generate warnings for
11073 simple cases of unchecked conversions, there are tricker and more
11074 indirect ways of creating type incorrect aliases which the compiler
11075 cannot detect. Examples are the use of address overlays and unchecked
11076 conversions involving composite types containing access types as
11077 components. In such cases, no warnings are generated, but there can
11078 still be aliasing problems. One safe coding practice is to forbid the
11079 use of address clauses for type overlaying, and to allow unchecked
11080 conversion only for primitive types. This is not really a significant
11081 restriction since any possible desired effect can be achieved by
11082 unchecked conversion of access values.
11084 The aliasing analysis done in strict aliasing mode can certainly
11085 have significant benefits. We have seen cases of large scale
11086 application code where the time is increased by up to 5% by turning
11087 this optimization off. If you have code that includes significant
11088 usage of unchecked conversion, you might want to just stick with
11089 @option{-O1} and avoid the entire issue. If you get adequate
11090 performance at this level of optimization level, that's probably
11091 the safest approach. If tests show that you really need higher
11092 levels of optimization, then you can experiment with @option{-O2}
11093 and @option{-O2 -fno-strict-aliasing} to see how much effect this
11094 has on size and speed of the code. If you really need to use
11095 @option{-O2} with strict aliasing in effect, then you should
11096 review any uses of unchecked conversion of access types,
11097 particularly if you are getting the warnings described above.
11099 @node Aliased Variables and Optimization
11100 @subsection Aliased Variables and Optimization
11102 There are scenarios in which programs may
11103 use low level techniques to modify variables
11104 that otherwise might be considered to be unassigned. For example,
11105 a variable can be passed to a procedure by reference, which takes
11106 the address of the parameter and uses the address to modify the
11107 variable's value, even though it is passed as an IN parameter.
11108 Consider the following example:
11110 @smallexample @c ada
11112 Max_Length : constant Natural := 16;
11113 type Char_Ptr is access all Character;
11115 procedure Get_String(Buffer: Char_Ptr; Size : Integer);
11116 pragma Import (C, Get_String, "get_string");
11118 Name : aliased String (1 .. Max_Length) := (others => ' ');
11121 function Addr (S : String) return Char_Ptr is
11122 function To_Char_Ptr is
11123 new Ada.Unchecked_Conversion (System.Address, Char_Ptr);
11125 return To_Char_Ptr (S (S'First)'Address);
11129 Temp := Addr (Name);
11130 Get_String (Temp, Max_Length);
11135 where Get_String is a C function that uses the address in Temp to
11136 modify the variable @code{Name}. This code is dubious, and arguably
11137 erroneous, and the compiler would be entitled to assume that
11138 @code{Name} is never modified, and generate code accordingly.
11140 However, in practice, this would cause some existing code that
11141 seems to work with no optimization to start failing at high
11142 levels of optimzization.
11144 What the compiler does for such cases is to assume that marking
11145 a variable as aliased indicates that some "funny business" may
11146 be going on. The optimizer recognizes the aliased keyword and
11147 inhibits optimizations that assume the value cannot be assigned.
11148 This means that the above example will in fact "work" reliably,
11149 that is, it will produce the expected results.
11151 @node Atomic Variables and Optimization
11152 @subsection Atomic Variables and Optimization
11154 There are two considerations with regard to performance when
11155 atomic variables are used.
11157 First, the RM only guarantees that access to atomic variables
11158 be atomic, it has nothing to say about how this is achieved,
11159 though there is a strong implication that this should not be
11160 achieved by explicit locking code. Indeed GNAT will never
11161 generate any locking code for atomic variable access (it will
11162 simply reject any attempt to make a variable or type atomic
11163 if the atomic access cannot be achieved without such locking code).
11165 That being said, it is important to understand that you cannot
11166 assume that the entire variable will always be accessed. Consider
11169 @smallexample @c ada
11171 A,B,C,D : Character;
11174 for R'Alignment use 4;
11177 pragma Atomic (RV);
11184 You cannot assume that the reference to @code{RV.B}
11185 will read the entire 32-bit
11186 variable with a single load instruction. It is perfectly legitimate if
11187 the hardware allows it to do a byte read of just the B field. This read
11188 is still atomic, which is all the RM requires. GNAT can and does take
11189 advantage of this, depending on the architecture and optimization level.
11190 Any assumption to the contrary is non-portable and risky. Even if you
11191 examine the assembly language and see a full 32-bit load, this might
11192 change in a future version of the compiler.
11194 If your application requires that all accesses to @code{RV} in this
11195 example be full 32-bit loads, you need to make a copy for the access
11198 @smallexample @c ada
11200 RV_Copy : constant R := RV;
11208 Now the reference to RV must read the whole variable.
11209 Actually one can imagine some compiler which figures
11210 out that the whole copy is not required (because only
11211 the B field is actually accessed), but GNAT
11212 certainly won't do that, and we don't know of any
11213 compiler that would not handle this right, and the
11214 above code will in practice work portably across
11215 all architectures (that permit the Atomic declaration).
11217 The second issue with atomic variables has to do with
11218 the possible requirement of generating synchronization
11219 code. For more details on this, consult the sections on
11220 the pragmas Enable/Disable_Atomic_Synchronization in the
11221 GNAT Reference Manual. If performance is critical, and
11222 such synchronization code is not required, it may be
11223 useful to disable it.
11225 @node Passive Task Optimization
11226 @subsection Passive Task Optimization
11227 @cindex Passive Task
11229 A passive task is one which is sufficiently simple that
11230 in theory a compiler could recognize it an implement it
11231 efficiently without creating a new thread. The original design
11232 of Ada 83 had in mind this kind of passive task optimization, but
11233 only a few Ada 83 compilers attempted it. The problem was that
11234 it was difficult to determine the exact conditions under which
11235 the optimization was possible. The result is a very fragile
11236 optimization where a very minor change in the program can
11237 suddenly silently make a task non-optimizable.
11239 With the revisiting of this issue in Ada 95, there was general
11240 agreement that this approach was fundamentally flawed, and the
11241 notion of protected types was introduced. When using protected
11242 types, the restrictions are well defined, and you KNOW that the
11243 operations will be optimized, and furthermore this optimized
11244 performance is fully portable.
11246 Although it would theoretically be possible for GNAT to attempt to
11247 do this optimization, but it really doesn't make sense in the
11248 context of Ada 95, and none of the Ada 95 compilers implement
11249 this optimization as far as we know. In particular GNAT never
11250 attempts to perform this optimization.
11252 In any new Ada 95 code that is written, you should always
11253 use protected types in place of tasks that might be able to
11254 be optimized in this manner.
11255 Of course this does not help if you have legacy Ada 83 code
11256 that depends on this optimization, but it is unusual to encounter
11257 a case where the performance gains from this optimization
11260 Your program should work correctly without this optimization. If
11261 you have performance problems, then the most practical
11262 approach is to figure out exactly where these performance problems
11263 arise, and update those particular tasks to be protected types. Note
11264 that typically clients of the tasks who call entries, will not have
11265 to be modified, only the task definition itself.
11268 @node Coverage Analysis
11269 @subsection Coverage Analysis
11272 GNAT supports the HP Performance Coverage Analyzer (PCA), which allows
11273 the user to determine the distribution of execution time across a program,
11274 @pxref{Profiling} for details of usage.
11278 @node Text_IO Suggestions
11279 @section @code{Text_IO} Suggestions
11280 @cindex @code{Text_IO} and performance
11283 The @code{Ada.Text_IO} package has fairly high overheads due in part to
11284 the requirement of maintaining page and line counts. If performance
11285 is critical, a recommendation is to use @code{Stream_IO} instead of
11286 @code{Text_IO} for volume output, since this package has less overhead.
11288 If @code{Text_IO} must be used, note that by default output to the standard
11289 output and standard error files is unbuffered (this provides better
11290 behavior when output statements are used for debugging, or if the
11291 progress of a program is observed by tracking the output, e.g. by
11292 using the Unix @command{tail -f} command to watch redirected output.
11294 If you are generating large volumes of output with @code{Text_IO} and
11295 performance is an important factor, use a designated file instead
11296 of the standard output file, or change the standard output file to
11297 be buffered using @code{Interfaces.C_Streams.setvbuf}.
11300 @ifclear FSFEDITION
11301 @node Reducing Size of Ada Executables with gnatelim
11302 @section Reducing Size of Ada Executables with @code{gnatelim}
11306 This section describes @command{gnatelim}, a tool which detects unused
11307 subprograms and helps the compiler to create a smaller executable for your
11312 * Running gnatelim::
11313 * Processing Precompiled Libraries::
11314 * Correcting the List of Eliminate Pragmas::
11315 * Making Your Executables Smaller::
11316 * Summary of the gnatelim Usage Cycle::
11319 @node About gnatelim
11320 @subsection About @code{gnatelim}
11323 When a program shares a set of Ada
11324 packages with other programs, it may happen that this program uses
11325 only a fraction of the subprograms defined in these packages. The code
11326 created for these unused subprograms increases the size of the executable.
11328 @code{gnatelim} tracks unused subprograms in an Ada program and
11329 outputs a list of GNAT-specific pragmas @code{Eliminate} marking all the
11330 subprograms that are declared but never called. By placing the list of
11331 @code{Eliminate} pragmas in the GNAT configuration file @file{gnat.adc} and
11332 recompiling your program, you may decrease the size of its executable,
11333 because the compiler will not generate the code for 'eliminated' subprograms.
11334 @xref{Pragma Eliminate,,, gnat_rm, GNAT Reference Manual}, for more
11335 information about this pragma.
11337 @code{gnatelim} needs as its input data the name of the main subprogram.
11339 If a set of source files is specified as @code{gnatelim} arguments, it
11340 treats these files as a complete set of sources making up a program to
11341 analyse, and analyses only these sources.
11343 After a full successful build of the main subprogram @code{gnatelim} can be
11344 called without specifying sources to analyse, in this case it computes
11345 the source closure of the main unit from the @file{ALI} files.
11347 The following command will create the set of @file{ALI} files needed for
11351 $ gnatmake ^-c Main_Prog^/ACTIONS=COMPILE MAIN_PROG^
11354 Note that @code{gnatelim} does not need object files.
11356 @node Running gnatelim
11357 @subsection Running @code{gnatelim}
11360 @code{gnatelim} has the following command-line interface:
11363 $ gnatelim [@var{switches}] ^-main^?MAIN^=@var{main_unit_name} @{@var{filename}@} @r{[}-cargs @var{gcc_switches}@r{]}
11367 @var{main_unit_name} should be a name of a source file that contains the main
11368 subprogram of a program (partition).
11370 Each @var{filename} is the name (including the extension) of a source
11371 file to process. ``Wildcards'' are allowed, and
11372 the file name may contain path information.
11374 @samp{@var{gcc_switches}} is a list of switches for
11375 @command{gcc}. They will be passed on to all compiler invocations made by
11376 @command{gnatelim} to generate the ASIS trees. Here you can provide
11377 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
11378 use the @option{-gnatec} switch to set the configuration file,
11379 use the @option{-gnat05} switch if sources should be compiled in
11382 @code{gnatelim} has the following switches:
11387 @cindex @option{--version} @command{gnatelim}
11388 Display Copyright and version, then exit disregarding all other options.
11391 @cindex @option{--help} @command{gnatelim}
11392 Display usage, then exit disregarding all other options.
11394 @item -P @var{file}
11395 @cindex @option{-P} @command{gnatelim}
11396 Indicates the name of the project file that describes the set of sources
11399 @item -X@var{name}=@var{value}
11400 @cindex @option{-X} @command{gnatelim}
11401 Indicates that external variable @var{name} in the argument project
11402 has the value @var{value}. Has no effect if no project is specified as
11405 @item ^-files^/FILES^=@var{filename}
11406 @cindex @option{^-files^/FILES^} (@code{gnatelim})
11407 Take the argument source files from the specified file. This file should be an
11408 ordinary text file containing file names separated by spaces or
11409 line breaks. You can use this switch more than once in the same call to
11410 @command{gnatelim}. You also can combine this switch with
11411 an explicit list of files.
11414 @cindex @option{^-log^/LOG^} (@command{gnatelim})
11415 Duplicate all the output sent to @file{stderr} into a log file. The log file
11416 is named @file{gnatelim.log} and is located in the current directory.
11419 @item ^-log^/LOGFILE^=@var{filename}
11420 @cindex @option{^-log^/LOGFILE^} (@command{gnatelim})
11421 Duplicate all the output sent to @file{stderr} into a specified log file.
11424 @cindex @option{^--no-elim-dispatch^/NO_DISPATCH^} (@command{gnatelim})
11425 @item ^--no-elim-dispatch^/NO_DISPATCH^
11426 Do not generate pragmas for dispatching operations.
11428 @item ^--ignore^/IGNORE^=@var{filename}
11429 @cindex @option{^--ignore^/IGNORE^} (@command{gnatelim})
11430 Do not generate pragmas for subprograms declared in the sources
11431 listed in a specified file
11433 @cindex @option{^-o^/OUTPUT^} (@command{gnatelim})
11434 @item ^-o^/OUTPUT^=@var{report_file}
11435 Put @command{gnatelim} output into a specified file. If this file already exists,
11436 it is overridden. If this switch is not used, @command{gnatelim} outputs its results
11439 @item ^-j^/PROCESSES=^@var{n}
11440 @cindex @option{^-j^/PROCESSES^} (@command{gnatelim})
11441 Use @var{n} processes to carry out the tree creations (internal representations
11442 of the argument sources). On a multiprocessor machine this speeds up processing
11443 of big sets of argument sources. If @var{n} is 0, then the maximum number of
11444 parallel tree creations is the number of core processors on the platform.
11447 @cindex @option{^-q^/QUIET^} (@command{gnatelim})
11448 Quiet mode: by default @code{gnatelim} outputs to the standard error
11449 stream the number of program units left to be processed. This option turns
11452 @cindex @option{^-t^/TIME^} (@command{gnatelim})
11454 Print out execution time.
11456 @item ^-v^/VERBOSE^
11457 @cindex @option{^-v^/VERBOSE^} (@command{gnatelim})
11458 Verbose mode: @code{gnatelim} version information is printed as Ada
11459 comments to the standard output stream. Also, in addition to the number of
11460 program units left @code{gnatelim} will output the name of the current unit
11463 @item ^-wq^/WARNINGS=QUIET^
11464 @cindex @option{^-wq^/WARNINGS=QUIET^} (@command{gnatelim})
11465 Quiet warning mode - some warnings are suppressed. In particular warnings that
11466 indicate that the analysed set of sources is incomplete to make up a
11467 partition and that some subprogram bodies are missing are not generated.
11471 Note: to invoke @command{gnatelim} with a project file, use the @code{gnat}
11472 driver (see @ref{The GNAT Driver and Project Files}).
11474 @node Processing Precompiled Libraries
11475 @subsection Processing Precompiled Libraries
11478 If some program uses a precompiled Ada library, it can be processed by
11479 @code{gnatelim} in a usual way. @code{gnatelim} will newer generate an
11480 Eliminate pragma for a subprogram if the body of this subprogram has not
11481 been analysed, this is a typical case for subprograms from precompiled
11482 libraries. Switch @option{^-wq^/WARNINGS=QUIET^} may be used to suppress
11483 warnings about missing source files and non-analyzed subprogram bodies
11484 that can be generated when processing precompiled Ada libraries.
11486 @node Correcting the List of Eliminate Pragmas
11487 @subsection Correcting the List of Eliminate Pragmas
11490 In some rare cases @code{gnatelim} may try to eliminate
11491 subprograms that are actually called in the program. In this case, the
11492 compiler will generate an error message of the form:
11495 main.adb:4:08: cannot reference subprogram "P" eliminated at elim.out:5
11499 You will need to manually remove the wrong @code{Eliminate} pragmas from
11500 the configuration file indicated in the error message. You should recompile
11501 your program from scratch after that, because you need a consistent
11502 configuration file(s) during the entire compilation.
11504 @node Making Your Executables Smaller
11505 @subsection Making Your Executables Smaller
11508 In order to get a smaller executable for your program you now have to
11509 recompile the program completely with the configuration file containing
11510 pragmas Eliminate generated by gnatelim. If these pragmas are placed in
11511 @file{gnat.adc} file located in your current directory, just do:
11514 $ gnatmake ^-f main_prog^/FORCE_COMPILE MAIN_PROG^
11518 (Use the @option{^-f^/FORCE_COMPILE^} option for @command{gnatmake} to
11519 recompile everything
11520 with the set of pragmas @code{Eliminate} that you have obtained with
11521 @command{gnatelim}).
11523 Be aware that the set of @code{Eliminate} pragmas is specific to each
11524 program. It is not recommended to merge sets of @code{Eliminate}
11525 pragmas created for different programs in one configuration file.
11527 @node Summary of the gnatelim Usage Cycle
11528 @subsection Summary of the @code{gnatelim} Usage Cycle
11531 Here is a quick summary of the steps to be taken in order to reduce
11532 the size of your executables with @code{gnatelim}. You may use
11533 other GNAT options to control the optimization level,
11534 to produce the debugging information, to set search path, etc.
11538 Create a complete set of @file{ALI} files (if the program has not been
11542 $ gnatmake ^-c main_prog^/ACTIONS=COMPILE MAIN_PROG^
11546 Generate a list of @code{Eliminate} pragmas in default configuration file
11547 @file{gnat.adc} in the current directory
11550 $ PIPE GNAT ELIM MAIN_PROG > GNAT.ADC
11553 $ gnatelim main_prog >@r{[}>@r{]} gnat.adc
11558 Recompile the application
11561 $ gnatmake ^-f main_prog^/FORCE_COMPILE MAIN_PROG^
11567 @node Reducing Size of Executables with unused subprogram/data elimination
11568 @section Reducing Size of Executables with Unused Subprogram/Data Elimination
11569 @findex unused subprogram/data elimination
11572 This section describes how you can eliminate unused subprograms and data from
11573 your executable just by setting options at compilation time.
11576 * About unused subprogram/data elimination::
11577 * Compilation options::
11578 * Example of unused subprogram/data elimination::
11581 @node About unused subprogram/data elimination
11582 @subsection About unused subprogram/data elimination
11585 By default, an executable contains all code and data of its composing objects
11586 (directly linked or coming from statically linked libraries), even data or code
11587 never used by this executable.
11589 This feature will allow you to eliminate such unused code from your
11590 executable, making it smaller (in disk and in memory).
11592 This functionality is available on all Linux platforms except for the IA-64
11593 architecture and on all cross platforms using the ELF binary file format.
11594 In both cases GNU binutils version 2.16 or later are required to enable it.
11596 @node Compilation options
11597 @subsection Compilation options
11600 The operation of eliminating the unused code and data from the final executable
11601 is directly performed by the linker.
11603 In order to do this, it has to work with objects compiled with the
11605 @option{-ffunction-sections} @option{-fdata-sections}.
11606 @cindex @option{-ffunction-sections} (@command{gcc})
11607 @cindex @option{-fdata-sections} (@command{gcc})
11608 These options are usable with C and Ada files.
11609 They will place respectively each
11610 function or data in a separate section in the resulting object file.
11612 Once the objects and static libraries are created with these options, the
11613 linker can perform the dead code elimination. You can do this by setting
11614 the @option{-Wl,--gc-sections} option to gcc command or in the
11615 @option{-largs} section of @command{gnatmake}. This will perform a
11616 garbage collection of code and data never referenced.
11618 If the linker performs a partial link (@option{-r} linker option), then you
11619 will need to provide the entry point using the @option{-e} / @option{--entry}
11622 Note that objects compiled without the @option{-ffunction-sections} and
11623 @option{-fdata-sections} options can still be linked with the executable.
11624 However, no dead code elimination will be performed on those objects (they will
11627 The GNAT static library is now compiled with -ffunction-sections and
11628 -fdata-sections on some platforms. This allows you to eliminate the unused code
11629 and data of the GNAT library from your executable.
11631 @node Example of unused subprogram/data elimination
11632 @subsection Example of unused subprogram/data elimination
11635 Here is a simple example:
11637 @smallexample @c ada
11646 Used_Data : Integer;
11647 Unused_Data : Integer;
11649 procedure Used (Data : Integer);
11650 procedure Unused (Data : Integer);
11653 package body Aux is
11654 procedure Used (Data : Integer) is
11659 procedure Unused (Data : Integer) is
11661 Unused_Data := Data;
11667 @code{Unused} and @code{Unused_Data} are never referenced in this code
11668 excerpt, and hence they may be safely removed from the final executable.
11673 $ nm test | grep used
11674 020015f0 T aux__unused
11675 02005d88 B aux__unused_data
11676 020015cc T aux__used
11677 02005d84 B aux__used_data
11679 $ gnatmake test -cargs -fdata-sections -ffunction-sections \
11680 -largs -Wl,--gc-sections
11682 $ nm test | grep used
11683 02005350 T aux__used
11684 0201ffe0 B aux__used_data
11688 It can be observed that the procedure @code{Unused} and the object
11689 @code{Unused_Data} are removed by the linker when using the
11690 appropriate options.
11692 @c ********************************
11693 @node Renaming Files with gnatchop
11694 @chapter Renaming Files with @code{gnatchop}
11698 This chapter discusses how to handle files with multiple units by using
11699 the @code{gnatchop} utility. This utility is also useful in renaming
11700 files to meet the standard GNAT default file naming conventions.
11703 * Handling Files with Multiple Units::
11704 * Operating gnatchop in Compilation Mode::
11705 * Command Line for gnatchop::
11706 * Switches for gnatchop::
11707 * Examples of gnatchop Usage::
11710 @node Handling Files with Multiple Units
11711 @section Handling Files with Multiple Units
11714 The basic compilation model of GNAT requires that a file submitted to the
11715 compiler have only one unit and there be a strict correspondence
11716 between the file name and the unit name.
11718 The @code{gnatchop} utility allows both of these rules to be relaxed,
11719 allowing GNAT to process files which contain multiple compilation units
11720 and files with arbitrary file names. @code{gnatchop}
11721 reads the specified file and generates one or more output files,
11722 containing one unit per file. The unit and the file name correspond,
11723 as required by GNAT.
11725 If you want to permanently restructure a set of ``foreign'' files so that
11726 they match the GNAT rules, and do the remaining development using the
11727 GNAT structure, you can simply use @command{gnatchop} once, generate the
11728 new set of files and work with them from that point on.
11730 Alternatively, if you want to keep your files in the ``foreign'' format,
11731 perhaps to maintain compatibility with some other Ada compilation
11732 system, you can set up a procedure where you use @command{gnatchop} each
11733 time you compile, regarding the source files that it writes as temporary
11734 files that you throw away.
11736 Note that if your file containing multiple units starts with a byte order
11737 mark (BOM) specifying UTF-8 encoding, then the files generated by gnatchop
11738 will each start with a copy of this BOM, meaning that they can be compiled
11739 automatically in UTF-8 mode without needing to specify an explicit encoding.
11741 @node Operating gnatchop in Compilation Mode
11742 @section Operating gnatchop in Compilation Mode
11745 The basic function of @code{gnatchop} is to take a file with multiple units
11746 and split it into separate files. The boundary between files is reasonably
11747 clear, except for the issue of comments and pragmas. In default mode, the
11748 rule is that any pragmas between units belong to the previous unit, except
11749 that configuration pragmas always belong to the following unit. Any comments
11750 belong to the following unit. These rules
11751 almost always result in the right choice of
11752 the split point without needing to mark it explicitly and most users will
11753 find this default to be what they want. In this default mode it is incorrect to
11754 submit a file containing only configuration pragmas, or one that ends in
11755 configuration pragmas, to @code{gnatchop}.
11757 However, using a special option to activate ``compilation mode'',
11759 can perform another function, which is to provide exactly the semantics
11760 required by the RM for handling of configuration pragmas in a compilation.
11761 In the absence of configuration pragmas (at the main file level), this
11762 option has no effect, but it causes such configuration pragmas to be handled
11763 in a quite different manner.
11765 First, in compilation mode, if @code{gnatchop} is given a file that consists of
11766 only configuration pragmas, then this file is appended to the
11767 @file{gnat.adc} file in the current directory. This behavior provides
11768 the required behavior described in the RM for the actions to be taken
11769 on submitting such a file to the compiler, namely that these pragmas
11770 should apply to all subsequent compilations in the same compilation
11771 environment. Using GNAT, the current directory, possibly containing a
11772 @file{gnat.adc} file is the representation
11773 of a compilation environment. For more information on the
11774 @file{gnat.adc} file, see @ref{Handling of Configuration Pragmas}.
11776 Second, in compilation mode, if @code{gnatchop}
11777 is given a file that starts with
11778 configuration pragmas, and contains one or more units, then these
11779 configuration pragmas are prepended to each of the chopped files. This
11780 behavior provides the required behavior described in the RM for the
11781 actions to be taken on compiling such a file, namely that the pragmas
11782 apply to all units in the compilation, but not to subsequently compiled
11785 Finally, if configuration pragmas appear between units, they are appended
11786 to the previous unit. This results in the previous unit being illegal,
11787 since the compiler does not accept configuration pragmas that follow
11788 a unit. This provides the required RM behavior that forbids configuration
11789 pragmas other than those preceding the first compilation unit of a
11792 For most purposes, @code{gnatchop} will be used in default mode. The
11793 compilation mode described above is used only if you need exactly
11794 accurate behavior with respect to compilations, and you have files
11795 that contain multiple units and configuration pragmas. In this
11796 circumstance the use of @code{gnatchop} with the compilation mode
11797 switch provides the required behavior, and is for example the mode
11798 in which GNAT processes the ACVC tests.
11800 @node Command Line for gnatchop
11801 @section Command Line for @code{gnatchop}
11804 The @code{gnatchop} command has the form:
11807 @c $ gnatchop switches @var{file name} @r{[}@var{file name} @dots{}@r{]}
11808 @c @ovar{directory}
11809 @c Expanding @ovar macro inline (explanation in macro def comments)
11810 $ gnatchop switches @var{file name} @r{[}@var{file name} @dots{}@r{]}
11811 @r{[}@var{directory}@r{]}
11815 The only required argument is the file name of the file to be chopped.
11816 There are no restrictions on the form of this file name. The file itself
11817 contains one or more Ada units, in normal GNAT format, concatenated
11818 together. As shown, more than one file may be presented to be chopped.
11820 When run in default mode, @code{gnatchop} generates one output file in
11821 the current directory for each unit in each of the files.
11823 @var{directory}, if specified, gives the name of the directory to which
11824 the output files will be written. If it is not specified, all files are
11825 written to the current directory.
11827 For example, given a
11828 file called @file{hellofiles} containing
11830 @smallexample @c ada
11835 with Text_IO; use Text_IO;
11838 Put_Line ("Hello");
11848 $ gnatchop ^hellofiles^HELLOFILES.^
11852 generates two files in the current directory, one called
11853 @file{hello.ads} containing the single line that is the procedure spec,
11854 and the other called @file{hello.adb} containing the remaining text. The
11855 original file is not affected. The generated files can be compiled in
11859 When gnatchop is invoked on a file that is empty or that contains only empty
11860 lines and/or comments, gnatchop will not fail, but will not produce any
11863 For example, given a
11864 file called @file{toto.txt} containing
11866 @smallexample @c ada
11878 $ gnatchop ^toto.txt^TOT.TXT^
11882 will not produce any new file and will result in the following warnings:
11885 toto.txt:1:01: warning: empty file, contains no compilation units
11886 no compilation units found
11887 no source files written
11890 @node Switches for gnatchop
11891 @section Switches for @code{gnatchop}
11894 @command{gnatchop} recognizes the following switches:
11900 @cindex @option{--version} @command{gnatchop}
11901 Display Copyright and version, then exit disregarding all other options.
11904 @cindex @option{--help} @command{gnatchop}
11905 If @option{--version} was not used, display usage, then exit disregarding
11908 @item ^-c^/COMPILATION^
11909 @cindex @option{^-c^/COMPILATION^} (@code{gnatchop})
11910 Causes @code{gnatchop} to operate in compilation mode, in which
11911 configuration pragmas are handled according to strict RM rules. See
11912 previous section for a full description of this mode.
11915 @item -gnat@var{xxx}
11916 This passes the given @option{-gnat@var{xxx}} switch to @code{gnat} which is
11917 used to parse the given file. Not all @var{xxx} options make sense,
11918 but for example, the use of @option{-gnati2} allows @code{gnatchop} to
11919 process a source file that uses Latin-2 coding for identifiers.
11923 Causes @code{gnatchop} to generate a brief help summary to the standard
11924 output file showing usage information.
11926 @item ^-k@var{mm}^/FILE_NAME_MAX_LENGTH=@var{mm}^
11927 @cindex @option{^-k^/FILE_NAME_MAX_LENGTH^} (@code{gnatchop})
11928 Limit generated file names to the specified number @code{mm}
11930 This is useful if the
11931 resulting set of files is required to be interoperable with systems
11932 which limit the length of file names.
11934 If no value is given, or
11935 if no @code{/FILE_NAME_MAX_LENGTH} qualifier is given,
11936 a default of 39, suitable for OpenVMS Alpha
11937 Systems, is assumed
11940 No space is allowed between the @option{-k} and the numeric value. The numeric
11941 value may be omitted in which case a default of @option{-k8},
11943 with DOS-like file systems, is used. If no @option{-k} switch
11945 there is no limit on the length of file names.
11948 @item ^-p^/PRESERVE^
11949 @cindex @option{^-p^/PRESERVE^} (@code{gnatchop})
11950 Causes the file ^modification^creation^ time stamp of the input file to be
11951 preserved and used for the time stamp of the output file(s). This may be
11952 useful for preserving coherency of time stamps in an environment where
11953 @code{gnatchop} is used as part of a standard build process.
11956 @cindex @option{^-q^/QUIET^} (@code{gnatchop})
11957 Causes output of informational messages indicating the set of generated
11958 files to be suppressed. Warnings and error messages are unaffected.
11960 @item ^-r^/REFERENCE^
11961 @cindex @option{^-r^/REFERENCE^} (@code{gnatchop})
11962 @findex Source_Reference
11963 Generate @code{Source_Reference} pragmas. Use this switch if the output
11964 files are regarded as temporary and development is to be done in terms
11965 of the original unchopped file. This switch causes
11966 @code{Source_Reference} pragmas to be inserted into each of the
11967 generated files to refers back to the original file name and line number.
11968 The result is that all error messages refer back to the original
11970 In addition, the debugging information placed into the object file (when
11971 the @option{^-g^/DEBUG^} switch of @command{gcc} or @command{gnatmake} is
11973 also refers back to this original file so that tools like profilers and
11974 debuggers will give information in terms of the original unchopped file.
11976 If the original file to be chopped itself contains
11977 a @code{Source_Reference}
11978 pragma referencing a third file, then gnatchop respects
11979 this pragma, and the generated @code{Source_Reference} pragmas
11980 in the chopped file refer to the original file, with appropriate
11981 line numbers. This is particularly useful when @code{gnatchop}
11982 is used in conjunction with @code{gnatprep} to compile files that
11983 contain preprocessing statements and multiple units.
11985 @item ^-v^/VERBOSE^
11986 @cindex @option{^-v^/VERBOSE^} (@code{gnatchop})
11987 Causes @code{gnatchop} to operate in verbose mode. The version
11988 number and copyright notice are output, as well as exact copies of
11989 the gnat1 commands spawned to obtain the chop control information.
11991 @item ^-w^/OVERWRITE^
11992 @cindex @option{^-w^/OVERWRITE^} (@code{gnatchop})
11993 Overwrite existing file names. Normally @code{gnatchop} regards it as a
11994 fatal error if there is already a file with the same name as a
11995 file it would otherwise output, in other words if the files to be
11996 chopped contain duplicated units. This switch bypasses this
11997 check, and causes all but the last instance of such duplicated
11998 units to be skipped.
12001 @item --GCC=@var{xxxx}
12002 @cindex @option{--GCC=} (@code{gnatchop})
12003 Specify the path of the GNAT parser to be used. When this switch is used,
12004 no attempt is made to add the prefix to the GNAT parser executable.
12008 @node Examples of gnatchop Usage
12009 @section Examples of @code{gnatchop} Usage
12013 @item gnatchop /OVERWRITE HELLO_S.ADA [PRERELEASE.FILES]
12016 @item gnatchop -w hello_s.ada prerelease/files
12019 Chops the source file @file{hello_s.ada}. The output files will be
12020 placed in the directory @file{^prerelease/files^[PRERELEASE.FILES]^},
12022 files with matching names in that directory (no files in the current
12023 directory are modified).
12025 @item gnatchop ^archive^ARCHIVE.^
12026 Chops the source file @file{^archive^ARCHIVE.^}
12027 into the current directory. One
12028 useful application of @code{gnatchop} is in sending sets of sources
12029 around, for example in email messages. The required sources are simply
12030 concatenated (for example, using a ^Unix @code{cat}^VMS @code{APPEND/NEW}^
12032 @command{gnatchop} is used at the other end to reconstitute the original
12035 @item gnatchop file1 file2 file3 direc
12036 Chops all units in files @file{file1}, @file{file2}, @file{file3}, placing
12037 the resulting files in the directory @file{direc}. Note that if any units
12038 occur more than once anywhere within this set of files, an error message
12039 is generated, and no files are written. To override this check, use the
12040 @option{^-w^/OVERWRITE^} switch,
12041 in which case the last occurrence in the last file will
12042 be the one that is output, and earlier duplicate occurrences for a given
12043 unit will be skipped.
12046 @node Configuration Pragmas
12047 @chapter Configuration Pragmas
12048 @cindex Configuration pragmas
12049 @cindex Pragmas, configuration
12052 * Handling of Configuration Pragmas::
12053 * The Configuration Pragmas Files::
12057 Configuration pragmas include those pragmas described as
12058 such in the Ada Reference Manual, as well as
12059 implementation-dependent pragmas that are configuration pragmas.
12060 @xref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference Manual},
12061 for details on these additional GNAT-specific configuration pragmas.
12062 Most notably, the pragma @code{Source_File_Name}, which allows
12063 specifying non-default names for source files, is a configuration
12064 pragma. The following is a complete list of configuration pragmas
12065 recognized by GNAT:
12074 Allow_Integer_Address
12077 Assume_No_Invalid_Values
12082 Compile_Time_Warning
12084 Component_Alignment
12085 Convention_Identifier
12088 Default_Storage_Pool
12094 External_Name_Casing
12097 Float_Representation
12110 Priority_Specific_Dispatching
12113 Propagate_Exceptions
12116 Restricted_Run_Time
12118 Restrictions_Warnings
12120 Short_Circuit_And_Or
12122 Source_File_Name_Project
12126 Suppress_Exception_Locations
12127 Task_Dispatching_Policy
12133 Wide_Character_Encoding
12136 @node Handling of Configuration Pragmas
12137 @section Handling of Configuration Pragmas
12139 Configuration pragmas may either appear at the start of a compilation
12140 unit, or they can appear in a configuration pragma file to apply to
12141 all compilations performed in a given compilation environment.
12143 GNAT also provides the @code{gnatchop} utility to provide an automatic
12144 way to handle configuration pragmas following the semantics for
12145 compilations (that is, files with multiple units), described in the RM.
12146 See @ref{Operating gnatchop in Compilation Mode} for details.
12147 However, for most purposes, it will be more convenient to edit the
12148 @file{gnat.adc} file that contains configuration pragmas directly,
12149 as described in the following section.
12151 In the case of @code{Restrictions} pragmas appearing as configuration
12152 pragmas in individual compilation units, the exact handling depends on
12153 the type of restriction.
12155 Restrictions that require partition-wide consistency (like
12156 @code{No_Tasking}) are
12157 recognized wherever they appear
12158 and can be freely inherited, e.g. from a with'ed unit to the with'ing
12159 unit. This makes sense since the binder will in any case insist on seeing
12160 consistent use, so any unit not conforming to any restrictions that are
12161 anywhere in the partition will be rejected, and you might as well find
12162 that out at compile time rather than at bind time.
12164 For restrictions that do not require partition-wide consistency, e.g.
12165 SPARK or No_Implementation_Attributes, in general the restriction applies
12166 only to the unit in which the pragma appears, and not to any other units.
12168 The exception is No_Elaboration_Code which always applies to the entire
12169 object file from a compilation, i.e. to the body, spec, and all subunits.
12170 This restriction can be specified in a configuration pragma file, or it
12171 can be on the body and/or the spec (in eithe case it applies to all the
12172 relevant units). It can appear on a subunit only if it has previously
12173 appeared in the body of spec.
12175 @node The Configuration Pragmas Files
12176 @section The Configuration Pragmas Files
12177 @cindex @file{gnat.adc}
12180 In GNAT a compilation environment is defined by the current
12181 directory at the time that a compile command is given. This current
12182 directory is searched for a file whose name is @file{gnat.adc}. If
12183 this file is present, it is expected to contain one or more
12184 configuration pragmas that will be applied to the current compilation.
12185 However, if the switch @option{-gnatA} is used, @file{gnat.adc} is not
12188 Configuration pragmas may be entered into the @file{gnat.adc} file
12189 either by running @code{gnatchop} on a source file that consists only of
12190 configuration pragmas, or more conveniently by
12191 direct editing of the @file{gnat.adc} file, which is a standard format
12194 In addition to @file{gnat.adc}, additional files containing configuration
12195 pragmas may be applied to the current compilation using the switch
12196 @option{-gnatec}@var{path}. @var{path} must designate an existing file that
12197 contains only configuration pragmas. These configuration pragmas are
12198 in addition to those found in @file{gnat.adc} (provided @file{gnat.adc}
12199 is present and switch @option{-gnatA} is not used).
12201 It is allowed to specify several switches @option{-gnatec}, all of which
12202 will be taken into account.
12204 If you are using project file, a separate mechanism is provided using
12205 project attributes, see @ref{Specifying Configuration Pragmas} for more
12209 Of special interest to GNAT OpenVMS Alpha is the following
12210 configuration pragma:
12212 @smallexample @c ada
12214 pragma Extend_System (Aux_DEC);
12219 In the presence of this pragma, GNAT adds to the definition of the
12220 predefined package SYSTEM all the additional types and subprograms that are
12221 defined in HP Ada. See @ref{Compatibility with HP Ada} for details.
12224 @node Handling Arbitrary File Naming Conventions with gnatname
12225 @chapter Handling Arbitrary File Naming Conventions with @code{gnatname}
12226 @cindex Arbitrary File Naming Conventions
12229 * Arbitrary File Naming Conventions::
12230 * Running gnatname::
12231 * Switches for gnatname::
12232 * Examples of gnatname Usage::
12235 @node Arbitrary File Naming Conventions
12236 @section Arbitrary File Naming Conventions
12239 The GNAT compiler must be able to know the source file name of a compilation
12240 unit. When using the standard GNAT default file naming conventions
12241 (@code{.ads} for specs, @code{.adb} for bodies), the GNAT compiler
12242 does not need additional information.
12245 When the source file names do not follow the standard GNAT default file naming
12246 conventions, the GNAT compiler must be given additional information through
12247 a configuration pragmas file (@pxref{Configuration Pragmas})
12249 When the non-standard file naming conventions are well-defined,
12250 a small number of pragmas @code{Source_File_Name} specifying a naming pattern
12251 (@pxref{Alternative File Naming Schemes}) may be sufficient. However,
12252 if the file naming conventions are irregular or arbitrary, a number
12253 of pragma @code{Source_File_Name} for individual compilation units
12255 To help maintain the correspondence between compilation unit names and
12256 source file names within the compiler,
12257 GNAT provides a tool @code{gnatname} to generate the required pragmas for a
12260 @node Running gnatname
12261 @section Running @code{gnatname}
12264 The usual form of the @code{gnatname} command is
12267 @c $ gnatname @ovar{switches} @var{naming_pattern} @ovar{naming_patterns}
12268 @c @r{[}--and @ovar{switches} @var{naming_pattern} @ovar{naming_patterns}@r{]}
12269 @c Expanding @ovar macro inline (explanation in macro def comments)
12270 $ gnatname @r{[}@var{switches}@r{]} @var{naming_pattern} @r{[}@var{naming_patterns}@r{]}
12271 @r{[}--and @r{[}@var{switches}@r{]} @var{naming_pattern} @r{[}@var{naming_patterns}@r{]}@r{]}
12275 All of the arguments are optional. If invoked without any argument,
12276 @code{gnatname} will display its usage.
12279 When used with at least one naming pattern, @code{gnatname} will attempt to
12280 find all the compilation units in files that follow at least one of the
12281 naming patterns. To find these compilation units,
12282 @code{gnatname} will use the GNAT compiler in syntax-check-only mode on all
12286 One or several Naming Patterns may be given as arguments to @code{gnatname}.
12287 Each Naming Pattern is enclosed between double quotes (or single
12288 quotes on Windows).
12289 A Naming Pattern is a regular expression similar to the wildcard patterns
12290 used in file names by the Unix shells or the DOS prompt.
12293 @code{gnatname} may be called with several sections of directories/patterns.
12294 Sections are separated by switch @code{--and}. In each section, there must be
12295 at least one pattern. If no directory is specified in a section, the current
12296 directory (or the project directory is @code{-P} is used) is implied.
12297 The options other that the directory switches and the patterns apply globally
12298 even if they are in different sections.
12301 Examples of Naming Patterns are
12310 For a more complete description of the syntax of Naming Patterns,
12311 see the second kind of regular expressions described in @file{g-regexp.ads}
12312 (the ``Glob'' regular expressions).
12315 When invoked with no switch @code{-P}, @code{gnatname} will create a
12316 configuration pragmas file @file{gnat.adc} in the current working directory,
12317 with pragmas @code{Source_File_Name} for each file that contains a valid Ada
12320 @node Switches for gnatname
12321 @section Switches for @code{gnatname}
12324 Switches for @code{gnatname} must precede any specified Naming Pattern.
12327 You may specify any of the following switches to @code{gnatname}:
12333 @cindex @option{--version} @command{gnatname}
12334 Display Copyright and version, then exit disregarding all other options.
12337 @cindex @option{--help} @command{gnatname}
12338 If @option{--version} was not used, display usage, then exit disregarding
12341 @item --subdirs=<dir>
12342 Real object, library or exec directories are subdirectories <dir> of the
12346 Do not create a backup copy of an existing project file.
12349 Start another section of directories/patterns.
12351 @item ^-c^/CONFIG_FILE=^@file{file}
12352 @cindex @option{^-c^/CONFIG_FILE^} (@code{gnatname})
12353 Create a configuration pragmas file @file{file} (instead of the default
12356 There may be zero, one or more space between @option{-c} and
12359 @file{file} may include directory information. @file{file} must be
12360 writable. There may be only one switch @option{^-c^/CONFIG_FILE^}.
12361 When a switch @option{^-c^/CONFIG_FILE^} is
12362 specified, no switch @option{^-P^/PROJECT_FILE^} may be specified (see below).
12364 @item ^-d^/SOURCE_DIRS=^@file{dir}
12365 @cindex @option{^-d^/SOURCE_DIRS^} (@code{gnatname})
12366 Look for source files in directory @file{dir}. There may be zero, one or more
12367 spaces between @option{^-d^/SOURCE_DIRS=^} and @file{dir}.
12368 @file{dir} may end with @code{/**}, that is it may be of the form
12369 @code{root_dir/**}. In this case, the directory @code{root_dir} and all of its
12370 subdirectories, recursively, have to be searched for sources.
12371 When a switch @option{^-d^/SOURCE_DIRS^}
12372 is specified, the current working directory will not be searched for source
12373 files, unless it is explicitly specified with a @option{^-d^/SOURCE_DIRS^}
12374 or @option{^-D^/DIR_FILES^} switch.
12375 Several switches @option{^-d^/SOURCE_DIRS^} may be specified.
12376 If @file{dir} is a relative path, it is relative to the directory of
12377 the configuration pragmas file specified with switch
12378 @option{^-c^/CONFIG_FILE^},
12379 or to the directory of the project file specified with switch
12380 @option{^-P^/PROJECT_FILE^} or,
12381 if neither switch @option{^-c^/CONFIG_FILE^}
12382 nor switch @option{^-P^/PROJECT_FILE^} are specified, it is relative to the
12383 current working directory. The directory
12384 specified with switch @option{^-d^/SOURCE_DIRS^} must exist and be readable.
12386 @item ^-D^/DIRS_FILE=^@file{file}
12387 @cindex @option{^-D^/DIRS_FILE^} (@code{gnatname})
12388 Look for source files in all directories listed in text file @file{file}.
12389 There may be zero, one or more spaces between @option{^-D^/DIRS_FILE=^}
12391 @file{file} must be an existing, readable text file.
12392 Each nonempty line in @file{file} must be a directory.
12393 Specifying switch @option{^-D^/DIRS_FILE^} is equivalent to specifying as many
12394 switches @option{^-d^/SOURCE_DIRS^} as there are nonempty lines in
12398 Follow symbolic links when processing project files.
12400 @item ^-f^/FOREIGN_PATTERN=^@file{pattern}
12401 @cindex @option{^-f^/FOREIGN_PATTERN^} (@code{gnatname})
12402 Foreign patterns. Using this switch, it is possible to add sources of languages
12403 other than Ada to the list of sources of a project file.
12404 It is only useful if a ^-P^/PROJECT_FILE^ switch is used.
12407 gnatname ^-Pprj -f"*.c"^/PROJECT_FILE=PRJ /FOREIGN_PATTERN=*.C^ "*.ada"
12410 will look for Ada units in all files with the @file{.ada} extension,
12411 and will add to the list of file for project @file{prj.gpr} the C files
12412 with extension @file{.^c^C^}.
12415 @cindex @option{^-h^/HELP^} (@code{gnatname})
12416 Output usage (help) information. The output is written to @file{stdout}.
12418 @item ^-P^/PROJECT_FILE=^@file{proj}
12419 @cindex @option{^-P^/PROJECT_FILE^} (@code{gnatname})
12420 Create or update project file @file{proj}. There may be zero, one or more space
12421 between @option{-P} and @file{proj}. @file{proj} may include directory
12422 information. @file{proj} must be writable.
12423 There may be only one switch @option{^-P^/PROJECT_FILE^}.
12424 When a switch @option{^-P^/PROJECT_FILE^} is specified,
12425 no switch @option{^-c^/CONFIG_FILE^} may be specified.
12426 On all platforms, except on VMS, when @code{gnatname} is invoked for an
12427 existing project file <proj>.gpr, a backup copy of the project file is created
12428 in the project directory with file name <proj>.gpr.saved_x. 'x' is the first
12429 non negative number that makes this backup copy a new file.
12431 @item ^-v^/VERBOSE^
12432 @cindex @option{^-v^/VERBOSE^} (@code{gnatname})
12433 Verbose mode. Output detailed explanation of behavior to @file{stdout}.
12434 This includes name of the file written, the name of the directories to search
12435 and, for each file in those directories whose name matches at least one of
12436 the Naming Patterns, an indication of whether the file contains a unit,
12437 and if so the name of the unit.
12439 @item ^-v -v^/VERBOSE /VERBOSE^
12440 @cindex @option{^-v -v^/VERBOSE /VERBOSE^} (@code{gnatname})
12441 Very Verbose mode. In addition to the output produced in verbose mode,
12442 for each file in the searched directories whose name matches none of
12443 the Naming Patterns, an indication is given that there is no match.
12445 @item ^-x^/EXCLUDED_PATTERN=^@file{pattern}
12446 @cindex @option{^-x^/EXCLUDED_PATTERN^} (@code{gnatname})
12447 Excluded patterns. Using this switch, it is possible to exclude some files
12448 that would match the name patterns. For example,
12450 gnatname ^-x "*_nt.ada"^/EXCLUDED_PATTERN=*_nt.ada^ "*.ada"
12453 will look for Ada units in all files with the @file{.ada} extension,
12454 except those whose names end with @file{_nt.ada}.
12458 @node Examples of gnatname Usage
12459 @section Examples of @code{gnatname} Usage
12463 $ gnatname /CONFIG_FILE=[HOME.ME]NAMES.ADC /SOURCE_DIRS=SOURCES "[a-z]*.ada*"
12469 $ gnatname -c /home/me/names.adc -d sources "[a-z]*.ada*"
12474 In this example, the directory @file{^/home/me^[HOME.ME]^} must already exist
12475 and be writable. In addition, the directory
12476 @file{^/home/me/sources^[HOME.ME.SOURCES]^} (specified by
12477 @option{^-d sources^/SOURCE_DIRS=SOURCES^}) must exist and be readable.
12480 Note the optional spaces after @option{-c} and @option{-d}.
12485 $ gnatname -P/home/me/proj -x "*_nt_body.ada"
12486 -dsources -dsources/plus -Dcommon_dirs.txt "body_*" "spec_*"
12489 $ gnatname /PROJECT_FILE=[HOME.ME]PROJ
12490 /EXCLUDED_PATTERN=*_nt_body.ada
12491 /SOURCE_DIRS=(SOURCES,[SOURCES.PLUS])
12492 /DIRS_FILE=COMMON_DIRS.TXT "body_*" "spec_*"
12496 Note that several switches @option{^-d^/SOURCE_DIRS^} may be used,
12497 even in conjunction with one or several switches
12498 @option{^-D^/DIRS_FILE^}. Several Naming Patterns and one excluded pattern
12499 are used in this example.
12501 @c *****************************************
12502 @c * G N A T P r o j e c t M a n a g e r *
12503 @c *****************************************
12505 @c ------ macros for projects.texi
12506 @c These macros are needed when building the gprbuild documentation, but
12507 @c should have no effect in the gnat user's guide
12509 @macro CODESAMPLE{TXT}
12517 @macro PROJECTFILE{TXT}
12521 @c simulates a newline when in a @CODESAMPLE
12532 @macro TIPHTML{TXT}
12536 @macro IMPORTANT{TXT}
12551 @include projects.texi
12553 @c ---------------------------------------------
12554 @c Tools Supporting Project Files
12555 @c ---------------------------------------------
12557 @node Tools Supporting Project Files
12558 @chapter Tools Supporting Project Files
12563 * gnatmake and Project Files::
12564 * The GNAT Driver and Project Files::
12567 @c ---------------------------------------------
12568 @node gnatmake and Project Files
12569 @section gnatmake and Project Files
12570 @c ---------------------------------------------
12573 This section covers several topics related to @command{gnatmake} and
12574 project files: defining ^switches^switches^ for @command{gnatmake}
12575 and for the tools that it invokes; specifying configuration pragmas;
12576 the use of the @code{Main} attribute; building and rebuilding library project
12580 * Switches Related to Project Files::
12581 * Switches and Project Files::
12582 * Specifying Configuration Pragmas::
12583 * Project Files and Main Subprograms::
12584 * Library Project Files::
12587 @c ---------------------------------------------
12588 @node Switches Related to Project Files
12589 @subsection Switches Related to Project Files
12590 @c ---------------------------------------------
12593 The following switches are used by GNAT tools that support project files:
12597 @item ^-P^/PROJECT_FILE=^@var{project}
12598 @cindex @option{^-P^/PROJECT_FILE^} (any project-aware tool)
12599 Indicates the name of a project file. This project file will be parsed with
12600 the verbosity indicated by @option{^-vP^MESSAGE_PROJECT_FILES=^@emph{x}},
12601 if any, and using the external references indicated
12602 by @option{^-X^/EXTERNAL_REFERENCE^} switches, if any.
12604 There may zero, one or more spaces between @option{-P} and @var{project}.
12607 There must be only one @option{^-P^/PROJECT_FILE^} switch on the command line.
12609 Since the Project Manager parses the project file only after all the switches
12610 on the command line are checked, the order of the switches
12611 @option{^-P^/PROJECT_FILE^},
12612 @option{^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}}
12613 or @option{^-X^/EXTERNAL_REFERENCE^} is not significant.
12615 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
12616 @cindex @option{^-X^/EXTERNAL_REFERENCE^} (any project-aware tool)
12617 Indicates that external variable @var{name} has the value @var{value}.
12618 The Project Manager will use this value for occurrences of
12619 @code{external(name)} when parsing the project file.
12622 If @var{name} or @var{value} includes a space, then @var{name=value} should be
12623 put between quotes.
12630 Several @option{^-X^/EXTERNAL_REFERENCE^} switches can be used simultaneously.
12631 If several @option{^-X^/EXTERNAL_REFERENCE^} switches specify the same
12632 @var{name}, only the last one is used.
12634 An external variable specified with a @option{^-X^/EXTERNAL_REFERENCE^} switch
12635 takes precedence over the value of the same name in the environment.
12637 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
12638 @cindex @option{^-vP^/MESSAGES_PROJECT_FILE^} (any project-aware tool)
12639 Indicates the verbosity of the parsing of GNAT project files.
12642 @option{-vP0} means Default;
12643 @option{-vP1} means Medium;
12644 @option{-vP2} means High.
12648 There are three possible options for this qualifier: DEFAULT, MEDIUM and
12652 The default is ^Default^DEFAULT^: no output for syntactically correct
12654 If several @option{^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}} switches are present,
12655 only the last one is used.
12657 @item ^-aP^/ADD_PROJECT_SEARCH_DIR=^<dir>
12658 @cindex @option{^-aP^/ADD_PROJECT_SEARCH_DIR=^} (any project-aware tool)
12659 Add directory <dir> at the beginning of the project search path, in order,
12660 after the current working directory.
12664 @cindex @option{-eL} (any project-aware tool)
12665 Follow all symbolic links when processing project files.
12668 @item ^--subdirs^/SUBDIRS^=<subdir>
12669 @cindex @option{^--subdirs^/SUBDIRS^=} (gnatmake and gnatclean)
12670 This switch is recognized by @command{gnatmake} and @command{gnatclean}. It
12671 indicate that the real directories (except the source directories) are the
12672 subdirectories <subdir> of the directories specified in the project files.
12673 This applies in particular to object directories, library directories and
12674 exec directories. If the subdirectories do not exist, they are created
12679 @c ---------------------------------------------
12680 @node Switches and Project Files
12681 @subsection Switches and Project Files
12682 @c ---------------------------------------------
12686 It is not currently possible to specify VMS style qualifiers in the project
12687 files; only Unix style ^switches^switches^ may be specified.
12690 For each of the packages @code{Builder}, @code{Compiler}, @code{Binder}, and
12691 @code{Linker}, you can specify a @code{^Default_Switches^Default_Switches^}
12692 attribute, a @code{Switches} attribute, or both;
12693 as their names imply, these ^switch^switch^-related
12694 attributes affect the ^switches^switches^ that are used for each of these GNAT
12696 @command{gnatmake} is invoked. As will be explained below, these
12697 component-specific ^switches^switches^ precede
12698 the ^switches^switches^ provided on the @command{gnatmake} command line.
12700 The @code{^Default_Switches^Default_Switches^} attribute is an attribute
12701 indexed by language name (case insensitive) whose value is a string list.
12704 @smallexample @c projectfile
12706 package Compiler is
12707 for ^Default_Switches^Default_Switches^ ("Ada")
12708 use ("^-gnaty^-gnaty^",
12715 The @code{Switches} attribute is indexed on a file name (which may or may
12716 not be case sensitive, depending
12717 on the operating system) whose value is a string list. For example:
12719 @smallexample @c projectfile
12722 for Switches ("main1.adb")
12724 for Switches ("main2.adb")
12731 For the @code{Builder} package, the file names must designate source files
12732 for main subprograms. For the @code{Binder} and @code{Linker} packages, the
12733 file names must designate @file{ALI} or source files for main subprograms.
12734 In each case just the file name without an explicit extension is acceptable.
12736 For each tool used in a program build (@command{gnatmake}, the compiler, the
12737 binder, and the linker), the corresponding package @dfn{contributes} a set of
12738 ^switches^switches^ for each file on which the tool is invoked, based on the
12739 ^switch^switch^-related attributes defined in the package.
12740 In particular, the ^switches^switches^
12741 that each of these packages contributes for a given file @var{f} comprise:
12744 @item the value of attribute @code{Switches (@var{f})},
12745 if it is specified in the package for the given file,
12746 @item otherwise, the value of @code{^Default_Switches^Default_Switches^ ("Ada")},
12747 if it is specified in the package.
12752 If neither of these attributes is defined in the package, then the package does
12753 not contribute any ^switches^switches^ for the given file.
12755 When @command{gnatmake} is invoked on a file, the ^switches^switches^ comprise
12756 two sets, in the following order: those contributed for the file
12757 by the @code{Builder} package;
12758 and the switches passed on the command line.
12760 When @command{gnatmake} invokes a tool (compiler, binder, linker) on a file,
12761 the ^switches^switches^ passed to the tool comprise three sets,
12762 in the following order:
12766 the applicable ^switches^switches^ contributed for the file
12767 by the @code{Builder} package in the project file supplied on the command line;
12770 those contributed for the file by the package (in the relevant project file --
12771 see below) corresponding to the tool; and
12774 the applicable switches passed on the command line.
12777 The term @emph{applicable ^switches^switches^} reflects the fact that
12778 @command{gnatmake} ^switches^switches^ may or may not be passed to individual
12779 tools, depending on the individual ^switch^switch^.
12781 @command{gnatmake} may invoke the compiler on source files from different
12782 projects. The Project Manager will use the appropriate project file to
12783 determine the @code{Compiler} package for each source file being compiled.
12784 Likewise for the @code{Binder} and @code{Linker} packages.
12786 As an example, consider the following package in a project file:
12788 @smallexample @c projectfile
12791 package Compiler is
12792 for ^Default_Switches^Default_Switches^ ("Ada")
12794 for Switches ("a.adb")
12796 for Switches ("b.adb")
12798 "^-gnaty^-gnaty^");
12805 If @command{gnatmake} is invoked with this project file, and it needs to
12806 compile, say, the files @file{a.adb}, @file{b.adb}, and @file{c.adb}, then
12807 @file{a.adb} will be compiled with the ^switch^switch^
12808 @option{^-O1^-O1^},
12809 @file{b.adb} with ^switches^switches^
12811 and @option{^-gnaty^-gnaty^},
12812 and @file{c.adb} with @option{^-g^-g^}.
12814 The following example illustrates the ordering of the ^switches^switches^
12815 contributed by different packages:
12817 @smallexample @c projectfile
12821 for Switches ("main.adb")
12829 package Compiler is
12830 for Switches ("main.adb")
12838 If you issue the command:
12841 gnatmake ^-Pproj2^/PROJECT_FILE=PROJ2^ -O0 main
12845 then the compiler will be invoked on @file{main.adb} with the following
12846 sequence of ^switches^switches^
12849 ^-g -O1 -O2 -O0^-g -O1 -O2 -O0^
12853 with the last @option{^-O^-O^}
12854 ^switch^switch^ having precedence over the earlier ones;
12855 several other ^switches^switches^
12856 (such as @option{^-c^-c^}) are added implicitly.
12858 The ^switches^switches^
12860 and @option{^-O1^-O1^} are contributed by package
12861 @code{Builder}, @option{^-O2^-O2^} is contributed
12862 by the package @code{Compiler}
12863 and @option{^-O0^-O0^} comes from the command line.
12865 The @option{^-g^-g^}
12866 ^switch^switch^ will also be passed in the invocation of
12867 @command{Gnatlink.}
12869 A final example illustrates switch contributions from packages in different
12872 @smallexample @c projectfile
12875 for Source_Files use ("pack.ads", "pack.adb");
12876 package Compiler is
12877 for ^Default_Switches^Default_Switches^ ("Ada")
12878 use ("^-gnata^-gnata^");
12886 for Source_Files use ("foo_main.adb", "bar_main.adb");
12888 for Switches ("foo_main.adb")
12896 -- Ada source file:
12898 procedure Foo_Main is
12907 gnatmake ^-PProj4^/PROJECT_FILE=PROJ4^ foo_main.adb -cargs -gnato
12911 then the ^switches^switches^ passed to the compiler for @file{foo_main.adb} are
12912 @option{^-g^-g^} (contributed by the package @code{Proj4.Builder}) and
12913 @option{^-gnato^-gnato^} (passed on the command line).
12914 When the imported package @code{Pack} is compiled, the ^switches^switches^ used
12915 are @option{^-g^-g^} from @code{Proj4.Builder},
12916 @option{^-gnata^-gnata^} (contributed from package @code{Proj3.Compiler},
12917 and @option{^-gnato^-gnato^} from the command line.
12919 When using @command{gnatmake} with project files, some ^switches^switches^ or
12920 arguments may be expressed as relative paths. As the working directory where
12921 compilation occurs may change, these relative paths are converted to absolute
12922 paths. For the ^switches^switches^ found in a project file, the relative paths
12923 are relative to the project file directory, for the switches on the command
12924 line, they are relative to the directory where @command{gnatmake} is invoked.
12925 The ^switches^switches^ for which this occurs are:
12931 ^-aI^-aI^, as well as all arguments that are not switches (arguments to
12933 ^-o^-o^, object files specified in package @code{Linker} or after
12934 -largs on the command line). The exception to this rule is the ^switch^switch^
12935 ^--RTS=^--RTS=^ for which a relative path argument is never converted.
12937 @c ---------------------------------------------
12938 @node Specifying Configuration Pragmas
12939 @subsection Specifying Configuration Pragmas
12940 @c ---------------------------------------------
12943 When using @command{gnatmake} with project files, if there exists a file
12944 @file{gnat.adc} that contains configuration pragmas, this file will be
12947 Configuration pragmas can be defined by means of the following attributes in
12948 project files: @code{Global_Configuration_Pragmas} in package @code{Builder}
12949 and @code{Local_Configuration_Pragmas} in package @code{Compiler}.
12951 Both these attributes are single string attributes. Their values is the path
12952 name of a file containing configuration pragmas. If a path name is relative,
12953 then it is relative to the project directory of the project file where the
12954 attribute is defined.
12956 When compiling a source, the configuration pragmas used are, in order,
12957 those listed in the file designated by attribute
12958 @code{Global_Configuration_Pragmas} in package @code{Builder} of the main
12959 project file, if it is specified, and those listed in the file designated by
12960 attribute @code{Local_Configuration_Pragmas} in package @code{Compiler} of
12961 the project file of the source, if it exists.
12963 @c ---------------------------------------------
12964 @node Project Files and Main Subprograms
12965 @subsection Project Files and Main Subprograms
12966 @c ---------------------------------------------
12969 When using a project file, you can invoke @command{gnatmake}
12970 with one or several main subprograms, by specifying their source files on the
12974 gnatmake ^-P^/PROJECT_FILE=^prj main1.adb main2.adb main3.adb
12978 Each of these needs to be a source file of the same project, except
12979 when the switch ^-u^/UNIQUE^ is used.
12981 When ^-u^/UNIQUE^ is not used, all the mains need to be sources of the
12982 same project, one of the project in the tree rooted at the project specified
12983 on the command line. The package @code{Builder} of this common project, the
12984 "main project" is the one that is considered by @command{gnatmake}.
12986 When ^-u^/UNIQUE^ is used, the specified source files may be in projects
12987 imported directly or indirectly by the project specified on the command line.
12988 Note that if such a source file is not part of the project specified on the
12989 command line, the ^switches^switches^ found in package @code{Builder} of the
12990 project specified on the command line, if any, that are transmitted
12991 to the compiler will still be used, not those found in the project file of
12994 When using a project file, you can also invoke @command{gnatmake} without
12995 explicitly specifying any main, and the effect depends on whether you have
12996 defined the @code{Main} attribute. This attribute has a string list value,
12997 where each element in the list is the name of a source file (the file
12998 extension is optional) that contains a unit that can be a main subprogram.
13000 If the @code{Main} attribute is defined in a project file as a non-empty
13001 string list and the switch @option{^-u^/UNIQUE^} is not used on the command
13002 line, then invoking @command{gnatmake} with this project file but without any
13003 main on the command line is equivalent to invoking @command{gnatmake} with all
13004 the file names in the @code{Main} attribute on the command line.
13007 @smallexample @c projectfile
13010 for Main use ("main1.adb", "main2.adb", "main3.adb");
13016 With this project file, @code{"gnatmake ^-Pprj^/PROJECT_FILE=PRJ^"}
13018 @code{"gnatmake ^-Pprj^/PROJECT_FILE=PRJ^ main1.adb main2.adb main3.adb"}.
13020 When the project attribute @code{Main} is not specified, or is specified
13021 as an empty string list, or when the switch @option{-u} is used on the command
13022 line, then invoking @command{gnatmake} with no main on the command line will
13023 result in all immediate sources of the project file being checked, and
13024 potentially recompiled. Depending on the presence of the switch @option{-u},
13025 sources from other project files on which the immediate sources of the main
13026 project file depend are also checked and potentially recompiled. In other
13027 words, the @option{-u} switch is applied to all of the immediate sources of the
13030 When no main is specified on the command line and attribute @code{Main} exists
13031 and includes several mains, or when several mains are specified on the
13032 command line, the default ^switches^switches^ in package @code{Builder} will
13033 be used for all mains, even if there are specific ^switches^switches^
13034 specified for one or several mains.
13036 But the ^switches^switches^ from package @code{Binder} or @code{Linker} will be
13037 the specific ^switches^switches^ for each main, if they are specified.
13039 @c ---------------------------------------------
13040 @node Library Project Files
13041 @subsection Library Project Files
13042 @c ---------------------------------------------
13045 When @command{gnatmake} is invoked with a main project file that is a library
13046 project file, it is not allowed to specify one or more mains on the command
13049 When a library project file is specified, switches ^-b^/ACTION=BIND^ and
13050 ^-l^/ACTION=LINK^ have special meanings.
13053 @item ^-b^/ACTION=BIND^ is only allowed for stand-alone libraries. It indicates
13054 to @command{gnatmake} that @command{gnatbind} should be invoked for the
13057 @item ^-l^/ACTION=LINK^ may be used for all library projects. It indicates
13058 to @command{gnatmake} that the binder generated file should be compiled
13059 (in the case of a stand-alone library) and that the library should be built.
13062 @c ---------------------------------------------
13063 @node The GNAT Driver and Project Files
13064 @section The GNAT Driver and Project Files
13065 @c ---------------------------------------------
13068 A number of GNAT tools, other than @command{^gnatmake^gnatmake^}
13069 can benefit from project files:
13070 (@command{^gnatbind^gnatbind^},
13071 @ifclear FSFEDITION
13072 @command{^gnatcheck^gnatcheck^},
13074 @command{^gnatclean^gnatclean^},
13075 @ifclear FSFEDITION
13076 @command{^gnatelim^gnatelim^},
13078 @command{^gnatfind^gnatfind^},
13079 @command{^gnatlink^gnatlink^},
13080 @command{^gnatls^gnatls^},
13081 @ifclear FSFEDITION
13082 @command{^gnatmetric^gnatmetric^},
13083 @command{^gnatpp^gnatpp^},
13084 @command{^gnatstub^gnatstub^},
13086 and @command{^gnatxref^gnatxref^}). However, none of these tools can be invoked
13087 directly with a project file switch (@option{^-P^/PROJECT_FILE=^}).
13088 They must be invoked through the @command{gnat} driver.
13090 The @command{gnat} driver is a wrapper that accepts a number of commands and
13091 calls the corresponding tool. It was designed initially for VMS platforms (to
13092 convert VMS qualifiers to Unix-style switches), but it is now available on all
13095 On non-VMS platforms, the @command{gnat} driver accepts the following commands
13096 (case insensitive):
13099 @item BIND to invoke @command{^gnatbind^gnatbind^}
13100 @item CHOP to invoke @command{^gnatchop^gnatchop^}
13101 @item CLEAN to invoke @command{^gnatclean^gnatclean^}
13102 @item COMP or COMPILE to invoke the compiler
13103 @ifclear FSFEDITION
13104 @item ELIM to invoke @command{^gnatelim^gnatelim^}
13106 @item FIND to invoke @command{^gnatfind^gnatfind^}
13107 @item KR or KRUNCH to invoke @command{^gnatkr^gnatkr^}
13108 @item LINK to invoke @command{^gnatlink^gnatlink^}
13109 @item LS or LIST to invoke @command{^gnatls^gnatls^}
13110 @item MAKE to invoke @command{^gnatmake^gnatmake^}
13111 @item NAME to invoke @command{^gnatname^gnatname^}
13112 @item PREP or PREPROCESS to invoke @command{^gnatprep^gnatprep^}
13113 @ifclear FSFEDITION
13114 @item PP or PRETTY to invoke @command{^gnatpp^gnatpp^}
13115 @item METRIC to invoke @command{^gnatmetric^gnatmetric^}
13116 @item STUB to invoke @command{^gnatstub^gnatstub^}
13118 @item XREF to invoke @command{^gnatxref^gnatxref^}
13123 (note that the compiler is invoked using the command
13124 @command{^gnatmake -f -u -c^gnatmake -f -u -c^}).
13126 On non-VMS platforms, between @command{gnat} and the command, two
13127 special switches may be used:
13130 @item @command{-v} to display the invocation of the tool.
13131 @item @command{-dn} to prevent the @command{gnat} driver from removing
13132 the temporary files it has created. These temporary files are
13133 configuration files and temporary file list files.
13138 The command may be followed by switches and arguments for the invoked
13142 gnat bind -C main.ali
13148 Switches may also be put in text files, one switch per line, and the text
13149 files may be specified with their path name preceded by '@@'.
13152 gnat bind @@args.txt main.ali
13156 In addition, for commands BIND, COMP or COMPILE, FIND,
13157 @ifclear FSFEDITION
13161 @ifclear FSFEDITION
13166 and XREF, the project file related switches
13167 (@option{^-P^/PROJECT_FILE^},
13168 @option{^-X^/EXTERNAL_REFERENCE^} and
13169 @option{^-vP^/MESSAGES_PROJECT_FILE=^x}) may be used in addition to
13170 the switches of the invoking tool.
13172 @ifclear FSFEDITION
13173 When GNAT PP or GNAT PRETTY is used with a project file, but with no source
13174 specified on the command line, it invokes @command{^gnatpp^gnatpp^} with all
13175 the immediate sources of the specified project file.
13178 @ifclear FSFEDITION
13179 When GNAT METRIC is used with a project file, but with no source
13180 specified on the command line, it invokes @command{^gnatmetric^gnatmetric^}
13181 with all the immediate sources of the specified project file and with
13182 @option{^-d^/DIRECTORY^} with the parameter pointing to the object directory
13186 @ifclear FSFEDITION
13187 In addition, when GNAT PP, GNAT PRETTY or GNAT METRIC is used with
13188 a project file, no source is specified on the command line and
13189 switch ^-U^/ALL_PROJECTS^ is specified on the command line, then
13190 the underlying tool (^gnatpp^gnatpp^ or
13191 ^gnatmetric^gnatmetric^) is invoked for all sources of all projects,
13192 not only for the immediate sources of the main project.
13194 (-U stands for Universal or Union of the project files of the project tree)
13198 For each of the following commands, there is optionally a corresponding
13199 package in the main project.
13202 @item package @code{Binder} for command BIND (invoking @code{^gnatbind^gnatbind^})
13204 @ifclear FSFEDITION
13205 @item package @code{Check} for command CHECK (invoking
13206 @code{^gnatcheck^gnatcheck^})
13209 @item package @code{Compiler} for command COMP or COMPILE (invoking the compiler)
13211 @item package @code{Cross_Reference} for command XREF (invoking
13212 @code{^gnatxref^gnatxref^})
13214 @ifclear FSFEDITION
13215 @item package @code{Eliminate} for command ELIM (invoking
13216 @code{^gnatelim^gnatelim^})
13219 @item package @code{Finder} for command FIND (invoking @code{^gnatfind^gnatfind^})
13221 @item package @code{Gnatls} for command LS or LIST (invoking @code{^gnatls^gnatls^})
13223 @ifclear FSFEDITION
13224 @item package @code{Gnatstub} for command STUB
13225 (invoking @code{^gnatstub^gnatstub^})
13228 @item package @code{Linker} for command LINK (invoking @code{^gnatlink^gnatlink^})
13230 @ifclear FSFEDITION
13231 @item package @code{Check} for command CHECK
13232 (invoking @code{^gnatcheck^gnatcheck^})
13235 @ifclear FSFEDITION
13236 @item package @code{Metrics} for command METRIC
13237 (invoking @code{^gnatmetric^gnatmetric^})
13240 @ifclear FSFEDITION
13241 @item package @code{Pretty_Printer} for command PP or PRETTY
13242 (invoking @code{^gnatpp^gnatpp^})
13248 Package @code{Gnatls} has a unique attribute @code{Switches},
13249 a simple variable with a string list value. It contains ^switches^switches^
13250 for the invocation of @code{^gnatls^gnatls^}.
13252 @smallexample @c projectfile
13265 All other packages have two attribute @code{Switches} and
13266 @code{^Default_Switches^Default_Switches^}.
13268 @code{Switches} is an indexed attribute, indexed by the
13269 source file name, that has a string list value: the ^switches^switches^ to be
13270 used when the tool corresponding to the package is invoked for the specific
13273 @code{^Default_Switches^Default_Switches^} is an attribute,
13274 indexed by the programming language that has a string list value.
13275 @code{^Default_Switches^Default_Switches^ ("Ada")} contains the
13276 ^switches^switches^ for the invocation of the tool corresponding
13277 to the package, except if a specific @code{Switches} attribute
13278 is specified for the source file.
13280 @smallexample @c projectfile
13284 for Source_Dirs use ("**");
13294 package Compiler is
13295 for ^Default_Switches^Default_Switches^ ("Ada")
13296 use ("^-gnatv^-gnatv^",
13297 "^-gnatwa^-gnatwa^");
13303 for ^Default_Switches^Default_Switches^ ("Ada")
13311 for ^Default_Switches^Default_Switches^ ("Ada")
13313 for Switches ("main.adb")
13322 for ^Default_Switches^Default_Switches^ ("Ada")
13329 package Cross_Reference is
13330 for ^Default_Switches^Default_Switches^ ("Ada")
13335 end Cross_Reference;
13341 With the above project file, commands such as
13344 ^gnat comp -Pproj main^GNAT COMP /PROJECT_FILE=PROJ MAIN^
13345 ^gnat ls -Pproj main^GNAT LIST /PROJECT_FILE=PROJ MAIN^
13346 ^gnat xref -Pproj main^GNAT XREF /PROJECT_FILE=PROJ MAIN^
13347 ^gnat bind -Pproj main.ali^GNAT BIND /PROJECT_FILE=PROJ MAIN.ALI^
13348 ^gnat link -Pproj main.ali^GNAT LINK /PROJECT_FILE=PROJ MAIN.ALI^
13352 will set up the environment properly and invoke the tool with the switches
13353 found in the package corresponding to the tool:
13354 @code{^Default_Switches^Default_Switches^ ("Ada")} for all tools,
13355 except @code{Switches ("main.adb")}
13356 for @code{^gnatlink^gnatlink^}.
13357 @ifclear FSFEDITION
13358 It is also possible to invoke some of the tools,
13359 (@code{^gnatcheck^gnatcheck^},
13360 @code{^gnatmetric^gnatmetric^},
13361 and @code{^gnatpp^gnatpp^})
13362 on a set of project units thanks to the combination of the switches
13363 @option{-P}, @option{-U} and possibly the main unit when one is interested
13364 in its closure. For instance,
13370 will compute the metrics for all the immediate units of project
13373 gnat metric -Pproj -U
13377 will compute the metrics for all the units of the closure of projects
13378 rooted at @code{proj}.
13380 gnat metric -Pproj -U main_unit
13384 will compute the metrics for the closure of units rooted at
13385 @code{main_unit}. This last possibility relies implicitly
13386 on @command{gnatbind}'s option @option{-R}. But if the argument files for the
13387 tool invoked by the @command{gnat} driver are explicitly specified
13388 either directly or through the tool @option{-files} option, then the tool
13389 is called only for these explicitly specified files.
13392 @c *****************************************
13393 @c * Cross-referencing tools
13394 @c *****************************************
13396 @node The Cross-Referencing Tools gnatxref and gnatfind
13397 @chapter The Cross-Referencing Tools @code{gnatxref} and @code{gnatfind}
13402 The compiler generates cross-referencing information (unless
13403 you set the @samp{-gnatx} switch), which are saved in the @file{.ali} files.
13404 This information indicates where in the source each entity is declared and
13405 referenced. Note that entities in package Standard are not included, but
13406 entities in all other predefined units are included in the output.
13408 Before using any of these two tools, you need to compile successfully your
13409 application, so that GNAT gets a chance to generate the cross-referencing
13412 The two tools @code{gnatxref} and @code{gnatfind} take advantage of this
13413 information to provide the user with the capability to easily locate the
13414 declaration and references to an entity. These tools are quite similar,
13415 the difference being that @code{gnatfind} is intended for locating
13416 definitions and/or references to a specified entity or entities, whereas
13417 @code{gnatxref} is oriented to generating a full report of all
13420 To use these tools, you must not compile your application using the
13421 @option{-gnatx} switch on the @command{gnatmake} command line
13422 (@pxref{The GNAT Make Program gnatmake}). Otherwise, cross-referencing
13423 information will not be generated.
13425 Note: to invoke @code{gnatxref} or @code{gnatfind} with a project file,
13426 use the @code{gnat} driver (see @ref{The GNAT Driver and Project Files}).
13429 * Switches for gnatxref::
13430 * Switches for gnatfind::
13431 * Project Files for gnatxref and gnatfind::
13432 * Regular Expressions in gnatfind and gnatxref::
13433 * Examples of gnatxref Usage::
13434 * Examples of gnatfind Usage::
13437 @node Switches for gnatxref
13438 @section @code{gnatxref} Switches
13441 The command invocation for @code{gnatxref} is:
13443 @c $ gnatxref @ovar{switches} @var{sourcefile1} @r{[}@var{sourcefile2} @dots{}@r{]}
13444 @c Expanding @ovar macro inline (explanation in macro def comments)
13445 $ gnatxref @r{[}@var{switches}@r{]} @var{sourcefile1} @r{[}@var{sourcefile2} @dots{}@r{]}
13454 identifies the source files for which a report is to be generated. The
13455 ``with''ed units will be processed too. You must provide at least one file.
13457 These file names are considered to be regular expressions, so for instance
13458 specifying @file{source*.adb} is the same as giving every file in the current
13459 directory whose name starts with @file{source} and whose extension is
13462 You shouldn't specify any directory name, just base names. @command{gnatxref}
13463 and @command{gnatfind} will be able to locate these files by themselves using
13464 the source path. If you specify directories, no result is produced.
13469 The switches can be:
13473 @cindex @option{--version} @command{gnatxref}
13474 Display Copyright and version, then exit disregarding all other options.
13477 @cindex @option{--help} @command{gnatxref}
13478 If @option{--version} was not used, display usage, then exit disregarding
13481 @item ^-a^/ALL_FILES^
13482 @cindex @option{^-a^/ALL_FILES^} (@command{gnatxref})
13483 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
13484 the read-only files found in the library search path. Otherwise, these files
13485 will be ignored. This option can be used to protect Gnat sources or your own
13486 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
13487 much faster, and their output much smaller. Read-only here refers to access
13488 or permissions status in the file system for the current user.
13491 @cindex @option{-aIDIR} (@command{gnatxref})
13492 When looking for source files also look in directory DIR. The order in which
13493 source file search is undertaken is the same as for @command{gnatmake}.
13496 @cindex @option{-aODIR} (@command{gnatxref})
13497 When searching for library and object files, look in directory
13498 DIR. The order in which library files are searched is the same as for
13499 @command{gnatmake}.
13502 @cindex @option{-nostdinc} (@command{gnatxref})
13503 Do not look for sources in the system default directory.
13506 @cindex @option{-nostdlib} (@command{gnatxref})
13507 Do not look for library files in the system default directory.
13509 @item --ext=@var{extension}
13510 @cindex @option{--ext} (@command{gnatxref})
13511 Specify an alternate ali file extension. The default is @code{ali} and other
13512 extensions (e.g. @code{gli} for C/C++ sources when using @option{-fdump-xref})
13513 may be specified via this switch. Note that if this switch overrides the
13514 default, which means that only the new extension will be considered.
13516 @item --RTS=@var{rts-path}
13517 @cindex @option{--RTS} (@command{gnatxref})
13518 Specifies the default location of the runtime library. Same meaning as the
13519 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
13521 @item ^-d^/DERIVED_TYPES^
13522 @cindex @option{^-d^/DERIVED_TYPES^} (@command{gnatxref})
13523 If this switch is set @code{gnatxref} will output the parent type
13524 reference for each matching derived types.
13526 @item ^-f^/FULL_PATHNAME^
13527 @cindex @option{^-f^/FULL_PATHNAME^} (@command{gnatxref})
13528 If this switch is set, the output file names will be preceded by their
13529 directory (if the file was found in the search path). If this switch is
13530 not set, the directory will not be printed.
13532 @item ^-g^/IGNORE_LOCALS^
13533 @cindex @option{^-g^/IGNORE_LOCALS^} (@command{gnatxref})
13534 If this switch is set, information is output only for library-level
13535 entities, ignoring local entities. The use of this switch may accelerate
13536 @code{gnatfind} and @code{gnatxref}.
13539 @cindex @option{-IDIR} (@command{gnatxref})
13540 Equivalent to @samp{-aODIR -aIDIR}.
13543 @cindex @option{-pFILE} (@command{gnatxref})
13544 Specify a project file to use @xref{GNAT Project Manager}.
13545 If you need to use the @file{.gpr}
13546 project files, you should use gnatxref through the GNAT driver
13547 (@command{gnat xref -Pproject}).
13549 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
13550 project file in the current directory.
13552 If a project file is either specified or found by the tools, then the content
13553 of the source directory and object directory lines are added as if they
13554 had been specified respectively by @samp{^-aI^/SOURCE_SEARCH^}
13555 and @samp{^-aO^OBJECT_SEARCH^}.
13557 Output only unused symbols. This may be really useful if you give your
13558 main compilation unit on the command line, as @code{gnatxref} will then
13559 display every unused entity and 'with'ed package.
13563 Instead of producing the default output, @code{gnatxref} will generate a
13564 @file{tags} file that can be used by vi. For examples how to use this
13565 feature, see @ref{Examples of gnatxref Usage}. The tags file is output
13566 to the standard output, thus you will have to redirect it to a file.
13572 All these switches may be in any order on the command line, and may even
13573 appear after the file names. They need not be separated by spaces, thus
13574 you can say @samp{gnatxref ^-ag^/ALL_FILES/IGNORE_LOCALS^} instead of
13575 @samp{gnatxref ^-a -g^/ALL_FILES /IGNORE_LOCALS^}.
13577 @node Switches for gnatfind
13578 @section @code{gnatfind} Switches
13581 The command line for @code{gnatfind} is:
13584 @c $ gnatfind @ovar{switches} @var{pattern}@r{[}:@var{sourcefile}@r{[}:@var{line}@r{[}:@var{column}@r{]]]}
13585 @c @r{[}@var{file1} @var{file2} @dots{}]
13586 @c Expanding @ovar macro inline (explanation in macro def comments)
13587 $ gnatfind @r{[}@var{switches}@r{]} @var{pattern}@r{[}:@var{sourcefile}@r{[}:@var{line}@r{[}:@var{column}@r{]]]}
13588 @r{[}@var{file1} @var{file2} @dots{}@r{]}
13596 An entity will be output only if it matches the regular expression found
13597 in @var{pattern}, see @ref{Regular Expressions in gnatfind and gnatxref}.
13599 Omitting the pattern is equivalent to specifying @samp{*}, which
13600 will match any entity. Note that if you do not provide a pattern, you
13601 have to provide both a sourcefile and a line.
13603 Entity names are given in Latin-1, with uppercase/lowercase equivalence
13604 for matching purposes. At the current time there is no support for
13605 8-bit codes other than Latin-1, or for wide characters in identifiers.
13608 @code{gnatfind} will look for references, bodies or declarations
13609 of symbols referenced in @file{@var{sourcefile}}, at line @var{line}
13610 and column @var{column}. See @ref{Examples of gnatfind Usage}
13611 for syntax examples.
13614 is a decimal integer identifying the line number containing
13615 the reference to the entity (or entities) to be located.
13618 is a decimal integer identifying the exact location on the
13619 line of the first character of the identifier for the
13620 entity reference. Columns are numbered from 1.
13622 @item file1 file2 @dots{}
13623 The search will be restricted to these source files. If none are given, then
13624 the search will be done for every library file in the search path.
13625 These file must appear only after the pattern or sourcefile.
13627 These file names are considered to be regular expressions, so for instance
13628 specifying @file{source*.adb} is the same as giving every file in the current
13629 directory whose name starts with @file{source} and whose extension is
13632 The location of the spec of the entity will always be displayed, even if it
13633 isn't in one of @file{@var{file1}}, @file{@var{file2}},@enddots{} The
13634 occurrences of the entity in the separate units of the ones given on the
13635 command line will also be displayed.
13637 Note that if you specify at least one file in this part, @code{gnatfind} may
13638 sometimes not be able to find the body of the subprograms.
13643 At least one of 'sourcefile' or 'pattern' has to be present on
13646 The following switches are available:
13650 @cindex @option{--version} @command{gnatfind}
13651 Display Copyright and version, then exit disregarding all other options.
13654 @cindex @option{--help} @command{gnatfind}
13655 If @option{--version} was not used, display usage, then exit disregarding
13658 @item ^-a^/ALL_FILES^
13659 @cindex @option{^-a^/ALL_FILES^} (@command{gnatfind})
13660 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
13661 the read-only files found in the library search path. Otherwise, these files
13662 will be ignored. This option can be used to protect Gnat sources or your own
13663 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
13664 much faster, and their output much smaller. Read-only here refers to access
13665 or permission status in the file system for the current user.
13668 @cindex @option{-aIDIR} (@command{gnatfind})
13669 When looking for source files also look in directory DIR. The order in which
13670 source file search is undertaken is the same as for @command{gnatmake}.
13673 @cindex @option{-aODIR} (@command{gnatfind})
13674 When searching for library and object files, look in directory
13675 DIR. The order in which library files are searched is the same as for
13676 @command{gnatmake}.
13679 @cindex @option{-nostdinc} (@command{gnatfind})
13680 Do not look for sources in the system default directory.
13683 @cindex @option{-nostdlib} (@command{gnatfind})
13684 Do not look for library files in the system default directory.
13686 @item --ext=@var{extension}
13687 @cindex @option{--ext} (@command{gnatfind})
13688 Specify an alternate ali file extension. The default is @code{ali} and other
13689 extensions (e.g. @code{gli} for C/C++ sources when using @option{-fdump-xref})
13690 may be specified via this switch. Note that if this switch overrides the
13691 default, which means that only the new extension will be considered.
13693 @item --RTS=@var{rts-path}
13694 @cindex @option{--RTS} (@command{gnatfind})
13695 Specifies the default location of the runtime library. Same meaning as the
13696 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
13698 @item ^-d^/DERIVED_TYPE_INFORMATION^
13699 @cindex @option{^-d^/DERIVED_TYPE_INFORMATION^} (@code{gnatfind})
13700 If this switch is set, then @code{gnatfind} will output the parent type
13701 reference for each matching derived types.
13703 @item ^-e^/EXPRESSIONS^
13704 @cindex @option{^-e^/EXPRESSIONS^} (@command{gnatfind})
13705 By default, @code{gnatfind} accept the simple regular expression set for
13706 @samp{pattern}. If this switch is set, then the pattern will be
13707 considered as full Unix-style regular expression.
13709 @item ^-f^/FULL_PATHNAME^
13710 @cindex @option{^-f^/FULL_PATHNAME^} (@command{gnatfind})
13711 If this switch is set, the output file names will be preceded by their
13712 directory (if the file was found in the search path). If this switch is
13713 not set, the directory will not be printed.
13715 @item ^-g^/IGNORE_LOCALS^
13716 @cindex @option{^-g^/IGNORE_LOCALS^} (@command{gnatfind})
13717 If this switch is set, information is output only for library-level
13718 entities, ignoring local entities. The use of this switch may accelerate
13719 @code{gnatfind} and @code{gnatxref}.
13722 @cindex @option{-IDIR} (@command{gnatfind})
13723 Equivalent to @samp{-aODIR -aIDIR}.
13726 @cindex @option{-pFILE} (@command{gnatfind})
13727 Specify a project file (@pxref{GNAT Project Manager}) to use.
13728 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
13729 project file in the current directory.
13731 If a project file is either specified or found by the tools, then the content
13732 of the source directory and object directory lines are added as if they
13733 had been specified respectively by @samp{^-aI^/SOURCE_SEARCH^} and
13734 @samp{^-aO^/OBJECT_SEARCH^}.
13736 @item ^-r^/REFERENCES^
13737 @cindex @option{^-r^/REFERENCES^} (@command{gnatfind})
13738 By default, @code{gnatfind} will output only the information about the
13739 declaration, body or type completion of the entities. If this switch is
13740 set, the @code{gnatfind} will locate every reference to the entities in
13741 the files specified on the command line (or in every file in the search
13742 path if no file is given on the command line).
13744 @item ^-s^/PRINT_LINES^
13745 @cindex @option{^-s^/PRINT_LINES^} (@command{gnatfind})
13746 If this switch is set, then @code{gnatfind} will output the content
13747 of the Ada source file lines were the entity was found.
13749 @item ^-t^/TYPE_HIERARCHY^
13750 @cindex @option{^-t^/TYPE_HIERARCHY^} (@command{gnatfind})
13751 If this switch is set, then @code{gnatfind} will output the type hierarchy for
13752 the specified type. It act like -d option but recursively from parent
13753 type to parent type. When this switch is set it is not possible to
13754 specify more than one file.
13759 All these switches may be in any order on the command line, and may even
13760 appear after the file names. They need not be separated by spaces, thus
13761 you can say @samp{gnatxref ^-ag^/ALL_FILES/IGNORE_LOCALS^} instead of
13762 @samp{gnatxref ^-a -g^/ALL_FILES /IGNORE_LOCALS^}.
13764 As stated previously, gnatfind will search in every directory in the
13765 search path. You can force it to look only in the current directory if
13766 you specify @code{*} at the end of the command line.
13768 @node Project Files for gnatxref and gnatfind
13769 @section Project Files for @command{gnatxref} and @command{gnatfind}
13772 Project files allow a programmer to specify how to compile its
13773 application, where to find sources, etc. These files are used
13775 primarily by GPS, but they can also be used
13778 @code{gnatxref} and @code{gnatfind}.
13780 A project file name must end with @file{.gpr}. If a single one is
13781 present in the current directory, then @code{gnatxref} and @code{gnatfind} will
13782 extract the information from it. If multiple project files are found, none of
13783 them is read, and you have to use the @samp{-p} switch to specify the one
13786 The following lines can be included, even though most of them have default
13787 values which can be used in most cases.
13788 The lines can be entered in any order in the file.
13789 Except for @file{src_dir} and @file{obj_dir}, you can only have one instance of
13790 each line. If you have multiple instances, only the last one is taken into
13795 [default: @code{"^./^[]^"}]
13796 specifies a directory where to look for source files. Multiple @code{src_dir}
13797 lines can be specified and they will be searched in the order they
13801 [default: @code{"^./^[]^"}]
13802 specifies a directory where to look for object and library files. Multiple
13803 @code{obj_dir} lines can be specified, and they will be searched in the order
13806 @item comp_opt=SWITCHES
13807 [default: @code{""}]
13808 creates a variable which can be referred to subsequently by using
13809 the @code{$@{comp_opt@}} notation. This is intended to store the default
13810 switches given to @command{gnatmake} and @command{gcc}.
13812 @item bind_opt=SWITCHES
13813 [default: @code{""}]
13814 creates a variable which can be referred to subsequently by using
13815 the @samp{$@{bind_opt@}} notation. This is intended to store the default
13816 switches given to @command{gnatbind}.
13818 @item link_opt=SWITCHES
13819 [default: @code{""}]
13820 creates a variable which can be referred to subsequently by using
13821 the @samp{$@{link_opt@}} notation. This is intended to store the default
13822 switches given to @command{gnatlink}.
13824 @item main=EXECUTABLE
13825 [default: @code{""}]
13826 specifies the name of the executable for the application. This variable can
13827 be referred to in the following lines by using the @samp{$@{main@}} notation.
13830 @item comp_cmd=COMMAND
13831 [default: @code{"GNAT COMPILE /SEARCH=$@{src_dir@} /DEBUG /TRY_SEMANTICS"}]
13834 @item comp_cmd=COMMAND
13835 [default: @code{"gcc -c -I$@{src_dir@} -g -gnatq"}]
13837 specifies the command used to compile a single file in the application.
13840 @item make_cmd=COMMAND
13841 [default: @code{"GNAT MAKE $@{main@}
13842 /SOURCE_SEARCH=$@{src_dir@} /OBJECT_SEARCH=$@{obj_dir@}
13843 /DEBUG /TRY_SEMANTICS /COMPILER_QUALIFIERS $@{comp_opt@}
13844 /BINDER_QUALIFIERS $@{bind_opt@} /LINKER_QUALIFIERS $@{link_opt@}"}]
13847 @item make_cmd=COMMAND
13848 [default: @code{"gnatmake $@{main@} -aI$@{src_dir@}
13849 -aO$@{obj_dir@} -g -gnatq -cargs $@{comp_opt@}
13850 -bargs $@{bind_opt@} -largs $@{link_opt@}"}]
13852 specifies the command used to recompile the whole application.
13854 @item run_cmd=COMMAND
13855 [default: @code{"$@{main@}"}]
13856 specifies the command used to run the application.
13858 @item debug_cmd=COMMAND
13859 [default: @code{"gdb $@{main@}"}]
13860 specifies the command used to debug the application
13865 @command{gnatxref} and @command{gnatfind} only take into account the
13866 @code{src_dir} and @code{obj_dir} lines, and ignore the others.
13868 @node Regular Expressions in gnatfind and gnatxref
13869 @section Regular Expressions in @code{gnatfind} and @code{gnatxref}
13872 As specified in the section about @command{gnatfind}, the pattern can be a
13873 regular expression. Actually, there are to set of regular expressions
13874 which are recognized by the program:
13877 @item globbing patterns
13878 These are the most usual regular expression. They are the same that you
13879 generally used in a Unix shell command line, or in a DOS session.
13881 Here is a more formal grammar:
13888 term ::= elmt -- matches elmt
13889 term ::= elmt elmt -- concatenation (elmt then elmt)
13890 term ::= * -- any string of 0 or more characters
13891 term ::= ? -- matches any character
13892 term ::= [char @{char@}] -- matches any character listed
13893 term ::= [char - char] -- matches any character in range
13897 @item full regular expression
13898 The second set of regular expressions is much more powerful. This is the
13899 type of regular expressions recognized by utilities such a @file{grep}.
13901 The following is the form of a regular expression, expressed in Ada
13902 reference manual style BNF is as follows
13909 regexp ::= term @{| term@} -- alternation (term or term @dots{})
13911 term ::= item @{item@} -- concatenation (item then item)
13913 item ::= elmt -- match elmt
13914 item ::= elmt * -- zero or more elmt's
13915 item ::= elmt + -- one or more elmt's
13916 item ::= elmt ? -- matches elmt or nothing
13919 elmt ::= nschar -- matches given character
13920 elmt ::= [nschar @{nschar@}] -- matches any character listed
13921 elmt ::= [^^^ nschar @{nschar@}] -- matches any character not listed
13922 elmt ::= [char - char] -- matches chars in given range
13923 elmt ::= \ char -- matches given character
13924 elmt ::= . -- matches any single character
13925 elmt ::= ( regexp ) -- parens used for grouping
13927 char ::= any character, including special characters
13928 nschar ::= any character except ()[].*+?^^^
13932 Following are a few examples:
13936 will match any of the two strings @samp{abcde} and @samp{fghi},
13939 will match any string like @samp{abd}, @samp{abcd}, @samp{abccd},
13940 @samp{abcccd}, and so on,
13943 will match any string which has only lowercase characters in it (and at
13944 least one character.
13949 @node Examples of gnatxref Usage
13950 @section Examples of @code{gnatxref} Usage
13952 @subsection General Usage
13955 For the following examples, we will consider the following units:
13957 @smallexample @c ada
13963 3: procedure Foo (B : in Integer);
13970 1: package body Main is
13971 2: procedure Foo (B : in Integer) is
13982 2: procedure Print (B : Integer);
13991 The first thing to do is to recompile your application (for instance, in
13992 that case just by doing a @samp{gnatmake main}, so that GNAT generates
13993 the cross-referencing information.
13994 You can then issue any of the following commands:
13996 @item gnatxref main.adb
13997 @code{gnatxref} generates cross-reference information for main.adb
13998 and every unit 'with'ed by main.adb.
14000 The output would be:
14008 Decl: main.ads 3:20
14009 Body: main.adb 2:20
14010 Ref: main.adb 4:13 5:13 6:19
14013 Ref: main.adb 6:8 7:8
14023 Decl: main.ads 3:15
14024 Body: main.adb 2:15
14027 Body: main.adb 1:14
14030 Ref: main.adb 6:12 7:12
14034 that is the entity @code{Main} is declared in main.ads, line 2, column 9,
14035 its body is in main.adb, line 1, column 14 and is not referenced any where.
14037 The entity @code{Print} is declared in bar.ads, line 2, column 15 and it
14038 is referenced in main.adb, line 6 column 12 and line 7 column 12.
14040 @item gnatxref package1.adb package2.ads
14041 @code{gnatxref} will generates cross-reference information for
14042 package1.adb, package2.ads and any other package 'with'ed by any
14048 @subsection Using gnatxref with vi
14050 @code{gnatxref} can generate a tags file output, which can be used
14051 directly from @command{vi}. Note that the standard version of @command{vi}
14052 will not work properly with overloaded symbols. Consider using another
14053 free implementation of @command{vi}, such as @command{vim}.
14056 $ gnatxref -v gnatfind.adb > tags
14060 will generate the tags file for @code{gnatfind} itself (if the sources
14061 are in the search path!).
14063 From @command{vi}, you can then use the command @samp{:tag @var{entity}}
14064 (replacing @var{entity} by whatever you are looking for), and vi will
14065 display a new file with the corresponding declaration of entity.
14068 @node Examples of gnatfind Usage
14069 @section Examples of @code{gnatfind} Usage
14073 @item gnatfind ^-f^/FULL_PATHNAME^ xyz:main.adb
14074 Find declarations for all entities xyz referenced at least once in
14075 main.adb. The references are search in every library file in the search
14078 The directories will be printed as well (as the @samp{^-f^/FULL_PATHNAME^}
14081 The output will look like:
14083 ^directory/^[directory]^main.ads:106:14: xyz <= declaration
14084 ^directory/^[directory]^main.adb:24:10: xyz <= body
14085 ^directory/^[directory]^foo.ads:45:23: xyz <= declaration
14089 that is to say, one of the entities xyz found in main.adb is declared at
14090 line 12 of main.ads (and its body is in main.adb), and another one is
14091 declared at line 45 of foo.ads
14093 @item gnatfind ^-fs^/FULL_PATHNAME/SOURCE_LINE^ xyz:main.adb
14094 This is the same command as the previous one, instead @code{gnatfind} will
14095 display the content of the Ada source file lines.
14097 The output will look like:
14100 ^directory/^[directory]^main.ads:106:14: xyz <= declaration
14102 ^directory/^[directory]^main.adb:24:10: xyz <= body
14104 ^directory/^[directory]^foo.ads:45:23: xyz <= declaration
14109 This can make it easier to find exactly the location your are looking
14112 @item gnatfind ^-r^/REFERENCES^ "*x*":main.ads:123 foo.adb
14113 Find references to all entities containing an x that are
14114 referenced on line 123 of main.ads.
14115 The references will be searched only in main.ads and foo.adb.
14117 @item gnatfind main.ads:123
14118 Find declarations and bodies for all entities that are referenced on
14119 line 123 of main.ads.
14121 This is the same as @code{gnatfind "*":main.adb:123}.
14123 @item gnatfind ^mydir/^[mydir]^main.adb:123:45
14124 Find the declaration for the entity referenced at column 45 in
14125 line 123 of file main.adb in directory mydir. Note that it
14126 is usual to omit the identifier name when the column is given,
14127 since the column position identifies a unique reference.
14129 The column has to be the beginning of the identifier, and should not
14130 point to any character in the middle of the identifier.
14134 @ifclear FSFEDITION
14135 @c *********************************
14136 @node The GNAT Pretty-Printer gnatpp
14137 @chapter The GNAT Pretty-Printer @command{gnatpp}
14139 @cindex Pretty-Printer
14142 * Switches for gnatpp::
14143 * Formatting Rules::
14147 ^The @command{gnatpp} tool^GNAT PRETTY^ is an ASIS-based utility
14148 for source reformatting / pretty-printing.
14149 It takes an Ada source file as input and generates a reformatted
14151 You can specify various style directives via switches; e.g.,
14152 identifier case conventions, rules of indentation, and comment layout.
14154 Note: A newly-redesigned set of formatting algorithms used by gnatpp
14156 To invoke the old formatting algorithms, use the @option{--pp-old} switch.
14157 Support for @option{--pp-old} will be removed in some future version.
14159 To produce a reformatted file, @command{gnatpp} invokes the Ada
14160 compiler and generates and uses the ASIS tree for the input source;
14161 thus the input must be legal Ada code, and the tool should have all the
14162 information needed to compile the input source. To provide this information,
14163 you may specify as a tool parameter the project file the input source belongs to
14164 (or you may call @command{gnatpp}
14165 through the @command{gnat} driver (see @ref{The GNAT Driver and
14166 Project Files}). Another possibility is to specify the source search
14167 path and needed configuration files in @option{-cargs} section of @command{gnatpp}
14168 call, see the description of the @command{gnatpp} switches below.
14170 @command{gnatpp} cannot process sources that contain
14171 preprocessing directives.
14173 The @command{gnatpp} command has the form
14176 @c $ gnatpp @ovar{switches} @var{filename}
14177 @c Expanding @ovar macro inline (explanation in macro def comments)
14178 $ gnatpp @r{[}@var{switches}@r{]} @var{filename} @r{[}-cargs @var{gcc_switches}@r{]}
14185 @var{switches} is an optional sequence of switches defining such properties as
14186 the formatting rules, the source search path, and the destination for the
14190 @var{filename} is the name (including the extension) of the source file to
14191 reformat; wildcards or several file names on the same gnatpp command are
14192 allowed. The file name may contain path information; it does not have to
14193 follow the GNAT file naming rules
14196 @samp{@var{gcc_switches}} is a list of switches for
14197 @command{gcc}. They will be passed on to all compiler invocations made by
14198 @command{gnatpp} to generate the ASIS trees. Here you can provide
14199 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
14200 use the @option{-gnatec} switch to set the configuration file, etc.
14203 @node Switches for gnatpp
14204 @section Switches for @command{gnatpp}
14207 The following subsections describe the various switches accepted by
14208 @command{gnatpp}, organized by category.
14211 You specify a switch by supplying a name and generally also a value.
14212 In many cases the values for a switch with a given name are incompatible with
14214 (for example the switch that controls the casing of a reserved word may have
14215 exactly one value: upper case, lower case, or
14216 mixed case) and thus exactly one such switch can be in effect for an
14217 invocation of @command{gnatpp}.
14218 If more than one is supplied, the last one is used.
14219 However, some values for the same switch are mutually compatible.
14220 You may supply several such switches to @command{gnatpp}, but then
14221 each must be specified in full, with both the name and the value.
14222 Abbreviated forms (the name appearing once, followed by each value) are
14227 In many cases the set of options for a given qualifier are incompatible with
14228 each other (for example the qualifier that controls the casing of a reserved
14229 word may have exactly one option, which specifies either upper case, lower
14230 case, or mixed case), and thus exactly one such option can be in effect for
14231 an invocation of @command{gnatpp}.
14232 If more than one is supplied, the last one is used.
14236 * Alignment Control::
14238 * General Text Layout Control::
14239 * Other Formatting Options::
14240 * Setting the Source Search Path::
14241 * Output File Control::
14242 * Other gnatpp Switches::
14245 @node Alignment Control
14246 @subsection Alignment Control
14247 @cindex Alignment control in @command{gnatpp}
14250 Programs can be easier to read if certain constructs are vertically aligned.
14251 By default alignment of the following constructs is set ON:
14252 @code{:} in declarations, @code{:=} in initializations in declarations
14253 @code{:=} in assignment statements, @code{=>} in associations, and
14254 @code{at} keywords in the component clauses in record
14255 representation clauses.
14258 @cindex @option{^-A@var{n}^/ALIGN^} (@command{gnatpp})
14260 @item ^-A0^/ALIGN=OFF^
14261 Set alignment to OFF
14263 @item ^-A1^/ALIGN=ON^
14264 Set alignment to ON
14267 @node Casing Control
14268 @subsection Casing Control
14269 @cindex Casing control in @command{gnatpp}
14272 @command{gnatpp} allows you to specify the casing for reserved words,
14273 pragma names, attribute designators and identifiers.
14274 For identifiers you may define a
14275 general rule for name casing but also override this rule
14276 via a set of dictionary files.
14278 Three types of casing are supported: lower case, upper case, and mixed case.
14279 ``Mixed case'' means that the first letter, and also each letter immediately
14280 following an underscore, are converted to their uppercase forms;
14281 all the other letters are converted to their lowercase forms.
14284 @cindex @option{^-a@var{x}^/ATTRIBUTE^} (@command{gnatpp})
14285 @item ^-aL^/ATTRIBUTE_CASING=LOWER_CASE^
14286 Attribute designators are lower case
14288 @item ^-aU^/ATTRIBUTE_CASING=UPPER_CASE^
14289 Attribute designators are upper case
14291 @item ^-aM^/ATTRIBUTE_CASING=MIXED_CASE^
14292 Attribute designators are mixed case (this is the default)
14294 @cindex @option{^-k@var{x}^/KEYWORD_CASING^} (@command{gnatpp})
14295 @item ^-kL^/KEYWORD_CASING=LOWER_CASE^
14296 Keywords (technically, these are known in Ada as @emph{reserved words}) are
14297 lower case (this is the default)
14299 @item ^-kU^/KEYWORD_CASING=UPPER_CASE^
14300 Keywords are upper case
14302 @cindex @option{^-n@var{x}^/NAME_CASING^} (@command{gnatpp})
14303 @item ^-nD^/NAME_CASING=AS_DECLARED^
14304 Name casing for defining occurrences are as they appear in the source file
14305 (this is the default)
14307 @item ^-nU^/NAME_CASING=UPPER_CASE^
14308 Names are in upper case
14310 @item ^-nL^/NAME_CASING=LOWER_CASE^
14311 Names are in lower case
14313 @item ^-nM^/NAME_CASING=MIXED_CASE^
14314 Names are in mixed case
14316 @cindex @option{^-ne@var{x}^/ENUM_CASING^} (@command{gnatpp})
14317 @item ^-neD^/ENUM_CASING=AS_DECLARED^
14318 Enumeration literal casing for defining occurrences are as they appear in the
14319 source file. Overrides ^-n^/NAME_CASING^ casing setting.
14321 @item ^-neU^/ENUM_CASING=UPPER_CASE^
14322 Enumeration literals are in upper case. Overrides ^-n^/NAME_CASING^ casing
14325 @item ^-neL^/ENUM_CASING=LOWER_CASE^
14326 Enumeration literals are in lower case. Overrides ^-n^/NAME_CASING^ casing
14329 @item ^-neM^/ENUM_CASING=MIXED_CASE^
14330 Enumeration literals are in mixed case. Overrides ^-n^/NAME_CASING^ casing
14333 @cindex @option{^-nt@var{x}^/TYPE_CASING^} (@command{gnatpp})
14334 @item ^-neD^/TYPE_CASING=AS_DECLARED^
14335 Names introduced by type and subtype declarations are always
14336 cased as they appear in the declaration in the source file.
14337 Overrides ^-n^/NAME_CASING^ casing setting.
14339 @item ^-ntU^/TYPE_CASING=UPPER_CASE^
14340 Names introduced by type and subtype declarations are always in
14341 upper case. Overrides ^-n^/NAME_CASING^ casing setting.
14343 @item ^-ntL^/TYPE_CASING=LOWER_CASE^
14344 Names introduced by type and subtype declarations are always in
14345 lower case. Overrides ^-n^/NAME_CASING^ casing setting.
14347 @item ^-ntM^/TYPE_CASING=MIXED_CASE^
14348 Names introduced by type and subtype declarations are always in
14349 mixed case. Overrides ^-n^/NAME_CASING^ casing setting.
14351 @item ^-nnU^/NUMBER_CASING=UPPER_CASE^
14352 Names introduced by number declarations are always in
14353 upper case. Overrides ^-n^/NAME_CASING^ casing setting.
14355 @item ^-nnL^/NUMBER_CASING=LOWER_CASE^
14356 Names introduced by number declarations are always in
14357 lower case. Overrides ^-n^/NAME_CASING^ casing setting.
14359 @item ^-nnM^/NUMBER_CASING=MIXED_CASE^
14360 Names introduced by number declarations are always in
14361 mixed case. Overrides ^-n^/NAME_CASING^ casing setting.
14363 @cindex @option{^-p@var{x}^/PRAGMA_CASING^} (@command{gnatpp})
14364 @item ^-pL^/PRAGMA_CASING=LOWER_CASE^
14365 Pragma names are lower case
14367 @item ^-pU^/PRAGMA_CASING=UPPER_CASE^
14368 Pragma names are upper case
14370 @item ^-pM^/PRAGMA_CASING=MIXED_CASE^
14371 Pragma names are mixed case (this is the default)
14373 @item ^-D@var{file}^/DICTIONARY=@var{file}^
14374 @cindex @option{^-D^/DICTIONARY^} (@command{gnatpp})
14375 Use @var{file} as a @emph{dictionary file} that defines
14376 the casing for a set of specified names,
14377 thereby overriding the effect on these names by
14378 any explicit or implicit
14379 ^-n^/NAME_CASING^ switch.
14380 To supply more than one dictionary file,
14381 use ^several @option{-D} switches^a list of files as options^.
14384 @option{gnatpp} implicitly uses a @emph{default dictionary file}
14385 to define the casing for the Ada predefined names and
14386 the names declared in the GNAT libraries.
14388 @item ^-D-^/SPECIFIC_CASING^
14389 @cindex @option{^-D-^/SPECIFIC_CASING^} (@command{gnatpp})
14390 Do not use the default dictionary file;
14391 instead, use the casing
14392 defined by a @option{^-n^/NAME_CASING^} switch and any explicit
14397 The structure of a dictionary file, and details on the conventions
14398 used in the default dictionary file, are defined in @ref{Name Casing}.
14400 The @option{^-D-^/SPECIFIC_CASING^} and
14401 @option{^-D@var{file}^/DICTIONARY=@var{file}^} switches are mutually
14405 This group of @command{gnatpp} switches controls the layout of comments and
14406 complex syntactic constructs. See @ref{Formatting Comments} for details
14410 @cindex @option{^-c@var{n}^/COMMENTS_LAYOUT^} (@command{gnatpp})
14411 @item ^-c0^/COMMENTS_LAYOUT=UNTOUCHED^
14412 All comments remain unchanged.
14414 @item ^-c1^/COMMENTS_LAYOUT=DEFAULT^
14415 GNAT-style comment line indentation.
14416 This is the default.
14418 @item ^-c3^/COMMENTS_LAYOUT=GNAT_BEGINNING^
14419 GNAT-style comment beginning.
14421 @item ^-c4^/COMMENTS_LAYOUT=REFORMAT^
14422 Fill comment blocks.
14424 @item ^-c5^/COMMENTS_LAYOUT=KEEP_SPECIAL^
14425 Keep unchanged special form comments.
14426 This is the default.
14428 @item --comments-only
14429 @cindex @option{--comments-only} @command{gnatpp}
14430 Format just the comments.
14432 @cindex @option{^--no-separate-is^/NO_SEPARATE_IS^} (@command{gnatpp})
14433 @item ^--no-separate-is^/NO_SEPARATE_IS^
14434 Do not place the keyword @code{is} on a separate line in a subprogram body in
14435 case if the spec occupies more than one line.
14437 @cindex @option{^--separate-loop-then^/SEPARATE_LOOP_THEN^} (@command{gnatpp})
14438 @item ^--separate-loop-then^/SEPARATE_LOOP_THEN^
14439 Place the keyword @code{loop} in FOR and WHILE loop statements and the
14440 keyword @code{then} in IF statements on a separate line.
14442 @cindex @option{^--no-separate-loop-then^/NO_SEPARATE_LOOP_THEN^} (@command{gnatpp})
14443 @item ^--no-separate-loop-then^/NO_SEPARATE_LOOP_THEN^
14444 Do not place the keyword @code{loop} in FOR and WHILE loop statements and the
14445 keyword @code{then} in IF statements on a separate line. This option is
14446 incompatible with @option{^--separate-loop-then^/SEPARATE_LOOP_THEN^} option.
14448 @cindex @option{^--use-on-new-line^/USE_ON_NEW_LINE^} (@command{gnatpp})
14449 @item ^--use-on-new-line^/USE_ON_NEW_LINE^
14450 Start each USE clause in a context clause from a separate line.
14452 @cindex @option{^--insert-blank-lines^/INSERT_BLANK_LINES^} (@command{gnatpp})
14453 @item ^--insert-blank-lines^/INSERT_BLANK_LINES^
14454 Insert blank lines where appropriate (between bodies and other large
14457 @cindex @option{^--preserve-blank-lines^/PRESERVE_BLANK_LINES^} (@command{gnatpp})
14458 @item ^--preserve-blank-lines^/PRESERVE_BLANK_LINES^
14459 Preserve blank lines in the input. By default, gnatpp will squeeze
14460 multiple blank lines down to one.
14466 The @option{-c} switches are compatible with one another, except that
14467 the @option{-c0} switch disables all other comment formatting
14473 For the @option{/COMMENTS_LAYOUT} qualifier,
14474 The @option{GNAT_BEGINNING}, @option{REFORMAT}, and @option{DEFAULT}
14475 options are compatible with one another.
14478 @node General Text Layout Control
14479 @subsection General Text Layout Control
14482 These switches allow control over line length and indentation.
14485 @item ^-M@var{nnn}^/LINE_LENGTH_MAX=@var{nnn}^
14486 @cindex @option{^-M^/LINE_LENGTH^} (@command{gnatpp})
14487 Maximum line length, @var{nnn} from 32@dots{}256, the default value is 79
14489 @item ^-i@var{nnn}^/INDENTATION_LEVEL=@var{nnn}^
14490 @cindex @option{^-i^/INDENTATION_LEVEL^} (@command{gnatpp})
14491 Indentation level, @var{nnn} from 1@dots{}9, the default value is 3
14493 @item ^-cl@var{nnn}^/CONTINUATION_INDENT=@var{nnn}^
14494 @cindex @option{^-cl^/CONTINUATION_INDENT^} (@command{gnatpp})
14495 Indentation level for continuation lines (relative to the line being
14496 continued), @var{nnn} from 1@dots{}9.
14498 value is one less than the (normal) indentation level, unless the
14499 indentation is set to 1 (in which case the default value for continuation
14500 line indentation is also 1)
14503 @node Other Formatting Options
14504 @subsection Other Formatting Options
14507 These switches control other formatting not listed above.
14510 @item --decimal-grouping=@var{n}
14511 @cindex @option{--decimal-grouping} @command{gnatpp}
14512 Put underscores in decimal literals (numeric literals without a base)
14513 every @var{n} characters. If a literal already has one or more
14514 underscores, it is not modified. For example, with
14515 @code{--decimal-grouping=3}, @code{1000000} will be changed to
14518 @item --based-grouping=@var{n}
14519 @cindex @option{--based-grouping} @command{gnatpp}
14520 Same as @code{--decimal-grouping}, but for based literals. For
14521 example, with @code{--based-grouping=4}, @code{16#0001FFFE#} will be
14522 changed to @code{16#0001_FFFE#}.
14524 @item ^--RM-style-spacing^/RM_STYLE_SPACING^
14525 @cindex @option{^--RM-style-spacing^/RM_STYLE_SPACING^} (@command{gnatpp})
14526 Do not insert an extra blank before various occurrences of
14527 `(' and `:'. This also turns off alignment.
14529 @item ^-ff^/FORM_FEED_AFTER_PRAGMA_PAGE^
14530 @cindex @option{^-ff^/FORM_FEED_AFTER_PRAGMA_PAGE^} (@command{gnatpp})
14531 Insert a Form Feed character after a pragma Page.
14533 @item ^--call_threshold=@var{nnn}^/MAX_ACT=@var{nnn}^
14534 @cindex @option{^--call_threshold^/MAX_ACT^} (@command{gnatpp})
14535 If the number of parameter associations is greater than @var{nnn} and if at
14536 least one association uses named notation, start each association from
14537 a new line. If @var{nnn} is 0, no check for the number of associations
14538 is made; this is the default.
14540 @item ^--par_threshold=@var{nnn}^/MAX_PAR=@var{nnn}^
14541 @cindex @option{^--par_threshold^/MAX_PAR^} (@command{gnatpp})
14542 If the number of parameter specifications is greater than @var{nnn}
14543 (or equal to @var{nnn} in case of a function), start each specification from
14544 a new line. This feature is disabled by default.
14547 @node Setting the Source Search Path
14548 @subsection Setting the Source Search Path
14551 To define the search path for the input source file, @command{gnatpp}
14552 uses the same switches as the GNAT compiler, with the same effects:
14555 @item ^-I^/SEARCH=^@var{dir}
14556 @cindex @option{^-I^/SEARCH^} (@command{gnatpp})
14558 @item ^-I-^/NOCURRENT_DIRECTORY^
14559 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gnatpp})
14561 @item ^-gnatec^/CONFIGURATION_PRAGMAS_FILE^=@var{path}
14562 @cindex @option{^-gnatec^/CONFIGURATION_PRAGMAS_FILE^} (@command{gnatpp})
14564 @item ^--RTS^/RUNTIME_SYSTEM^=@var{path}
14565 @cindex @option{^--RTS^/RUNTIME_SYSTEM^} (@command{gnatpp})
14569 @node Output File Control
14570 @subsection Output File Control
14573 By default the output is sent to a file whose name is obtained by appending
14574 the ^@file{.pp}^@file{$PP}^ suffix to the name of the input file.
14575 If the file with this name already exists, it is overwritten.
14576 Thus if the input file is @file{^my_ada_proc.adb^MY_ADA_PROC.ADB^} then
14577 @command{gnatpp} will produce @file{^my_ada_proc.adb.pp^MY_ADA_PROC.ADB$PP^}
14579 The output may be redirected by the following switches:
14582 @item ^-pipe^/STANDARD_OUTPUT^
14583 @cindex @option{^-pipe^/STANDARD_OUTPUT^} (@command{gnatpp})
14584 Send the output to @code{Standard_Output}
14586 @item ^-o @var{output_file}^/OUTPUT=@var{output_file}^
14587 @cindex @option{^-o^/OUTPUT^} (@code{gnatpp})
14588 Write the output into @var{output_file}.
14589 If @var{output_file} already exists, @command{gnatpp} terminates without
14590 reading or processing the input file.
14592 @item ^-of ^/FORCED_OUTPUT=^@var{output_file}
14593 @cindex @option{^-of^/FORCED_OUTPUT^} (@command{gnatpp})
14594 Write the output into @var{output_file}, overwriting the existing file
14595 (if one is present).
14597 @item ^-r^/REPLACE^
14598 @cindex @option{^-r^/REPLACE^} (@command{gnatpp})
14599 Replace the input source file with the reformatted output, and copy the
14600 original input source into the file whose name is obtained by appending the
14601 ^@file{.npp}^@file{$NPP}^ suffix to the name of the input file.
14602 If a file with this name already exists, @command{gnatpp} terminates without
14603 reading or processing the input file.
14605 @item ^-rf^/OVERRIDING_REPLACE^
14606 @cindex @option{^-rf^/OVERRIDING_REPLACE^} (@code{gnatpp})
14607 Like @option{^-r^/REPLACE^} except that if the file with the specified name
14608 already exists, it is overwritten.
14610 @item ^-rnb^/REPLACE_NO_BACKUP^
14611 @cindex @option{^-rnb^/REPLACE_NO_BACKUP^} (@command{gnatpp})
14612 Replace the input source file with the reformatted output without
14613 creating any backup copy of the input source.
14615 @item ^--eol=@var{xxx}^/END_OF_LINE=@var{xxx}^
14616 @cindex @option{^--eol^/END_OF_LINE^} (@code{gnatpp})
14617 Specifies the line-ending style of the reformatted output file. The @var{xxx}
14618 ^string specified with the switch^option^ may be:
14620 @item ``@option{^dos^DOS^}'' MS DOS style, lines end with CR LF characters
14621 @item ``@option{^crlf^CRLF^}''
14622 the same as @option{^dos^DOS^}
14623 @item ``@option{^unix^UNIX^}'' UNIX style, lines end with LF character
14624 @item ``@option{^lf^LF^}''
14625 the same as @option{^unix^UNIX^}
14628 @item ^-W^/RESULT_ENCODING=^@var{e}
14629 @cindex @option{^-W^/RESULT_ENCODING=^} (@command{gnatpp})
14630 Specify the wide character encoding method for the input and output files.
14631 @var{e} is one of the following:
14639 Upper half encoding
14641 @item ^s^SHIFT_JIS^
14651 Brackets encoding (default value)
14657 Options @option{^-o^/OUTPUT^} and
14658 @option{^-of^/FORCED_OUTPUT^} are allowed only if the call to gnatpp
14659 contains only one file to reformat.
14661 @option{^--eol^/END_OF_LINE^}
14663 @option{^-W^/RESULT_ENCODING^}
14664 cannot be used together
14665 with @option{^-pipe^/STANDARD_OUTPUT^} option.
14667 @node Other gnatpp Switches
14668 @subsection Other @code{gnatpp} Switches
14671 The additional @command{gnatpp} switches are defined in this subsection.
14675 @cindex @option{--version} @command{gnatpp}
14676 Display copyright and version, then exit disregarding all other options.
14679 @cindex @option{--help} @command{gnatpp}
14680 Display usage, then exit disregarding all other options.
14682 @item -P @var{file}
14683 @cindex @option{-P} @command{gnatpp}
14684 Indicates the name of the project file that describes the set of sources
14685 to be processed. The exact set of argument sources depends on other options
14686 specified; see below.
14689 @cindex @option{-U} @command{gnatpp}
14690 If a project file is specified and no argument source is explicitly
14691 specified (either directly or by means of @option{-files} option), process
14692 all the units of the closure of the argument project. Otherwise this option
14695 @item -U @var{main_unit}
14696 If a project file is specified and no argument source is explicitly
14697 specified (either directly or by means of @option{-files} option), process
14698 the closure of units rooted at @var{main_unit}. Otherwise this option
14701 @item -X@var{name}=@var{value}
14702 @cindex @option{-X} @command{gnatpp}
14703 Indicates that external variable @var{name} in the argument project
14704 has the value @var{value}. Has no effect if no project is specified as
14707 @item --pp-off=@var{xxx}
14708 @cindex @option{--pp-off} @command{gnatpp}
14709 Use @code{--xxx} as the command to turn off pretty printing, instead
14710 of the default @code{--!pp off}.
14712 @item --pp-on=@var{xxx}
14713 @cindex @option{--pp-on} @command{gnatpp}
14714 Use @code{--xxx} as the command to turn pretty printing back on, instead
14715 of the default @code{--!pp on}.
14718 @cindex @option{--pp-old} @command{gnatpp}
14719 Use the old formatting algorithms.
14721 @item ^-files @var{filename}^/FILES=@var{filename}^
14722 @cindex @option{^-files^/FILES^} (@code{gnatpp})
14723 Take the argument source files from the specified file. This file should be an
14724 ordinary text file containing file names separated by spaces or
14725 line breaks. You can use this switch more than once in the same call to
14726 @command{gnatpp}. You also can combine this switch with an explicit list of
14729 @item ^-j^/PROCESSES=^@var{n}
14730 @cindex @option{^-j^/PROCESSES^} (@command{gnatpp})
14731 Use @var{n} processes to carry out the tree creations (internal representations
14732 of the argument sources). On a multiprocessor machine this speeds up processing
14733 of big sets of argument sources. If @var{n} is 0, then the maximum number of
14734 parallel tree creations is the number of core processors on the platform.
14735 This option cannot be used together with @option{^-r^/REPLACE^},
14736 @option{^-rf^/OVERRIDING_REPLACE^} or
14737 @option{^-rnb^/REPLACE_NO_BACKUP^} option.
14739 @cindex @option{^-t^/TIME^} (@command{gnatpp})
14741 Print out execution time.
14743 @item ^-v^/VERBOSE^
14744 @cindex @option{^-v^/VERBOSE^} (@command{gnatpp})
14748 @cindex @option{^-q^/QUIET^} (@command{gnatpp})
14753 If a project file is specified and no argument source is explicitly
14754 specified (either directly or by means of @option{-files} option), and no
14755 @option{-U} is specified, then the set of processed sources is
14756 all the immediate units of the argument project.
14759 @node Formatting Rules
14760 @section Formatting Rules
14763 The following subsections show how @command{gnatpp} treats white space,
14764 comments, program layout, and name casing.
14765 They provide detailed descriptions of the switches shown above.
14768 * Disabling Pretty Printing::
14769 * White Space and Empty Lines::
14770 * Formatting Comments::
14774 @node Disabling Pretty Printing
14775 @subsection Disabling Pretty Printing
14778 Pretty printing is highly heuristic in nature, and sometimes doesn't
14779 do exactly what you want. If you wish to format a certain region of
14780 code by hand, you can turn off pretty printing in that region by
14781 surrounding it with special comments that start with @code{--!pp off}
14782 and @code{--!pp on}. The text in that region will then be reproduced
14783 verbatim in the output with no formatting.
14785 To disable pretty printing for the whole file, put @code{--!pp off} at
14786 the top, with no following @code{--!pp on}.
14788 The comments must appear on a line by themselves, with nothing
14789 preceding except spaces. The initial text of the comment must be
14790 exactly @code{--!pp off} or @code{--!pp on} (case sensitive), but may
14791 be followed by arbitrary additional text. For example:
14793 @smallexample @c ada
14795 package Interrupts is
14796 --!pp off -- turn off pretty printing so "Interrupt_Kind" lines up
14797 type Interrupt_Kind is
14798 (Asynchronous_Interrupt_Kind,
14799 Synchronous_Interrupt_Kind,
14800 Green_Interrupt_Kind);
14801 --!pp on -- reenable pretty printing
14807 You can specify different comment strings using the @code{--pp-off}
14808 and @code{--pp-on} switches. For example, if you say @code{gnatpp
14809 --pp-off=' pp-' *.ad?} then gnatpp will recognize comments of the form
14810 @code{-- pp-} instead of @code{--!pp off} for disabling pretty
14811 printing. Note that the leading @code{--} of the comment is not
14812 included in the argument to these switches.
14814 @node White Space and Empty Lines
14815 @subsection White Space and Empty Lines
14818 @command{gnatpp} does not have an option to control space characters.
14819 It will add or remove spaces according to the style illustrated by the
14820 examples in the @cite{Ada Reference Manual}.
14821 The output file will contain no lines with trailing white space.
14823 By default, a sequence of one or more blank lines in the input is
14824 converted to a single blank line in the output; multiple blank lines
14825 are squeezed down to one.
14826 The @option{^--preserve-blank-lines^/PRESERVE_BLANK_LINES^} option
14827 turns off the squeezing; each blank line in the input is copied
14829 The @option{^--insert-blank-lines^/INSERT_BLANK_LINES^} option
14830 causes additional blank lines to be inserted if not already
14831 present in the input (e.g. between bodies).
14833 @node Formatting Comments
14834 @subsection Formatting Comments
14837 Comments in Ada code are of two kinds:
14840 a @emph{whole-line comment}, which appears by itself (possibly preceded by
14841 white space) on a line
14844 an @emph{end-of-line comment}, which follows some other Ada code on
14849 A whole-line comment is indented according to the surrounding code,
14850 with some exceptions.
14851 Comments that start in column 1 are kept there.
14852 If possible, comments are not moved so far to the right that the maximum
14853 line length is exceeded.
14854 The @option{^-c0^/COMMENTS_LAYOUT=UNTOUCHED^} option
14855 turns off comment formatting.
14856 Special-form comments such as SPARK-style @code{--#...} are left alone.
14858 For an end-of-line comment, @command{gnatpp} tries to leave the same
14859 number of spaces between the end of the preceding Ada code and the
14860 beginning of the comment as appear in the original source.
14863 The @option{^-c3^/COMMENTS_LAYOUT=GNAT_BEGINNING^} switch
14864 (GNAT style comment beginning) has the following
14869 For each whole-line comment that does not end with two hyphens,
14870 @command{gnatpp} inserts spaces if necessary after the starting two hyphens
14871 to ensure that there are at least two spaces between these hyphens and the
14872 first non-blank character of the comment.
14876 The @option{^-c4^/COMMENTS_LAYOUT=REFORMAT^} switch specifies that
14877 whole-line comments that form a paragraph will be filled in typical
14878 word processor style (that is, moving words between lines to make the
14879 lines other than the last similar in length ).
14882 The @option{--comments-only} switch specifies that only the comments
14883 are formatted; the rest of the program text is left alone. The
14884 comments are formatted according to the -c3 and -c4 switches; other
14885 formatting switches are ignored. For example, @option{--comments-only
14886 -c4} means to fill comment paragraphs, and do nothing else. Likewise,
14887 @option{--comments-only -c3} ensures comments start with at least two
14888 spaces after @code{--}, and @option{--comments-only -c3 -c4} does
14889 both. If @option{--comments-only} is given without @option{-c3} or
14890 @option{-c4}, then gnatpp doesn't format anything.
14893 @subsection Name Casing
14896 @command{gnatpp} always converts the usage occurrence of a (simple) name to
14897 the same casing as the corresponding defining identifier.
14899 You control the casing for defining occurrences via the
14900 @option{^-n^/NAME_CASING^} switch.
14902 With @option{-nD} (``as declared'', which is the default),
14905 With @option{/NAME_CASING=AS_DECLARED}, which is the default,
14907 defining occurrences appear exactly as in the source file
14908 where they are declared.
14909 The other ^values for this switch^options for this qualifier^ ---
14910 @option{^-nU^UPPER_CASE^},
14911 @option{^-nL^LOWER_CASE^},
14912 @option{^-nM^MIXED_CASE^} ---
14914 ^upper, lower, or mixed case, respectively^the corresponding casing^.
14915 If @command{gnatpp} changes the casing of a defining
14916 occurrence, it analogously changes the casing of all the
14917 usage occurrences of this name.
14919 If the defining occurrence of a name is not in the source compilation unit
14920 currently being processed by @command{gnatpp}, the casing of each reference to
14921 this name is changed according to the value of the @option{^-n^/NAME_CASING^}
14922 switch (subject to the dictionary file mechanism described below).
14923 Thus @command{gnatpp} acts as though the @option{^-n^/NAME_CASING^} switch
14925 casing for the defining occurrence of the name.
14928 @option{^-a@var{x}^/ATTRIBUTE^},
14929 @option{^-k@var{x}^/KEYWORD_CASING^},
14930 @option{^-ne@var{x}^/ENUM_CASING^},
14931 @option{^-nt@var{x}^/TYPE_CASING^},
14932 @option{^-nn@var{x}^/NUMBER_CASING^}, and
14933 @option{^-p@var{x}^/PRAGMA_CASING^}
14934 allow finer-grained control over casing for
14935 attributes, keywords, enumeration literals,
14936 types, named numbers and pragmas, respectively.
14937 @option{^-nt@var{x}^/TYPE_CASING^} covers subtypes and
14938 task and protected bodies as well.
14940 Some names may need to be spelled with casing conventions that are not
14941 covered by the upper-, lower-, and mixed-case transformations.
14942 You can arrange correct casing by placing such names in a
14943 @emph{dictionary file},
14944 and then supplying a @option{^-D^/DICTIONARY^} switch.
14945 The casing of names from dictionary files overrides
14946 any @option{^-n^/NAME_CASING^} switch.
14948 To handle the casing of Ada predefined names and the names from GNAT libraries,
14949 @command{gnatpp} assumes a default dictionary file.
14950 The name of each predefined entity is spelled with the same casing as is used
14951 for the entity in the @cite{Ada Reference Manual} (usually mixed case).
14952 The name of each entity in the GNAT libraries is spelled with the same casing
14953 as is used in the declaration of that entity.
14955 The @w{@option{^-D-^/SPECIFIC_CASING^}} switch suppresses the use of
14956 the default dictionary file. Instead, the casing for predefined and
14957 GNAT-defined names will be established by the
14958 @option{^-n^/NAME_CASING^} switch or explicit dictionary files. For
14959 example, by default the names @code{Ada.Text_IO} and
14960 @code{GNAT.OS_Lib} will appear as just shown, even in the presence of
14961 a @option{^-nU^/NAME_CASING=UPPER_CASE^} switch. To ensure that even
14962 such names are rendered in uppercase, additionally supply the
14963 @w{@option{^-D-^/SPECIFIC_CASING^}} switch (or else place these names
14964 in upper case in a dictionary file).
14966 A dictionary file is a plain text file; each line in this file can be
14967 either a blank line (containing only space characters), an Ada comment
14968 line, or the specification of exactly one @emph{casing schema}.
14970 A casing schema is a string that has the following syntax:
14974 @var{casing_schema} ::= @var{identifier} | *@var{simple_identifier}*
14976 @var{simple_identifier} ::= @var{letter}@{@var{letter_or_digit}@}
14981 (See @cite{Ada Reference Manual}, Section 2.3) for the definition of the
14982 @var{identifier} lexical element and the @var{letter_or_digit} category.)
14984 The casing schema string can be followed by white space and/or an Ada-style
14985 comment; any amount of white space is allowed before the string.
14987 If a dictionary file is passed as
14989 the value of a @option{-D@var{file}} switch
14992 an option to the @option{/DICTIONARY} qualifier
14995 simple name and every identifier, @command{gnatpp} checks if the dictionary
14996 defines the casing for the name or for some of its parts (the term ``subword''
14997 is used below to denote the part of a name which is delimited by ``_'' or by
14998 the beginning or end of the word and which does not contain any ``_'' inside):
15002 if the whole name is in the dictionary, @command{gnatpp} uses for this name
15003 the casing defined by the dictionary; no subwords are checked for this word
15006 for every subword @command{gnatpp} checks if the dictionary contains the
15007 corresponding string of the form @code{*@var{simple_identifier}*},
15008 and if it does, the casing of this @var{simple_identifier} is used
15012 if the whole name does not contain any ``_'' inside, and if for this name
15013 the dictionary contains two entries - one of the form @var{identifier},
15014 and another - of the form *@var{simple_identifier}*, then the first one
15015 is applied to define the casing of this name
15018 if more than one dictionary file is passed as @command{gnatpp} switches, each
15019 dictionary adds new casing exceptions and overrides all the existing casing
15020 exceptions set by the previous dictionaries
15023 when @command{gnatpp} checks if the word or subword is in the dictionary,
15024 this check is not case sensitive
15028 For example, suppose we have the following source to reformat:
15030 @smallexample @c ada
15033 name1 : integer := 1;
15034 name4_name3_name2 : integer := 2;
15035 name2_name3_name4 : Boolean;
15038 name2_name3_name4 := name4_name3_name2 > name1;
15044 And suppose we have two dictionaries:
15061 If @command{gnatpp} is called with the following switches:
15065 @command{gnatpp -nM -D dict1 -D dict2 test.adb}
15068 @command{gnatpp test.adb /NAME_CASING=MIXED_CASE /DICTIONARY=(dict1, dict2)}
15073 then we will get the following name casing in the @command{gnatpp} output:
15075 @smallexample @c ada
15078 NAME1 : Integer := 1;
15079 Name4_NAME3_Name2 : Integer := 2;
15080 Name2_NAME3_Name4 : Boolean;
15083 Name2_NAME3_Name4 := Name4_NAME3_Name2 > NAME1;
15089 @ifclear FSFEDITION
15091 @c *********************************
15092 @node The Ada-to-XML converter gnat2xml
15093 @chapter The Ada-to-XML converter @command{gnat2xml}
15095 @cindex XML generation
15098 The @command{gnat2xml} tool is an ASIS-based utility that converts
15099 Ada source code into XML.
15102 * Switches for gnat2xml::
15104 * Structure of the XML::
15107 @node Switches for gnat2xml
15108 @section Switches for @command{gnat2xml}
15111 @command{gnat2xml} takes Ada source code as input, and produces XML
15112 that conforms to the schema.
15117 gnat2xml [options] files
15120 ``files'' are the Ada source file names.
15126 --help -- generate usage information and quit, ignoring all other options
15128 -P @file{file} -- indicates the name of the project file that describes
15129 the set of sources to be processed. The exact set of argument
15130 sources depends on other options specified, see below.
15132 -U -- if a project file is specified and no argument source is explicitly
15133 specified, process all the units of the closure of the argument project.
15134 Otherwise this option has no effect.
15136 -U @var{main_unit} -- if a project file is specified and no argument source
15137 is explicitly specified (either directly or by means of @option{-files}
15138 option), process the closure of units rooted at @var{main_unit}.
15139 Otherwise this option has no effect.
15141 -X@var{name}=@var{value} -- indicates that external variable @var{name} in
15142 the argument project has the value @var{value}. Has no effect if no
15143 project is specified as tool argument.
15145 --incremental -- incremental processing on a per-file basis. Source files are
15146 only processed if they have been modified, or if files they depend
15147 on have been modified. This is similar to the way gnatmake/gprbuild
15148 only compiles files that need to be recompiled.
15150 --output-dir=@var{dir} -- generate one .xml file for each Ada source file, in
15151 directory @file{dir}. (Default is to generate the XML to standard
15154 --compact -- debugging version, with interspersed source, and a more
15155 compact representation of "sloc". This version does not conform
15159 directories to search for dependencies
15160 You can also set the ADA_INCLUDE_PATH environment variable for this.
15164 -v -- verbose (print out the command line options, and the names of
15165 output files as they are generated).
15167 -cargs ... -- options to pass to gcc
15171 If a project file is specified and no argument source is explicitly
15172 specified, and no @option{-U} is specified, then the set of processed
15173 sources is all the immediate units of the argument project.
15178 gnat2xml -v -mxml-files *.ad[sb] -cargs -gnat2012
15182 The above will create *.xml files in the @file{xml-files} subdirectory.
15183 For example, if there is an Ada package Mumble.Dumble, whose spec and
15184 body source code lives in mumble-dumble.ads and mumble-dumble.adb,
15185 the above will produce xml-files/mumble-dumble.ads.xml and
15186 xml-files/mumble-dumble.adb.xml.
15188 @node Other Programs
15189 @section Other Programs
15192 The distribution includes two other programs that are related to
15193 @command{gnat2xml}:
15195 @command{gnat2xsd} is the schema generator, which generates the schema
15196 to standard output, based on the structure of Ada as encoded by
15197 ASIS. You don't need to run @command{gnat2xsd} in order to use
15198 @command{gnat2xml}. To generate the schema, type:
15201 gnat2xsd > ada-schema.xsd
15205 @command{gnat2xml} generates XML files that will validate against
15206 @file{ada-schema.xsd}.
15208 @command{xml2gnat} is a back-translator that translates the XML back
15209 into Ada source code. The Ada generated by @command{xml2gnat} has
15210 identical semantics to the original Ada code passed to
15211 @command{gnat2xml}. It is not textually identical, however --- for
15212 example, no attempt is made to preserve the original indentation.
15214 @node Structure of the XML
15215 @section Structure of the XML
15218 The primary documentation for the structure of the XML generated by
15219 @command{gnat2xml} is the schema (see @command{gnat2xsd} above). The
15220 following documentation gives additional details needed to understand
15221 the schema and therefore the XML.
15223 The elements listed under Defining Occurrences, Usage Occurrences, and
15224 Other Elements represent the syntactic structure of the Ada program.
15225 Element names are given in lower case, with the corresponding element
15226 type Capitalized_Like_This. The element and element type names are
15227 derived directly from the ASIS enumeration type Flat_Element_Kinds,
15228 declared in Asis.Extensions.Flat_Kinds, with the leading ``An_'' or ``A_''
15229 removed. For example, the ASIS enumeration literal
15230 An_Assignment_Statement corresponds to the XML element
15231 assignment_statement of XML type Assignment_Statement.
15233 To understand the details of the schema and the corresponding XML, it is
15234 necessary to understand the ASIS standard, as well as the GNAT-specific
15237 A defining occurrence is an identifier (or character literal or operator
15238 symbol) declared by a declaration. A usage occurrence is an identifier
15239 (or ...) that references such a declared entity. For example, in:
15242 type T is range 1..10;
15243 X, Y : constant T := 1;
15247 The first ``T'' is the defining occurrence of a type. The ``X'' is the
15248 defining occurrence of a constant, as is the ``Y'', and the second ``T'' is
15249 a usage occurrence referring to the defining occurrence of T.
15251 Each element has a 'sloc' (source location), and subelements for each
15252 syntactic subtree, reflecting the Ada grammar as implemented by ASIS.
15253 The types of subelements are as defined in the ASIS standard. For
15254 example, for the right-hand side of an assignment_statement we have
15255 the following comment in asis-statements.ads:
15258 ------------------------------------------------------------------------------
15259 -- 18.3 function Assignment_Expression
15260 ------------------------------------------------------------------------------
15262 function Assignment_Expression
15263 (Statement : Asis.Statement)
15264 return Asis.Expression;
15266 ------------------------------------------------------------------------------
15268 -- Returns the expression from the right hand side of the assignment.
15270 -- Returns Element_Kinds:
15275 The corresponding sub-element of type Assignment_Statement is:
15278 <xsd:element name="assignment_expression_q" type="Expression_Class"/>
15282 where Expression_Class is defined by an xsd:choice of all the
15283 various kinds of expression.
15285 The 'sloc' of each element indicates the starting and ending line and
15286 column numbers. Column numbers are character counts; that is, a tab
15287 counts as 1, not as however many spaces it might expand to.
15289 Subelements of type Element have names ending in ``_q'' (for ASIS
15290 ``Query''), and those of type Element_List end in ``_ql'' (``Query returning
15293 Some subelements are ``Boolean''. For example, Private_Type_Definition
15294 has has_abstract_q and has_limited_q, to indicate whether those
15295 keywords are present, as in @code{type T is abstract limited
15296 private;}. False is represented by a Nil_Element. True is represented
15297 by an element type specific to that query (for example, Abstract and
15300 The root of the tree is a Compilation_Unit, with attributes:
15304 unit_kind, unit_class, and unit_origin. These are strings that match the
15305 enumeration literals of types Unit_Kinds, Unit_Classes, and Unit_Origins
15309 unit_full_name is the full expanded name of the unit, starting from a
15310 root library unit. So for @code{package P.Q.R is ...},
15311 @code{unit_full_name="P.Q.R"}. Same for @code{separate (P.Q) package R is ...}.
15314 def_name is the same as unit_full_name for library units; for subunits,
15315 it is just the simple name.
15318 source_file is the name of the Ada source file. For example, for
15319 the spec of @code{P.Q.R}, @code{source_file="p-q-r.ads"}. This allows one to
15320 interpret the source locations --- the ``sloc'' of all elements
15321 within this Compilation_Unit refers to line and column numbers
15322 within the named file.
15326 Defining occurrences have these attributes:
15330 def_name is the simple name of the declared entity, as written in the Ada
15334 def is a unique URI of the form:
15336 ada://kind/fully/qualified/name
15340 kind indicates the kind of Ada entity being declared (see below), and
15342 fully/qualified/name, is the fully qualified name of the Ada
15343 entity, with each of ``fully'', ``qualified'', and ``name'' being
15344 mangled for uniqueness. We do not document the mangling
15345 algorithm, which is subject to change; we just guarantee that the
15346 names are unique in the face of overloading.
15349 type is the type of the declared object, or @code{null} for
15350 declarations of things other than objects.
15354 Usage occurrences have these attributes:
15358 ref_name is the same as the def_name of the corresponding defining
15359 occurrence. This attribute is not of much use, because of
15360 overloading; use ref for lookups, instead.
15363 ref is the same as the def of the corresponding defining
15368 In summary, @code{def_name} and @code{ref_name} are as in the source
15369 code of the declaration, possibly overloaded, whereas @code{def} and
15370 @code{ref} are unique-ified.
15372 Literal elements have this attribute:
15376 lit_val is the value of the literal as written in the source text,
15377 appropriately escaped (e.g. @code{"} ---> @code{"}). This applies
15378 only to numeric and string literals. Enumeration literals in Ada are
15379 not really "literals" in the usual sense; they are usage occurrences,
15380 and have ref_name and ref as described above. Note also that string
15381 literals used as operator symbols are treated as defining or usage
15382 occurrences, not as literals.
15386 Elements that can syntactically represent names and expressions (which
15387 includes usage occurrences, plus function calls and so forth) have this
15392 type. If the element represents an expression or the name of an object,
15393 'type' is the 'def' for the defining occurrence of the type of that
15394 expression or name. Names of other kinds of entities, such as package
15395 names and type names, do not have a type in Ada; these have type="null"
15400 Pragma elements have this attribute:
15404 pragma_name is the name of the pragma. For language-defined pragmas, the
15405 pragma name is redundant with the element kind (for example, an
15406 assert_pragma element necessarily has pragma_name="Assert"). However, all
15407 implementation-defined pragmas are lumped together in ASIS as a single
15408 element kind (for example, the GNAT-specific pragma Unreferenced is
15409 represented by an implementation_defined_pragma element with
15410 pragma_name="Unreferenced").
15414 Defining occurrences of formal parameters and generic formal objects have this
15419 mode indicates that the parameter is of mode 'in', 'in out', or 'out'.
15423 All elements other than Not_An_Element have this attribute:
15427 checks is a comma-separated list of run-time checks that are needed
15428 for that element. The possible checks are: do_accessibility_check,
15429 do_discriminant_check,do_division_check,do_length_check,
15430 do_overflow_check,do_range_check,do_storage_check,do_tag_check.
15434 The "kind" part of the "def" and "ref" attributes is taken from the ASIS
15435 enumeration type Flat_Declaration_Kinds, declared in
15436 Asis.Extensions.Flat_Kinds, with the leading "An_" or "A_" removed, and
15437 any trailing "_Declaration" or "_Specification" removed. Thus, the
15438 possible kinds are as follows:
15445 tagged_incomplete_type
15456 enumeration_literal
15460 generalized_iterator
15470 expression_function
15478 generic_package_renaming
15479 generic_procedure_renaming
15480 generic_function_renaming
15486 procedure_body_stub
15490 protected_body_stub
15496 package_instantiation
15497 procedure_instantiation
15498 function_instantiation
15501 formal_incomplete_type
15505 formal_package_declaration_with_box
15511 @ifclear FSFEDITION
15512 @c *********************************
15513 @node The GNAT Metrics Tool gnatmetric
15514 @chapter The GNAT Metrics Tool @command{gnatmetric}
15516 @cindex Metric tool
15519 ^The @command{gnatmetric} tool^@command{GNAT METRIC}^ is an ASIS-based utility
15520 for computing various program metrics.
15521 It takes an Ada source file as input and generates a file containing the
15522 metrics data as output. Various switches control which
15523 metrics are computed and output.
15526 * Switches for gnatmetric::
15529 To compute program metrics, @command{gnatmetric} invokes the Ada
15530 compiler and generates and uses the ASIS tree for the input source;
15531 thus the input must be legal Ada code, and the tool should have all the
15532 information needed to compile the input source. To provide this information,
15533 you may specify as a tool parameter the project file the input source belongs to
15534 (or you may call @command{gnatmetric}
15535 through the @command{gnat} driver (see @ref{The GNAT Driver and
15536 Project Files}). Another possibility is to specify the source search
15537 path and needed configuration files in @option{-cargs} section of @command{gnatmetric}
15538 call, see the description of the @command{gnatmetric} switches below.
15540 The @command{gnatmetric} command has the form
15543 @c $ gnatmetric @ovar{switches} @{@var{filename}@} @r{[}-cargs @var{gcc_switches}@r{]}
15544 @c Expanding @ovar macro inline (explanation in macro def comments)
15545 $ gnatmetric @r{[}@var{switches}@r{]} @{@var{filename}@} @r{[}-cargs @var{gcc_switches}@r{]}
15552 @var{switches} specify the metrics to compute and define the destination for
15556 Each @var{filename} is the name (including the extension) of a source
15557 file to process. ``Wildcards'' are allowed, and
15558 the file name may contain path information.
15559 If no @var{filename} is supplied, then the @var{switches} list must contain
15561 @option{-files} switch (@pxref{Other gnatmetric Switches}).
15562 Including both a @option{-files} switch and one or more
15563 @var{filename} arguments is permitted.
15566 @samp{@var{gcc_switches}} is a list of switches for
15567 @command{gcc}. They will be passed on to all compiler invocations made by
15568 @command{gnatmetric} to generate the ASIS trees. Here you can provide
15569 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
15570 and use the @option{-gnatec} switch to set the configuration file,
15571 use the @option{-gnat05} switch if sources should be compiled in
15575 @node Switches for gnatmetric
15576 @section Switches for @command{gnatmetric}
15579 The following subsections describe the various switches accepted by
15580 @command{gnatmetric}, organized by category.
15583 * Output Files Control::
15584 * Disable Metrics For Local Units::
15585 * Specifying a set of metrics to compute::
15586 * Other gnatmetric Switches::
15588 * Generate project-wide metrics::
15592 @node Output Files Control
15593 @subsection Output File Control
15594 @cindex Output file control in @command{gnatmetric}
15597 @command{gnatmetric} has two output formats. It can generate a
15598 textual (human-readable) form, and also XML. By default only textual
15599 output is generated.
15601 When generating the output in textual form, @command{gnatmetric} creates
15602 for each Ada source file a corresponding text file
15603 containing the computed metrics, except for the case when the set of metrics
15604 specified by gnatmetric parameters consists only of metrics that are computed
15605 for the whole set of analyzed sources, but not for each Ada source.
15606 By default, the name of the file containing metric information for a source
15607 is obtained by appending the ^@file{.metrix}^@file{$METRIX}^ suffix to the
15608 name of the input source file. If not otherwise specified and no project file
15609 is specified as @command{gnatmetric} option this file is placed in the same
15610 directory as where the source file is located. If @command{gnatmetric} has a
15611 project file as its parameter, it places all the generated files in the
15612 object directory of the project (or in the project source directory if the
15613 project does not define an objects directory), if @option{--subdirs} option
15614 is specified, the files are placed in the subrirectory of this directory
15615 specified by this option.
15617 All the output information generated in XML format is placed in a single
15618 file. By default the name of this file is ^@file{metrix.xml}^@file{METRIX$XML}^.
15619 If not otherwise specified and if no project file is specified
15620 as @command{gnatmetric} option this file is placed in the
15623 Some of the computed metrics are summed over the units passed to
15624 @command{gnatmetric}; for example, the total number of lines of code.
15625 By default this information is sent to @file{stdout}, but a file
15626 can be specified with the @option{-og} switch.
15628 The following switches control the @command{gnatmetric} output:
15631 @cindex @option{^-x^/XML^} (@command{gnatmetric})
15633 Generate the XML output
15635 @cindex @option{^-xs^/XSD^} (@command{gnatmetric})
15637 Generate the XML output and the XML schema file that describes the structure
15638 of the XML metric report, this schema is assigned to the XML file. The schema
15639 file has the same name as the XML output file with @file{.xml} suffix replaced
15642 @cindex @option{^-nt^/NO_TEXT^} (@command{gnatmetric})
15643 @item ^-nt^/NO_TEXT^
15644 Do not generate the output in text form (implies @option{^-x^/XML^})
15646 @cindex @option{^-d^/DIRECTORY^} (@command{gnatmetric})
15647 @item ^-d @var{output_dir}^/DIRECTORY=@var{output_dir}^
15648 Put text files with detailed metrics into @var{output_dir}
15650 @cindex @option{^-o^/SUFFIX_DETAILS^} (@command{gnatmetric})
15651 @item ^-o @var{file_suffix}^/SUFFIX_DETAILS=@var{file_suffix}^
15652 Use @var{file_suffix}, instead of ^@file{.metrix}^@file{$METRIX}^
15653 in the name of the output file.
15655 @cindex @option{^-og^/GLOBAL_OUTPUT^} (@command{gnatmetric})
15656 @item ^-og @var{file_name}^/GLOBAL_OUTPUT=@var{file_name}^
15657 Put global metrics into @var{file_name}
15659 @cindex @option{^-ox^/XML_OUTPUT^} (@command{gnatmetric})
15660 @item ^-ox @var{file_name}^/XML_OUTPUT=@var{file_name}^
15661 Put the XML output into @var{file_name} (also implies @option{^-x^/XML^})
15663 @cindex @option{^-sfn^/SHORT_SOURCE_FILE_NAME^} (@command{gnatmetric})
15664 @item ^-sfn^/SHORT_SOURCE_FILE_NAME^
15665 Use ``short'' source file names in the output. (The @command{gnatmetric}
15666 output includes the name(s) of the Ada source file(s) from which the metrics
15667 are computed. By default each name includes the absolute path. The
15668 @option{^-sfn^/SHORT_SOURCE_FILE_NAME^} switch causes @command{gnatmetric}
15669 to exclude all directory information from the file names that are output.)
15673 @node Disable Metrics For Local Units
15674 @subsection Disable Metrics For Local Units
15675 @cindex Disable Metrics For Local Units in @command{gnatmetric}
15678 @command{gnatmetric} relies on the GNAT compilation model @minus{}
15680 unit per one source file. It computes line metrics for the whole source
15681 file, and it also computes syntax
15682 and complexity metrics for the file's outermost unit.
15684 By default, @command{gnatmetric} will also compute all metrics for certain
15685 kinds of locally declared program units:
15689 subprogram (and generic subprogram) bodies;
15692 package (and generic package) specs and bodies;
15695 task object and type specifications and bodies;
15698 protected object and type specifications and bodies.
15702 These kinds of entities will be referred to as
15703 @emph{eligible local program units}, or simply @emph{eligible local units},
15704 @cindex Eligible local unit (for @command{gnatmetric})
15705 in the discussion below.
15707 Note that a subprogram declaration, generic instantiation,
15708 or renaming declaration only receives metrics
15709 computation when it appear as the outermost entity
15712 Suppression of metrics computation for eligible local units can be
15713 obtained via the following switch:
15716 @cindex @option{^-nolocal^/SUPPRESS^} (@command{gnatmetric})
15717 @item ^-nolocal^/SUPPRESS=LOCAL_DETAILS^
15718 Do not compute detailed metrics for eligible local program units
15722 @node Specifying a set of metrics to compute
15723 @subsection Specifying a set of metrics to compute
15726 By default all the metrics are computed and reported. The switches
15727 described in this subsection allow you to control, on an individual
15728 basis, whether metrics are computed and
15729 reported. If at least one positive metric
15730 switch is specified (that is, a switch that defines that a given
15731 metric or set of metrics is to be computed), then only
15732 explicitly specified metrics are reported.
15735 * Line Metrics Control::
15736 * Syntax Metrics Control::
15737 * Complexity Metrics Control::
15738 * Coupling Metrics Control::
15741 @node Line Metrics Control
15742 @subsubsection Line Metrics Control
15743 @cindex Line metrics control in @command{gnatmetric}
15746 For any (legal) source file, and for each of its
15747 eligible local program units, @command{gnatmetric} computes the following
15752 the total number of lines;
15755 the total number of code lines (i.e., non-blank lines that are not comments)
15758 the number of comment lines
15761 the number of code lines containing end-of-line comments;
15764 the comment percentage: the ratio between the number of lines that contain
15765 comments and the number of all non-blank lines, expressed as a percentage;
15768 the number of empty lines and lines containing only space characters and/or
15769 format effectors (blank lines)
15772 the average number of code lines in subprogram bodies, task bodies, entry
15773 bodies and statement sequences in package bodies (this metric is only computed
15774 across the whole set of the analyzed units)
15779 @command{gnatmetric} sums the values of the line metrics for all the
15780 files being processed and then generates the cumulative results. The tool
15781 also computes for all the files being processed the average number of code
15784 You can use the following switches to select the specific line metrics
15785 to be computed and reported.
15788 @cindex @option{^--lines@var{x}^/LINE_COUNT_METRICS^} (@command{gnatmetric})
15791 @cindex @option{--no-lines@var{x}}
15794 @item ^--lines-all^/LINE_COUNT_METRICS=ALL^
15795 Report all the line metrics
15797 @item ^--no-lines-all^/LINE_COUNT_METRICS=NONE^
15798 Do not report any of line metrics
15800 @item ^--lines^/LINE_COUNT_METRICS=ALL_LINES^
15801 Report the number of all lines
15803 @item ^--no-lines^/LINE_COUNT_METRICS=NOALL_LINES^
15804 Do not report the number of all lines
15806 @item ^--lines-code^/LINE_COUNT_METRICS=CODE_LINES^
15807 Report the number of code lines
15809 @item ^--no-lines-code^/LINE_COUNT_METRICS=NOCODE_LINES^
15810 Do not report the number of code lines
15812 @item ^--lines-comment^/LINE_COUNT_METRICS=COMMENT_LINES^
15813 Report the number of comment lines
15815 @item ^--no-lines-comment^/LINE_COUNT_METRICS=NOCOMMENT_LINES^
15816 Do not report the number of comment lines
15818 @item ^--lines-eol-comment^/LINE_COUNT_METRICS=CODE_COMMENT_LINES^
15819 Report the number of code lines containing
15820 end-of-line comments
15822 @item ^--no-lines-eol-comment^/LINE_COUNT_METRICS=NOCODE_COMMENT_LINES^
15823 Do not report the number of code lines containing
15824 end-of-line comments
15826 @item ^--lines-ratio^/LINE_COUNT_METRICS=COMMENT_PERCENTAGE^
15827 Report the comment percentage in the program text
15829 @item ^--no-lines-ratio^/LINE_COUNT_METRICS=NOCOMMENT_PERCENTAGE^
15830 Do not report the comment percentage in the program text
15832 @item ^--lines-blank^/LINE_COUNT_METRICS=BLANK_LINES^
15833 Report the number of blank lines
15835 @item ^--no-lines-blank^/LINE_COUNT_METRICS=NOBLANK_LINES^
15836 Do not report the number of blank lines
15838 @item ^--lines-average^/LINE_COUNT_METRICS=AVERAGE_BODY_LINES^
15839 Report the average number of code lines in subprogram bodies, task bodies,
15840 entry bodies and statement sequences in package bodies. The metric is computed
15841 and reported for the whole set of processed Ada sources only.
15843 @item ^--no-lines-average^/LINE_COUNT_METRICS=NOAVERAGE_BODY_LINES^
15844 Do not report the average number of code lines in subprogram bodies,
15845 task bodies, entry bodies and statement sequences in package bodies.
15849 @node Syntax Metrics Control
15850 @subsubsection Syntax Metrics Control
15851 @cindex Syntax metrics control in @command{gnatmetric}
15854 @command{gnatmetric} computes various syntactic metrics for the
15855 outermost unit and for each eligible local unit:
15858 @item LSLOC (``Logical Source Lines Of Code'')
15859 The total number of declarations and the total number of statements. Note
15860 that the definition of declarations is the one given in the reference
15864 ``Each of the following is defined to be a declaration: any basic_declaration;
15865 an enumeration_literal_specification; a discriminant_specification;
15866 a component_declaration; a loop_parameter_specification; a
15867 parameter_specification; a subprogram_body; an entry_declaration;
15868 an entry_index_specification; a choice_parameter_specification;
15869 a generic_formal_parameter_declaration.''
15871 This means for example that each enumeration literal adds one to the count,
15872 as well as each subprogram parameter.
15874 Thus the results from this metric will be significantly greater than might
15875 be expected from a naive view of counting semicolons.
15877 @item Maximal static nesting level of inner program units
15879 @cite{Ada Reference Manual}, 10.1(1), ``A program unit is either a
15880 package, a task unit, a protected unit, a
15881 protected entry, a generic unit, or an explicitly declared subprogram other
15882 than an enumeration literal.''
15884 @item Maximal nesting level of composite syntactic constructs
15885 This corresponds to the notion of the
15886 maximum nesting level in the GNAT built-in style checks
15887 (@pxref{Style Checking})
15891 For the outermost unit in the file, @command{gnatmetric} additionally computes
15892 the following metrics:
15895 @item Public subprograms
15896 This metric is computed for package specs. It is the
15897 number of subprograms and generic subprograms declared in the visible
15898 part (including the visible part of nested packages, protected objects, and
15901 @item All subprograms
15902 This metric is computed for bodies and subunits. The
15903 metric is equal to a total number of subprogram bodies in the compilation
15905 Neither generic instantiations nor renamings-as-a-body nor body stubs
15906 are counted. Any subprogram body is counted, independently of its nesting
15907 level and enclosing constructs. Generic bodies and bodies of protected
15908 subprograms are counted in the same way as ``usual'' subprogram bodies.
15911 This metric is computed for package specs and
15912 generic package declarations. It is the total number of types
15913 that can be referenced from outside this compilation unit, plus the
15914 number of types from all the visible parts of all the visible generic
15915 packages. Generic formal types are not counted. Only types, not subtypes,
15919 Along with the total number of public types, the following
15920 types are counted and reported separately:
15927 Root tagged types (abstract, non-abstract, private, non-private). Type
15928 extensions are @emph{not} counted
15931 Private types (including private extensions)
15942 This metric is computed for any compilation unit. It is equal to the total
15943 number of the declarations of different types given in the compilation unit.
15944 The private and the corresponding full type declaration are counted as one
15945 type declaration. Incomplete type declarations and generic formal types
15947 No distinction is made among different kinds of types (abstract,
15948 private etc.); the total number of types is computed and reported.
15953 By default, all the syntax metrics are computed and reported. You can use the
15954 following switches to select specific syntax metrics.
15958 @cindex @option{^--syntax@var{x}^/SYNTAX_METRICS^} (@command{gnatmetric})
15961 @cindex @option{--no-syntax@var{x}} (@command{gnatmetric})
15964 @item ^--syntax-all^/SYNTAX_METRICS=ALL^
15965 Report all the syntax metrics
15967 @item ^--no-syntax-all^/SYNTAX_METRICS=NONE^
15968 Do not report any of syntax metrics
15970 @item ^--declarations^/SYNTAX_METRICS=DECLARATIONS^
15971 Report the total number of declarations
15973 @item ^--no-declarations^/SYNTAX_METRICS=NODECLARATIONS^
15974 Do not report the total number of declarations
15976 @item ^--statements^/SYNTAX_METRICS=STATEMENTS^
15977 Report the total number of statements
15979 @item ^--no-statements^/SYNTAX_METRICS=NOSTATEMENTS^
15980 Do not report the total number of statements
15982 @item ^--public-subprograms^/SYNTAX_METRICS=PUBLIC_SUBPROGRAMS^
15983 Report the number of public subprograms in a compilation unit
15985 @item ^--no-public-subprograms^/SYNTAX_METRICS=NOPUBLIC_SUBPROGRAMS^
15986 Do not report the number of public subprograms in a compilation unit
15988 @item ^--all-subprograms^/SYNTAX_METRICS=ALL_SUBPROGRAMS^
15989 Report the number of all the subprograms in a compilation unit
15991 @item ^--no-all-subprograms^/SYNTAX_METRICS=NOALL_SUBPROGRAMS^
15992 Do not report the number of all the subprograms in a compilation unit
15994 @item ^--public-types^/SYNTAX_METRICS=PUBLIC_TYPES^
15995 Report the number of public types in a compilation unit
15997 @item ^--no-public-types^/SYNTAX_METRICS=NOPUBLIC_TYPES^
15998 Do not report the number of public types in a compilation unit
16000 @item ^--all-types^/SYNTAX_METRICS=ALL_TYPES^
16001 Report the number of all the types in a compilation unit
16003 @item ^--no-all-types^/SYNTAX_METRICS=NOALL_TYPES^
16004 Do not report the number of all the types in a compilation unit
16006 @item ^--unit-nesting^/SYNTAX_METRICS=UNIT_NESTING^
16007 Report the maximal program unit nesting level
16009 @item ^--no-unit-nesting^/SYNTAX_METRICS=UNIT_NESTING_OFF^
16010 Do not report the maximal program unit nesting level
16012 @item ^--construct-nesting^/SYNTAX_METRICS=CONSTRUCT_NESTING^
16013 Report the maximal construct nesting level
16015 @item ^--no-construct-nesting^/SYNTAX_METRICS=NOCONSTRUCT_NESTING^
16016 Do not report the maximal construct nesting level
16020 @node Complexity Metrics Control
16021 @subsubsection Complexity Metrics Control
16022 @cindex Complexity metrics control in @command{gnatmetric}
16025 For a program unit that is an executable body (a subprogram body (including
16026 generic bodies), task body, entry body or a package body containing
16027 its own statement sequence) @command{gnatmetric} computes the following
16028 complexity metrics:
16032 McCabe cyclomatic complexity;
16035 McCabe essential complexity;
16038 maximal loop nesting level;
16041 extra exit points (for subprograms);
16045 The McCabe cyclomatic complexity metric is defined
16046 in @url{http://www.mccabe.com/pdf/mccabe-nist235r.pdf}
16048 According to McCabe, both control statements and short-circuit control forms
16049 should be taken into account when computing cyclomatic complexity.
16050 For Ada 2012 we have also take into account conditional expressions
16051 and quantified expressions. For each body, we compute three metric values:
16055 the complexity introduced by control
16056 statements only, without taking into account short-circuit forms,
16059 the complexity introduced by short-circuit control forms only, and
16063 cyclomatic complexity, which is the sum of these two values.
16068 The cyclomatic complexity is also computed for Ada 2012 expression functions.
16069 An expression function cannot have statements as its components, so only one
16070 metric value is computed as a cyclomatic complexity of an expression function.
16072 The origin of cyclomatic complexity metric is the need to estimate the number
16073 of independent paths in the control flow graph that in turn gives the number
16074 of tests needed to satisfy paths coverage testing completeness criterion.
16075 Considered from the testing point of view, a static Ada @code{loop} (that is,
16076 the @code{loop} statement having static subtype in loop parameter
16077 specification) does not add to cyclomatic complexity. By providing
16078 @option{^--no-static-loop^NO_STATIC_LOOP^} option a user
16079 may specify that such loops should not be counted when computing the
16080 cyclomatic complexity metric
16082 The Ada essential complexity metric is a McCabe cyclomatic complexity metric
16083 counted for the code that is reduced by excluding all the pure structural Ada
16084 control statements. An compound statement is considered as a non-structural
16085 if it contains a @code{raise} or @code{return} statement as it subcomponent,
16086 or if it contains a @code{goto} statement that transfers the control outside
16087 the operator. A selective accept statement with @code{terminate} alternative
16088 is considered as non-structural statement. When computing this metric,
16089 @code{exit} statements are treated in the same way as @code{goto}
16090 statements unless @option{^-ne^NO_EXITS_AS_GOTOS^} option is specified.
16092 The Ada essential complexity metric defined here is intended to quantify
16093 the extent to which the software is unstructured. It is adapted from
16094 the McCabe essential complexity metric defined in
16095 @url{http://www.mccabe.com/pdf/mccabe-nist235r.pdf} but is modified to be more
16096 suitable for typical Ada usage. For example, short circuit forms
16097 are not penalized as unstructured in the Ada essential complexity metric.
16099 When computing cyclomatic and essential complexity, @command{gnatmetric} skips
16100 the code in the exception handlers and in all the nested program units. The
16101 code of assertions and predicates (that is, subprogram preconditions and
16102 postconditions, subtype predicates and type invariants) is also skipped.
16104 By default, all the complexity metrics are computed and reported.
16105 For more fine-grained control you can use
16106 the following switches:
16109 @cindex @option{^-complexity@var{x}^/COMPLEXITY_METRICS^} (@command{gnatmetric})
16112 @cindex @option{--no-complexity@var{x}}
16115 @item ^--complexity-all^/COMPLEXITY_METRICS=ALL^
16116 Report all the complexity metrics
16118 @item ^--no-complexity-all^/COMPLEXITY_METRICS=NONE^
16119 Do not report any of complexity metrics
16121 @item ^--complexity-cyclomatic^/COMPLEXITY_METRICS=CYCLOMATIC^
16122 Report the McCabe Cyclomatic Complexity
16124 @item ^--no-complexity-cyclomatic^/COMPLEXITY_METRICS=NOCYCLOMATIC^
16125 Do not report the McCabe Cyclomatic Complexity
16127 @item ^--complexity-essential^/COMPLEXITY_METRICS=ESSENTIAL^
16128 Report the Essential Complexity
16130 @item ^--no-complexity-essential^/COMPLEXITY_METRICS=NOESSENTIAL^
16131 Do not report the Essential Complexity
16133 @item ^--loop-nesting^/COMPLEXITY_METRICS=LOOP_NESTING_ON^
16134 Report maximal loop nesting level
16136 @item ^--no-loop-nesting^/COMPLEXITY_METRICS=NOLOOP_NESTING^
16137 Do not report maximal loop nesting level
16139 @item ^--complexity-average^/COMPLEXITY_METRICS=AVERAGE_COMPLEXITY^
16140 Report the average McCabe Cyclomatic Complexity for all the subprogram bodies,
16141 task bodies, entry bodies and statement sequences in package bodies.
16142 The metric is computed and reported for whole set of processed Ada sources
16145 @item ^--no-complexity-average^/COMPLEXITY_METRICS=NOAVERAGE_COMPLEXITY^
16146 Do not report the average McCabe Cyclomatic Complexity for all the subprogram
16147 bodies, task bodies, entry bodies and statement sequences in package bodies
16149 @cindex @option{^-ne^/NO_EXITS_AS_GOTOS^} (@command{gnatmetric})
16150 @item ^-ne^/NO_EXITS_AS_GOTOS^
16151 Do not consider @code{exit} statements as @code{goto}s when
16152 computing Essential Complexity
16154 @cindex @option{^--no-static-loop^/NO_STATIC_LOOP^} (@command{gnatmetric})
16155 @item ^--no-static-loop^/NO_STATIC_LOOP^
16156 Do not consider static loops when computing cyclomatic complexity
16158 @item ^--extra-exit-points^/EXTRA_EXIT_POINTS^
16159 Report the extra exit points for subprogram bodies. As an exit point, this
16160 metric counts @code{return} statements and raise statements in case when the
16161 raised exception is not handled in the same body. In case of a function this
16162 metric subtracts 1 from the number of exit points, because a function body
16163 must contain at least one @code{return} statement.
16165 @item ^--no-extra-exit-points^/NOEXTRA_EXIT_POINTS^
16166 Do not report the extra exit points for subprogram bodies
16170 @node Coupling Metrics Control
16171 @subsubsection Coupling Metrics Control
16172 @cindex Coupling metrics control in @command{gnatmetric}
16175 @cindex Coupling metrics (in @command{gnatmetric})
16176 Coupling metrics measure the dependencies between a given entity and other
16177 entities in the program. This information is useful since high coupling
16178 may signal potential issues with maintainability as the program evolves.
16180 @command{gnatmetric} computes the following coupling metrics:
16185 @emph{object-oriented coupling}, for classes in traditional object-oriented
16189 @emph{unit coupling}, for all the program units making up a program;
16192 @emph{control coupling}, reflecting dependencies between a unit and
16193 other units that contain subprograms.
16197 Two kinds of coupling metrics are computed:
16200 @item fan-out coupling (``efferent coupling''):
16201 @cindex fan-out coupling
16202 @cindex efferent coupling
16203 the number of entities the given entity depends upon. This metric
16204 reflects how the given entity depends on the changes in the
16205 ``external world''.
16207 @item fan-in coupling (``afferent'' coupling):
16208 @cindex fan-in coupling
16209 @cindex afferent coupling
16210 the number of entities that depend on a given entity.
16211 This metric reflects how the ``external world'' depends on the changes in a
16216 Object-oriented coupling metrics measure the dependencies
16217 between a given class (or a group of classes) and the other classes in the
16218 program. In this subsection the term ``class'' is used in its traditional
16219 object-oriented programming sense (an instantiable module that contains data
16220 and/or method members). A @emph{category} (of classes) is a group of closely
16221 related classes that are reused and/or modified together.
16223 A class @code{K}'s fan-out coupling is the number of classes
16224 that @code{K} depends upon.
16225 A category's fan-out coupling is the number of classes outside the
16226 category that the classes inside the category depend upon.
16228 A class @code{K}'s fan-in coupling is the number of classes
16229 that depend upon @code{K}.
16230 A category's fan-in coupling is the number of classes outside the
16231 category that depend on classes belonging to the category.
16233 Ada's object-oriented paradigm separates the instantiable entity
16234 (type) from the module (package), so the definition of the coupling
16235 metrics for Ada maps the class and class category notions
16236 onto Ada constructs.
16238 For the coupling metrics, several kinds of modules that define a tagged type
16239 or an interface type -- library packages, library generic packages, and
16240 library generic package instantiations -- are considered to be classes.
16241 A category consists of a library package (or
16242 a library generic package) that defines a tagged or an interface type,
16243 together with all its descendant (generic) packages that define tagged
16244 or interface types. Thus a
16245 category is an Ada hierarchy of library-level program units. Class
16246 coupling in Ada is referred to as ``tagged coupling'', and category coupling
16247 is referred to as ``hierarchy coupling''.
16249 For any package serving as a class, its body and subunits (if any) are
16250 considered together with its spec when computing dependencies, and coupling
16251 metrics are reported for spec units only. Dependencies between classes
16252 mean Ada semantic dependencies. For object-oriented coupling
16253 metrics, only dependencies on units treated as classes are
16256 Similarly, for unit and control coupling an entity is considered to be the
16257 conceptual construct consisting of the entity's specification, body, and
16258 any subunits (transitively).
16259 @command{gnatmetric} computes
16260 the dependencies of all these units as a whole, but
16261 metrics are only reported for spec
16262 units (or for a subprogram body unit in case if there is no
16263 separate spec for the given subprogram).
16265 For unit coupling, dependencies are computed between all kinds of program
16266 units. For control coupling, the dependencies of a given unit are limited to
16267 those units that define subprograms. Thus control fan-out coupling is reported
16268 for all units, but control fan-in coupling is only reported for units
16269 that define subprograms.
16271 The following simple example illustrates the difference between unit coupling
16272 and control coupling metrics:
16274 @smallexample @c ada
16277 function F_1 (I : Integer) return Integer;
16283 type T_2 is new Integer;
16288 package body Lib_1 is
16289 function F_1 (I : Integer) return Integer is
16297 with Lib_2; use Lib_2;
16300 function Fun (I : Integer) return Integer;
16305 with Lib_1; use Lib_1;
16306 package body Pack is
16307 function Fun (I : Integer) return Integer is
16316 If we apply @command{gnatmetric} with the @option{--coupling-all} option to
16317 these units, the result will be:
16323 Unit Lib_1 (C:\customers\662\L406-007\lib_1.ads)
16324 control fan-out coupling : 0
16325 control fan-in coupling : 1
16326 unit fan-out coupling : 0
16327 unit fan-in coupling : 1
16331 Unit Pack (C:\customers\662\L406-007\pack.ads)
16332 control fan-out coupling : 1
16333 control fan-in coupling : 0
16334 unit fan-out coupling : 2
16335 unit fan-in coupling : 0
16339 Unit Lib_2 (C:\customers\662\L406-007\lib_2.ads)
16340 control fan-out coupling : 0
16341 unit fan-out coupling : 0
16342 unit fan-in coupling : 1
16347 The result does not contain values for object-oriented
16348 coupling because none of the argument units contains a tagged type and
16349 therefore none of these units can be treated as a class.
16351 The @code{Pack} package (spec and body) depends on two
16352 units -- @code{Lib_1} @code{and Lib_2} -- and so its unit fan-out coupling
16353 is 2. Since nothing depends on it, its unit fan-in coupling is 0, as
16354 is its control fan-in coupling. Only one of the units @code{Pack} depends
16355 upon defines a subprogram, so its control fan-out coupling is 1.
16357 @code{Lib_2} depends on nothing, so its fan-out metrics are 0. It does
16358 not define any subprograms, so it has no control fan-in metric.
16359 One unit (@code{Pack}) depends on it , so its unit fan-in coupling is 1.
16361 @code{Lib_1} is similar to @code{Lib_2}, but it does define a subprogram.
16362 Its control fan-in coupling is 1 (because there is one unit
16365 When computing coupling metrics, @command{gnatmetric} counts only
16366 dependencies between units that are arguments of the @command{gnatmetric}
16367 invocation. Coupling metrics are program-wide (or project-wide) metrics, so
16368 you should invoke @command{gnatmetric} for
16369 the complete set of sources comprising your program. This can be done
16370 by invoking @command{gnatmetric} with the corresponding project file
16371 and with the @option{-U} option.
16373 By default, all the coupling metrics are disabled. You can use the following
16374 switches to specify the coupling metrics to be computed and reported:
16379 @cindex @option{--tagged-coupling@var{x}} (@command{gnatmetric})
16380 @cindex @option{--hierarchy-coupling@var{x}} (@command{gnatmetric})
16381 @cindex @option{--unit-coupling@var{x}} (@command{gnatmetric})
16382 @cindex @option{--control-coupling@var{x}} (@command{gnatmetric})
16386 @cindex @option{/COUPLING_METRICS} (@command{gnatmetric})
16389 @item ^--coupling-all^/COUPLING_METRICS=ALL^
16390 Report all the coupling metrics
16392 @item ^--tagged-coupling-out^/COUPLING_METRICS=TAGGED_OUT^
16393 Report tagged (class) fan-out coupling
16395 @item ^--tagged-coupling-in^/COUPLING_METRICS=TAGGED_IN^
16396 Report tagged (class) fan-in coupling
16398 @item ^--hierarchy-coupling-out^/COUPLING_METRICS=HIERARCHY_OUT^
16399 Report hierarchy (category) fan-out coupling
16401 @item ^--hierarchy-coupling-in^/COUPLING_METRICS=HIERARCHY_IN^
16402 Report hierarchy (category) fan-in coupling
16404 @item ^--unit-coupling-out^/COUPLING_METRICS=UNIT_OUT^
16405 Report unit fan-out coupling
16407 @item ^--unit-coupling-in^/COUPLING_METRICS=UNIT_IN^
16408 Report unit fan-in coupling
16410 @item ^--control-coupling-out^/COUPLING_METRICS=CONTROL_OUT^
16411 Report control fan-out coupling
16413 @item ^--control-coupling-in^/COUPLING_METRICS=CONTROL_IN^
16414 Report control fan-in coupling
16417 @node Other gnatmetric Switches
16418 @subsection Other @code{gnatmetric} Switches
16421 Additional @command{gnatmetric} switches are as follows:
16425 @cindex @option{--version} @command{gnatmetric}
16426 Display Copyright and version, then exit disregarding all other options.
16429 @cindex @option{--help} @command{gnatmetric}
16430 Display usage, then exit disregarding all other options.
16432 @item -P @var{file}
16433 @cindex @option{-P} @command{gnatmetric}
16434 Indicates the name of the project file that describes the set of sources
16435 to be processed. The exact set of argument sources depends on other options
16436 specified, see below.
16439 @cindex @option{-U} @command{gnatmetric}
16440 If a project file is specified and no argument source is explicitly
16441 specified (either directly or by means of @option{-files} option), process
16442 all the units of the closure of the argument project. Otherwise this option
16445 @item -U @var{main_unit}
16446 If a project file is specified and no argument source is explicitly
16447 specified (either directly or by means of @option{-files} option), process
16448 the closure of units rooted at @var{main_unit}. Otherwise this option
16451 @item -X@var{name}=@var{value}
16452 @cindex @option{-X} @command{gnatmetric}
16453 Indicates that external variable @var{name} in the argument project
16454 has the value @var{value}. Has no effect if no project is specified as
16457 @item --subdirs=@var{dir}
16458 @cindex @option{--subdirs=@var{dir}} @command{gnatmetric}
16459 Use the specified subdirectory of the project objects file (or of the
16460 project file directory if the project does not specify an object directory)
16461 for tool output files. Has no effect if no project is specified as
16462 tool argument r if @option{--no_objects_dir} is specified.
16464 @item --no_objects_dir
16465 @cindex @option{--no_objects_dir} @command{gnatmetric}
16466 Place all the result files into the current directory instead of
16467 project objects directory. This corresponds to the @command{gnatcheck}
16468 behavior when it is called with the project file from the
16469 GNAT driver. Has no effect if no project is specified.
16471 @item ^-files @var{filename}^/FILES=@var{filename}^
16472 @cindex @option{^-files^/FILES^} (@code{gnatmetric})
16473 Take the argument source files from the specified file. This file should be an
16474 ordinary text file containing file names separated by spaces or
16475 line breaks. You can use this switch more than once in the same call to
16476 @command{gnatmetric}. You also can combine this switch with
16477 an explicit list of files.
16479 @item ^-j^/PROCESSES=^@var{n}
16480 @cindex @option{^-j^/PROCESSES^} (@command{gnatmetric})
16481 Use @var{n} processes to carry out the tree creations (internal representations
16482 of the argument sources). On a multiprocessor machine this speeds up processing
16483 of big sets of argument sources. If @var{n} is 0, then the maximum number of
16484 parallel tree creations is the number of core processors on the platform.
16486 @cindex @option{^-t^/TIME^} (@command{gnatmetric})
16488 Print out execution time.
16490 @item ^-v^/VERBOSE^
16491 @cindex @option{^-v^/VERBOSE^} (@command{gnatmetric})
16493 @command{gnatmetric} generates version information and then
16494 a trace of sources being processed.
16497 @cindex @option{^-q^/QUIET^} (@command{gnatmetric})
16502 If a project file is specified and no argument source is explicitly
16503 specified (either directly or by means of @option{-files} option), and no
16504 @option{-U} is specified, then the set of processed sources is
16505 all the immediate units of the argument project.
16509 @node Generate project-wide metrics
16510 @subsection Generate project-wide metrics
16512 In order to compute metrics on all units of a given project, you can use
16513 the @command{gnat} driver along with the @option{-P} option:
16519 If the project @code{proj} depends upon other projects, you can compute
16520 the metrics on the project closure using the @option{-U} option:
16522 gnat metric -Pproj -U
16526 Finally, if not all the units are relevant to a particular main
16527 program in the project closure, you can generate metrics for the set
16528 of units needed to create a given main program (unit closure) using
16529 the @option{-U} option followed by the name of the main unit:
16531 gnat metric -Pproj -U main
16537 @c ***********************************
16538 @node File Name Krunching with gnatkr
16539 @chapter File Name Krunching with @code{gnatkr}
16543 This chapter discusses the method used by the compiler to shorten
16544 the default file names chosen for Ada units so that they do not
16545 exceed the maximum length permitted. It also describes the
16546 @code{gnatkr} utility that can be used to determine the result of
16547 applying this shortening.
16551 * Krunching Method::
16552 * Examples of gnatkr Usage::
16556 @section About @code{gnatkr}
16559 The default file naming rule in GNAT
16560 is that the file name must be derived from
16561 the unit name. The exact default rule is as follows:
16564 Take the unit name and replace all dots by hyphens.
16566 If such a replacement occurs in the
16567 second character position of a name, and the first character is
16568 ^@samp{a}, @samp{g}, @samp{s}, or @samp{i}, ^@samp{A}, @samp{G}, @samp{S}, or @samp{I},^
16569 then replace the dot by the character
16570 ^@samp{~} (tilde)^@samp{$} (dollar sign)^
16571 instead of a minus.
16573 The reason for this exception is to avoid clashes
16574 with the standard names for children of System, Ada, Interfaces,
16575 and GNAT, which use the prefixes
16576 ^@samp{s-}, @samp{a-}, @samp{i-}, and @samp{g-},^@samp{S-}, @samp{A-}, @samp{I-}, and @samp{G-},^
16579 The @option{^-gnatk^/FILE_NAME_MAX_LENGTH=^@var{nn}}
16580 switch of the compiler activates a ``krunching''
16581 circuit that limits file names to nn characters (where nn is a decimal
16582 integer). For example, using OpenVMS,
16583 where the maximum file name length is
16584 39, the value of nn is usually set to 39, but if you want to generate
16585 a set of files that would be usable if ported to a system with some
16586 different maximum file length, then a different value can be specified.
16587 The default value of 39 for OpenVMS need not be specified.
16589 The @code{gnatkr} utility can be used to determine the krunched name for
16590 a given file, when krunched to a specified maximum length.
16593 @section Using @code{gnatkr}
16596 The @code{gnatkr} command has the form
16600 @c $ gnatkr @var{name} @ovar{length}
16601 @c Expanding @ovar macro inline (explanation in macro def comments)
16602 $ gnatkr @var{name} @r{[}@var{length}@r{]}
16608 $ gnatkr @var{name} /COUNT=nn
16613 @var{name} is the uncrunched file name, derived from the name of the unit
16614 in the standard manner described in the previous section (i.e., in particular
16615 all dots are replaced by hyphens). The file name may or may not have an
16616 extension (defined as a suffix of the form period followed by arbitrary
16617 characters other than period). If an extension is present then it will
16618 be preserved in the output. For example, when krunching @file{hellofile.ads}
16619 to eight characters, the result will be hellofil.ads.
16621 Note: for compatibility with previous versions of @code{gnatkr} dots may
16622 appear in the name instead of hyphens, but the last dot will always be
16623 taken as the start of an extension. So if @code{gnatkr} is given an argument
16624 such as @file{Hello.World.adb} it will be treated exactly as if the first
16625 period had been a hyphen, and for example krunching to eight characters
16626 gives the result @file{hellworl.adb}.
16628 Note that the result is always all lower case (except on OpenVMS where it is
16629 all upper case). Characters of the other case are folded as required.
16631 @var{length} represents the length of the krunched name. The default
16632 when no argument is given is ^8^39^ characters. A length of zero stands for
16633 unlimited, in other words do not chop except for system files where the
16634 implied crunching length is always eight characters.
16637 The output is the krunched name. The output has an extension only if the
16638 original argument was a file name with an extension.
16640 @node Krunching Method
16641 @section Krunching Method
16644 The initial file name is determined by the name of the unit that the file
16645 contains. The name is formed by taking the full expanded name of the
16646 unit and replacing the separating dots with hyphens and
16647 using ^lowercase^uppercase^
16648 for all letters, except that a hyphen in the second character position is
16649 replaced by a ^tilde^dollar sign^ if the first character is
16650 ^@samp{a}, @samp{i}, @samp{g}, or @samp{s}^@samp{A}, @samp{I}, @samp{G}, or @samp{S}^.
16651 The extension is @code{.ads} for a
16652 spec and @code{.adb} for a body.
16653 Krunching does not affect the extension, but the file name is shortened to
16654 the specified length by following these rules:
16658 The name is divided into segments separated by hyphens, tildes or
16659 underscores and all hyphens, tildes, and underscores are
16660 eliminated. If this leaves the name short enough, we are done.
16663 If the name is too long, the longest segment is located (left-most
16664 if there are two of equal length), and shortened by dropping
16665 its last character. This is repeated until the name is short enough.
16667 As an example, consider the krunching of @*@file{our-strings-wide_fixed.adb}
16668 to fit the name into 8 characters as required by some operating systems.
16671 our-strings-wide_fixed 22
16672 our strings wide fixed 19
16673 our string wide fixed 18
16674 our strin wide fixed 17
16675 our stri wide fixed 16
16676 our stri wide fixe 15
16677 our str wide fixe 14
16678 our str wid fixe 13
16684 Final file name: oustwifi.adb
16688 The file names for all predefined units are always krunched to eight
16689 characters. The krunching of these predefined units uses the following
16690 special prefix replacements:
16694 replaced by @file{^a^A^-}
16697 replaced by @file{^g^G^-}
16700 replaced by @file{^i^I^-}
16703 replaced by @file{^s^S^-}
16706 These system files have a hyphen in the second character position. That
16707 is why normal user files replace such a character with a
16708 ^tilde^dollar sign^, to
16709 avoid confusion with system file names.
16711 As an example of this special rule, consider
16712 @*@file{ada-strings-wide_fixed.adb}, which gets krunched as follows:
16715 ada-strings-wide_fixed 22
16716 a- strings wide fixed 18
16717 a- string wide fixed 17
16718 a- strin wide fixed 16
16719 a- stri wide fixed 15
16720 a- stri wide fixe 14
16721 a- str wide fixe 13
16727 Final file name: a-stwifi.adb
16731 Of course no file shortening algorithm can guarantee uniqueness over all
16732 possible unit names, and if file name krunching is used then it is your
16733 responsibility to ensure that no name clashes occur. The utility
16734 program @code{gnatkr} is supplied for conveniently determining the
16735 krunched name of a file.
16737 @node Examples of gnatkr Usage
16738 @section Examples of @code{gnatkr} Usage
16745 $ gnatkr very_long_unit_name.ads --> velounna.ads
16746 $ gnatkr grandparent-parent-child.ads --> grparchi.ads
16747 $ gnatkr Grandparent.Parent.Child.ads --> grparchi.ads
16748 $ gnatkr grandparent-parent-child --> grparchi
16750 $ gnatkr very_long_unit_name.ads/count=6 --> vlunna.ads
16751 $ gnatkr very_long_unit_name.ads/count=0 --> very_long_unit_name.ads
16754 @node Preprocessing with gnatprep
16755 @chapter Preprocessing with @code{gnatprep}
16759 This chapter discusses how to use GNAT's @code{gnatprep} utility for simple
16761 Although designed for use with GNAT, @code{gnatprep} does not depend on any
16762 special GNAT features.
16763 For further discussion of conditional compilation in general, see
16764 @ref{Conditional Compilation}.
16767 * Preprocessing Symbols::
16769 * Switches for gnatprep::
16770 * Form of Definitions File::
16771 * Form of Input Text for gnatprep::
16774 @node Preprocessing Symbols
16775 @section Preprocessing Symbols
16778 Preprocessing symbols are defined in definition files and referred to in
16779 sources to be preprocessed. A Preprocessing symbol is an identifier, following
16780 normal Ada (case-insensitive) rules for its syntax, with the restriction that
16781 all characters need to be in the ASCII set (no accented letters).
16783 @node Using gnatprep
16784 @section Using @code{gnatprep}
16787 To call @code{gnatprep} use
16790 @c $ gnatprep @ovar{switches} @var{infile} @var{outfile} @ovar{deffile}
16791 @c Expanding @ovar macro inline (explanation in macro def comments)
16792 $ gnatprep @r{[}@var{switches}@r{]} @var{infile} @var{outfile} @r{[}@var{deffile}@r{]}
16799 is an optional sequence of switches as described in the next section.
16802 is the full name of the input file, which is an Ada source
16803 file containing preprocessor directives.
16806 is the full name of the output file, which is an Ada source
16807 in standard Ada form. When used with GNAT, this file name will
16808 normally have an ads or adb suffix.
16811 is the full name of a text file containing definitions of
16812 preprocessing symbols to be referenced by the preprocessor. This argument is
16813 optional, and can be replaced by the use of the @option{-D} switch.
16817 @node Switches for gnatprep
16818 @section Switches for @code{gnatprep}
16823 @item ^-b^/BLANK_LINES^
16824 @cindex @option{^-b^/BLANK_LINES^} (@command{gnatprep})
16825 Causes both preprocessor lines and the lines deleted by
16826 preprocessing to be replaced by blank lines in the output source file,
16827 preserving line numbers in the output file.
16829 @item ^-c^/COMMENTS^
16830 @cindex @option{^-c^/COMMENTS^} (@command{gnatprep})
16831 Causes both preprocessor lines and the lines deleted
16832 by preprocessing to be retained in the output source as comments marked
16833 with the special string @code{"--! "}. This option will result in line numbers
16834 being preserved in the output file.
16836 @item ^-C^/REPLACE_IN_COMMENTS^
16837 @cindex @option{^-C^/REPLACE_IN_COMMENTS^} (@command{gnatprep})
16838 Causes comments to be scanned. Normally comments are ignored by gnatprep.
16839 If this option is specified, then comments are scanned and any $symbol
16840 substitutions performed as in program text. This is particularly useful
16841 when structured comments are used (e.g., when writing programs in the
16842 SPARK dialect of Ada). Note that this switch is not available when
16843 doing integrated preprocessing (it would be useless in this context
16844 since comments are ignored by the compiler in any case).
16846 @item ^-Dsymbol=value^/ASSOCIATE="symbol=value"^
16847 @cindex @option{^-D^/ASSOCIATE^} (@command{gnatprep})
16848 Defines a new preprocessing symbol, associated with value. If no value is given
16849 on the command line, then symbol is considered to be @code{True}. This switch
16850 can be used in place of a definition file.
16854 @cindex @option{/REMOVE} (@command{gnatprep})
16855 This is the default setting which causes lines deleted by preprocessing
16856 to be entirely removed from the output file.
16859 @item ^-r^/REFERENCE^
16860 @cindex @option{^-r^/REFERENCE^} (@command{gnatprep})
16861 Causes a @code{Source_Reference} pragma to be generated that
16862 references the original input file, so that error messages will use
16863 the file name of this original file. The use of this switch implies
16864 that preprocessor lines are not to be removed from the file, so its
16865 use will force @option{^-b^/BLANK_LINES^} mode if
16866 @option{^-c^/COMMENTS^}
16867 has not been specified explicitly.
16869 Note that if the file to be preprocessed contains multiple units, then
16870 it will be necessary to @code{gnatchop} the output file from
16871 @code{gnatprep}. If a @code{Source_Reference} pragma is present
16872 in the preprocessed file, it will be respected by
16873 @code{gnatchop ^-r^/REFERENCE^}
16874 so that the final chopped files will correctly refer to the original
16875 input source file for @code{gnatprep}.
16877 @item ^-s^/SYMBOLS^
16878 @cindex @option{^-s^/SYMBOLS^} (@command{gnatprep})
16879 Causes a sorted list of symbol names and values to be
16880 listed on the standard output file.
16882 @item ^-u^/UNDEFINED^
16883 @cindex @option{^-u^/UNDEFINED^} (@command{gnatprep})
16884 Causes undefined symbols to be treated as having the value FALSE in the context
16885 of a preprocessor test. In the absence of this option, an undefined symbol in
16886 a @code{#if} or @code{#elsif} test will be treated as an error.
16892 Note: if neither @option{-b} nor @option{-c} is present,
16893 then preprocessor lines and
16894 deleted lines are completely removed from the output, unless -r is
16895 specified, in which case -b is assumed.
16898 @node Form of Definitions File
16899 @section Form of Definitions File
16902 The definitions file contains lines of the form
16909 where symbol is a preprocessing symbol, and value is one of the following:
16913 Empty, corresponding to a null substitution
16915 A string literal using normal Ada syntax
16917 Any sequence of characters from the set
16918 (letters, digits, period, underline).
16922 Comment lines may also appear in the definitions file, starting with
16923 the usual @code{--},
16924 and comments may be added to the definitions lines.
16926 @node Form of Input Text for gnatprep
16927 @section Form of Input Text for @code{gnatprep}
16930 The input text may contain preprocessor conditional inclusion lines,
16931 as well as general symbol substitution sequences.
16933 The preprocessor conditional inclusion commands have the form
16938 #if @i{expression} @r{[}then@r{]}
16940 #elsif @i{expression} @r{[}then@r{]}
16942 #elsif @i{expression} @r{[}then@r{]}
16953 In this example, @i{expression} is defined by the following grammar:
16955 @i{expression} ::= <symbol>
16956 @i{expression} ::= <symbol> = "<value>"
16957 @i{expression} ::= <symbol> = <symbol>
16958 @i{expression} ::= <symbol> = <integer>
16959 @i{expression} ::= <symbol> > <integer>
16960 @i{expression} ::= <symbol> >= <integer>
16961 @i{expression} ::= <symbol> < <integer>
16962 @i{expression} ::= <symbol> <= <integer>
16963 @i{expression} ::= <symbol> 'Defined
16964 @i{expression} ::= not @i{expression}
16965 @i{expression} ::= @i{expression} and @i{expression}
16966 @i{expression} ::= @i{expression} or @i{expression}
16967 @i{expression} ::= @i{expression} and then @i{expression}
16968 @i{expression} ::= @i{expression} or else @i{expression}
16969 @i{expression} ::= ( @i{expression} )
16972 The following restriction exists: it is not allowed to have "and" or "or"
16973 following "not" in the same expression without parentheses. For example, this
16980 This should be one of the following:
16988 For the first test (@i{expression} ::= <symbol>) the symbol must have
16989 either the value true or false, that is to say the right-hand of the
16990 symbol definition must be one of the (case-insensitive) literals
16991 @code{True} or @code{False}. If the value is true, then the
16992 corresponding lines are included, and if the value is false, they are
16995 When comparing a symbol to an integer, the integer is any non negative
16996 literal integer as defined in the Ada Reference Manual, such as 3, 16#FF# or
16997 2#11#. The symbol value must also be a non negative integer. Integer values
16998 in the range 0 .. 2**31-1 are supported.
17000 The test (@i{expression} ::= <symbol> @code{'Defined}) is true only if
17001 the symbol has been defined in the definition file or by a @option{-D}
17002 switch on the command line. Otherwise, the test is false.
17004 The equality tests are case insensitive, as are all the preprocessor lines.
17006 If the symbol referenced is not defined in the symbol definitions file,
17007 then the effect depends on whether or not switch @option{-u}
17008 is specified. If so, then the symbol is treated as if it had the value
17009 false and the test fails. If this switch is not specified, then
17010 it is an error to reference an undefined symbol. It is also an error to
17011 reference a symbol that is defined with a value other than @code{True}
17014 The use of the @code{not} operator inverts the sense of this logical test.
17015 The @code{not} operator cannot be combined with the @code{or} or @code{and}
17016 operators, without parentheses. For example, "if not X or Y then" is not
17017 allowed, but "if (not X) or Y then" and "if not (X or Y) then" are.
17019 The @code{then} keyword is optional as shown
17021 The @code{#} must be the first non-blank character on a line, but
17022 otherwise the format is free form. Spaces or tabs may appear between
17023 the @code{#} and the keyword. The keywords and the symbols are case
17024 insensitive as in normal Ada code. Comments may be used on a
17025 preprocessor line, but other than that, no other tokens may appear on a
17026 preprocessor line. Any number of @code{elsif} clauses can be present,
17027 including none at all. The @code{else} is optional, as in Ada.
17029 The @code{#} marking the start of a preprocessor line must be the first
17030 non-blank character on the line, i.e., it must be preceded only by
17031 spaces or horizontal tabs.
17033 Symbol substitution outside of preprocessor lines is obtained by using
17041 anywhere within a source line, except in a comment or within a
17042 string literal. The identifier
17043 following the @code{$} must match one of the symbols defined in the symbol
17044 definition file, and the result is to substitute the value of the
17045 symbol in place of @code{$symbol} in the output file.
17047 Note that although the substitution of strings within a string literal
17048 is not possible, it is possible to have a symbol whose defined value is
17049 a string literal. So instead of setting XYZ to @code{hello} and writing:
17052 Header : String := "$XYZ";
17056 you should set XYZ to @code{"hello"} and write:
17059 Header : String := $XYZ;
17063 and then the substitution will occur as desired.
17065 @node The GNAT Library Browser gnatls
17066 @chapter The GNAT Library Browser @code{gnatls}
17068 @cindex Library browser
17071 @code{gnatls} is a tool that outputs information about compiled
17072 units. It gives the relationship between objects, unit names and source
17073 files. It can also be used to check the source dependencies of a unit
17074 as well as various characteristics.
17076 Note: to invoke @code{gnatls} with a project file, use the @code{gnat}
17077 driver (see @ref{The GNAT Driver and Project Files}).
17081 * Switches for gnatls::
17082 * Examples of gnatls Usage::
17085 @node Running gnatls
17086 @section Running @code{gnatls}
17089 The @code{gnatls} command has the form
17092 $ gnatls switches @var{object_or_ali_file}
17096 The main argument is the list of object or @file{ali} files
17097 (@pxref{The Ada Library Information Files})
17098 for which information is requested.
17100 In normal mode, without additional option, @code{gnatls} produces a
17101 four-column listing. Each line represents information for a specific
17102 object. The first column gives the full path of the object, the second
17103 column gives the name of the principal unit in this object, the third
17104 column gives the status of the source and the fourth column gives the
17105 full path of the source representing this unit.
17106 Here is a simple example of use:
17110 ^./^[]^demo1.o demo1 DIF demo1.adb
17111 ^./^[]^demo2.o demo2 OK demo2.adb
17112 ^./^[]^hello.o h1 OK hello.adb
17113 ^./^[]^instr-child.o instr.child MOK instr-child.adb
17114 ^./^[]^instr.o instr OK instr.adb
17115 ^./^[]^tef.o tef DIF tef.adb
17116 ^./^[]^text_io_example.o text_io_example OK text_io_example.adb
17117 ^./^[]^tgef.o tgef DIF tgef.adb
17121 The first line can be interpreted as follows: the main unit which is
17123 object file @file{demo1.o} is demo1, whose main source is in
17124 @file{demo1.adb}. Furthermore, the version of the source used for the
17125 compilation of demo1 has been modified (DIF). Each source file has a status
17126 qualifier which can be:
17129 @item OK (unchanged)
17130 The version of the source file used for the compilation of the
17131 specified unit corresponds exactly to the actual source file.
17133 @item MOK (slightly modified)
17134 The version of the source file used for the compilation of the
17135 specified unit differs from the actual source file but not enough to
17136 require recompilation. If you use gnatmake with the qualifier
17137 @option{^-m (minimal recompilation)^/MINIMAL_RECOMPILATION^}, a file marked
17138 MOK will not be recompiled.
17140 @item DIF (modified)
17141 No version of the source found on the path corresponds to the source
17142 used to build this object.
17144 @item ??? (file not found)
17145 No source file was found for this unit.
17147 @item HID (hidden, unchanged version not first on PATH)
17148 The version of the source that corresponds exactly to the source used
17149 for compilation has been found on the path but it is hidden by another
17150 version of the same source that has been modified.
17154 @node Switches for gnatls
17155 @section Switches for @code{gnatls}
17158 @code{gnatls} recognizes the following switches:
17162 @cindex @option{--version} @command{gnatls}
17163 Display Copyright and version, then exit disregarding all other options.
17166 @cindex @option{--help} @command{gnatls}
17167 If @option{--version} was not used, display usage, then exit disregarding
17170 @item ^-a^/ALL_UNITS^
17171 @cindex @option{^-a^/ALL_UNITS^} (@code{gnatls})
17172 Consider all units, including those of the predefined Ada library.
17173 Especially useful with @option{^-d^/DEPENDENCIES^}.
17175 @item ^-d^/DEPENDENCIES^
17176 @cindex @option{^-d^/DEPENDENCIES^} (@code{gnatls})
17177 List sources from which specified units depend on.
17179 @item ^-h^/OUTPUT=OPTIONS^
17180 @cindex @option{^-h^/OUTPUT=OPTIONS^} (@code{gnatls})
17181 Output the list of options.
17183 @item ^-o^/OUTPUT=OBJECTS^
17184 @cindex @option{^-o^/OUTPUT=OBJECTS^} (@code{gnatls})
17185 Only output information about object files.
17187 @item ^-s^/OUTPUT=SOURCES^
17188 @cindex @option{^-s^/OUTPUT=SOURCES^} (@code{gnatls})
17189 Only output information about source files.
17191 @item ^-u^/OUTPUT=UNITS^
17192 @cindex @option{^-u^/OUTPUT=UNITS^} (@code{gnatls})
17193 Only output information about compilation units.
17195 @item ^-files^/FILES^=@var{file}
17196 @cindex @option{^-files^/FILES^} (@code{gnatls})
17197 Take as arguments the files listed in text file @var{file}.
17198 Text file @var{file} may contain empty lines that are ignored.
17199 Each nonempty line should contain the name of an existing file.
17200 Several such switches may be specified simultaneously.
17202 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
17203 @itemx ^-aI^/SOURCE_SEARCH=^@var{dir}
17204 @itemx ^-I^/SEARCH=^@var{dir}
17205 @itemx ^-I-^/NOCURRENT_DIRECTORY^
17207 @cindex @option{^-aO^/OBJECT_SEARCH^} (@code{gnatls})
17208 @cindex @option{^-aI^/SOURCE_SEARCH^} (@code{gnatls})
17209 @cindex @option{^-I^/SEARCH^} (@code{gnatls})
17210 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatls})
17211 Source path manipulation. Same meaning as the equivalent @command{gnatmake}
17212 flags (@pxref{Switches for gnatmake}).
17214 @item ^-aP^/ADD_PROJECT_SEARCH_DIR=^@var{dir}
17215 @cindex @option{^-aP^/ADD_PROJECT_SEARCH_DIR=^} (@code{gnatls})
17216 Add @var{dir} at the beginning of the project search dir.
17218 @item --RTS=@var{rts-path}
17219 @cindex @option{--RTS} (@code{gnatls})
17220 Specifies the default location of the runtime library. Same meaning as the
17221 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
17223 @item ^-v^/OUTPUT=VERBOSE^
17224 @cindex @option{^-v^/OUTPUT=VERBOSE^} (@code{gnatls})
17225 Verbose mode. Output the complete source, object and project paths. Do not use
17226 the default column layout but instead use long format giving as much as
17227 information possible on each requested units, including special
17228 characteristics such as:
17231 @item Preelaborable
17232 The unit is preelaborable in the Ada sense.
17235 No elaboration code has been produced by the compiler for this unit.
17238 The unit is pure in the Ada sense.
17240 @item Elaborate_Body
17241 The unit contains a pragma Elaborate_Body.
17244 The unit contains a pragma Remote_Types.
17246 @item Shared_Passive
17247 The unit contains a pragma Shared_Passive.
17250 This unit is part of the predefined environment and cannot be modified
17253 @item Remote_Call_Interface
17254 The unit contains a pragma Remote_Call_Interface.
17260 @node Examples of gnatls Usage
17261 @section Example of @code{gnatls} Usage
17265 Example of using the verbose switch. Note how the source and
17266 object paths are affected by the -I switch.
17269 $ gnatls -v -I.. demo1.o
17271 GNATLS 5.03w (20041123-34)
17272 Copyright 1997-2004 Free Software Foundation, Inc.
17274 Source Search Path:
17275 <Current_Directory>
17277 /home/comar/local/adainclude/
17279 Object Search Path:
17280 <Current_Directory>
17282 /home/comar/local/lib/gcc-lib/x86-linux/3.4.3/adalib/
17284 Project Search Path:
17285 <Current_Directory>
17286 /home/comar/local/lib/gnat/
17291 Kind => subprogram body
17292 Flags => No_Elab_Code
17293 Source => demo1.adb modified
17297 The following is an example of use of the dependency list.
17298 Note the use of the -s switch
17299 which gives a straight list of source files. This can be useful for
17300 building specialized scripts.
17303 $ gnatls -d demo2.o
17304 ./demo2.o demo2 OK demo2.adb
17310 $ gnatls -d -s -a demo1.o
17312 /home/comar/local/adainclude/ada.ads
17313 /home/comar/local/adainclude/a-finali.ads
17314 /home/comar/local/adainclude/a-filico.ads
17315 /home/comar/local/adainclude/a-stream.ads
17316 /home/comar/local/adainclude/a-tags.ads
17319 /home/comar/local/adainclude/gnat.ads
17320 /home/comar/local/adainclude/g-io.ads
17322 /home/comar/local/adainclude/system.ads
17323 /home/comar/local/adainclude/s-exctab.ads
17324 /home/comar/local/adainclude/s-finimp.ads
17325 /home/comar/local/adainclude/s-finroo.ads
17326 /home/comar/local/adainclude/s-secsta.ads
17327 /home/comar/local/adainclude/s-stalib.ads
17328 /home/comar/local/adainclude/s-stoele.ads
17329 /home/comar/local/adainclude/s-stratt.ads
17330 /home/comar/local/adainclude/s-tasoli.ads
17331 /home/comar/local/adainclude/s-unstyp.ads
17332 /home/comar/local/adainclude/unchconv.ads
17338 GNAT LIST /DEPENDENCIES /OUTPUT=SOURCES /ALL_UNITS DEMO1.ADB
17340 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]ada.ads
17341 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-finali.ads
17342 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-filico.ads
17343 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-stream.ads
17344 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-tags.ads
17348 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]gnat.ads
17349 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]g-io.ads
17351 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]system.ads
17352 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-exctab.ads
17353 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-finimp.ads
17354 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-finroo.ads
17355 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-secsta.ads
17356 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stalib.ads
17357 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stoele.ads
17358 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stratt.ads
17359 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-tasoli.ads
17360 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-unstyp.ads
17361 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]unchconv.ads
17365 @node Cleaning Up with gnatclean
17366 @chapter Cleaning Up with @code{gnatclean}
17368 @cindex Cleaning tool
17371 @code{gnatclean} is a tool that allows the deletion of files produced by the
17372 compiler, binder and linker, including ALI files, object files, tree files,
17373 expanded source files, library files, interface copy source files, binder
17374 generated files and executable files.
17377 * Running gnatclean::
17378 * Switches for gnatclean::
17379 @c * Examples of gnatclean Usage::
17382 @node Running gnatclean
17383 @section Running @code{gnatclean}
17386 The @code{gnatclean} command has the form:
17389 $ gnatclean switches @var{names}
17393 @var{names} is a list of source file names. Suffixes @code{.^ads^ADS^} and
17394 @code{^adb^ADB^} may be omitted. If a project file is specified using switch
17395 @code{^-P^/PROJECT_FILE=^}, then @var{names} may be completely omitted.
17398 In normal mode, @code{gnatclean} delete the files produced by the compiler and,
17399 if switch @code{^-c^/COMPILER_FILES_ONLY^} is not specified, by the binder and
17400 the linker. In informative-only mode, specified by switch
17401 @code{^-n^/NODELETE^}, the list of files that would have been deleted in
17402 normal mode is listed, but no file is actually deleted.
17404 @node Switches for gnatclean
17405 @section Switches for @code{gnatclean}
17408 @code{gnatclean} recognizes the following switches:
17412 @cindex @option{--version} @command{gnatclean}
17413 Display Copyright and version, then exit disregarding all other options.
17416 @cindex @option{--help} @command{gnatclean}
17417 If @option{--version} was not used, display usage, then exit disregarding
17420 @item ^--subdirs^/SUBDIRS^=subdir
17421 Actual object directory of each project file is the subdirectory subdir of the
17422 object directory specified or defaulted in the project file.
17424 @item ^--unchecked-shared-lib-imports^/UNCHECKED_SHARED_LIB_IMPORTS^
17425 By default, shared library projects are not allowed to import static library
17426 projects. When this switch is used on the command line, this restriction is
17429 @item ^-c^/COMPILER_FILES_ONLY^
17430 @cindex @option{^-c^/COMPILER_FILES_ONLY^} (@code{gnatclean})
17431 Only attempt to delete the files produced by the compiler, not those produced
17432 by the binder or the linker. The files that are not to be deleted are library
17433 files, interface copy files, binder generated files and executable files.
17435 @item ^-D ^/DIRECTORY_OBJECTS=^@var{dir}
17436 @cindex @option{^-D^/DIRECTORY_OBJECTS^} (@code{gnatclean})
17437 Indicate that ALI and object files should normally be found in directory
17440 @item ^-F^/FULL_PATH_IN_BRIEF_MESSAGES^
17441 @cindex @option{^-F^/FULL_PATH_IN_BRIEF_MESSAGES^} (@code{gnatclean})
17442 When using project files, if some errors or warnings are detected during
17443 parsing and verbose mode is not in effect (no use of switch
17444 ^-v^/VERBOSE^), then error lines start with the full path name of the project
17445 file, rather than its simple file name.
17448 @cindex @option{^-h^/HELP^} (@code{gnatclean})
17449 Output a message explaining the usage of @code{^gnatclean^gnatclean^}.
17451 @item ^-n^/NODELETE^
17452 @cindex @option{^-n^/NODELETE^} (@code{gnatclean})
17453 Informative-only mode. Do not delete any files. Output the list of the files
17454 that would have been deleted if this switch was not specified.
17456 @item ^-P^/PROJECT_FILE=^@var{project}
17457 @cindex @option{^-P^/PROJECT_FILE^} (@code{gnatclean})
17458 Use project file @var{project}. Only one such switch can be used.
17459 When cleaning a project file, the files produced by the compilation of the
17460 immediate sources or inherited sources of the project files are to be
17461 deleted. This is not depending on the presence or not of executable names
17462 on the command line.
17465 @cindex @option{^-q^/QUIET^} (@code{gnatclean})
17466 Quiet output. If there are no errors, do not output anything, except in
17467 verbose mode (switch ^-v^/VERBOSE^) or in informative-only mode
17468 (switch ^-n^/NODELETE^).
17470 @item ^-r^/RECURSIVE^
17471 @cindex @option{^-r^/RECURSIVE^} (@code{gnatclean})
17472 When a project file is specified (using switch ^-P^/PROJECT_FILE=^),
17473 clean all imported and extended project files, recursively. If this switch
17474 is not specified, only the files related to the main project file are to be
17475 deleted. This switch has no effect if no project file is specified.
17477 @item ^-v^/VERBOSE^
17478 @cindex @option{^-v^/VERBOSE^} (@code{gnatclean})
17481 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
17482 @cindex @option{^-vP^/MESSAGES_PROJECT_FILE^} (@code{gnatclean})
17483 Indicates the verbosity of the parsing of GNAT project files.
17484 @xref{Switches Related to Project Files}.
17486 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
17487 @cindex @option{^-X^/EXTERNAL_REFERENCE^} (@code{gnatclean})
17488 Indicates that external variable @var{name} has the value @var{value}.
17489 The Project Manager will use this value for occurrences of
17490 @code{external(name)} when parsing the project file.
17491 @xref{Switches Related to Project Files}.
17493 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
17494 @cindex @option{^-aO^/OBJECT_SEARCH^} (@code{gnatclean})
17495 When searching for ALI and object files, look in directory
17498 @item ^-I^/SEARCH=^@var{dir}
17499 @cindex @option{^-I^/SEARCH^} (@code{gnatclean})
17500 Equivalent to @option{^-aO^/OBJECT_SEARCH=^@var{dir}}.
17502 @item ^-I-^/NOCURRENT_DIRECTORY^
17503 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatclean})
17504 @cindex Source files, suppressing search
17505 Do not look for ALI or object files in the directory
17506 where @code{gnatclean} was invoked.
17510 @c @node Examples of gnatclean Usage
17511 @c @section Examples of @code{gnatclean} Usage
17514 @node GNAT and Libraries
17515 @chapter GNAT and Libraries
17516 @cindex Library, building, installing, using
17519 This chapter describes how to build and use libraries with GNAT, and also shows
17520 how to recompile the GNAT run-time library. You should be familiar with the
17521 Project Manager facility (@pxref{GNAT Project Manager}) before reading this
17525 * Introduction to Libraries in GNAT::
17526 * General Ada Libraries::
17527 * Stand-alone Ada Libraries::
17528 * Rebuilding the GNAT Run-Time Library::
17531 @node Introduction to Libraries in GNAT
17532 @section Introduction to Libraries in GNAT
17535 A library is, conceptually, a collection of objects which does not have its
17536 own main thread of execution, but rather provides certain services to the
17537 applications that use it. A library can be either statically linked with the
17538 application, in which case its code is directly included in the application,
17539 or, on platforms that support it, be dynamically linked, in which case
17540 its code is shared by all applications making use of this library.
17542 GNAT supports both types of libraries.
17543 In the static case, the compiled code can be provided in different ways. The
17544 simplest approach is to provide directly the set of objects resulting from
17545 compilation of the library source files. Alternatively, you can group the
17546 objects into an archive using whatever commands are provided by the operating
17547 system. For the latter case, the objects are grouped into a shared library.
17549 In the GNAT environment, a library has three types of components:
17555 @xref{The Ada Library Information Files}.
17557 Object files, an archive or a shared library.
17561 A GNAT library may expose all its source files, which is useful for
17562 documentation purposes. Alternatively, it may expose only the units needed by
17563 an external user to make use of the library. That is to say, the specs
17564 reflecting the library services along with all the units needed to compile
17565 those specs, which can include generic bodies or any body implementing an
17566 inlined routine. In the case of @emph{stand-alone libraries} those exposed
17567 units are called @emph{interface units} (@pxref{Stand-alone Ada Libraries}).
17569 All compilation units comprising an application, including those in a library,
17570 need to be elaborated in an order partially defined by Ada's semantics. GNAT
17571 computes the elaboration order from the @file{ALI} files and this is why they
17572 constitute a mandatory part of GNAT libraries.
17573 @emph{Stand-alone libraries} are the exception to this rule because a specific
17574 library elaboration routine is produced independently of the application(s)
17577 @node General Ada Libraries
17578 @section General Ada Libraries
17581 * Building a library::
17582 * Installing a library::
17583 * Using a library::
17586 @node Building a library
17587 @subsection Building a library
17590 The easiest way to build a library is to use the Project Manager,
17591 which supports a special type of project called a @emph{Library Project}
17592 (@pxref{Library Projects}).
17594 A project is considered a library project, when two project-level attributes
17595 are defined in it: @code{Library_Name} and @code{Library_Dir}. In order to
17596 control different aspects of library configuration, additional optional
17597 project-level attributes can be specified:
17600 This attribute controls whether the library is to be static or dynamic
17602 @item Library_Version
17603 This attribute specifies the library version; this value is used
17604 during dynamic linking of shared libraries to determine if the currently
17605 installed versions of the binaries are compatible.
17607 @item Library_Options
17609 These attributes specify additional low-level options to be used during
17610 library generation, and redefine the actual application used to generate
17615 The GNAT Project Manager takes full care of the library maintenance task,
17616 including recompilation of the source files for which objects do not exist
17617 or are not up to date, assembly of the library archive, and installation of
17618 the library (i.e., copying associated source, object and @file{ALI} files
17619 to the specified location).
17621 Here is a simple library project file:
17622 @smallexample @c ada
17624 for Source_Dirs use ("src1", "src2");
17625 for Object_Dir use "obj";
17626 for Library_Name use "mylib";
17627 for Library_Dir use "lib";
17628 for Library_Kind use "dynamic";
17633 and the compilation command to build and install the library:
17635 @smallexample @c ada
17636 $ gnatmake -Pmy_lib
17640 It is not entirely trivial to perform manually all the steps required to
17641 produce a library. We recommend that you use the GNAT Project Manager
17642 for this task. In special cases where this is not desired, the necessary
17643 steps are discussed below.
17645 There are various possibilities for compiling the units that make up the
17646 library: for example with a Makefile (@pxref{Using the GNU make Utility}) or
17647 with a conventional script. For simple libraries, it is also possible to create
17648 a dummy main program which depends upon all the packages that comprise the
17649 interface of the library. This dummy main program can then be given to
17650 @command{gnatmake}, which will ensure that all necessary objects are built.
17652 After this task is accomplished, you should follow the standard procedure
17653 of the underlying operating system to produce the static or shared library.
17655 Here is an example of such a dummy program:
17656 @smallexample @c ada
17658 with My_Lib.Service1;
17659 with My_Lib.Service2;
17660 with My_Lib.Service3;
17661 procedure My_Lib_Dummy is
17669 Here are the generic commands that will build an archive or a shared library.
17672 # compiling the library
17673 $ gnatmake -c my_lib_dummy.adb
17675 # we don't need the dummy object itself
17676 $ rm my_lib_dummy.o my_lib_dummy.ali
17678 # create an archive with the remaining objects
17679 $ ar rc libmy_lib.a *.o
17680 # some systems may require "ranlib" to be run as well
17682 # or create a shared library
17683 $ gcc -shared -o libmy_lib.so *.o
17684 # some systems may require the code to have been compiled with -fPIC
17686 # remove the object files that are now in the library
17689 # Make the ALI files read-only so that gnatmake will not try to
17690 # regenerate the objects that are in the library
17695 Please note that the library must have a name of the form @file{lib@var{xxx}.a}
17696 or @file{lib@var{xxx}.so} (or @file{lib@var{xxx}.dll} on Windows) in order to
17697 be accessed by the directive @option{-l@var{xxx}} at link time.
17699 @node Installing a library
17700 @subsection Installing a library
17701 @cindex @code{ADA_PROJECT_PATH}
17702 @cindex @code{GPR_PROJECT_PATH}
17705 If you use project files, library installation is part of the library build
17706 process (@pxref{Installing a library with project files}).
17708 When project files are not an option, it is also possible, but not recommended,
17709 to install the library so that the sources needed to use the library are on the
17710 Ada source path and the ALI files & libraries be on the Ada Object path (see
17711 @ref{Search Paths and the Run-Time Library (RTL)}. Alternatively, the system
17712 administrator can place general-purpose libraries in the default compiler
17713 paths, by specifying the libraries' location in the configuration files
17714 @file{ada_source_path} and @file{ada_object_path}. These configuration files
17715 must be located in the GNAT installation tree at the same place as the gcc spec
17716 file. The location of the gcc spec file can be determined as follows:
17722 The configuration files mentioned above have a simple format: each line
17723 must contain one unique directory name.
17724 Those names are added to the corresponding path
17725 in their order of appearance in the file. The names can be either absolute
17726 or relative; in the latter case, they are relative to where theses files
17729 The files @file{ada_source_path} and @file{ada_object_path} might not be
17731 GNAT installation, in which case, GNAT will look for its run-time library in
17732 the directories @file{adainclude} (for the sources) and @file{adalib} (for the
17733 objects and @file{ALI} files). When the files exist, the compiler does not
17734 look in @file{adainclude} and @file{adalib}, and thus the
17735 @file{ada_source_path} file
17736 must contain the location for the GNAT run-time sources (which can simply
17737 be @file{adainclude}). In the same way, the @file{ada_object_path} file must
17738 contain the location for the GNAT run-time objects (which can simply
17741 You can also specify a new default path to the run-time library at compilation
17742 time with the switch @option{--RTS=rts-path}. You can thus choose / change
17743 the run-time library you want your program to be compiled with. This switch is
17744 recognized by @command{gcc}, @command{gnatmake}, @command{gnatbind},
17745 @command{gnatls}, @command{gnatfind} and @command{gnatxref}.
17747 It is possible to install a library before or after the standard GNAT
17748 library, by reordering the lines in the configuration files. In general, a
17749 library must be installed before the GNAT library if it redefines
17752 @node Using a library
17753 @subsection Using a library
17755 @noindent Once again, the project facility greatly simplifies the use of
17756 libraries. In this context, using a library is just a matter of adding a
17757 @code{with} clause in the user project. For instance, to make use of the
17758 library @code{My_Lib} shown in examples in earlier sections, you can
17761 @smallexample @c projectfile
17768 Even if you have a third-party, non-Ada library, you can still use GNAT's
17769 Project Manager facility to provide a wrapper for it. For example, the
17770 following project, when @code{with}ed by your main project, will link with the
17771 third-party library @file{liba.a}:
17773 @smallexample @c projectfile
17776 for Externally_Built use "true";
17777 for Source_Files use ();
17778 for Library_Dir use "lib";
17779 for Library_Name use "a";
17780 for Library_Kind use "static";
17784 This is an alternative to the use of @code{pragma Linker_Options}. It is
17785 especially interesting in the context of systems with several interdependent
17786 static libraries where finding a proper linker order is not easy and best be
17787 left to the tools having visibility over project dependence information.
17790 In order to use an Ada library manually, you need to make sure that this
17791 library is on both your source and object path
17792 (see @ref{Search Paths and the Run-Time Library (RTL)}
17793 and @ref{Search Paths for gnatbind}). Furthermore, when the objects are grouped
17794 in an archive or a shared library, you need to specify the desired
17795 library at link time.
17797 For example, you can use the library @file{mylib} installed in
17798 @file{/dir/my_lib_src} and @file{/dir/my_lib_obj} with the following commands:
17801 $ gnatmake -aI/dir/my_lib_src -aO/dir/my_lib_obj my_appl \
17806 This can be expressed more simply:
17811 when the following conditions are met:
17814 @file{/dir/my_lib_src} has been added by the user to the environment
17815 variable @env{ADA_INCLUDE_PATH}, or by the administrator to the file
17816 @file{ada_source_path}
17818 @file{/dir/my_lib_obj} has been added by the user to the environment
17819 variable @env{ADA_OBJECTS_PATH}, or by the administrator to the file
17820 @file{ada_object_path}
17822 a pragma @code{Linker_Options} has been added to one of the sources.
17825 @smallexample @c ada
17826 pragma Linker_Options ("-lmy_lib");
17830 @node Stand-alone Ada Libraries
17831 @section Stand-alone Ada Libraries
17832 @cindex Stand-alone library, building, using
17835 * Introduction to Stand-alone Libraries::
17836 * Building a Stand-alone Library::
17837 * Creating a Stand-alone Library to be used in a non-Ada context::
17838 * Restrictions in Stand-alone Libraries::
17841 @node Introduction to Stand-alone Libraries
17842 @subsection Introduction to Stand-alone Libraries
17845 A Stand-alone Library (abbreviated ``SAL'') is a library that contains the
17847 elaborate the Ada units that are included in the library. In contrast with
17848 an ordinary library, which consists of all sources, objects and @file{ALI}
17850 library, a SAL may specify a restricted subset of compilation units
17851 to serve as a library interface. In this case, the fully
17852 self-sufficient set of files will normally consist of an objects
17853 archive, the sources of interface units' specs, and the @file{ALI}
17854 files of interface units.
17855 If an interface spec contains a generic unit or an inlined subprogram,
17857 source must also be provided; if the units that must be provided in the source
17858 form depend on other units, the source and @file{ALI} files of those must
17861 The main purpose of a SAL is to minimize the recompilation overhead of client
17862 applications when a new version of the library is installed. Specifically,
17863 if the interface sources have not changed, client applications do not need to
17864 be recompiled. If, furthermore, a SAL is provided in the shared form and its
17865 version, controlled by @code{Library_Version} attribute, is not changed,
17866 then the clients do not need to be relinked.
17868 SALs also allow the library providers to minimize the amount of library source
17869 text exposed to the clients. Such ``information hiding'' might be useful or
17870 necessary for various reasons.
17872 Stand-alone libraries are also well suited to be used in an executable whose
17873 main routine is not written in Ada.
17875 @node Building a Stand-alone Library
17876 @subsection Building a Stand-alone Library
17879 GNAT's Project facility provides a simple way of building and installing
17880 stand-alone libraries; see @ref{Stand-alone Library Projects}.
17881 To be a Stand-alone Library Project, in addition to the two attributes
17882 that make a project a Library Project (@code{Library_Name} and
17883 @code{Library_Dir}; see @ref{Library Projects}), the attribute
17884 @code{Library_Interface} must be defined. For example:
17886 @smallexample @c projectfile
17888 for Library_Dir use "lib_dir";
17889 for Library_Name use "dummy";
17890 for Library_Interface use ("int1", "int1.child");
17895 Attribute @code{Library_Interface} has a non-empty string list value,
17896 each string in the list designating a unit contained in an immediate source
17897 of the project file.
17899 When a Stand-alone Library is built, first the binder is invoked to build
17900 a package whose name depends on the library name
17901 (@file{^b~dummy.ads/b^B$DUMMY.ADS/B^} in the example above).
17902 This binder-generated package includes initialization and
17903 finalization procedures whose
17904 names depend on the library name (@code{dummyinit} and @code{dummyfinal}
17906 above). The object corresponding to this package is included in the library.
17908 You must ensure timely (e.g., prior to any use of interfaces in the SAL)
17909 calling of these procedures if a static SAL is built, or if a shared SAL
17911 with the project-level attribute @code{Library_Auto_Init} set to
17914 For a Stand-Alone Library, only the @file{ALI} files of the Interface Units
17915 (those that are listed in attribute @code{Library_Interface}) are copied to
17916 the Library Directory. As a consequence, only the Interface Units may be
17917 imported from Ada units outside of the library. If other units are imported,
17918 the binding phase will fail.
17921 It is also possible to build an encapsulated library where not only
17922 the code to elaborate and finalize the library is embedded but also
17923 ensuring that the library is linked only against static
17924 libraries. So an encapsulated library only depends on system
17925 libraries, all other code, including the GNAT runtime, is embedded. To
17926 build an encapsulated library the attribute
17927 @code{Library_Standalone} must be set to @code{encapsulated}:
17929 @smallexample @c projectfile
17931 for Library_Dir use "lib_dir";
17932 for Library_Name use "dummy";
17933 for Library_Kind use "dynamic";
17934 for Library_Interface use ("int1", "int1.child");
17935 for Library_Standalone use "encapsulated";
17940 The default value for this attribute is @code{standard} in which case
17941 a stand-alone library is built.
17943 The attribute @code{Library_Src_Dir} may be specified for a
17944 Stand-Alone Library. @code{Library_Src_Dir} is a simple attribute that has a
17945 single string value. Its value must be the path (absolute or relative to the
17946 project directory) of an existing directory. This directory cannot be the
17947 object directory or one of the source directories, but it can be the same as
17948 the library directory. The sources of the Interface
17949 Units of the library that are needed by an Ada client of the library will be
17950 copied to the designated directory, called the Interface Copy directory.
17951 These sources include the specs of the Interface Units, but they may also
17952 include bodies and subunits, when pragmas @code{Inline} or @code{Inline_Always}
17953 are used, or when there is a generic unit in the spec. Before the sources
17954 are copied to the Interface Copy directory, an attempt is made to delete all
17955 files in the Interface Copy directory.
17957 Building stand-alone libraries by hand is somewhat tedious, but for those
17958 occasions when it is necessary here are the steps that you need to perform:
17961 Compile all library sources.
17964 Invoke the binder with the switch @option{-n} (No Ada main program),
17965 with all the @file{ALI} files of the interfaces, and
17966 with the switch @option{-L} to give specific names to the @code{init}
17967 and @code{final} procedures. For example:
17969 gnatbind -n int1.ali int2.ali -Lsal1
17973 Compile the binder generated file:
17979 Link the dynamic library with all the necessary object files,
17980 indicating to the linker the names of the @code{init} (and possibly
17981 @code{final}) procedures for automatic initialization (and finalization).
17982 The built library should be placed in a directory different from
17983 the object directory.
17986 Copy the @code{ALI} files of the interface to the library directory,
17987 add in this copy an indication that it is an interface to a SAL
17988 (i.e., add a word @option{SL} on the line in the @file{ALI} file that starts
17989 with letter ``P'') and make the modified copy of the @file{ALI} file
17994 Using SALs is not different from using other libraries
17995 (see @ref{Using a library}).
17997 @node Creating a Stand-alone Library to be used in a non-Ada context
17998 @subsection Creating a Stand-alone Library to be used in a non-Ada context
18001 It is easy to adapt the SAL build procedure discussed above for use of a SAL in
18004 The only extra step required is to ensure that library interface subprograms
18005 are compatible with the main program, by means of @code{pragma Export}
18006 or @code{pragma Convention}.
18008 Here is an example of simple library interface for use with C main program:
18010 @smallexample @c ada
18011 package My_Package is
18013 procedure Do_Something;
18014 pragma Export (C, Do_Something, "do_something");
18016 procedure Do_Something_Else;
18017 pragma Export (C, Do_Something_Else, "do_something_else");
18023 On the foreign language side, you must provide a ``foreign'' view of the
18024 library interface; remember that it should contain elaboration routines in
18025 addition to interface subprograms.
18027 The example below shows the content of @code{mylib_interface.h} (note
18028 that there is no rule for the naming of this file, any name can be used)
18030 /* the library elaboration procedure */
18031 extern void mylibinit (void);
18033 /* the library finalization procedure */
18034 extern void mylibfinal (void);
18036 /* the interface exported by the library */
18037 extern void do_something (void);
18038 extern void do_something_else (void);
18042 Libraries built as explained above can be used from any program, provided
18043 that the elaboration procedures (named @code{mylibinit} in the previous
18044 example) are called before the library services are used. Any number of
18045 libraries can be used simultaneously, as long as the elaboration
18046 procedure of each library is called.
18048 Below is an example of a C program that uses the @code{mylib} library.
18051 #include "mylib_interface.h"
18056 /* First, elaborate the library before using it */
18059 /* Main program, using the library exported entities */
18061 do_something_else ();
18063 /* Library finalization at the end of the program */
18070 Note that invoking any library finalization procedure generated by
18071 @code{gnatbind} shuts down the Ada run-time environment.
18073 finalization of all Ada libraries must be performed at the end of the program.
18074 No call to these libraries or to the Ada run-time library should be made
18075 after the finalization phase.
18077 @node Restrictions in Stand-alone Libraries
18078 @subsection Restrictions in Stand-alone Libraries
18081 The pragmas listed below should be used with caution inside libraries,
18082 as they can create incompatibilities with other Ada libraries:
18084 @item pragma @code{Locking_Policy}
18085 @item pragma @code{Partition_Elaboration_Policy}
18086 @item pragma @code{Queuing_Policy}
18087 @item pragma @code{Task_Dispatching_Policy}
18088 @item pragma @code{Unreserve_All_Interrupts}
18092 When using a library that contains such pragmas, the user must make sure
18093 that all libraries use the same pragmas with the same values. Otherwise,
18094 @code{Program_Error} will
18095 be raised during the elaboration of the conflicting
18096 libraries. The usage of these pragmas and its consequences for the user
18097 should therefore be well documented.
18099 Similarly, the traceback in the exception occurrence mechanism should be
18100 enabled or disabled in a consistent manner across all libraries.
18101 Otherwise, Program_Error will be raised during the elaboration of the
18102 conflicting libraries.
18104 If the @code{Version} or @code{Body_Version}
18105 attributes are used inside a library, then you need to
18106 perform a @code{gnatbind} step that specifies all @file{ALI} files in all
18107 libraries, so that version identifiers can be properly computed.
18108 In practice these attributes are rarely used, so this is unlikely
18109 to be a consideration.
18111 @node Rebuilding the GNAT Run-Time Library
18112 @section Rebuilding the GNAT Run-Time Library
18113 @cindex GNAT Run-Time Library, rebuilding
18114 @cindex Building the GNAT Run-Time Library
18115 @cindex Rebuilding the GNAT Run-Time Library
18116 @cindex Run-Time Library, rebuilding
18119 It may be useful to recompile the GNAT library in various contexts, the
18120 most important one being the use of partition-wide configuration pragmas
18121 such as @code{Normalize_Scalars}. A special Makefile called
18122 @code{Makefile.adalib} is provided to that effect and can be found in
18123 the directory containing the GNAT library. The location of this
18124 directory depends on the way the GNAT environment has been installed and can
18125 be determined by means of the command:
18132 The last entry in the object search path usually contains the
18133 gnat library. This Makefile contains its own documentation and in
18134 particular the set of instructions needed to rebuild a new library and
18137 @node Using the GNU make Utility
18138 @chapter Using the GNU @code{make} Utility
18142 This chapter offers some examples of makefiles that solve specific
18143 problems. It does not explain how to write a makefile (@pxref{Top,, GNU
18144 make, make, GNU @code{make}}), nor does it try to replace the
18145 @command{gnatmake} utility (@pxref{The GNAT Make Program gnatmake}).
18147 All the examples in this section are specific to the GNU version of
18148 make. Although @command{make} is a standard utility, and the basic language
18149 is the same, these examples use some advanced features found only in
18153 * Using gnatmake in a Makefile::
18154 * Automatically Creating a List of Directories::
18155 * Generating the Command Line Switches::
18156 * Overcoming Command Line Length Limits::
18159 @node Using gnatmake in a Makefile
18160 @section Using gnatmake in a Makefile
18165 Complex project organizations can be handled in a very powerful way by
18166 using GNU make combined with gnatmake. For instance, here is a Makefile
18167 which allows you to build each subsystem of a big project into a separate
18168 shared library. Such a makefile allows you to significantly reduce the link
18169 time of very big applications while maintaining full coherence at
18170 each step of the build process.
18172 The list of dependencies are handled automatically by
18173 @command{gnatmake}. The Makefile is simply used to call gnatmake in each of
18174 the appropriate directories.
18176 Note that you should also read the example on how to automatically
18177 create the list of directories
18178 (@pxref{Automatically Creating a List of Directories})
18179 which might help you in case your project has a lot of subdirectories.
18184 @font@heightrm=cmr8
18187 ## This Makefile is intended to be used with the following directory
18189 ## - The sources are split into a series of csc (computer software components)
18190 ## Each of these csc is put in its own directory.
18191 ## Their name are referenced by the directory names.
18192 ## They will be compiled into shared library (although this would also work
18193 ## with static libraries
18194 ## - The main program (and possibly other packages that do not belong to any
18195 ## csc is put in the top level directory (where the Makefile is).
18196 ## toplevel_dir __ first_csc (sources) __ lib (will contain the library)
18197 ## \_ second_csc (sources) __ lib (will contain the library)
18199 ## Although this Makefile is build for shared library, it is easy to modify
18200 ## to build partial link objects instead (modify the lines with -shared and
18203 ## With this makefile, you can change any file in the system or add any new
18204 ## file, and everything will be recompiled correctly (only the relevant shared
18205 ## objects will be recompiled, and the main program will be re-linked).
18207 # The list of computer software component for your project. This might be
18208 # generated automatically.
18211 # Name of the main program (no extension)
18214 # If we need to build objects with -fPIC, uncomment the following line
18217 # The following variable should give the directory containing libgnat.so
18218 # You can get this directory through 'gnatls -v'. This is usually the last
18219 # directory in the Object_Path.
18222 # The directories for the libraries
18223 # (This macro expands the list of CSC to the list of shared libraries, you
18224 # could simply use the expanded form:
18225 # LIB_DIR=aa/lib/libaa.so bb/lib/libbb.so cc/lib/libcc.so
18226 LIB_DIR=$@{foreach dir,$@{CSC_LIST@},$@{dir@}/lib/lib$@{dir@}.so@}
18228 $@{MAIN@}: objects $@{LIB_DIR@}
18229 gnatbind $@{MAIN@} $@{CSC_LIST:%=-aO%/lib@} -shared
18230 gnatlink $@{MAIN@} $@{CSC_LIST:%=-l%@}
18233 # recompile the sources
18234 gnatmake -c -i $@{MAIN@}.adb $@{NEED_FPIC@} $@{CSC_LIST:%=-I%@}
18236 # Note: In a future version of GNAT, the following commands will be simplified
18237 # by a new tool, gnatmlib
18239 mkdir -p $@{dir $@@ @}
18240 cd $@{dir $@@ @} && gcc -shared -o $@{notdir $@@ @} ../*.o -L$@{GLIB@} -lgnat
18241 cd $@{dir $@@ @} && cp -f ../*.ali .
18243 # The dependencies for the modules
18244 # Note that we have to force the expansion of *.o, since in some cases
18245 # make won't be able to do it itself.
18246 aa/lib/libaa.so: $@{wildcard aa/*.o@}
18247 bb/lib/libbb.so: $@{wildcard bb/*.o@}
18248 cc/lib/libcc.so: $@{wildcard cc/*.o@}
18250 # Make sure all of the shared libraries are in the path before starting the
18253 LD_LIBRARY_PATH=`pwd`/aa/lib:`pwd`/bb/lib:`pwd`/cc/lib ./$@{MAIN@}
18256 $@{RM@} -rf $@{CSC_LIST:%=%/lib@}
18257 $@{RM@} $@{CSC_LIST:%=%/*.ali@}
18258 $@{RM@} $@{CSC_LIST:%=%/*.o@}
18259 $@{RM@} *.o *.ali $@{MAIN@}
18262 @node Automatically Creating a List of Directories
18263 @section Automatically Creating a List of Directories
18266 In most makefiles, you will have to specify a list of directories, and
18267 store it in a variable. For small projects, it is often easier to
18268 specify each of them by hand, since you then have full control over what
18269 is the proper order for these directories, which ones should be
18272 However, in larger projects, which might involve hundreds of
18273 subdirectories, it might be more convenient to generate this list
18276 The example below presents two methods. The first one, although less
18277 general, gives you more control over the list. It involves wildcard
18278 characters, that are automatically expanded by @command{make}. Its
18279 shortcoming is that you need to explicitly specify some of the
18280 organization of your project, such as for instance the directory tree
18281 depth, whether some directories are found in a separate tree, @enddots{}
18283 The second method is the most general one. It requires an external
18284 program, called @command{find}, which is standard on all Unix systems. All
18285 the directories found under a given root directory will be added to the
18291 @font@heightrm=cmr8
18294 # The examples below are based on the following directory hierarchy:
18295 # All the directories can contain any number of files
18296 # ROOT_DIRECTORY -> a -> aa -> aaa
18299 # -> b -> ba -> baa
18302 # This Makefile creates a variable called DIRS, that can be reused any time
18303 # you need this list (see the other examples in this section)
18305 # The root of your project's directory hierarchy
18309 # First method: specify explicitly the list of directories
18310 # This allows you to specify any subset of all the directories you need.
18313 DIRS := a/aa/ a/ab/ b/ba/
18316 # Second method: use wildcards
18317 # Note that the argument(s) to wildcard below should end with a '/'.
18318 # Since wildcards also return file names, we have to filter them out
18319 # to avoid duplicate directory names.
18320 # We thus use make's @code{dir} and @code{sort} functions.
18321 # It sets DIRs to the following value (note that the directories aaa and baa
18322 # are not given, unless you change the arguments to wildcard).
18323 # DIRS= ./a/a/ ./b/ ./a/aa/ ./a/ab/ ./a/ac/ ./b/ba/ ./b/bb/ ./b/bc/
18326 DIRS := $@{sort $@{dir $@{wildcard $@{ROOT_DIRECTORY@}/*/
18327 $@{ROOT_DIRECTORY@}/*/*/@}@}@}
18330 # Third method: use an external program
18331 # This command is much faster if run on local disks, avoiding NFS slowdowns.
18332 # This is the most complete command: it sets DIRs to the following value:
18333 # DIRS= ./a ./a/aa ./a/aa/aaa ./a/ab ./a/ac ./b ./b/ba ./b/ba/baa ./b/bb ./b/bc
18336 DIRS := $@{shell find $@{ROOT_DIRECTORY@} -type d -print@}
18340 @node Generating the Command Line Switches
18341 @section Generating the Command Line Switches
18344 Once you have created the list of directories as explained in the
18345 previous section (@pxref{Automatically Creating a List of Directories}),
18346 you can easily generate the command line arguments to pass to gnatmake.
18348 For the sake of completeness, this example assumes that the source path
18349 is not the same as the object path, and that you have two separate lists
18353 # see "Automatically creating a list of directories" to create
18358 GNATMAKE_SWITCHES := $@{patsubst %,-aI%,$@{SOURCE_DIRS@}@}
18359 GNATMAKE_SWITCHES += $@{patsubst %,-aO%,$@{OBJECT_DIRS@}@}
18362 gnatmake $@{GNATMAKE_SWITCHES@} main_unit
18365 @node Overcoming Command Line Length Limits
18366 @section Overcoming Command Line Length Limits
18369 One problem that might be encountered on big projects is that many
18370 operating systems limit the length of the command line. It is thus hard to give
18371 gnatmake the list of source and object directories.
18373 This example shows how you can set up environment variables, which will
18374 make @command{gnatmake} behave exactly as if the directories had been
18375 specified on the command line, but have a much higher length limit (or
18376 even none on most systems).
18378 It assumes that you have created a list of directories in your Makefile,
18379 using one of the methods presented in
18380 @ref{Automatically Creating a List of Directories}.
18381 For the sake of completeness, we assume that the object
18382 path (where the ALI files are found) is different from the sources patch.
18384 Note a small trick in the Makefile below: for efficiency reasons, we
18385 create two temporary variables (SOURCE_LIST and OBJECT_LIST), that are
18386 expanded immediately by @code{make}. This way we overcome the standard
18387 make behavior which is to expand the variables only when they are
18390 On Windows, if you are using the standard Windows command shell, you must
18391 replace colons with semicolons in the assignments to these variables.
18396 @font@heightrm=cmr8
18399 # In this example, we create both ADA_INCLUDE_PATH and ADA_OBJECTS_PATH.
18400 # This is the same thing as putting the -I arguments on the command line.
18401 # (the equivalent of using -aI on the command line would be to define
18402 # only ADA_INCLUDE_PATH, the equivalent of -aO is ADA_OBJECTS_PATH).
18403 # You can of course have different values for these variables.
18405 # Note also that we need to keep the previous values of these variables, since
18406 # they might have been set before running 'make' to specify where the GNAT
18407 # library is installed.
18409 # see "Automatically creating a list of directories" to create these
18415 space:=$@{empty@} $@{empty@}
18416 SOURCE_LIST := $@{subst $@{space@},:,$@{SOURCE_DIRS@}@}
18417 OBJECT_LIST := $@{subst $@{space@},:,$@{OBJECT_DIRS@}@}
18418 ADA_INCLUDE_PATH += $@{SOURCE_LIST@}
18419 ADA_OBJECTS_PATH += $@{OBJECT_LIST@}
18420 export ADA_INCLUDE_PATH
18421 export ADA_OBJECTS_PATH
18428 @node Memory Management Issues
18429 @chapter Memory Management Issues
18432 This chapter describes some useful memory pools provided in the GNAT library
18433 and in particular the GNAT Debug Pool facility, which can be used to detect
18434 incorrect uses of access values (including ``dangling references'').
18436 @ifclear FSFEDITION
18437 It also describes the @command{gnatmem} tool, which can be used to track down
18443 * Some Useful Memory Pools::
18444 * The GNAT Debug Pool Facility::
18446 @ifclear FSFEDITION
18447 * The gnatmem Tool::
18452 @node Some Useful Memory Pools
18453 @section Some Useful Memory Pools
18454 @findex Memory Pool
18455 @cindex storage, pool
18458 The @code{System.Pool_Global} package offers the Unbounded_No_Reclaim_Pool
18459 storage pool. Allocations use the standard system call @code{malloc} while
18460 deallocations use the standard system call @code{free}. No reclamation is
18461 performed when the pool goes out of scope. For performance reasons, the
18462 standard default Ada allocators/deallocators do not use any explicit storage
18463 pools but if they did, they could use this storage pool without any change in
18464 behavior. That is why this storage pool is used when the user
18465 manages to make the default implicit allocator explicit as in this example:
18466 @smallexample @c ada
18467 type T1 is access Something;
18468 -- no Storage pool is defined for T2
18469 type T2 is access Something_Else;
18470 for T2'Storage_Pool use T1'Storage_Pool;
18471 -- the above is equivalent to
18472 for T2'Storage_Pool use System.Pool_Global.Global_Pool_Object;
18476 The @code{System.Pool_Local} package offers the Unbounded_Reclaim_Pool storage
18477 pool. The allocation strategy is similar to @code{Pool_Local}'s
18478 except that the all
18479 storage allocated with this pool is reclaimed when the pool object goes out of
18480 scope. This pool provides a explicit mechanism similar to the implicit one
18481 provided by several Ada 83 compilers for allocations performed through a local
18482 access type and whose purpose was to reclaim memory when exiting the
18483 scope of a given local access. As an example, the following program does not
18484 leak memory even though it does not perform explicit deallocation:
18486 @smallexample @c ada
18487 with System.Pool_Local;
18488 procedure Pooloc1 is
18489 procedure Internal is
18490 type A is access Integer;
18491 X : System.Pool_Local.Unbounded_Reclaim_Pool;
18492 for A'Storage_Pool use X;
18495 for I in 1 .. 50 loop
18500 for I in 1 .. 100 loop
18507 The @code{System.Pool_Size} package implements the Stack_Bounded_Pool used when
18508 @code{Storage_Size} is specified for an access type.
18509 The whole storage for the pool is
18510 allocated at once, usually on the stack at the point where the access type is
18511 elaborated. It is automatically reclaimed when exiting the scope where the
18512 access type is defined. This package is not intended to be used directly by the
18513 user and it is implicitly used for each such declaration:
18515 @smallexample @c ada
18516 type T1 is access Something;
18517 for T1'Storage_Size use 10_000;
18520 @node The GNAT Debug Pool Facility
18521 @section The GNAT Debug Pool Facility
18523 @cindex storage, pool, memory corruption
18526 The use of unchecked deallocation and unchecked conversion can easily
18527 lead to incorrect memory references. The problems generated by such
18528 references are usually difficult to tackle because the symptoms can be
18529 very remote from the origin of the problem. In such cases, it is
18530 very helpful to detect the problem as early as possible. This is the
18531 purpose of the Storage Pool provided by @code{GNAT.Debug_Pools}.
18533 In order to use the GNAT specific debugging pool, the user must
18534 associate a debug pool object with each of the access types that may be
18535 related to suspected memory problems. See Ada Reference Manual 13.11.
18536 @smallexample @c ada
18537 type Ptr is access Some_Type;
18538 Pool : GNAT.Debug_Pools.Debug_Pool;
18539 for Ptr'Storage_Pool use Pool;
18543 @code{GNAT.Debug_Pools} is derived from a GNAT-specific kind of
18544 pool: the @code{Checked_Pool}. Such pools, like standard Ada storage pools,
18545 allow the user to redefine allocation and deallocation strategies. They
18546 also provide a checkpoint for each dereference, through the use of
18547 the primitive operation @code{Dereference} which is implicitly called at
18548 each dereference of an access value.
18550 Once an access type has been associated with a debug pool, operations on
18551 values of the type may raise four distinct exceptions,
18552 which correspond to four potential kinds of memory corruption:
18555 @code{GNAT.Debug_Pools.Accessing_Not_Allocated_Storage}
18557 @code{GNAT.Debug_Pools.Accessing_Deallocated_Storage}
18559 @code{GNAT.Debug_Pools.Freeing_Not_Allocated_Storage}
18561 @code{GNAT.Debug_Pools.Freeing_Deallocated_Storage }
18565 For types associated with a Debug_Pool, dynamic allocation is performed using
18566 the standard GNAT allocation routine. References to all allocated chunks of
18567 memory are kept in an internal dictionary. Several deallocation strategies are
18568 provided, whereupon the user can choose to release the memory to the system,
18569 keep it allocated for further invalid access checks, or fill it with an easily
18570 recognizable pattern for debug sessions. The memory pattern is the old IBM
18571 hexadecimal convention: @code{16#DEADBEEF#}.
18573 See the documentation in the file g-debpoo.ads for more information on the
18574 various strategies.
18576 Upon each dereference, a check is made that the access value denotes a
18577 properly allocated memory location. Here is a complete example of use of
18578 @code{Debug_Pools}, that includes typical instances of memory corruption:
18579 @smallexample @c ada
18583 with Gnat.Io; use Gnat.Io;
18584 with Unchecked_Deallocation;
18585 with Unchecked_Conversion;
18586 with GNAT.Debug_Pools;
18587 with System.Storage_Elements;
18588 with Ada.Exceptions; use Ada.Exceptions;
18589 procedure Debug_Pool_Test is
18591 type T is access Integer;
18592 type U is access all T;
18594 P : GNAT.Debug_Pools.Debug_Pool;
18595 for T'Storage_Pool use P;
18597 procedure Free is new Unchecked_Deallocation (Integer, T);
18598 function UC is new Unchecked_Conversion (U, T);
18601 procedure Info is new GNAT.Debug_Pools.Print_Info(Put_Line);
18611 Put_Line (Integer'Image(B.all));
18613 when E : others => Put_Line ("raised: " & Exception_Name (E));
18618 when E : others => Put_Line ("raised: " & Exception_Name (E));
18622 Put_Line (Integer'Image(B.all));
18624 when E : others => Put_Line ("raised: " & Exception_Name (E));
18629 when E : others => Put_Line ("raised: " & Exception_Name (E));
18632 end Debug_Pool_Test;
18636 The debug pool mechanism provides the following precise diagnostics on the
18637 execution of this erroneous program:
18640 Total allocated bytes : 0
18641 Total deallocated bytes : 0
18642 Current Water Mark: 0
18646 Total allocated bytes : 8
18647 Total deallocated bytes : 0
18648 Current Water Mark: 8
18651 raised: GNAT.DEBUG_POOLS.ACCESSING_DEALLOCATED_STORAGE
18652 raised: GNAT.DEBUG_POOLS.FREEING_DEALLOCATED_STORAGE
18653 raised: GNAT.DEBUG_POOLS.ACCESSING_NOT_ALLOCATED_STORAGE
18654 raised: GNAT.DEBUG_POOLS.FREEING_NOT_ALLOCATED_STORAGE
18656 Total allocated bytes : 8
18657 Total deallocated bytes : 4
18658 Current Water Mark: 4
18663 @ifclear FSFEDITION
18664 @node The gnatmem Tool
18665 @section The @command{gnatmem} Tool
18669 The @code{gnatmem} utility monitors dynamic allocation and
18670 deallocation activity in a program, and displays information about
18671 incorrect deallocations and possible sources of memory leaks.
18672 It is designed to work in association with a static runtime library
18673 only and in this context provides three types of information:
18676 General information concerning memory management, such as the total
18677 number of allocations and deallocations, the amount of allocated
18678 memory and the high water mark, i.e.@: the largest amount of allocated
18679 memory in the course of program execution.
18682 Backtraces for all incorrect deallocations, that is to say deallocations
18683 which do not correspond to a valid allocation.
18686 Information on each allocation that is potentially the origin of a memory
18691 * Running gnatmem::
18692 * Switches for gnatmem::
18693 * Example of gnatmem Usage::
18696 @node Running gnatmem
18697 @subsection Running @code{gnatmem}
18700 @code{gnatmem} makes use of the output created by the special version of
18701 allocation and deallocation routines that record call information. This
18702 allows to obtain accurate dynamic memory usage history at a minimal cost to
18703 the execution speed. Note however, that @code{gnatmem} is not supported on
18704 all platforms (currently, it is supported on AIX, HP-UX, GNU/Linux,
18705 Solaris and Windows NT/2000/XP (x86).
18708 The @code{gnatmem} command has the form
18711 @c $ gnatmem @ovar{switches} user_program
18712 @c Expanding @ovar macro inline (explanation in macro def comments)
18713 $ gnatmem @r{[}@var{switches}@r{]} @var{user_program}
18717 The program must have been linked with the instrumented version of the
18718 allocation and deallocation routines. This is done by linking with the
18719 @file{libgmem.a} library. For correct symbolic backtrace information,
18720 the user program should be compiled with debugging options
18721 (see @ref{Switches for gcc}). For example to build @file{my_program}:
18724 $ gnatmake -g my_program -largs -lgmem
18728 As library @file{libgmem.a} contains an alternate body for package
18729 @code{System.Memory}, @file{s-memory.adb} should not be compiled and linked
18730 when an executable is linked with library @file{libgmem.a}. It is then not
18731 recommended to use @command{gnatmake} with switch @option{^-a^/ALL_FILES^}.
18734 When @file{my_program} is executed, the file @file{gmem.out} is produced.
18735 This file contains information about all allocations and deallocations
18736 performed by the program. It is produced by the instrumented allocations and
18737 deallocations routines and will be used by @code{gnatmem}.
18739 In order to produce symbolic backtrace information for allocations and
18740 deallocations performed by the GNAT run-time library, you need to use a
18741 version of that library that has been compiled with the @option{-g} switch
18742 (see @ref{Rebuilding the GNAT Run-Time Library}).
18744 Gnatmem must be supplied with the @file{gmem.out} file and the executable to
18745 examine. If the location of @file{gmem.out} file was not explicitly supplied by
18746 @option{-i} switch, gnatmem will assume that this file can be found in the
18747 current directory. For example, after you have executed @file{my_program},
18748 @file{gmem.out} can be analyzed by @code{gnatmem} using the command:
18751 $ gnatmem my_program
18755 This will produce the output with the following format:
18757 *************** debut cc
18759 $ gnatmem my_program
18763 Total number of allocations : 45
18764 Total number of deallocations : 6
18765 Final Water Mark (non freed mem) : 11.29 Kilobytes
18766 High Water Mark : 11.40 Kilobytes
18771 Allocation Root # 2
18772 -------------------
18773 Number of non freed allocations : 11
18774 Final Water Mark (non freed mem) : 1.16 Kilobytes
18775 High Water Mark : 1.27 Kilobytes
18777 my_program.adb:23 my_program.alloc
18783 The first block of output gives general information. In this case, the
18784 Ada construct ``@code{@b{new}}'' was executed 45 times, and only 6 calls to an
18785 Unchecked_Deallocation routine occurred.
18788 Subsequent paragraphs display information on all allocation roots.
18789 An allocation root is a specific point in the execution of the program
18790 that generates some dynamic allocation, such as a ``@code{@b{new}}''
18791 construct. This root is represented by an execution backtrace (or subprogram
18792 call stack). By default the backtrace depth for allocations roots is 1, so
18793 that a root corresponds exactly to a source location. The backtrace can
18794 be made deeper, to make the root more specific.
18796 @node Switches for gnatmem
18797 @subsection Switches for @code{gnatmem}
18800 @code{gnatmem} recognizes the following switches:
18805 @cindex @option{-q} (@code{gnatmem})
18806 Quiet. Gives the minimum output needed to identify the origin of the
18807 memory leaks. Omits statistical information.
18810 @cindex @var{N} (@code{gnatmem})
18811 N is an integer literal (usually between 1 and 10) which controls the
18812 depth of the backtraces defining allocation root. The default value for
18813 N is 1. The deeper the backtrace, the more precise the localization of
18814 the root. Note that the total number of roots can depend on this
18815 parameter. This parameter must be specified @emph{before} the name of the
18816 executable to be analyzed, to avoid ambiguity.
18819 @cindex @option{-b} (@code{gnatmem})
18820 This switch has the same effect as just depth parameter.
18822 @item -i @var{file}
18823 @cindex @option{-i} (@code{gnatmem})
18824 Do the @code{gnatmem} processing starting from @file{file}, rather than
18825 @file{gmem.out} in the current directory.
18828 @cindex @option{-m} (@code{gnatmem})
18829 This switch causes @code{gnatmem} to mask the allocation roots that have less
18830 than n leaks. The default value is 1. Specifying the value of 0 will allow to
18831 examine even the roots that didn't result in leaks.
18834 @cindex @option{-s} (@code{gnatmem})
18835 This switch causes @code{gnatmem} to sort the allocation roots according to the
18836 specified order of sort criteria, each identified by a single letter. The
18837 currently supported criteria are @code{n, h, w} standing respectively for
18838 number of unfreed allocations, high watermark, and final watermark
18839 corresponding to a specific root. The default order is @code{nwh}.
18843 @node Example of gnatmem Usage
18844 @subsection Example of @code{gnatmem} Usage
18847 The following example shows the use of @code{gnatmem}
18848 on a simple memory-leaking program.
18849 Suppose that we have the following Ada program:
18851 @smallexample @c ada
18854 with Unchecked_Deallocation;
18855 procedure Test_Gm is
18857 type T is array (1..1000) of Integer;
18858 type Ptr is access T;
18859 procedure Free is new Unchecked_Deallocation (T, Ptr);
18862 procedure My_Alloc is
18867 procedure My_DeAlloc is
18875 for I in 1 .. 5 loop
18876 for J in I .. 5 loop
18887 The program needs to be compiled with debugging option and linked with
18888 @code{gmem} library:
18891 $ gnatmake -g test_gm -largs -lgmem
18895 Then we execute the program as usual:
18902 Then @code{gnatmem} is invoked simply with
18908 which produces the following output (result may vary on different platforms):
18913 Total number of allocations : 18
18914 Total number of deallocations : 5
18915 Final Water Mark (non freed mem) : 53.00 Kilobytes
18916 High Water Mark : 56.90 Kilobytes
18918 Allocation Root # 1
18919 -------------------
18920 Number of non freed allocations : 11
18921 Final Water Mark (non freed mem) : 42.97 Kilobytes
18922 High Water Mark : 46.88 Kilobytes
18924 test_gm.adb:11 test_gm.my_alloc
18926 Allocation Root # 2
18927 -------------------
18928 Number of non freed allocations : 1
18929 Final Water Mark (non freed mem) : 10.02 Kilobytes
18930 High Water Mark : 10.02 Kilobytes
18932 s-secsta.adb:81 system.secondary_stack.ss_init
18934 Allocation Root # 3
18935 -------------------
18936 Number of non freed allocations : 1
18937 Final Water Mark (non freed mem) : 12 Bytes
18938 High Water Mark : 12 Bytes
18940 s-secsta.adb:181 system.secondary_stack.ss_init
18944 Note that the GNAT run time contains itself a certain number of
18945 allocations that have no corresponding deallocation,
18946 as shown here for root #2 and root
18947 #3. This is a normal behavior when the number of non-freed allocations
18948 is one, it allocates dynamic data structures that the run time needs for
18949 the complete lifetime of the program. Note also that there is only one
18950 allocation root in the user program with a single line back trace:
18951 test_gm.adb:11 test_gm.my_alloc, whereas a careful analysis of the
18952 program shows that 'My_Alloc' is called at 2 different points in the
18953 source (line 21 and line 24). If those two allocation roots need to be
18954 distinguished, the backtrace depth parameter can be used:
18957 $ gnatmem 3 test_gm
18961 which will give the following output:
18966 Total number of allocations : 18
18967 Total number of deallocations : 5
18968 Final Water Mark (non freed mem) : 53.00 Kilobytes
18969 High Water Mark : 56.90 Kilobytes
18971 Allocation Root # 1
18972 -------------------
18973 Number of non freed allocations : 10
18974 Final Water Mark (non freed mem) : 39.06 Kilobytes
18975 High Water Mark : 42.97 Kilobytes
18977 test_gm.adb:11 test_gm.my_alloc
18978 test_gm.adb:24 test_gm
18979 b_test_gm.c:52 main
18981 Allocation Root # 2
18982 -------------------
18983 Number of non freed allocations : 1
18984 Final Water Mark (non freed mem) : 10.02 Kilobytes
18985 High Water Mark : 10.02 Kilobytes
18987 s-secsta.adb:81 system.secondary_stack.ss_init
18988 s-secsta.adb:283 <system__secondary_stack___elabb>
18989 b_test_gm.c:33 adainit
18991 Allocation Root # 3
18992 -------------------
18993 Number of non freed allocations : 1
18994 Final Water Mark (non freed mem) : 3.91 Kilobytes
18995 High Water Mark : 3.91 Kilobytes
18997 test_gm.adb:11 test_gm.my_alloc
18998 test_gm.adb:21 test_gm
18999 b_test_gm.c:52 main
19001 Allocation Root # 4
19002 -------------------
19003 Number of non freed allocations : 1
19004 Final Water Mark (non freed mem) : 12 Bytes
19005 High Water Mark : 12 Bytes
19007 s-secsta.adb:181 system.secondary_stack.ss_init
19008 s-secsta.adb:283 <system__secondary_stack___elabb>
19009 b_test_gm.c:33 adainit
19013 The allocation root #1 of the first example has been split in 2 roots #1
19014 and #3 thanks to the more precise associated backtrace.
19018 @node Stack Related Facilities
19019 @chapter Stack Related Facilities
19022 This chapter describes some useful tools associated with stack
19023 checking and analysis. In
19024 particular, it deals with dynamic and static stack usage measurements.
19027 * Stack Overflow Checking::
19028 * Static Stack Usage Analysis::
19029 * Dynamic Stack Usage Analysis::
19032 @node Stack Overflow Checking
19033 @section Stack Overflow Checking
19034 @cindex Stack Overflow Checking
19035 @cindex -fstack-check
19038 For most operating systems, @command{gcc} does not perform stack overflow
19039 checking by default. This means that if the main environment task or
19040 some other task exceeds the available stack space, then unpredictable
19041 behavior will occur. Most native systems offer some level of protection by
19042 adding a guard page at the end of each task stack. This mechanism is usually
19043 not enough for dealing properly with stack overflow situations because
19044 a large local variable could ``jump'' above the guard page.
19045 Furthermore, when the
19046 guard page is hit, there may not be any space left on the stack for executing
19047 the exception propagation code. Enabling stack checking avoids
19050 To activate stack checking, compile all units with the gcc option
19051 @option{-fstack-check}. For example:
19054 gcc -c -fstack-check package1.adb
19058 Units compiled with this option will generate extra instructions to check
19059 that any use of the stack (for procedure calls or for declaring local
19060 variables in declare blocks) does not exceed the available stack space.
19061 If the space is exceeded, then a @code{Storage_Error} exception is raised.
19063 For declared tasks, the stack size is controlled by the size
19064 given in an applicable @code{Storage_Size} pragma or by the value specified
19065 at bind time with @option{-d} (@pxref{Switches for gnatbind}) or is set to
19066 the default size as defined in the GNAT runtime otherwise.
19068 For the environment task, the stack size depends on
19069 system defaults and is unknown to the compiler. Stack checking
19070 may still work correctly if a fixed
19071 size stack is allocated, but this cannot be guaranteed.
19073 To ensure that a clean exception is signalled for stack
19074 overflow, set the environment variable
19075 @env{GNAT_STACK_LIMIT} to indicate the maximum
19076 stack area that can be used, as in:
19077 @cindex GNAT_STACK_LIMIT
19080 SET GNAT_STACK_LIMIT 1600
19084 The limit is given in kilobytes, so the above declaration would
19085 set the stack limit of the environment task to 1.6 megabytes.
19086 Note that the only purpose of this usage is to limit the amount
19087 of stack used by the environment task. If it is necessary to
19088 increase the amount of stack for the environment task, then this
19089 is an operating systems issue, and must be addressed with the
19090 appropriate operating systems commands.
19093 To have a fixed size stack in the environment task, the stack must be put
19094 in the P0 address space and its size specified. Use these switches to
19098 gnatmake my_progs -largs "-Wl,--opt=STACK=4000,/p0image"
19102 The quotes are required to keep case. The number after @samp{STACK=} is the
19103 size of the environmental task stack in pagelets (512 bytes). In this example
19104 the stack size is about 2 megabytes.
19107 A consequence of the @option{/p0image} qualifier is also to makes RMS buffers
19108 be placed in P0 space. Refer to @cite{HP OpenVMS Linker Utility Manual} for
19109 more details about the @option{/p0image} qualifier and the @option{stack}
19113 On Itanium platforms, you can instead assign the @samp{GNAT_STACK_SIZE} and
19114 @samp{GNAT_RBS_SIZE} logicals to the size of the primary and register
19115 stack in kilobytes. For example:
19118 $ define GNAT_RBS_SIZE 1024 ! Limit the RBS size to 1MB.
19122 @node Static Stack Usage Analysis
19123 @section Static Stack Usage Analysis
19124 @cindex Static Stack Usage Analysis
19125 @cindex -fstack-usage
19128 A unit compiled with @option{-fstack-usage} will generate an extra file
19130 the maximum amount of stack used, on a per-function basis.
19131 The file has the same
19132 basename as the target object file with a @file{.su} extension.
19133 Each line of this file is made up of three fields:
19137 The name of the function.
19141 One or more qualifiers: @code{static}, @code{dynamic}, @code{bounded}.
19144 The second field corresponds to the size of the known part of the function
19147 The qualifier @code{static} means that the function frame size
19149 It usually means that all local variables have a static size.
19150 In this case, the second field is a reliable measure of the function stack
19153 The qualifier @code{dynamic} means that the function frame size is not static.
19154 It happens mainly when some local variables have a dynamic size. When this
19155 qualifier appears alone, the second field is not a reliable measure
19156 of the function stack analysis. When it is qualified with @code{bounded}, it
19157 means that the second field is a reliable maximum of the function stack
19160 A unit compiled with @option{-Wstack-usage} will issue a warning for each
19161 subprogram whose stack usage might be larger than the specified amount of
19162 bytes. The wording is in keeping with the qualifier documented above.
19164 @node Dynamic Stack Usage Analysis
19165 @section Dynamic Stack Usage Analysis
19168 It is possible to measure the maximum amount of stack used by a task, by
19169 adding a switch to @command{gnatbind}, as:
19172 $ gnatbind -u0 file
19176 With this option, at each task termination, its stack usage is output on
19178 It is not always convenient to output the stack usage when the program
19179 is still running. Hence, it is possible to delay this output until program
19180 termination. for a given number of tasks specified as the argument of the
19181 @option{-u} option. For instance:
19184 $ gnatbind -u100 file
19188 will buffer the stack usage information of the first 100 tasks to terminate and
19189 output this info at program termination. Results are displayed in four
19193 Index | Task Name | Stack Size | Stack Usage
19200 is a number associated with each task.
19203 is the name of the task analyzed.
19206 is the maximum size for the stack.
19209 is the measure done by the stack analyzer. In order to prevent overflow, the stack
19210 is not entirely analyzed, and it's not possible to know exactly how
19211 much has actually been used.
19216 The environment task stack, e.g., the stack that contains the main unit, is
19217 only processed when the environment variable GNAT_STACK_LIMIT is set.
19220 The package @code{GNAT.Task_Stack_Usage} provides facilities to get
19221 stack usage reports at run-time. See its body for the details.
19223 @ifclear FSFEDITION
19224 @c *********************************
19226 @c *********************************
19227 @node Verifying Properties with gnatcheck
19228 @chapter Verifying Properties with @command{gnatcheck}
19230 @cindex @command{gnatcheck}
19233 The @command{gnatcheck} tool is an ASIS-based utility that checks properties
19234 of Ada source files according to a given set of semantic rules.
19237 In order to check compliance with a given rule, @command{gnatcheck} has to
19238 semantically analyze the Ada sources.
19239 Therefore, checks can only be performed on
19240 legal Ada units. Moreover, when a unit depends semantically upon units located
19241 outside the current directory, the source search path has to be provided when
19242 calling @command{gnatcheck}, either through a specified project file or
19243 through @command{gnatcheck} switches.
19245 For full details, refer to @cite{GNATcheck Reference Manual} document.
19248 @ifclear FSFEDITION
19249 @c *********************************
19250 @node Creating Sample Bodies with gnatstub
19251 @chapter Creating Sample Bodies with @command{gnatstub}
19255 @command{gnatstub} creates body stubs, that is, empty but compilable bodies
19256 for library unit declarations.
19258 To create a body stub, @command{gnatstub} invokes the Ada
19259 compiler and generates and uses the ASIS tree for the input source;
19260 thus the input must be legal Ada code, and the tool should have all the
19261 information needed to compile the input source. To provide this information,
19262 you may specify as a tool parameter the project file the input source belongs to
19263 (or you may call @command{gnatstub}
19264 through the @command{gnat} driver (see @ref{The GNAT Driver and
19265 Project Files}). Another possibility is to specify the source search
19266 path and needed configuration files in @option{-cargs} section of @command{gnatstub}
19267 call, see the description of the @command{gnatstub} switches below.
19269 By default, all the program unit body stubs generated by @code{gnatstub}
19270 raise the predefined @code{Program_Error} exception, which will catch
19271 accidental calls of generated stubs. This behavior can be changed with
19272 option @option{^--no-exception^/NO_EXCEPTION^} (see below).
19275 * Running gnatstub::
19276 * Switches for gnatstub::
19279 @node Running gnatstub
19280 @section Running @command{gnatstub}
19283 @command{gnatstub} has a command-line interface of the form:
19286 @c $ gnatstub @ovar{switches} @var{filename} @ovar{directory}
19287 @c Expanding @ovar macro inline (explanation in macro def comments)
19288 $ gnatstub @r{[}@var{switches}@r{]} @var{filename} @r{[}@var{directory}@r{]} @r{[}-cargs @var{gcc_switches}@r{]}
19295 is the name of the source file that contains a library unit declaration
19296 for which a body must be created. The file name may contain the path
19298 The file name does not have to follow the GNAT file name conventions. If the
19300 does not follow GNAT file naming conventions, the name of the body file must
19302 explicitly as the value of the @option{^-o^/BODY=^@var{body-name}} option.
19303 If the file name follows the GNAT file naming
19304 conventions and the name of the body file is not provided,
19307 of the body file from the argument file name by replacing the @file{.ads}
19309 with the @file{.adb} suffix.
19312 indicates the directory in which the body stub is to be placed (the default
19316 @item @samp{@var{gcc_switches}} is a list of switches for
19317 @command{gcc}. They will be passed on to all compiler invocations made by
19318 @command{gnatstub} to generate the ASIS trees. Here you can provide
19319 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
19320 use the @option{-gnatec} switch to set the configuration file,
19321 use the @option{-gnat05} switch if sources should be compiled in
19325 is an optional sequence of switches as described in the next section
19328 @node Switches for gnatstub
19329 @section Switches for @command{gnatstub}
19335 @cindex @option{--version} @command{gnatstub}
19336 Display Copyright and version, then exit disregarding all other options.
19339 @cindex @option{--help} @command{gnatstub}
19340 Display usage, then exit disregarding all other options.
19342 @item -P @var{file}
19343 @cindex @option{-P} @command{gnatstub}
19344 Indicates the name of the project file that describes the set of sources
19347 @item -X@var{name}=@var{value}
19348 @cindex @option{-X} @command{gnatstub}
19349 Indicates that external variable @var{name} in the argument project
19350 has the value @var{value}. Has no effect if no project is specified as
19354 @cindex @option{^-f^/FULL^} (@command{gnatstub})
19355 If the destination directory already contains a file with the name of the
19357 for the argument spec file, replace it with the generated body stub.
19359 @item ^-hs^/HEADER=SPEC^
19360 @cindex @option{^-hs^/HEADER=SPEC^} (@command{gnatstub})
19361 Put the comment header (i.e., all the comments preceding the
19362 compilation unit) from the source of the library unit declaration
19363 into the body stub.
19365 @item ^-hg^/HEADER=GENERAL^
19366 @cindex @option{^-hg^/HEADER=GENERAL^} (@command{gnatstub})
19367 Put a sample comment header into the body stub.
19369 @item ^--header-file=@var{filename}^/FROM_HEADER_FILE=@var{filename}^
19370 @cindex @option{^--header-file^/FROM_HEADER_FILE=^} (@command{gnatstub})
19371 Use the content of the file as the comment header for a generated body stub.
19375 @cindex @option{-IDIR} (@command{gnatstub})
19377 @cindex @option{-I-} (@command{gnatstub})
19380 @item /NOCURRENT_DIRECTORY
19381 @cindex @option{/NOCURRENT_DIRECTORY} (@command{gnatstub})
19383 ^These switches have ^This switch has^ the same meaning as in calls to
19385 ^They define ^It defines ^ the source search path in the call to
19386 @command{gcc} issued
19387 by @command{gnatstub} to compile an argument source file.
19389 @item ^-gnatec^/CONFIGURATION_PRAGMAS_FILE=^@var{PATH}
19390 @cindex @option{^-gnatec^/CONFIGURATION_PRAGMAS_FILE^} (@command{gnatstub})
19391 This switch has the same meaning as in calls to @command{gcc}.
19392 It defines the additional configuration file to be passed to the call to
19393 @command{gcc} issued
19394 by @command{gnatstub} to compile an argument source file.
19396 @item ^-gnatyM^/MAX_LINE_LENGTH=^@var{n}
19397 @cindex @option{^-gnatyM^/MAX_LINE_LENGTH^} (@command{gnatstub})
19398 (@var{n} is a non-negative integer). Set the maximum line length that is
19399 allowed in a source file. The default is 79. The maximum value that can be
19400 specified is 32767. Note that in the special case of configuration
19401 pragma files, the maximum is always 32767 regardless of whether or
19402 not this switch appears.
19404 @item ^-gnaty^/STYLE_CHECKS=^@var{n}
19405 @cindex @option{^-gnaty^/STYLE_CHECKS=^} (@command{gnatstub})
19406 (@var{n} is a non-negative integer from 1 to 9). Set the indentation level in
19407 the generated body sample to @var{n}.
19408 The default indentation is 3.
19410 @item ^-gnatyo^/ORDERED_SUBPROGRAMS^
19411 @cindex @option{^-gnatyo^/ORDERED_SUBPROGRAMS^} (@command{gnatstub})
19412 Order local bodies alphabetically. (By default local bodies are ordered
19413 in the same way as the corresponding local specs in the argument spec file.)
19415 @item ^-i^/INDENTATION=^@var{n}
19416 @cindex @option{^-i^/INDENTATION^} (@command{gnatstub})
19417 Same as @option{^-gnaty^/STYLE_CHECKS=^@var{n}}
19419 @item ^-k^/TREE_FILE=SAVE^
19420 @cindex @option{^-k^/TREE_FILE=SAVE^} (@command{gnatstub})
19421 Do not remove the tree file (i.e., the snapshot of the compiler internal
19422 structures used by @command{gnatstub}) after creating the body stub.
19424 @item ^-l^/LINE_LENGTH=^@var{n}
19425 @cindex @option{^-l^/LINE_LENGTH^} (@command{gnatstub})
19426 Same as @option{^-gnatyM^/MAX_LINE_LENGTH=^@var{n}}
19428 @item ^--no-exception^/NO_EXCEPTION^
19429 @cindex @option{^--no-exception^/NO_EXCEPTION^} (@command{gnatstub})
19430 Avoid raising PROGRAM_ERROR in the generated bodies of program unit stubs.
19431 This is not always possible for function stubs.
19433 @item ^--no-local-header^/NO_LOCAL_HEADER^
19434 @cindex @option{^--no-local-header^/NO_LOCAL_HEADER^} (@command{gnatstub})
19435 Do not place local comment header with unit name before body stub for a
19438 @item ^-o ^/BODY=^@var{body-name}
19439 @cindex @option{^-o^/BODY^} (@command{gnatstub})
19440 Body file name. This should be set if the argument file name does not
19442 the GNAT file naming
19443 conventions. If this switch is omitted the default name for the body will be
19445 from the argument file name according to the GNAT file naming conventions.
19447 @item ^-W^/RESULT_ENCODING=^@var{e}
19448 @cindex @option{^-W^/RESULT_ENCODING=^} (@command{gnatstub})
19449 Specify the wide character encoding method for the output body file.
19450 @var{e} is one of the following:
19458 Upper half encoding
19460 @item ^s^SHIFT_JIS^
19470 Brackets encoding (default value)
19474 @cindex @option{^-q^/QUIET^} (@command{gnatstub})
19475 Quiet mode: do not generate a confirmation when a body is
19476 successfully created, and do not generate a message when a body is not
19480 @item ^-r^/TREE_FILE=REUSE^
19481 @cindex @option{^-r^/TREE_FILE=REUSE^} (@command{gnatstub})
19482 Reuse the tree file (if it exists) instead of creating it. Instead of
19483 creating the tree file for the library unit declaration, @command{gnatstub}
19484 tries to find it in the current directory and use it for creating
19485 a body. If the tree file is not found, no body is created. This option
19486 also implies @option{^-k^/SAVE^}, whether or not
19487 the latter is set explicitly.
19489 @item ^-t^/TREE_FILE=OVERWRITE^
19490 @cindex @option{^-t^/TREE_FILE=OVERWRITE^} (@command{gnatstub})
19491 Overwrite the existing tree file. If the current directory already
19492 contains the file which, according to the GNAT file naming rules should
19493 be considered as a tree file for the argument source file,
19495 will refuse to create the tree file needed to create a sample body
19496 unless this option is set.
19498 @item ^-v^/VERBOSE^
19499 @cindex @option{^-v^/VERBOSE^} (@command{gnatstub})
19500 Verbose mode: generate version information.
19505 @ifclear FSFEDITION
19506 @c *********************************
19507 @node Creating Unit Tests with gnattest
19508 @chapter Creating Unit Tests with @command{gnattest}
19512 @command{gnattest} is an ASIS-based utility that creates unit-test skeletons
19513 as well as a test driver infrastructure (harness). @command{gnattest} creates
19514 a skeleton for each visible subprogram in the packages under consideration when
19515 they do not exist already.
19517 In order to process source files from a project, @command{gnattest} has to
19518 semantically analyze the sources. Therefore, test skeletons can only be
19519 generated for legal Ada units. If a unit is dependent on other units,
19520 those units should be among the source files of the project or of other projects
19521 imported by this one.
19523 Generated skeletons and harnesses are based on the AUnit testing framework.
19524 AUnit is an Ada adaptation of the xxxUnit testing frameworks, similar to JUnit
19525 for Java or CppUnit for C++. While it is advised that gnattest users read
19526 the AUnit manual, deep knowledge of AUnit is not necessary for using gnattest.
19527 For correct operation of @command{gnattest}, AUnit should be installed and
19528 aunit.gpr must be on the project path. This happens automatically when Aunit
19529 is installed at its default location.
19531 * Running gnattest::
19532 * Switches for gnattest::
19533 * Project Attributes for gnattest::
19535 * Setting Up and Tearing Down the Testing Environment::
19536 * Regenerating Tests::
19537 * Default Test Behavior::
19538 * Testing Primitive Operations of Tagged Types::
19539 * Testing Inheritance::
19540 * Tagged Types Substitutability Testing::
19541 * Testing with Contracts::
19542 * Additional Tests::
19544 * Support for other platforms/run-times::
19546 * Current Limitations::
19549 @node Running gnattest
19550 @section Running @command{gnattest}
19553 @command{gnattest} has a command-line interface of the form
19556 @c $ gnattest @var{-Pprojname} @ovar{switches} @ovar{filename} @ovar{directory}
19557 @c Expanding @ovar macro inline (explanation in macro def comments)
19558 $ gnattest @var{-Pprojname} @r{[}@var{--harness-dir=dirname}@r{]} @r{[}@var{switches}@r{]} @r{[}@var{filename}@r{]} @r{[}-cargs @var{gcc_switches}@r{]}
19566 specifies the project defining the location of source files. When no
19567 file names are provided on the command line, all sources in the project
19568 are used as input. This switch is required.
19571 is the name of the source file containing the library unit package declaration
19572 for which a test package will be created. The file name may be given with a
19575 @item @samp{@var{gcc_switches}}
19576 is a list of switches for
19577 @command{gcc}. These switches will be passed on to all compiler invocations
19578 made by @command{gnattest} to generate a set of ASIS trees. Here you can provide
19579 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
19580 use the @option{-gnatec} switch to set the configuration file,
19581 use the @option{-gnat05} switch if sources should be compiled in
19582 Ada 2005 mode, etc.
19585 is an optional sequence of switches as described in the next section.
19589 @command{gnattest} results can be found in two different places.
19592 @item automatic harness:
19593 the harness code, which is located by default in "gnattest/harness" directory
19594 that is created in the object directory of corresponding project file. All of
19595 this code is generated completely automatically and can be destroyed and
19596 regenerated at will. It is not recommended to modify this code manually, since
19597 it could easily be overridden by mistake. The entry point in the harness code is
19598 the project file named @command{test_driver.gpr}. Tests can be compiled and run
19599 using a command such as:
19602 gnatmake -P<harness-dir>/test_driver
19606 Note that you might need to specify the necessary values of scenario variables
19607 when you are not using the AUnit defaults.
19609 @item actual unit test skeletons:
19610 a test skeleton for each visible subprogram is created in a separate file, if it
19611 doesn't exist already. By default, those separate test files are located in a
19612 "gnattest/tests" directory that is created in the object directory of
19613 corresponding project file. For example, if a source file my_unit.ads in
19614 directory src contains a visible subprogram Proc, then the corresponding unit
19615 test will be found in file src/tests/my_unit-test_data-tests-proc_<code>.adb.
19616 <code> is a signature encoding used to differentiate test names in case of
19619 Note that if the project already has both my_unit.ads and my_unit-test_data.ads,
19620 this will cause a name conflict with the generated test package.
19623 @node Switches for gnattest
19624 @section Switches for @command{gnattest}
19629 @item --harness-only
19630 @cindex @option{--harness-only} (@command{gnattest})
19631 When this option is given, @command{gnattest} creates a harness for all
19632 sources, treating them as test packages.
19634 @item --additional-tests=@var{projname}
19635 @cindex @option{--additional-tests} (@command{gnattest})
19636 Sources described in @var{projname} are considered potential additional
19637 manual tests to be added to the test suite.
19640 @cindex @option{-r} (@command{gnattest})
19641 Recursively consider all sources from all projects.
19643 @item -X@var{name=value}
19644 @cindex @option{-X} (@command{gnattest})
19645 Indicate that external variable @var{name} has the value @var{value}.
19648 @cindex @option{-q} (@command{gnattest})
19649 Suppresses noncritical output messages.
19652 @cindex @option{-v} (@command{gnattest})
19653 Verbose mode: generates version information.
19655 @item --validate-type-extensions
19656 @cindex @option{--validate-type-extensions} (@command{gnattest})
19657 Enables substitution check: run all tests from all parents in order
19658 to check substitutability.
19660 @item --skeleton-default=@var{val}
19661 @cindex @option{--skeleton-default} (@command{gnattest})
19662 Specifies the default behavior of generated skeletons. @var{val} can be either
19663 "fail" or "pass", "fail" being the default.
19665 @item --passed-tests=@var{val}
19666 @cindex @option{--skeleton-default} (@command{gnattest})
19667 Specifies whether or not passed tests should be shown. @var{val} can be either
19668 "show" or "hide", "show" being the default.
19671 @item --tests-root=@var{dirname}
19672 @cindex @option{--tests-root} (@command{gnattest})
19673 The directory hierarchy of tested sources is recreated in the @var{dirname}
19674 directory, and test packages are placed in corresponding directories.
19675 If the @var{dirname} is a relative path, it is considered relative to the object
19676 directory of the project file. When all sources from all projects are taken
19677 recursively from all projects, directory hierarchies of tested sources are
19678 recreated for each project in their object directories and test packages are
19679 placed accordingly.
19681 @item --subdir=@var{dirname}
19682 @cindex @option{--subdir} (@command{gnattest})
19683 Test packages are placed in subdirectories.
19685 @item --tests-dir=@var{dirname}
19686 @cindex @option{--tests-dir} (@command{gnattest})
19687 All test packages are placed in the @var{dirname} directory.
19688 If the @var{dirname} is a relative path, it is considered relative to the object
19689 directory of the project file. When all sources from all projects are taken
19690 recursively from all projects, @var{dirname} directories are created for each
19691 project in their object directories and test packages are placed accordingly.
19693 @item --harness-dir=@var{dirname}
19694 @cindex @option{--harness-dir} (@command{gnattest})
19695 specifies the directory that will hold the harness packages and project file
19696 for the test driver. If the @var{dirname} is a relative path, it is considered
19697 relative to the object directory of the project file.
19700 @cindex @option{--separates} (@command{gnattest})
19701 Bodies of all test routines are generated as separates. Note that this mode is
19702 kept for compatibility reasons only and it is not advised to use it due to
19703 possible problems with hash in names of test skeletons when using an
19704 inconsistent casing. Separate test skeletons can be incorporated to monolith
19705 test package with improved hash being used by using @option{--transition}
19710 @cindex @option{--transition} (@command{gnattest})
19711 This allows transition from separate test routines to monolith test packages.
19712 All matching test routines are overwritten with contents of corresponding
19713 separates. Note that if separate test routines had any manually added with
19714 clauses they will be moved to the test package body as is and have to be moved
19719 @option{--tests_root}, @option{--subdir} and @option{--tests-dir} switches are
19720 mutually exclusive.
19722 @node Project Attributes for gnattest
19723 @section Project Attributes for @command{gnattest}
19727 Most of the command-line options can also be passed to the tool by adding
19728 special attributes to the project file. Those attributes should be put in
19729 package gnattest. Here is the list of attributes:
19734 is used to select the same output mode as with the --tests-root option.
19735 This attribute cannot be used together with Subdir or Tests_Dir.
19738 is used to select the same output mode as with the --subdir option.
19739 This attribute cannot be used together with Tests_Root or Tests_Dir.
19742 is used to select the same output mode as with the --tests-dir option.
19743 This attribute cannot be used together with Subdir or Tests_Root.
19746 is used to specify the directory in which to place harness packages and project
19747 file for the test driver, otherwise specified by --harness-dir.
19749 @item Additional_Tests
19750 is used to specify the project file, otherwise given by
19751 --additional-tests switch.
19753 @item Skeletons_Default
19754 is used to specify the default behaviour of test skeletons, otherwise
19755 specified by --skeleton-default option. The value of this attribute
19756 should be either "pass" or "fail".
19760 Each of those attributes can be overridden from the command line if needed.
19761 Other @command{gnattest} switches can also be passed via the project
19762 file as an attribute list called GNATtest_Switches.
19764 @node Simple Example
19765 @section Simple Example
19769 Let's take a very simple example using the first @command{gnattest} example
19773 <install_prefix>/share/examples/gnattest/simple
19776 This project contains a simple package containing one subprogram. By running gnattest:
19779 $ gnattest --harness-dir=driver -Psimple.gpr
19782 a test driver is created in directory "driver". It can be compiled and run:
19786 $ gnatmake -Ptest_driver
19790 One failed test with diagnosis "test not implemented" is reported.
19791 Since no special output option was specified, the test package Simple.Tests
19795 <install_prefix>/share/examples/gnattest/simple/obj/gnattest/tests
19798 For each package containing visible subprograms, a child test package is
19799 generated. It contains one test routine per tested subprogram. Each
19800 declaration of a test subprogram has a comment specifying which tested
19801 subprogram it corresponds to. Bodies of test routines are placed in test package
19802 bodies and are surrounded by special comment sections. Those comment sections
19803 should not be removed or modified in order for gnattest to be able to regenerate
19804 test packages and keep already written tests in place.
19805 The test routine Test_Inc_5eaee3 located at simple-test_data-tests.adb contains
19806 a single statement: a call to procedure Assert. It has two arguments:
19807 the Boolean expression we want to check and the diagnosis message to display if
19808 the condition is false.
19810 That is where actual testing code should be written after a proper setup.
19811 An actual check can be performed by replacing the Assert call with:
19813 @smallexample @c ada
19814 Assert (Inc (1) = 2, "wrong incrementation");
19817 After recompiling and running the test driver, one successfully passed test
19820 @node Setting Up and Tearing Down the Testing Environment
19821 @section Setting Up and Tearing Down the Testing Environment
19825 Besides test routines themselves, each test package has a parent package
19826 Test_Data that has two procedures: Set_Up and Tear_Down. This package is never
19827 overwritten by the tool. Set_Up is called before each test routine of the
19828 package and Tear_Down is called after each test routine. Those two procedures
19829 can be used to perform necessary initialization and finalization,
19830 memory allocation, etc. Test type declared in Test_Data package is parent type
19831 for the test type of test package and can have user-defined components whose
19832 values can be set by Set_Up routine and used in test routines afterwards.
19834 @node Regenerating Tests
19835 @section Regenerating Tests
19839 Bodies of test routines and test_data packages are never overridden after they
19840 have been created once. As long as the name of the subprogram, full expanded Ada
19841 names, and the order of its parameters is the same, and comment sections are
19842 intact the old test routine will fit in its place and no test skeleton will be
19843 generated for the subprogram.
19845 This can be demonstrated with the previous example. By uncommenting declaration
19846 and body of function Dec in simple.ads and simple.adb, running
19847 @command{gnattest} on the project, and then running the test driver:
19850 gnattest --harness-dir=driver -Psimple.gpr
19852 gnatmake -Ptest_driver
19856 the old test is not replaced with a stub, nor is it lost, but a new test
19857 skeleton is created for function Dec.
19859 The only way of regenerating tests skeletons is to remove the previously created
19860 tests together with corresponding comment sections.
19862 @node Default Test Behavior
19863 @section Default Test Behavior
19867 The generated test driver can treat unimplemented tests in two ways:
19868 either count them all as failed (this is useful to see which tests are still
19869 left to implement) or as passed (to sort out unimplemented ones from those
19872 The test driver accepts a switch to specify this behavior:
19873 --skeleton-default=val, where val is either "pass" or "fail" (exactly as for
19874 @command{gnattest}).
19876 The default behavior of the test driver is set with the same switch
19877 as passed to gnattest when generating the test driver.
19879 Passing it to the driver generated on the first example:
19882 test_runner --skeleton-default=pass
19885 makes both tests pass, even the unimplemented one.
19887 @node Testing Primitive Operations of Tagged Types
19888 @section Testing Primitive Operations of Tagged Types
19892 Creation of test skeletons for primitive operations of tagged types entails
19893 a number of features. Test routines for all primitives of a given tagged type
19894 are placed in a separate child package named according to the tagged type. For
19895 example, if you have tagged type T in package P, all tests for primitives
19896 of T will be in P.T_Test_Data.T_Tests.
19898 Consider running gnattest on the second example (note: actual tests for this
19899 example already exist, so there's no need to worry if the tool reports that
19900 no new stubs were generated):
19903 cd <install_prefix>/share/examples/gnattest/tagged_rec
19904 gnattest --harness-dir=driver -Ptagged_rec.gpr
19907 Taking a closer look at the test type declared in the test package
19908 Speed1.Controller_Test_Data is necessary. It is declared in:
19911 <install_prefix>/share/examples/gnattest/tagged_rec/obj/gnattest/tests
19914 Test types are direct or indirect descendants of
19915 AUnit.Test_Fixtures.Test_Fixture type. In the case of nonprimitive tested
19916 subprograms, the user doesn't need to be concerned with them. However,
19917 when generating test packages for primitive operations, there are some things
19918 the user needs to know.
19920 Type Test_Controller has components that allow assignment of various
19921 derivations of type Controller. And if you look at the specification of
19922 package Speed2.Auto_Controller, you will see that Test_Auto_Controller
19923 actually derives from Test_Controller rather than AUnit type Test_Fixture.
19924 Thus, test types mirror the hierarchy of tested types.
19926 The Set_Up procedure of Test_Data package corresponding to a test package
19927 of primitive operations of type T assigns to Fixture a reference to an
19928 object of that exact type T. Notice, however, that if the tagged type has
19929 discriminants, the Set_Up only has a commented template for setting
19930 up the fixture, since filling the discriminant with actual value is up
19933 The knowledge of the structure of test types allows additional testing
19934 without additional effort. Those possibilities are described below.
19936 @node Testing Inheritance
19937 @section Testing Inheritance
19941 Since the test type hierarchy mimics the hierarchy of tested types, the
19942 inheritance of tests takes place. An example of such inheritance can be
19943 seen by running the test driver generated for the second example. As previously
19944 mentioned, actual tests are already written for this example.
19948 gnatmake -Ptest_driver
19952 There are 6 passed tests while there are only 5 testable subprograms. The test
19953 routine for function Speed has been inherited and run against objects of the
19956 @node Tagged Types Substitutability Testing
19957 @section Tagged Types Substitutability Testing
19961 Tagged Types Substitutability Testing is a way of verifying the global type
19962 consistency by testing. Global type consistency is a principle stating that if
19963 S is a subtype of T (in Ada, S is a derived type of tagged type T),
19964 then objects of type T may be replaced with objects of type S (that is,
19965 objects of type S may be substituted for objects of type T), without
19966 altering any of the desirable properties of the program. When the properties
19967 of the program are expressed in the form of subprogram preconditions and
19968 postconditions (let's call them pre and post), the principle is formulated as
19969 relations between the pre and post of primitive operations and the pre and post
19970 of their derived operations. The pre of a derived operation should not be
19971 stronger than the original pre, and the post of the derived operation should
19972 not be weaker than the original post. Those relations ensure that verifying if
19973 a dispatching call is safe can be done just by using the pre and post of the
19976 Verifying global type consistency by testing consists of running all the unit
19977 tests associated with the primitives of a given tagged type with objects of its
19980 In the example used in the previous section, there was clearly a violation of
19981 type consistency. The overriding primitive Adjust_Speed in package Speed2
19982 removes the functionality of the overridden primitive and thus doesn't respect
19983 the consistency principle.
19984 Gnattest has a special option to run overridden parent tests against objects
19985 of the type which have overriding primitives:
19988 gnattest --harness-dir=driver --validate-type-extensions -Ptagged_rec.gpr
19990 gnatmake -Ptest_driver
19994 While all the tests pass by themselves, the parent test for Adjust_Speed fails
19995 against objects of the derived type.
19997 Non-overridden tests are already inherited for derived test types, so the
19998 --validate-type-extensions enables the application of overriden tests to objects
20001 @node Testing with Contracts
20002 @section Testing with Contracts
20006 @command{gnattest} supports pragmas Precondition, Postcondition, and Test_Case,
20007 as well as corresponding aspects.
20008 Test routines are generated, one per each Test_Case associated with a tested
20009 subprogram. Those test routines have special wrappers for tested functions
20010 that have composition of pre- and postcondition of the subprogram with
20011 "requires" and "ensures" of the Test_Case (depending on the mode, pre and post
20012 either count for Nominal mode or do not count for Robustness mode).
20014 The third example demonstrates how this works:
20017 cd <install_prefix>/share/examples/gnattest/contracts
20018 gnattest --harness-dir=driver -Pcontracts.gpr
20021 Putting actual checks within the range of the contract does not cause any
20022 error reports. For example, for the test routine which corresponds to
20025 @smallexample @c ada
20026 Assert (Sqrt (9.0) = 3.0, "wrong sqrt");
20029 and for the test routine corresponding to test case 2:
20031 @smallexample @c ada
20032 Assert (Sqrt (-5.0) = -1.0, "wrong error indication");
20039 gnatmake -Ptest_driver
20043 However, by changing 9.0 to 25.0 and 3.0 to 5.0, for example, you can get
20044 a precondition violation for test case one. Also, by using any otherwise
20045 correct but positive pair of numbers in the second test routine, you can also
20046 get a precondition violation. Postconditions are checked and reported
20049 @node Additional Tests
20050 @section Additional Tests
20053 @command{gnattest} can add user-written tests to the main suite of the test
20054 driver. @command{gnattest} traverses the given packages and searches for test
20055 routines. All procedures with a single in out parameter of a type which is
20056 derived from AUnit.Test_Fixtures.Test_Fixture and that are declared in package
20057 specifications are added to the suites and are then executed by the test driver.
20058 (Set_Up and Tear_Down are filtered out.)
20060 An example illustrates two ways of creating test harnesses for user-written
20061 tests. Directory additional_tests contains an AUnit-based test driver written
20065 <install_prefix>/share/examples/gnattest/additional_tests/
20068 To create a test driver for already-written tests, use the --harness-only
20072 gnattest -Padditional/harness/harness.gpr --harness-dir=harness_only \
20074 gnatmake -Pharness_only/test_driver.gpr
20075 harness_only/test_runner
20078 Additional tests can also be executed together with generated tests:
20081 gnattest -Psimple.gpr --additional-tests=additional/harness/harness.gpr \
20082 --harness-dir=mixing
20083 gnatmake -Pmixing/test_driver.gpr
20088 @node Support for other platforms/run-times
20089 @section Support for other platforms/run-times
20092 @command{gnattest} can be used to generate the test harness for platforms
20093 and run-time libraries others than the default native target with the
20094 default full run-time. For example, when using a limited run-time library
20095 such as Zero FootPrint (ZFP), a simplified harness is generated.
20097 Two variables are used to tell the underlying AUnit framework how to generate
20098 the test harness: @code{PLATFORM}, which identifies the target, and
20099 @code{RUNTIME}, used to determine the run-time library for which the harness
20100 is generated. Corresponding prefix should also be used when calling
20101 @command{gnattest} for non-native targets. For example, the following options
20102 are used to generate the AUnit test harness for a PowerPC ELF target using
20103 the ZFP run-time library:
20106 powerpc-elf-gnattest -Psimple.gpr -XPLATFORM=powerpc-elf -XRUNTIME=zfp
20110 @node Current Limitations
20111 @section Current Limitations
20115 The tool currently does not support following features:
20118 @item generic tests for generic packages and package instantiations
20119 @item tests for protected subprograms and entries
20125 @c *********************************
20126 @node Performing Dimensionality Analysis in GNAT
20127 @chapter Performing Dimensionality Analysis in GNAT
20129 The GNAT compiler now supports dimensionality checking. The user can
20130 specify physical units for objects, and the compiler will verify that uses
20131 of these objects are compatible with their dimensions, in a fashion that is
20132 familiar to engineering practice. The dimensions of algebraic expressions
20133 (including powers with static exponents) are computed from their consistuents.
20135 This feature depends on Ada 2012 aspect specifications, and is available from
20136 version 7.0.1 of GNAT onwards. The GNAT-specific aspect Dimension_System allows
20137 you to define a system of units; the aspect Dimension then allows the user
20138 to declare dimensioned quantities within a given system.
20140 The major advantage of this model is that it does not require the declaration of
20141 multiple operators for all possible combinations of types: it is only necessary
20142 to use the proper subtypes in object declarations.
20144 The simplest way to impose dimensionality checking on a computation is to make
20145 use of the package System.Dim.Mks, which is part of the GNAT library. This
20146 package defines a floating-point type MKS_Type, for which a sequence of
20147 dimension names are specified, together with their conventional abbreviations.
20148 The following should be read together with the full specification of the
20149 package, in file s-dimmks.ads.
20151 @smallexample @c ada
20152 type Mks_Type is new Long_Long_Float
20154 Dimension_System => (
20155 (Unit_Name => Meter, Unit_Symbol => 'm', Dim_Symbol => 'L'),
20156 (Unit_Name => Kilogram, Unit_Symbol => "kg", Dim_Symbol => 'M'),
20157 (Unit_Name => Second, Unit_Symbol => 's', Dim_Symbol => 'T'),
20158 (Unit_Name => Ampere, Unit_Symbol => 'A', Dim_Symbol => 'I'),
20159 (Unit_Name => Kelvin, Unit_Symbol => 'K', Dim_Symbol => "Theta"),
20160 (Unit_Name => Mole, Unit_Symbol => "mol", Dim_Symbol => 'N'),
20161 (Unit_Name => Candela, Unit_Symbol => "cd", Dim_Symbol => 'J'));
20165 The package then defines a series of subtypes that correspond to these
20166 conventional units. For example:
20167 @smallexample @c ada
20168 subtype Length is Mks_Type
20170 Dimension => (Symbol => 'm', Meter => 1, others => 0);
20173 and similarly for Mass, Time, Electric_Current, Thermodynamic_Temperature,
20174 Amount_Of_Substance, and Luminous_Intensity (the standard set of units of
20177 The package also defines conventional names for values of each unit, for
20180 @smallexample @c ada
20181 m : constant Length := 1.0;
20182 kg : constant Mass := 1.0;
20183 s : constant Time := 1.0;
20184 A : constant Electric_Current := 1.0;
20188 as well as useful multiples of these units:
20190 @smallexample @c ada
20191 cm : constant Length := 1.0E-02;
20192 g : constant Mass := 1.0E-03;
20193 min : constant Time := 60.0;
20194 day : constant TIme := 60.0 * 24.0 * min;
20199 Using this package, you can then define a derived unit by
20200 providing the aspect that
20201 specifies its dimensions within the MKS system, as well as the string to
20202 be used for output of a value of that unit:
20204 @smallexample @c ada
20205 subtype Acceleration is Mks_Type
20206 with Dimension => ("m/sec^^^2",
20213 Here is a complete example of use:
20215 @smallexample @c ada
20216 with System.Dim.MKS; use System.Dim.Mks;
20217 with System.Dim.Mks_IO; use System.Dim.Mks_IO;
20218 with Text_IO; use Text_IO;
20219 procedure Free_Fall is
20220 subtype Acceleration is Mks_Type
20221 with Dimension => ("m/sec^^^2", 1, 0, -2, others => 0);
20222 G : constant acceleration := 9.81 * m / (s ** 2);
20223 T : Time := 10.0*s;
20226 Put ("Gravitational constant: ");
20227 Put (G, Aft => 2, Exp => 0); Put_Line ("");
20228 Distance := 0.5 * G * T ** 2;
20229 Put ("distance travelled in 10 seconds of free fall ");
20230 Put (Distance, Aft => 2, Exp => 0);
20236 Execution of this program yields:
20238 Gravitational constant: 9.81 m/sec^^^2
20239 distance travelled in 10 seconds of free fall 490.50 m
20243 However, incorrect assignments such as:
20245 @smallexample @c ada
20247 Distance := 5.0 * kg:
20251 are rejected with the following diagnoses:
20255 >>> dimensions mismatch in assignment
20256 >>> left-hand side has dimension [L]
20257 >>> right-hand side is dimensionless
20259 Distance := 5.0 * kg:
20260 >>> dimensions mismatch in assignment
20261 >>> left-hand side has dimension [L]
20262 >>> right-hand side has dimension [M]
20266 The dimensions of an expression are properly displayed, even if there is
20267 no explicit subtype for it. If we add to the program:
20269 @smallexample @c ada
20270 Put ("Final velocity: ");
20271 Put (G * T, Aft =>2, Exp =>0);
20276 then the output includes:
20278 Final velocity: 98.10 m.s**(-1)
20281 @c *********************************
20282 @node Generating Ada Bindings for C and C++ headers
20283 @chapter Generating Ada Bindings for C and C++ headers
20287 GNAT now comes with a binding generator for C and C++ headers which is
20288 intended to do 95% of the tedious work of generating Ada specs from C
20289 or C++ header files.
20291 Note that this capability is not intended to generate 100% correct Ada specs,
20292 and will is some cases require manual adjustments, although it can often
20293 be used out of the box in practice.
20295 Some of the known limitations include:
20298 @item only very simple character constant macros are translated into Ada
20299 constants. Function macros (macros with arguments) are partially translated
20300 as comments, to be completed manually if needed.
20301 @item some extensions (e.g. vector types) are not supported
20302 @item pointers to pointers or complex structures are mapped to System.Address
20303 @item identifiers with identical name (except casing) will generate compilation
20304 errors (e.g. @code{shm_get} vs @code{SHM_GET}).
20307 The code generated is using the Ada 2005 syntax, which makes it
20308 easier to interface with other languages than previous versions of Ada.
20311 * Running the binding generator::
20312 * Generating bindings for C++ headers::
20316 @node Running the binding generator
20317 @section Running the binding generator
20320 The binding generator is part of the @command{gcc} compiler and can be
20321 invoked via the @option{-fdump-ada-spec} switch, which will generate Ada
20322 spec files for the header files specified on the command line, and all
20323 header files needed by these files transitively. For example:
20326 $ g++ -c -fdump-ada-spec -C /usr/include/time.h
20327 $ gcc -c -gnat05 *.ads
20330 will generate, under GNU/Linux, the following files: @file{time_h.ads},
20331 @file{bits_time_h.ads}, @file{stddef_h.ads}, @file{bits_types_h.ads} which
20332 correspond to the files @file{/usr/include/time.h},
20333 @file{/usr/include/bits/time.h}, etc@dots{}, and will then compile in Ada 2005
20334 mode these Ada specs.
20336 The @code{-C} switch tells @command{gcc} to extract comments from headers,
20337 and will attempt to generate corresponding Ada comments.
20339 If you want to generate a single Ada file and not the transitive closure, you
20340 can use instead the @option{-fdump-ada-spec-slim} switch.
20342 You can optionally specify a parent unit, of which all generated units will
20343 be children, using @code{-fada-spec-parent=}@var{unit}.
20345 Note that we recommend when possible to use the @command{g++} driver to
20346 generate bindings, even for most C headers, since this will in general
20347 generate better Ada specs. For generating bindings for C++ headers, it is
20348 mandatory to use the @command{g++} command, or @command{gcc -x c++} which
20349 is equivalent in this case. If @command{g++} cannot work on your C headers
20350 because of incompatibilities between C and C++, then you can fallback to
20351 @command{gcc} instead.
20353 For an example of better bindings generated from the C++ front-end,
20354 the name of the parameters (when available) are actually ignored by the C
20355 front-end. Consider the following C header:
20358 extern void foo (int variable);
20361 with the C front-end, @code{variable} is ignored, and the above is handled as:
20364 extern void foo (int);
20367 generating a generic:
20370 procedure foo (param1 : int);
20373 with the C++ front-end, the name is available, and we generate:
20376 procedure foo (variable : int);
20379 In some cases, the generated bindings will be more complete or more meaningful
20380 when defining some macros, which you can do via the @option{-D} switch. This
20381 is for example the case with @file{Xlib.h} under GNU/Linux:
20384 g++ -c -fdump-ada-spec -DXLIB_ILLEGAL_ACCESS -C /usr/include/X11/Xlib.h
20387 The above will generate more complete bindings than a straight call without
20388 the @option{-DXLIB_ILLEGAL_ACCESS} switch.
20390 In other cases, it is not possible to parse a header file in a stand-alone
20391 manner, because other include files need to be included first. In this
20392 case, the solution is to create a small header file including the needed
20393 @code{#include} and possible @code{#define} directives. For example, to
20394 generate Ada bindings for @file{readline/readline.h}, you need to first
20395 include @file{stdio.h}, so you can create a file with the following two
20396 lines in e.g. @file{readline1.h}:
20400 #include <readline/readline.h>
20403 and then generate Ada bindings from this file:
20406 $ g++ -c -fdump-ada-spec readline1.h
20409 @node Generating bindings for C++ headers
20410 @section Generating bindings for C++ headers
20413 Generating bindings for C++ headers is done using the same options, always
20414 with the @command{g++} compiler.
20416 In this mode, C++ classes will be mapped to Ada tagged types, constructors
20417 will be mapped using the @code{CPP_Constructor} pragma, and when possible,
20418 multiple inheritance of abstract classes will be mapped to Ada interfaces
20419 (@xref{Interfacing to C++,,,gnat_rm, GNAT Reference Manual}, for additional
20420 information on interfacing to C++).
20422 For example, given the following C++ header file:
20429 virtual int Number_Of_Teeth () = 0;
20434 virtual void Set_Owner (char* Name) = 0;
20440 virtual void Set_Age (int New_Age);
20443 class Dog : Animal, Carnivore, Domestic @{
20448 virtual int Number_Of_Teeth ();
20449 virtual void Set_Owner (char* Name);
20457 The corresponding Ada code is generated:
20459 @smallexample @c ada
20462 package Class_Carnivore is
20463 type Carnivore is limited interface;
20464 pragma Import (CPP, Carnivore);
20466 function Number_Of_Teeth (this : access Carnivore) return int is abstract;
20468 use Class_Carnivore;
20470 package Class_Domestic is
20471 type Domestic is limited interface;
20472 pragma Import (CPP, Domestic);
20474 procedure Set_Owner
20475 (this : access Domestic;
20476 Name : Interfaces.C.Strings.chars_ptr) is abstract;
20478 use Class_Domestic;
20480 package Class_Animal is
20481 type Animal is tagged limited record
20482 Age_Count : aliased int;
20484 pragma Import (CPP, Animal);
20486 procedure Set_Age (this : access Animal; New_Age : int);
20487 pragma Import (CPP, Set_Age, "_ZN6Animal7Set_AgeEi");
20491 package Class_Dog is
20492 type Dog is new Animal and Carnivore and Domestic with record
20493 Tooth_Count : aliased int;
20494 Owner : Interfaces.C.Strings.chars_ptr;
20496 pragma Import (CPP, Dog);
20498 function Number_Of_Teeth (this : access Dog) return int;
20499 pragma Import (CPP, Number_Of_Teeth, "_ZN3Dog15Number_Of_TeethEv");
20501 procedure Set_Owner
20502 (this : access Dog; Name : Interfaces.C.Strings.chars_ptr);
20503 pragma Import (CPP, Set_Owner, "_ZN3Dog9Set_OwnerEPc");
20505 function New_Dog return Dog;
20506 pragma CPP_Constructor (New_Dog);
20507 pragma Import (CPP, New_Dog, "_ZN3DogC1Ev");
20518 @item -fdump-ada-spec
20519 @cindex @option{-fdump-ada-spec} (@command{gcc})
20520 Generate Ada spec files for the given header files transitively (including
20521 all header files that these headers depend upon).
20523 @item -fdump-ada-spec-slim
20524 @cindex @option{-fdump-ada-spec-slim} (@command{gcc})
20525 Generate Ada spec files for the header files specified on the command line
20528 @item -fada-spec-parent=@var{unit}
20529 @cindex -fada-spec-parent (@command{gcc})
20530 Specifies that all files generated by @option{-fdump-ada-spec*} are
20531 to be child units of the specified parent unit.
20534 @cindex @option{-C} (@command{gcc})
20535 Extract comments from headers and generate Ada comments in the Ada spec files.
20538 @node Other Utility Programs
20539 @chapter Other Utility Programs
20542 This chapter discusses some other utility programs available in the Ada
20546 * Using Other Utility Programs with GNAT::
20547 * The External Symbol Naming Scheme of GNAT::
20548 * Converting Ada Files to html with gnathtml::
20549 * Installing gnathtml::
20556 @node Using Other Utility Programs with GNAT
20557 @section Using Other Utility Programs with GNAT
20560 The object files generated by GNAT are in standard system format and in
20561 particular the debugging information uses this format. This means
20562 programs generated by GNAT can be used with existing utilities that
20563 depend on these formats.
20566 In general, any utility program that works with C will also often work with
20567 Ada programs generated by GNAT. This includes software utilities such as
20568 gprof (a profiling program), @code{gdb} (the FSF debugger), and utilities such
20572 @node The External Symbol Naming Scheme of GNAT
20573 @section The External Symbol Naming Scheme of GNAT
20576 In order to interpret the output from GNAT, when using tools that are
20577 originally intended for use with other languages, it is useful to
20578 understand the conventions used to generate link names from the Ada
20581 All link names are in all lowercase letters. With the exception of library
20582 procedure names, the mechanism used is simply to use the full expanded
20583 Ada name with dots replaced by double underscores. For example, suppose
20584 we have the following package spec:
20586 @smallexample @c ada
20597 The variable @code{MN} has a full expanded Ada name of @code{QRS.MN}, so
20598 the corresponding link name is @code{qrs__mn}.
20600 Of course if a @code{pragma Export} is used this may be overridden:
20602 @smallexample @c ada
20607 pragma Export (Var1, C, External_Name => "var1_name");
20609 pragma Export (Var2, C, Link_Name => "var2_link_name");
20616 In this case, the link name for @var{Var1} is whatever link name the
20617 C compiler would assign for the C function @var{var1_name}. This typically
20618 would be either @var{var1_name} or @var{_var1_name}, depending on operating
20619 system conventions, but other possibilities exist. The link name for
20620 @var{Var2} is @var{var2_link_name}, and this is not operating system
20624 One exception occurs for library level procedures. A potential ambiguity
20625 arises between the required name @code{_main} for the C main program,
20626 and the name we would otherwise assign to an Ada library level procedure
20627 called @code{Main} (which might well not be the main program).
20629 To avoid this ambiguity, we attach the prefix @code{_ada_} to such
20630 names. So if we have a library level procedure such as
20632 @smallexample @c ada
20635 procedure Hello (S : String);
20641 the external name of this procedure will be @var{_ada_hello}.
20644 @node Converting Ada Files to html with gnathtml
20645 @section Converting Ada Files to HTML with @code{gnathtml}
20648 This @code{Perl} script allows Ada source files to be browsed using
20649 standard Web browsers. For installation procedure, see the section
20650 @xref{Installing gnathtml}.
20652 Ada reserved keywords are highlighted in a bold font and Ada comments in
20653 a blue font. Unless your program was compiled with the gcc @option{-gnatx}
20654 switch to suppress the generation of cross-referencing information, user
20655 defined variables and types will appear in a different color; you will
20656 be able to click on any identifier and go to its declaration.
20658 The command line is as follow:
20660 @c $ perl gnathtml.pl @ovar{^switches^options^} @var{ada-files}
20661 @c Expanding @ovar macro inline (explanation in macro def comments)
20662 $ perl gnathtml.pl @r{[}@var{^switches^options^}@r{]} @var{ada-files}
20666 You can pass it as many Ada files as you want. @code{gnathtml} will generate
20667 an html file for every ada file, and a global file called @file{index.htm}.
20668 This file is an index of every identifier defined in the files.
20670 The available ^switches^options^ are the following ones:
20674 @cindex @option{-83} (@code{gnathtml})
20675 Only the Ada 83 subset of keywords will be highlighted.
20677 @item -cc @var{color}
20678 @cindex @option{-cc} (@code{gnathtml})
20679 This option allows you to change the color used for comments. The default
20680 value is green. The color argument can be any name accepted by html.
20683 @cindex @option{-d} (@code{gnathtml})
20684 If the Ada files depend on some other files (for instance through
20685 @code{with} clauses, the latter files will also be converted to html.
20686 Only the files in the user project will be converted to html, not the files
20687 in the run-time library itself.
20690 @cindex @option{-D} (@code{gnathtml})
20691 This command is the same as @option{-d} above, but @command{gnathtml} will
20692 also look for files in the run-time library, and generate html files for them.
20694 @item -ext @var{extension}
20695 @cindex @option{-ext} (@code{gnathtml})
20696 This option allows you to change the extension of the generated HTML files.
20697 If you do not specify an extension, it will default to @file{htm}.
20700 @cindex @option{-f} (@code{gnathtml})
20701 By default, gnathtml will generate html links only for global entities
20702 ('with'ed units, global variables and types,@dots{}). If you specify
20703 @option{-f} on the command line, then links will be generated for local
20706 @item -l @var{number}
20707 @cindex @option{-l} (@code{gnathtml})
20708 If this ^switch^option^ is provided and @var{number} is not 0, then
20709 @code{gnathtml} will number the html files every @var{number} line.
20712 @cindex @option{-I} (@code{gnathtml})
20713 Specify a directory to search for library files (@file{.ALI} files) and
20714 source files. You can provide several -I switches on the command line,
20715 and the directories will be parsed in the order of the command line.
20718 @cindex @option{-o} (@code{gnathtml})
20719 Specify the output directory for html files. By default, gnathtml will
20720 saved the generated html files in a subdirectory named @file{html/}.
20722 @item -p @var{file}
20723 @cindex @option{-p} (@code{gnathtml})
20724 If you are using Emacs and the most recent Emacs Ada mode, which provides
20725 a full Integrated Development Environment for compiling, checking,
20726 running and debugging applications, you may use @file{.gpr} files
20727 to give the directories where Emacs can find sources and object files.
20729 Using this ^switch^option^, you can tell gnathtml to use these files.
20730 This allows you to get an html version of your application, even if it
20731 is spread over multiple directories.
20733 @item -sc @var{color}
20734 @cindex @option{-sc} (@code{gnathtml})
20735 This ^switch^option^ allows you to change the color used for symbol
20737 The default value is red. The color argument can be any name accepted by html.
20739 @item -t @var{file}
20740 @cindex @option{-t} (@code{gnathtml})
20741 This ^switch^option^ provides the name of a file. This file contains a list of
20742 file names to be converted, and the effect is exactly as though they had
20743 appeared explicitly on the command line. This
20744 is the recommended way to work around the command line length limit on some
20749 @node Installing gnathtml
20750 @section Installing @code{gnathtml}
20753 @code{Perl} needs to be installed on your machine to run this script.
20754 @code{Perl} is freely available for almost every architecture and
20755 Operating System via the Internet.
20757 On Unix systems, you may want to modify the first line of the script
20758 @code{gnathtml}, to explicitly tell the Operating system where Perl
20759 is. The syntax of this line is:
20761 #!full_path_name_to_perl
20765 Alternatively, you may run the script using the following command line:
20768 @c $ perl gnathtml.pl @ovar{switches} @var{files}
20769 @c Expanding @ovar macro inline (explanation in macro def comments)
20770 $ perl gnathtml.pl @r{[}@var{switches}@r{]} @var{files}
20779 The GNAT distribution provides an Ada 95 template for the HP Language
20780 Sensitive Editor (LSE), a component of DECset. In order to
20781 access it, invoke LSE with the qualifier /ENVIRONMENT=GNU:[LIB]ADA95.ENV.
20788 GNAT supports The HP Performance Coverage Analyzer (PCA), a component
20789 of DECset. To use it proceed as outlined under ``HELP PCA'', except for running
20790 the collection phase with the /DEBUG qualifier.
20793 $ GNAT MAKE /DEBUG <PROGRAM_NAME>
20794 $ DEFINE LIB$DEBUG PCA$COLLECTOR
20795 $ RUN/DEBUG <PROGRAM_NAME>
20801 @c ******************************
20802 @node Code Coverage and Profiling
20803 @chapter Code Coverage and Profiling
20804 @cindex Code Coverage
20808 This chapter describes how to use @code{gcov} - coverage testing tool - and
20809 @code{gprof} - profiler tool - on your Ada programs.
20812 * Code Coverage of Ada Programs with gcov::
20813 * Profiling an Ada Program with gprof::
20816 @node Code Coverage of Ada Programs with gcov
20817 @section Code Coverage of Ada Programs with gcov
20819 @cindex -fprofile-arcs
20820 @cindex -ftest-coverage
20822 @cindex Code Coverage
20825 @code{gcov} is a test coverage program: it analyzes the execution of a given
20826 program on selected tests, to help you determine the portions of the program
20827 that are still untested.
20829 @code{gcov} is part of the GCC suite, and is described in detail in the GCC
20830 User's Guide. You can refer to this documentation for a more complete
20833 This chapter provides a quick startup guide, and
20834 details some Gnat-specific features.
20837 * Quick startup guide::
20841 @node Quick startup guide
20842 @subsection Quick startup guide
20844 In order to perform coverage analysis of a program using @code{gcov}, 3
20849 Code instrumentation during the compilation process
20851 Execution of the instrumented program
20853 Execution of the @code{gcov} tool to generate the result.
20856 The code instrumentation needed by gcov is created at the object level:
20857 The source code is not modified in any way, because the instrumentation code is
20858 inserted by gcc during the compilation process. To compile your code with code
20859 coverage activated, you need to recompile your whole project using the
20861 @code{-fprofile-arcs} and @code{-ftest-coverage}, and link it using
20862 @code{-fprofile-arcs}.
20865 $ gnatmake -P my_project.gpr -f -cargs -fprofile-arcs -ftest-coverage \
20866 -largs -fprofile-arcs
20869 This compilation process will create @file{.gcno} files together with
20870 the usual object files.
20872 Once the program is compiled with coverage instrumentation, you can
20873 run it as many times as needed - on portions of a test suite for
20874 example. The first execution will produce @file{.gcda} files at the
20875 same location as the @file{.gcno} files. The following executions
20876 will update those files, so that a cumulative result of the covered
20877 portions of the program is generated.
20879 Finally, you need to call the @code{gcov} tool. The different options of
20880 @code{gcov} are available in the GCC User's Guide, section 'Invoking gcov'.
20882 This will create annotated source files with a @file{.gcov} extension:
20883 @file{my_main.adb} file will be analysed in @file{my_main.adb.gcov}.
20885 @node Gnat specifics
20886 @subsection Gnat specifics
20888 Because Ada semantics, portions of the source code may be shared among
20889 several object files. This is the case for example when generics are
20890 involved, when inlining is active or when declarations generate initialisation
20891 calls. In order to take
20892 into account this shared code, you need to call @code{gcov} on all
20893 source files of the tested program at once.
20895 The list of source files might exceed the system's maximum command line
20896 length. In order to bypass this limitation, a new mechanism has been
20897 implemented in @code{gcov}: you can now list all your project's files into a
20898 text file, and provide this file to gcov as a parameter, preceded by a @@
20899 (e.g. @samp{gcov @@mysrclist.txt}).
20901 Note that on AIX compiling a static library with @code{-fprofile-arcs} is
20902 not supported as there can be unresolved symbols during the final link.
20904 @node Profiling an Ada Program with gprof
20905 @section Profiling an Ada Program with gprof
20911 This section is not meant to be an exhaustive documentation of @code{gprof}.
20912 Full documentation for it can be found in the GNU Profiler User's Guide
20913 documentation that is part of this GNAT distribution.
20915 Profiling a program helps determine the parts of a program that are executed
20916 most often, and are therefore the most time-consuming.
20918 @code{gprof} is the standard GNU profiling tool; it has been enhanced to
20919 better handle Ada programs and multitasking.
20920 It is currently supported on the following platforms
20925 solaris sparc/sparc64/x86
20931 In order to profile a program using @code{gprof}, 3 steps are needed:
20935 Code instrumentation, requiring a full recompilation of the project with the
20938 Execution of the program under the analysis conditions, i.e. with the desired
20941 Analysis of the results using the @code{gprof} tool.
20945 The following sections detail the different steps, and indicate how
20946 to interpret the results:
20948 * Compilation for profiling::
20949 * Program execution::
20951 * Interpretation of profiling results::
20954 @node Compilation for profiling
20955 @subsection Compilation for profiling
20959 In order to profile a program the first step is to tell the compiler
20960 to generate the necessary profiling information. The compiler switch to be used
20961 is @code{-pg}, which must be added to other compilation switches. This
20962 switch needs to be specified both during compilation and link stages, and can
20963 be specified once when using gnatmake:
20966 gnatmake -f -pg -P my_project
20970 Note that only the objects that were compiled with the @samp{-pg} switch will
20971 be profiled; if you need to profile your whole project, use the @samp{-f}
20972 gnatmake switch to force full recompilation.
20974 @node Program execution
20975 @subsection Program execution
20978 Once the program has been compiled for profiling, you can run it as usual.
20980 The only constraint imposed by profiling is that the program must terminate
20981 normally. An interrupted program (via a Ctrl-C, kill, etc.) will not be
20984 Once the program completes execution, a data file called @file{gmon.out} is
20985 generated in the directory where the program was launched from. If this file
20986 already exists, it will be overwritten.
20988 @node Running gprof
20989 @subsection Running gprof
20992 The @code{gprof} tool is called as follow:
20995 gprof my_prog gmon.out
21006 The complete form of the gprof command line is the following:
21009 gprof [^switches^options^] [executable [data-file]]
21013 @code{gprof} supports numerous ^switch^options^. The order of these
21014 ^switch^options^ does not matter. The full list of options can be found in
21015 the GNU Profiler User's Guide documentation that comes with this documentation.
21017 The following is the subset of those switches that is most relevant:
21021 @item --demangle[=@var{style}]
21022 @itemx --no-demangle
21023 @cindex @option{--demangle} (@code{gprof})
21024 These options control whether symbol names should be demangled when
21025 printing output. The default is to demangle C++ symbols. The
21026 @code{--no-demangle} option may be used to turn off demangling. Different
21027 compilers have different mangling styles. The optional demangling style
21028 argument can be used to choose an appropriate demangling style for your
21029 compiler, in particular Ada symbols generated by GNAT can be demangled using
21030 @code{--demangle=gnat}.
21032 @item -e @var{function_name}
21033 @cindex @option{-e} (@code{gprof})
21034 The @samp{-e @var{function}} option tells @code{gprof} not to print
21035 information about the function @var{function_name} (and its
21036 children@dots{}) in the call graph. The function will still be listed
21037 as a child of any functions that call it, but its index number will be
21038 shown as @samp{[not printed]}. More than one @samp{-e} option may be
21039 given; only one @var{function_name} may be indicated with each @samp{-e}
21042 @item -E @var{function_name}
21043 @cindex @option{-E} (@code{gprof})
21044 The @code{-E @var{function}} option works like the @code{-e} option, but
21045 execution time spent in the function (and children who were not called from
21046 anywhere else), will not be used to compute the percentages-of-time for
21047 the call graph. More than one @samp{-E} option may be given; only one
21048 @var{function_name} may be indicated with each @samp{-E} option.
21050 @item -f @var{function_name}
21051 @cindex @option{-f} (@code{gprof})
21052 The @samp{-f @var{function}} option causes @code{gprof} to limit the
21053 call graph to the function @var{function_name} and its children (and
21054 their children@dots{}). More than one @samp{-f} option may be given;
21055 only one @var{function_name} may be indicated with each @samp{-f}
21058 @item -F @var{function_name}
21059 @cindex @option{-F} (@code{gprof})
21060 The @samp{-F @var{function}} option works like the @code{-f} option, but
21061 only time spent in the function and its children (and their
21062 children@dots{}) will be used to determine total-time and
21063 percentages-of-time for the call graph. More than one @samp{-F} option
21064 may be given; only one @var{function_name} may be indicated with each
21065 @samp{-F} option. The @samp{-F} option overrides the @samp{-E} option.
21069 @node Interpretation of profiling results
21070 @subsection Interpretation of profiling results
21074 The results of the profiling analysis are represented by two arrays: the
21075 'flat profile' and the 'call graph'. Full documentation of those outputs
21076 can be found in the GNU Profiler User's Guide.
21078 The flat profile shows the time spent in each function of the program, and how
21079 many time it has been called. This allows you to locate easily the most
21080 time-consuming functions.
21082 The call graph shows, for each subprogram, the subprograms that call it,
21083 and the subprograms that it calls. It also provides an estimate of the time
21084 spent in each of those callers/called subprograms.
21087 @c ******************************
21088 @node Running and Debugging Ada Programs
21089 @chapter Running and Debugging Ada Programs
21093 This chapter discusses how to debug Ada programs.
21095 It applies to GNAT on the Alpha OpenVMS platform;
21096 for I64 OpenVMS please refer to the @cite{OpenVMS Debugger Manual},
21097 since HP has implemented Ada support in the OpenVMS debugger on I64.
21100 An incorrect Ada program may be handled in three ways by the GNAT compiler:
21104 The illegality may be a violation of the static semantics of Ada. In
21105 that case GNAT diagnoses the constructs in the program that are illegal.
21106 It is then a straightforward matter for the user to modify those parts of
21110 The illegality may be a violation of the dynamic semantics of Ada. In
21111 that case the program compiles and executes, but may generate incorrect
21112 results, or may terminate abnormally with some exception.
21115 When presented with a program that contains convoluted errors, GNAT
21116 itself may terminate abnormally without providing full diagnostics on
21117 the incorrect user program.
21121 * The GNAT Debugger GDB::
21123 * Introduction to GDB Commands::
21124 * Using Ada Expressions::
21125 * Calling User-Defined Subprograms::
21126 * Using the Next Command in a Function::
21129 * Debugging Generic Units::
21130 * Remote Debugging with gdbserver::
21131 * GNAT Abnormal Termination or Failure to Terminate::
21132 * Naming Conventions for GNAT Source Files::
21133 * Getting Internal Debugging Information::
21134 * Stack Traceback::
21140 @node The GNAT Debugger GDB
21141 @section The GNAT Debugger GDB
21144 @code{GDB} is a general purpose, platform-independent debugger that
21145 can be used to debug mixed-language programs compiled with @command{gcc},
21146 and in particular is capable of debugging Ada programs compiled with
21147 GNAT. The latest versions of @code{GDB} are Ada-aware and can handle
21148 complex Ada data structures.
21150 @xref{Top,, Debugging with GDB, gdb, Debugging with GDB},
21152 located in the GNU:[DOCS] directory,
21154 for full details on the usage of @code{GDB}, including a section on
21155 its usage on programs. This manual should be consulted for full
21156 details. The section that follows is a brief introduction to the
21157 philosophy and use of @code{GDB}.
21159 When GNAT programs are compiled, the compiler optionally writes debugging
21160 information into the generated object file, including information on
21161 line numbers, and on declared types and variables. This information is
21162 separate from the generated code. It makes the object files considerably
21163 larger, but it does not add to the size of the actual executable that
21164 will be loaded into memory, and has no impact on run-time performance. The
21165 generation of debug information is triggered by the use of the
21166 ^-g^/DEBUG^ switch in the @command{gcc} or @command{gnatmake} command
21167 used to carry out the compilations. It is important to emphasize that
21168 the use of these options does not change the generated code.
21170 The debugging information is written in standard system formats that
21171 are used by many tools, including debuggers and profilers. The format
21172 of the information is typically designed to describe C types and
21173 semantics, but GNAT implements a translation scheme which allows full
21174 details about Ada types and variables to be encoded into these
21175 standard C formats. Details of this encoding scheme may be found in
21176 the file exp_dbug.ads in the GNAT source distribution. However, the
21177 details of this encoding are, in general, of no interest to a user,
21178 since @code{GDB} automatically performs the necessary decoding.
21180 When a program is bound and linked, the debugging information is
21181 collected from the object files, and stored in the executable image of
21182 the program. Again, this process significantly increases the size of
21183 the generated executable file, but it does not increase the size of
21184 the executable program itself. Furthermore, if this program is run in
21185 the normal manner, it runs exactly as if the debug information were
21186 not present, and takes no more actual memory.
21188 However, if the program is run under control of @code{GDB}, the
21189 debugger is activated. The image of the program is loaded, at which
21190 point it is ready to run. If a run command is given, then the program
21191 will run exactly as it would have if @code{GDB} were not present. This
21192 is a crucial part of the @code{GDB} design philosophy. @code{GDB} is
21193 entirely non-intrusive until a breakpoint is encountered. If no
21194 breakpoint is ever hit, the program will run exactly as it would if no
21195 debugger were present. When a breakpoint is hit, @code{GDB} accesses
21196 the debugging information and can respond to user commands to inspect
21197 variables, and more generally to report on the state of execution.
21201 @section Running GDB
21204 This section describes how to initiate the debugger.
21205 @c The above sentence is really just filler, but it was otherwise
21206 @c clumsy to get the first paragraph nonindented given the conditional
21207 @c nature of the description
21210 The debugger can be launched from a @code{GPS} menu or
21211 directly from the command line. The description below covers the latter use.
21212 All the commands shown can be used in the @code{GPS} debug console window,
21213 but there are usually more GUI-based ways to achieve the same effect.
21216 The command to run @code{GDB} is
21219 $ ^gdb program^GDB PROGRAM^
21223 where @code{^program^PROGRAM^} is the name of the executable file. This
21224 activates the debugger and results in a prompt for debugger commands.
21225 The simplest command is simply @code{run}, which causes the program to run
21226 exactly as if the debugger were not present. The following section
21227 describes some of the additional commands that can be given to @code{GDB}.
21229 @c *******************************
21230 @node Introduction to GDB Commands
21231 @section Introduction to GDB Commands
21234 @code{GDB} contains a large repertoire of commands. @xref{Top,,
21235 Debugging with GDB, gdb, Debugging with GDB},
21237 located in the GNU:[DOCS] directory,
21239 for extensive documentation on the use
21240 of these commands, together with examples of their use. Furthermore,
21241 the command @command{help} invoked from within GDB activates a simple help
21242 facility which summarizes the available commands and their options.
21243 In this section we summarize a few of the most commonly
21244 used commands to give an idea of what @code{GDB} is about. You should create
21245 a simple program with debugging information and experiment with the use of
21246 these @code{GDB} commands on the program as you read through the
21250 @item set args @var{arguments}
21251 The @var{arguments} list above is a list of arguments to be passed to
21252 the program on a subsequent run command, just as though the arguments
21253 had been entered on a normal invocation of the program. The @code{set args}
21254 command is not needed if the program does not require arguments.
21257 The @code{run} command causes execution of the program to start from
21258 the beginning. If the program is already running, that is to say if
21259 you are currently positioned at a breakpoint, then a prompt will ask
21260 for confirmation that you want to abandon the current execution and
21263 @item breakpoint @var{location}
21264 The breakpoint command sets a breakpoint, that is to say a point at which
21265 execution will halt and @code{GDB} will await further
21266 commands. @var{location} is
21267 either a line number within a file, given in the format @code{file:linenumber},
21268 or it is the name of a subprogram. If you request that a breakpoint be set on
21269 a subprogram that is overloaded, a prompt will ask you to specify on which of
21270 those subprograms you want to breakpoint. You can also
21271 specify that all of them should be breakpointed. If the program is run
21272 and execution encounters the breakpoint, then the program
21273 stops and @code{GDB} signals that the breakpoint was encountered by
21274 printing the line of code before which the program is halted.
21276 @item catch exception @var{name}
21277 This command causes the program execution to stop whenever exception
21278 @var{name} is raised. If @var{name} is omitted, then the execution is
21279 suspended when any exception is raised.
21281 @item print @var{expression}
21282 This will print the value of the given expression. Most simple
21283 Ada expression formats are properly handled by @code{GDB}, so the expression
21284 can contain function calls, variables, operators, and attribute references.
21287 Continues execution following a breakpoint, until the next breakpoint or the
21288 termination of the program.
21291 Executes a single line after a breakpoint. If the next statement
21292 is a subprogram call, execution continues into (the first statement of)
21293 the called subprogram.
21296 Executes a single line. If this line is a subprogram call, executes and
21297 returns from the call.
21300 Lists a few lines around the current source location. In practice, it
21301 is usually more convenient to have a separate edit window open with the
21302 relevant source file displayed. Successive applications of this command
21303 print subsequent lines. The command can be given an argument which is a
21304 line number, in which case it displays a few lines around the specified one.
21307 Displays a backtrace of the call chain. This command is typically
21308 used after a breakpoint has occurred, to examine the sequence of calls that
21309 leads to the current breakpoint. The display includes one line for each
21310 activation record (frame) corresponding to an active subprogram.
21313 At a breakpoint, @code{GDB} can display the values of variables local
21314 to the current frame. The command @code{up} can be used to
21315 examine the contents of other active frames, by moving the focus up
21316 the stack, that is to say from callee to caller, one frame at a time.
21319 Moves the focus of @code{GDB} down from the frame currently being
21320 examined to the frame of its callee (the reverse of the previous command),
21322 @item frame @var{n}
21323 Inspect the frame with the given number. The value 0 denotes the frame
21324 of the current breakpoint, that is to say the top of the call stack.
21327 Kills the child process in which the program is running under GDB.
21328 This may be useful for several purposes:
21331 It allows you to recompile and relink your program, since on many systems
21332 you cannot regenerate an executable file while it is running in a process.
21334 You can run your program outside the debugger, on systems that do not
21335 permit executing a program outside GDB while breakpoints are set
21338 It allows you to debug a core dump rather than a running process.
21343 The above list is a very short introduction to the commands that
21344 @code{GDB} provides. Important additional capabilities, including conditional
21345 breakpoints, the ability to execute command sequences on a breakpoint,
21346 the ability to debug at the machine instruction level and many other
21347 features are described in detail in @ref{Top,, Debugging with GDB, gdb,
21348 Debugging with GDB}. Note that most commands can be abbreviated
21349 (for example, c for continue, bt for backtrace).
21351 @node Using Ada Expressions
21352 @section Using Ada Expressions
21353 @cindex Ada expressions
21356 @code{GDB} supports a fairly large subset of Ada expression syntax, with some
21357 extensions. The philosophy behind the design of this subset is
21361 That @code{GDB} should provide basic literals and access to operations for
21362 arithmetic, dereferencing, field selection, indexing, and subprogram calls,
21363 leaving more sophisticated computations to subprograms written into the
21364 program (which therefore may be called from @code{GDB}).
21367 That type safety and strict adherence to Ada language restrictions
21368 are not particularly important to the @code{GDB} user.
21371 That brevity is important to the @code{GDB} user.
21375 Thus, for brevity, the debugger acts as if there were
21376 implicit @code{with} and @code{use} clauses in effect for all user-written
21377 packages, thus making it unnecessary to fully qualify most names with
21378 their packages, regardless of context. Where this causes ambiguity,
21379 @code{GDB} asks the user's intent.
21381 For details on the supported Ada syntax, see @ref{Top,, Debugging with
21382 GDB, gdb, Debugging with GDB}.
21384 @node Calling User-Defined Subprograms
21385 @section Calling User-Defined Subprograms
21388 An important capability of @code{GDB} is the ability to call user-defined
21389 subprograms while debugging. This is achieved simply by entering
21390 a subprogram call statement in the form:
21393 call subprogram-name (parameters)
21397 The keyword @code{call} can be omitted in the normal case where the
21398 @code{subprogram-name} does not coincide with any of the predefined
21399 @code{GDB} commands.
21401 The effect is to invoke the given subprogram, passing it the
21402 list of parameters that is supplied. The parameters can be expressions and
21403 can include variables from the program being debugged. The
21404 subprogram must be defined
21405 at the library level within your program, and @code{GDB} will call the
21406 subprogram within the environment of your program execution (which
21407 means that the subprogram is free to access or even modify variables
21408 within your program).
21410 The most important use of this facility is in allowing the inclusion of
21411 debugging routines that are tailored to particular data structures
21412 in your program. Such debugging routines can be written to provide a suitably
21413 high-level description of an abstract type, rather than a low-level dump
21414 of its physical layout. After all, the standard
21415 @code{GDB print} command only knows the physical layout of your
21416 types, not their abstract meaning. Debugging routines can provide information
21417 at the desired semantic level and are thus enormously useful.
21419 For example, when debugging GNAT itself, it is crucial to have access to
21420 the contents of the tree nodes used to represent the program internally.
21421 But tree nodes are represented simply by an integer value (which in turn
21422 is an index into a table of nodes).
21423 Using the @code{print} command on a tree node would simply print this integer
21424 value, which is not very useful. But the PN routine (defined in file
21425 treepr.adb in the GNAT sources) takes a tree node as input, and displays
21426 a useful high level representation of the tree node, which includes the
21427 syntactic category of the node, its position in the source, the integers
21428 that denote descendant nodes and parent node, as well as varied
21429 semantic information. To study this example in more detail, you might want to
21430 look at the body of the PN procedure in the stated file.
21432 @node Using the Next Command in a Function
21433 @section Using the Next Command in a Function
21436 When you use the @code{next} command in a function, the current source
21437 location will advance to the next statement as usual. A special case
21438 arises in the case of a @code{return} statement.
21440 Part of the code for a return statement is the ``epilog'' of the function.
21441 This is the code that returns to the caller. There is only one copy of
21442 this epilog code, and it is typically associated with the last return
21443 statement in the function if there is more than one return. In some
21444 implementations, this epilog is associated with the first statement
21447 The result is that if you use the @code{next} command from a return
21448 statement that is not the last return statement of the function you
21449 may see a strange apparent jump to the last return statement or to
21450 the start of the function. You should simply ignore this odd jump.
21451 The value returned is always that from the first return statement
21452 that was stepped through.
21454 @node Ada Exceptions
21455 @section Stopping when Ada Exceptions are Raised
21459 You can set catchpoints that stop the program execution when your program
21460 raises selected exceptions.
21463 @item catch exception
21464 Set a catchpoint that stops execution whenever (any task in the) program
21465 raises any exception.
21467 @item catch exception @var{name}
21468 Set a catchpoint that stops execution whenever (any task in the) program
21469 raises the exception @var{name}.
21471 @item catch exception unhandled
21472 Set a catchpoint that stops executing whenever (any task in the) program
21473 raises an exception for which there is no handler.
21475 @item info exceptions
21476 @itemx info exceptions @var{regexp}
21477 The @code{info exceptions} command permits the user to examine all defined
21478 exceptions within Ada programs. With a regular expression, @var{regexp}, as
21479 argument, prints out only those exceptions whose name matches @var{regexp}.
21487 @code{GDB} allows the following task-related commands:
21491 This command shows a list of current Ada tasks, as in the following example:
21498 ID TID P-ID Thread Pri State Name
21499 1 8088000 0 807e000 15 Child Activation Wait main_task
21500 2 80a4000 1 80ae000 15 Accept/Select Wait b
21501 3 809a800 1 80a4800 15 Child Activation Wait a
21502 * 4 80ae800 3 80b8000 15 Running c
21506 In this listing, the asterisk before the first task indicates it to be the
21507 currently running task. The first column lists the task ID that is used
21508 to refer to tasks in the following commands.
21510 @item break @var{linespec} task @var{taskid}
21511 @itemx break @var{linespec} task @var{taskid} if @dots{}
21512 @cindex Breakpoints and tasks
21513 These commands are like the @code{break @dots{} thread @dots{}}.
21514 @var{linespec} specifies source lines.
21516 Use the qualifier @samp{task @var{taskid}} with a breakpoint command
21517 to specify that you only want @code{GDB} to stop the program when a
21518 particular Ada task reaches this breakpoint. @var{taskid} is one of the
21519 numeric task identifiers assigned by @code{GDB}, shown in the first
21520 column of the @samp{info tasks} display.
21522 If you do not specify @samp{task @var{taskid}} when you set a
21523 breakpoint, the breakpoint applies to @emph{all} tasks of your
21526 You can use the @code{task} qualifier on conditional breakpoints as
21527 well; in this case, place @samp{task @var{taskid}} before the
21528 breakpoint condition (before the @code{if}).
21530 @item task @var{taskno}
21531 @cindex Task switching
21533 This command allows to switch to the task referred by @var{taskno}. In
21534 particular, This allows to browse the backtrace of the specified
21535 task. It is advised to switch back to the original task before
21536 continuing execution otherwise the scheduling of the program may be
21541 For more detailed information on the tasking support,
21542 see @ref{Top,, Debugging with GDB, gdb, Debugging with GDB}.
21544 @node Debugging Generic Units
21545 @section Debugging Generic Units
21546 @cindex Debugging Generic Units
21550 GNAT always uses code expansion for generic instantiation. This means that
21551 each time an instantiation occurs, a complete copy of the original code is
21552 made, with appropriate substitutions of formals by actuals.
21554 It is not possible to refer to the original generic entities in
21555 @code{GDB}, but it is always possible to debug a particular instance of
21556 a generic, by using the appropriate expanded names. For example, if we have
21558 @smallexample @c ada
21563 generic package k is
21564 procedure kp (v1 : in out integer);
21568 procedure kp (v1 : in out integer) is
21574 package k1 is new k;
21575 package k2 is new k;
21577 var : integer := 1;
21590 Then to break on a call to procedure kp in the k2 instance, simply
21594 (gdb) break g.k2.kp
21598 When the breakpoint occurs, you can step through the code of the
21599 instance in the normal manner and examine the values of local variables, as for
21602 @node Remote Debugging with gdbserver
21603 @section Remote Debugging with gdbserver
21604 @cindex Remote Debugging with gdbserver
21607 On platforms where gdbserver is supported, it is possible to use this tool
21608 to debug your application remotely. This can be useful in situations
21609 where the program needs to be run on a target host that is different
21610 from the host used for development, particularly when the target has
21611 a limited amount of resources (either CPU and/or memory).
21613 To do so, start your program using gdbserver on the target machine.
21614 gdbserver then automatically suspends the execution of your program
21615 at its entry point, waiting for a debugger to connect to it. The
21616 following commands starts an application and tells gdbserver to
21617 wait for a connection with the debugger on localhost port 4444.
21620 $ gdbserver localhost:4444 program
21621 Process program created; pid = 5685
21622 Listening on port 4444
21625 Once gdbserver has started listening, we can tell the debugger to establish
21626 a connection with this gdbserver, and then start the same debugging session
21627 as if the program was being debugged on the same host, directly under
21628 the control of GDB.
21632 (gdb) target remote targethost:4444
21633 Remote debugging using targethost:4444
21634 0x00007f29936d0af0 in ?? () from /lib64/ld-linux-x86-64.so.
21636 Breakpoint 1 at 0x401f0c: file foo.adb, line 3.
21640 Breakpoint 1, foo () at foo.adb:4
21644 It is also possible to use gdbserver to attach to an already running
21645 program, in which case the execution of that program is simply suspended
21646 until the connection between the debugger and gdbserver is established.
21648 For more information on how to use gdbserver, @ref{Top, Server, Using
21649 the gdbserver Program, gdb, Debugging with GDB}. @value{EDITION} provides support
21650 for gdbserver on x86-linux, x86-windows and x86_64-linux.
21652 @node GNAT Abnormal Termination or Failure to Terminate
21653 @section GNAT Abnormal Termination or Failure to Terminate
21654 @cindex GNAT Abnormal Termination or Failure to Terminate
21657 When presented with programs that contain serious errors in syntax
21659 GNAT may on rare occasions experience problems in operation, such
21661 segmentation fault or illegal memory access, raising an internal
21662 exception, terminating abnormally, or failing to terminate at all.
21663 In such cases, you can activate
21664 various features of GNAT that can help you pinpoint the construct in your
21665 program that is the likely source of the problem.
21667 The following strategies are presented in increasing order of
21668 difficulty, corresponding to your experience in using GNAT and your
21669 familiarity with compiler internals.
21673 Run @command{gcc} with the @option{-gnatf}. This first
21674 switch causes all errors on a given line to be reported. In its absence,
21675 only the first error on a line is displayed.
21677 The @option{-gnatdO} switch causes errors to be displayed as soon as they
21678 are encountered, rather than after compilation is terminated. If GNAT
21679 terminates prematurely or goes into an infinite loop, the last error
21680 message displayed may help to pinpoint the culprit.
21683 Run @command{gcc} with the @option{^-v (verbose)^/VERBOSE^} switch. In this
21684 mode, @command{gcc} produces ongoing information about the progress of the
21685 compilation and provides the name of each procedure as code is
21686 generated. This switch allows you to find which Ada procedure was being
21687 compiled when it encountered a code generation problem.
21690 @cindex @option{-gnatdc} switch
21691 Run @command{gcc} with the @option{-gnatdc} switch. This is a GNAT specific
21692 switch that does for the front-end what @option{^-v^VERBOSE^} does
21693 for the back end. The system prints the name of each unit,
21694 either a compilation unit or nested unit, as it is being analyzed.
21696 Finally, you can start
21697 @code{gdb} directly on the @code{gnat1} executable. @code{gnat1} is the
21698 front-end of GNAT, and can be run independently (normally it is just
21699 called from @command{gcc}). You can use @code{gdb} on @code{gnat1} as you
21700 would on a C program (but @pxref{The GNAT Debugger GDB} for caveats). The
21701 @code{where} command is the first line of attack; the variable
21702 @code{lineno} (seen by @code{print lineno}), used by the second phase of
21703 @code{gnat1} and by the @command{gcc} backend, indicates the source line at
21704 which the execution stopped, and @code{input_file name} indicates the name of
21708 @node Naming Conventions for GNAT Source Files
21709 @section Naming Conventions for GNAT Source Files
21712 In order to examine the workings of the GNAT system, the following
21713 brief description of its organization may be helpful:
21717 Files with prefix @file{^sc^SC^} contain the lexical scanner.
21720 All files prefixed with @file{^par^PAR^} are components of the parser. The
21721 numbers correspond to chapters of the Ada Reference Manual. For example,
21722 parsing of select statements can be found in @file{par-ch9.adb}.
21725 All files prefixed with @file{^sem^SEM^} perform semantic analysis. The
21726 numbers correspond to chapters of the Ada standard. For example, all
21727 issues involving context clauses can be found in @file{sem_ch10.adb}. In
21728 addition, some features of the language require sufficient special processing
21729 to justify their own semantic files: sem_aggr for aggregates, sem_disp for
21730 dynamic dispatching, etc.
21733 All files prefixed with @file{^exp^EXP^} perform normalization and
21734 expansion of the intermediate representation (abstract syntax tree, or AST).
21735 these files use the same numbering scheme as the parser and semantics files.
21736 For example, the construction of record initialization procedures is done in
21737 @file{exp_ch3.adb}.
21740 The files prefixed with @file{^bind^BIND^} implement the binder, which
21741 verifies the consistency of the compilation, determines an order of
21742 elaboration, and generates the bind file.
21745 The files @file{atree.ads} and @file{atree.adb} detail the low-level
21746 data structures used by the front-end.
21749 The files @file{sinfo.ads} and @file{sinfo.adb} detail the structure of
21750 the abstract syntax tree as produced by the parser.
21753 The files @file{einfo.ads} and @file{einfo.adb} detail the attributes of
21754 all entities, computed during semantic analysis.
21757 Library management issues are dealt with in files with prefix
21763 Ada files with the prefix @file{^a-^A-^} are children of @code{Ada}, as
21764 defined in Annex A.
21769 Files with prefix @file{^i-^I-^} are children of @code{Interfaces}, as
21770 defined in Annex B.
21774 Files with prefix @file{^s-^S-^} are children of @code{System}. This includes
21775 both language-defined children and GNAT run-time routines.
21779 Files with prefix @file{^g-^G-^} are children of @code{GNAT}. These are useful
21780 general-purpose packages, fully documented in their specs. All
21781 the other @file{.c} files are modifications of common @command{gcc} files.
21784 @node Getting Internal Debugging Information
21785 @section Getting Internal Debugging Information
21788 Most compilers have internal debugging switches and modes. GNAT
21789 does also, except GNAT internal debugging switches and modes are not
21790 secret. A summary and full description of all the compiler and binder
21791 debug flags are in the file @file{debug.adb}. You must obtain the
21792 sources of the compiler to see the full detailed effects of these flags.
21794 The switches that print the source of the program (reconstructed from
21795 the internal tree) are of general interest for user programs, as are the
21797 the full internal tree, and the entity table (the symbol table
21798 information). The reconstructed source provides a readable version of the
21799 program after the front-end has completed analysis and expansion,
21800 and is useful when studying the performance of specific constructs.
21801 For example, constraint checks are indicated, complex aggregates
21802 are replaced with loops and assignments, and tasking primitives
21803 are replaced with run-time calls.
21805 @node Stack Traceback
21806 @section Stack Traceback
21808 @cindex stack traceback
21809 @cindex stack unwinding
21812 Traceback is a mechanism to display the sequence of subprogram calls that
21813 leads to a specified execution point in a program. Often (but not always)
21814 the execution point is an instruction at which an exception has been raised.
21815 This mechanism is also known as @i{stack unwinding} because it obtains
21816 its information by scanning the run-time stack and recovering the activation
21817 records of all active subprograms. Stack unwinding is one of the most
21818 important tools for program debugging.
21820 The first entry stored in traceback corresponds to the deepest calling level,
21821 that is to say the subprogram currently executing the instruction
21822 from which we want to obtain the traceback.
21824 Note that there is no runtime performance penalty when stack traceback
21825 is enabled, and no exception is raised during program execution.
21828 * Non-Symbolic Traceback::
21829 * Symbolic Traceback::
21832 @node Non-Symbolic Traceback
21833 @subsection Non-Symbolic Traceback
21834 @cindex traceback, non-symbolic
21837 Note: this feature is not supported on all platforms. See
21838 @file{GNAT.Traceback spec in g-traceb.ads} for a complete list of supported
21842 * Tracebacks From an Unhandled Exception::
21843 * Tracebacks From Exception Occurrences (non-symbolic)::
21844 * Tracebacks From Anywhere in a Program (non-symbolic)::
21847 @node Tracebacks From an Unhandled Exception
21848 @subsubsection Tracebacks From an Unhandled Exception
21851 A runtime non-symbolic traceback is a list of addresses of call instructions.
21852 To enable this feature you must use the @option{-E}
21853 @code{gnatbind}'s option. With this option a stack traceback is stored as part
21854 of exception information. You can retrieve this information using the
21855 @code{addr2line} tool.
21857 Here is a simple example:
21859 @smallexample @c ada
21865 raise Constraint_Error;
21880 $ gnatmake stb -bargs -E
21883 Execution terminated by unhandled exception
21884 Exception name: CONSTRAINT_ERROR
21886 Call stack traceback locations:
21887 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
21891 As we see the traceback lists a sequence of addresses for the unhandled
21892 exception @code{CONSTRAINT_ERROR} raised in procedure P1. It is easy to
21893 guess that this exception come from procedure P1. To translate these
21894 addresses into the source lines where the calls appear, the
21895 @code{addr2line} tool, described below, is invaluable. The use of this tool
21896 requires the program to be compiled with debug information.
21899 $ gnatmake -g stb -bargs -E
21902 Execution terminated by unhandled exception
21903 Exception name: CONSTRAINT_ERROR
21905 Call stack traceback locations:
21906 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
21908 $ addr2line --exe=stb 0x401373 0x40138b 0x40139c 0x401335 0x4011c4
21909 0x4011f1 0x77e892a4
21911 00401373 at d:/stb/stb.adb:5
21912 0040138B at d:/stb/stb.adb:10
21913 0040139C at d:/stb/stb.adb:14
21914 00401335 at d:/stb/b~stb.adb:104
21915 004011C4 at /build/@dots{}/crt1.c:200
21916 004011F1 at /build/@dots{}/crt1.c:222
21917 77E892A4 in ?? at ??:0
21921 The @code{addr2line} tool has several other useful options:
21925 to get the function name corresponding to any location
21927 @item --demangle=gnat
21928 to use the gnat decoding mode for the function names. Note that
21929 for binutils version 2.9.x the option is simply @option{--demangle}.
21933 $ addr2line --exe=stb --functions --demangle=gnat 0x401373 0x40138b
21934 0x40139c 0x401335 0x4011c4 0x4011f1
21936 00401373 in stb.p1 at d:/stb/stb.adb:5
21937 0040138B in stb.p2 at d:/stb/stb.adb:10
21938 0040139C in stb at d:/stb/stb.adb:14
21939 00401335 in main at d:/stb/b~stb.adb:104
21940 004011C4 in <__mingw_CRTStartup> at /build/@dots{}/crt1.c:200
21941 004011F1 in <mainCRTStartup> at /build/@dots{}/crt1.c:222
21945 From this traceback we can see that the exception was raised in
21946 @file{stb.adb} at line 5, which was reached from a procedure call in
21947 @file{stb.adb} at line 10, and so on. The @file{b~std.adb} is the binder file,
21948 which contains the call to the main program.
21949 @xref{Running gnatbind}. The remaining entries are assorted runtime routines,
21950 and the output will vary from platform to platform.
21952 It is also possible to use @code{GDB} with these traceback addresses to debug
21953 the program. For example, we can break at a given code location, as reported
21954 in the stack traceback:
21960 Furthermore, this feature is not implemented inside Windows DLL. Only
21961 the non-symbolic traceback is reported in this case.
21964 (gdb) break *0x401373
21965 Breakpoint 1 at 0x401373: file stb.adb, line 5.
21969 It is important to note that the stack traceback addresses
21970 do not change when debug information is included. This is particularly useful
21971 because it makes it possible to release software without debug information (to
21972 minimize object size), get a field report that includes a stack traceback
21973 whenever an internal bug occurs, and then be able to retrieve the sequence
21974 of calls with the same program compiled with debug information.
21976 @node Tracebacks From Exception Occurrences (non-symbolic)
21977 @subsubsection Tracebacks From Exception Occurrences
21980 Non-symbolic tracebacks are obtained by using the @option{-E} binder argument.
21981 The stack traceback is attached to the exception information string, and can
21982 be retrieved in an exception handler within the Ada program, by means of the
21983 Ada facilities defined in @code{Ada.Exceptions}. Here is a simple example:
21985 @smallexample @c ada
21987 with Ada.Exceptions;
21992 use Ada.Exceptions;
22000 Text_IO.Put_Line (Exception_Information (E));
22014 This program will output:
22019 Exception name: CONSTRAINT_ERROR
22020 Message: stb.adb:12
22021 Call stack traceback locations:
22022 0x4015e4 0x401633 0x401644 0x401461 0x4011c4 0x4011f1 0x77e892a4
22025 @node Tracebacks From Anywhere in a Program (non-symbolic)
22026 @subsubsection Tracebacks From Anywhere in a Program
22029 It is also possible to retrieve a stack traceback from anywhere in a
22030 program. For this you need to
22031 use the @code{GNAT.Traceback} API. This package includes a procedure called
22032 @code{Call_Chain} that computes a complete stack traceback, as well as useful
22033 display procedures described below. It is not necessary to use the
22034 @option{-E gnatbind} option in this case, because the stack traceback mechanism
22035 is invoked explicitly.
22038 In the following example we compute a traceback at a specific location in
22039 the program, and we display it using @code{GNAT.Debug_Utilities.Image} to
22040 convert addresses to strings:
22042 @smallexample @c ada
22044 with GNAT.Traceback;
22045 with GNAT.Debug_Utilities;
22051 use GNAT.Traceback;
22054 TB : Tracebacks_Array (1 .. 10);
22055 -- We are asking for a maximum of 10 stack frames.
22057 -- Len will receive the actual number of stack frames returned.
22059 Call_Chain (TB, Len);
22061 Text_IO.Put ("In STB.P1 : ");
22063 for K in 1 .. Len loop
22064 Text_IO.Put (Debug_Utilities.Image (TB (K)));
22085 In STB.P1 : 16#0040_F1E4# 16#0040_14F2# 16#0040_170B# 16#0040_171C#
22086 16#0040_1461# 16#0040_11C4# 16#0040_11F1# 16#77E8_92A4#
22090 You can then get further information by invoking the @code{addr2line}
22091 tool as described earlier (note that the hexadecimal addresses
22092 need to be specified in C format, with a leading ``0x'').
22094 @node Symbolic Traceback
22095 @subsection Symbolic Traceback
22096 @cindex traceback, symbolic
22099 A symbolic traceback is a stack traceback in which procedure names are
22100 associated with each code location.
22103 Note that this feature is not supported on all platforms. See
22104 @file{GNAT.Traceback.Symbolic spec in g-trasym.ads} for a complete
22105 list of currently supported platforms.
22108 Note that the symbolic traceback requires that the program be compiled
22109 with debug information. If it is not compiled with debug information
22110 only the non-symbolic information will be valid.
22113 * Tracebacks From Exception Occurrences (symbolic)::
22114 * Tracebacks From Anywhere in a Program (symbolic)::
22117 @node Tracebacks From Exception Occurrences (symbolic)
22118 @subsubsection Tracebacks From Exception Occurrences
22120 @smallexample @c ada
22122 with GNAT.Traceback.Symbolic;
22128 raise Constraint_Error;
22145 Ada.Text_IO.Put_Line (GNAT.Traceback.Symbolic.Symbolic_Traceback (E));
22150 $ gnatmake -g .\stb -bargs -E
22153 0040149F in stb.p1 at stb.adb:8
22154 004014B7 in stb.p2 at stb.adb:13
22155 004014CF in stb.p3 at stb.adb:18
22156 004015DD in ada.stb at stb.adb:22
22157 00401461 in main at b~stb.adb:168
22158 004011C4 in __mingw_CRTStartup at crt1.c:200
22159 004011F1 in mainCRTStartup at crt1.c:222
22160 77E892A4 in ?? at ??:0
22164 In the above example the ``.\'' syntax in the @command{gnatmake} command
22165 is currently required by @command{addr2line} for files that are in
22166 the current working directory.
22167 Moreover, the exact sequence of linker options may vary from platform
22169 The above @option{-largs} section is for Windows platforms. By contrast,
22170 under Unix there is no need for the @option{-largs} section.
22171 Differences across platforms are due to details of linker implementation.
22173 @node Tracebacks From Anywhere in a Program (symbolic)
22174 @subsubsection Tracebacks From Anywhere in a Program
22177 It is possible to get a symbolic stack traceback
22178 from anywhere in a program, just as for non-symbolic tracebacks.
22179 The first step is to obtain a non-symbolic
22180 traceback, and then call @code{Symbolic_Traceback} to compute the symbolic
22181 information. Here is an example:
22183 @smallexample @c ada
22185 with GNAT.Traceback;
22186 with GNAT.Traceback.Symbolic;
22191 use GNAT.Traceback;
22192 use GNAT.Traceback.Symbolic;
22195 TB : Tracebacks_Array (1 .. 10);
22196 -- We are asking for a maximum of 10 stack frames.
22198 -- Len will receive the actual number of stack frames returned.
22200 Call_Chain (TB, Len);
22201 Text_IO.Put_Line (Symbolic_Traceback (TB (1 .. Len)));
22214 @c ******************************
22216 @node Compatibility with HP Ada
22217 @chapter Compatibility with HP Ada
22218 @cindex Compatibility
22223 @cindex Compatibility between GNAT and HP Ada
22224 This chapter compares HP Ada (formerly known as ``DEC Ada'')
22225 for OpenVMS Alpha and GNAT for OpenVMS for Alpha and for I64.
22226 GNAT is highly compatible
22227 with HP Ada, and it should generally be straightforward to port code
22228 from the HP Ada environment to GNAT. However, there are a few language
22229 and implementation differences of which the user must be aware. These
22230 differences are discussed in this chapter. In
22231 addition, the operating environment and command structure for the
22232 compiler are different, and these differences are also discussed.
22234 For further details on these and other compatibility issues,
22235 see Appendix E of the HP publication
22236 @cite{HP Ada, Technical Overview and Comparison on HP Platforms}.
22238 Except where otherwise indicated, the description of GNAT for OpenVMS
22239 applies to both the Alpha and I64 platforms.
22241 For information on porting Ada code from GNAT on Alpha OpenVMS to GNAT on
22242 I64 OpenVMS, see @ref{Transitioning to 64-Bit GNAT for OpenVMS}.
22244 The discussion in this chapter addresses specifically the implementation
22245 of Ada 83 for HP OpenVMS Alpha Systems. In cases where the implementation
22246 of HP Ada differs between OpenVMS Alpha Systems and OpenVMS VAX Systems,
22247 GNAT always follows the Alpha implementation.
22249 For GNAT running on other than VMS systems, all the HP Ada 83 pragmas and
22250 attributes are recognized, although only a subset of them can sensibly
22251 be implemented. The description of pragmas in
22252 @xref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference Manual},
22253 indicates whether or not they are applicable to non-VMS systems.
22256 * Ada Language Compatibility::
22257 * Differences in the Definition of Package System::
22258 * Language-Related Features::
22259 * The Package STANDARD::
22260 * The Package SYSTEM::
22261 * Tasking and Task-Related Features::
22262 * Pragmas and Pragma-Related Features::
22263 * Library of Predefined Units::
22265 * Main Program Definition::
22266 * Implementation-Defined Attributes::
22267 * Compiler and Run-Time Interfacing::
22268 * Program Compilation and Library Management::
22270 * Implementation Limits::
22271 * Tools and Utilities::
22274 @node Ada Language Compatibility
22275 @section Ada Language Compatibility
22278 GNAT handles Ada 95 and Ada 2005 as well as Ada 83, whereas HP Ada is only
22279 for Ada 83. Ada 95 and Ada 2005 are almost completely upwards compatible
22280 with Ada 83, and therefore Ada 83 programs will compile
22281 and run under GNAT with
22282 no changes or only minor changes. The @cite{Annotated Ada Reference Manual}
22283 provides details on specific incompatibilities.
22285 GNAT provides the switch @option{/83} on the @command{GNAT COMPILE} command,
22286 as well as the pragma @code{ADA_83}, to force the compiler to
22287 operate in Ada 83 mode. This mode does not guarantee complete
22288 conformance to Ada 83, but in practice is sufficient to
22289 eliminate most sources of incompatibilities.
22290 In particular, it eliminates the recognition of the
22291 additional Ada 95 and Ada 2005 keywords, so that their use as identifiers
22292 in Ada 83 programs is legal, and handles the cases of packages
22293 with optional bodies, and generics that instantiate unconstrained
22294 types without the use of @code{(<>)}.
22296 @node Differences in the Definition of Package System
22297 @section Differences in the Definition of Package @code{System}
22300 An Ada compiler is allowed to add
22301 implementation-dependent declarations to package @code{System}.
22303 GNAT does not take advantage of this permission, and the version of
22304 @code{System} provided by GNAT exactly matches that defined in the Ada
22307 However, HP Ada adds an extensive set of declarations to package
22309 as fully documented in the HP Ada manuals. To minimize changes required
22310 for programs that make use of these extensions, GNAT provides the pragma
22311 @code{Extend_System} for extending the definition of package System. By using:
22312 @cindex pragma @code{Extend_System}
22313 @cindex @code{Extend_System} pragma
22315 @smallexample @c ada
22318 pragma Extend_System (Aux_DEC);
22324 the set of definitions in @code{System} is extended to include those in
22325 package @code{System.Aux_DEC}.
22326 @cindex @code{System.Aux_DEC} package
22327 @cindex @code{Aux_DEC} package (child of @code{System})
22328 These definitions are incorporated directly into package @code{System},
22329 as though they had been declared there. For a
22330 list of the declarations added, see the spec of this package,
22331 which can be found in the file @file{s-auxdec.ads} in the GNAT library.
22332 @cindex @file{s-auxdec.ads} file
22333 The pragma @code{Extend_System} is a configuration pragma, which means that
22334 it can be placed in the file @file{gnat.adc}, so that it will automatically
22335 apply to all subsequent compilations. See @ref{Configuration Pragmas},
22336 for further details.
22338 An alternative approach that avoids the use of the non-standard
22339 @code{Extend_System} pragma is to add a context clause to the unit that
22340 references these facilities:
22342 @smallexample @c ada
22344 with System.Aux_DEC;
22345 use System.Aux_DEC;
22350 The effect is not quite semantically identical to incorporating
22351 the declarations directly into package @code{System},
22352 but most programs will not notice a difference
22353 unless they use prefix notation (e.g.@: @code{System.Integer_8})
22354 to reference the entities directly in package @code{System}.
22355 For units containing such references,
22356 the prefixes must either be removed, or the pragma @code{Extend_System}
22359 @node Language-Related Features
22360 @section Language-Related Features
22363 The following sections highlight differences in types,
22364 representations of types, operations, alignment, and
22368 * Integer Types and Representations::
22369 * Floating-Point Types and Representations::
22370 * Pragmas Float_Representation and Long_Float::
22371 * Fixed-Point Types and Representations::
22372 * Record and Array Component Alignment::
22373 * Address Clauses::
22374 * Other Representation Clauses::
22377 @node Integer Types and Representations
22378 @subsection Integer Types and Representations
22381 The set of predefined integer types is identical in HP Ada and GNAT.
22382 Furthermore the representation of these integer types is also identical,
22383 including the capability of size clauses forcing biased representation.
22386 HP Ada for OpenVMS Alpha systems has defined the
22387 following additional integer types in package @code{System}:
22404 @code{LARGEST_INTEGER}
22408 In GNAT, the first four of these types may be obtained from the
22409 standard Ada package @code{Interfaces}.
22410 Alternatively, by use of the pragma @code{Extend_System}, identical
22411 declarations can be referenced directly in package @code{System}.
22412 On both GNAT and HP Ada, the maximum integer size is 64 bits.
22414 @node Floating-Point Types and Representations
22415 @subsection Floating-Point Types and Representations
22416 @cindex Floating-Point types
22419 The set of predefined floating-point types is identical in HP Ada and GNAT.
22420 Furthermore the representation of these floating-point
22421 types is also identical. One important difference is that the default
22422 representation for HP Ada is @code{VAX_Float}, but the default representation
22425 Specific types may be declared to be @code{VAX_Float} or IEEE, using the
22426 pragma @code{Float_Representation} as described in the HP Ada
22428 For example, the declarations:
22430 @smallexample @c ada
22432 type F_Float is digits 6;
22433 pragma Float_Representation (VAX_Float, F_Float);
22438 declares a type @code{F_Float} that will be represented in @code{VAX_Float}
22440 This set of declarations actually appears in @code{System.Aux_DEC},
22442 the full set of additional floating-point declarations provided in
22443 the HP Ada version of package @code{System}.
22444 This and similar declarations may be accessed in a user program
22445 by using pragma @code{Extend_System}. The use of this
22446 pragma, and the related pragma @code{Long_Float} is described in further
22447 detail in the following section.
22449 @node Pragmas Float_Representation and Long_Float
22450 @subsection Pragmas @code{Float_Representation} and @code{Long_Float}
22453 HP Ada provides the pragma @code{Float_Representation}, which
22454 acts as a program library switch to allow control over
22455 the internal representation chosen for the predefined
22456 floating-point types declared in the package @code{Standard}.
22457 The format of this pragma is as follows:
22459 @smallexample @c ada
22461 pragma Float_Representation(VAX_Float | IEEE_Float);
22466 This pragma controls the representation of floating-point
22471 @code{VAX_Float} specifies that floating-point
22472 types are represented by default with the VAX system hardware types
22473 @code{F-floating}, @code{D-floating}, @code{G-floating}.
22474 Note that the @code{H-floating}
22475 type was available only on VAX systems, and is not available
22476 in either HP Ada or GNAT.
22479 @code{IEEE_Float} specifies that floating-point
22480 types are represented by default with the IEEE single and
22481 double floating-point types.
22485 GNAT provides an identical implementation of the pragma
22486 @code{Float_Representation}, except that it functions as a
22487 configuration pragma. Note that the
22488 notion of configuration pragma corresponds closely to the
22489 HP Ada notion of a program library switch.
22491 When no pragma is used in GNAT, the default is @code{IEEE_Float},
22493 from HP Ada 83, where the default is @code{VAX_Float}. In addition, the
22494 predefined libraries in GNAT are built using @code{IEEE_Float}, so it is not
22495 advisable to change the format of numbers passed to standard library
22496 routines, and if necessary explicit type conversions may be needed.
22498 The use of @code{IEEE_Float} is recommended in GNAT since it is more
22499 efficient, and (given that it conforms to an international standard)
22500 potentially more portable.
22501 The situation in which @code{VAX_Float} may be useful is in interfacing
22502 to existing code and data that expect the use of @code{VAX_Float}.
22503 In such a situation use the predefined @code{VAX_Float}
22504 types in package @code{System}, as extended by
22505 @code{Extend_System}. For example, use @code{System.F_Float}
22506 to specify the 32-bit @code{F-Float} format.
22509 On OpenVMS systems, HP Ada provides the pragma @code{Long_Float}
22510 to allow control over the internal representation chosen
22511 for the predefined type @code{Long_Float} and for floating-point
22512 type declarations with digits specified in the range 7 .. 15.
22513 The format of this pragma is as follows:
22515 @smallexample @c ada
22517 pragma Long_Float (D_FLOAT | G_FLOAT);
22521 @node Fixed-Point Types and Representations
22522 @subsection Fixed-Point Types and Representations
22525 On HP Ada for OpenVMS Alpha systems, rounding is
22526 away from zero for both positive and negative numbers.
22527 Therefore, @code{+0.5} rounds to @code{1},
22528 and @code{-0.5} rounds to @code{-1}.
22530 On GNAT the results of operations
22531 on fixed-point types are in accordance with the Ada
22532 rules. In particular, results of operations on decimal
22533 fixed-point types are truncated.
22535 @node Record and Array Component Alignment
22536 @subsection Record and Array Component Alignment
22539 On HP Ada for OpenVMS Alpha, all non-composite components
22540 are aligned on natural boundaries. For example, 1-byte
22541 components are aligned on byte boundaries, 2-byte
22542 components on 2-byte boundaries, 4-byte components on 4-byte
22543 byte boundaries, and so on. The OpenVMS Alpha hardware
22544 runs more efficiently with naturally aligned data.
22546 On GNAT, alignment rules are compatible
22547 with HP Ada for OpenVMS Alpha.
22549 @node Address Clauses
22550 @subsection Address Clauses
22553 In HP Ada and GNAT, address clauses are supported for
22554 objects and imported subprograms.
22555 The predefined type @code{System.Address} is a private type
22556 in both compilers on Alpha OpenVMS, with the same representation
22557 (it is simply a machine pointer). Addition, subtraction, and comparison
22558 operations are available in the standard Ada package
22559 @code{System.Storage_Elements}, or in package @code{System}
22560 if it is extended to include @code{System.Aux_DEC} using a
22561 pragma @code{Extend_System} as previously described.
22563 Note that code that @code{with}'s both this extended package @code{System}
22564 and the package @code{System.Storage_Elements} should not @code{use}
22565 both packages, or ambiguities will result. In general it is better
22566 not to mix these two sets of facilities. The Ada package was
22567 designed specifically to provide the kind of features that HP Ada
22568 adds directly to package @code{System}.
22570 The type @code{System.Address} is a 64-bit integer type in GNAT for
22571 I64 OpenVMS. For more information,
22572 see @ref{Transitioning to 64-Bit GNAT for OpenVMS}.
22574 GNAT is compatible with HP Ada in its handling of address
22575 clauses, except for some limitations in
22576 the form of address clauses for composite objects with
22577 initialization. Such address clauses are easily replaced
22578 by the use of an explicitly-defined constant as described
22579 in the Ada Reference Manual (13.1(22)). For example, the sequence
22582 @smallexample @c ada
22584 X, Y : Integer := Init_Func;
22585 Q : String (X .. Y) := "abc";
22587 for Q'Address use Compute_Address;
22592 will be rejected by GNAT, since the address cannot be computed at the time
22593 that @code{Q} is declared. To achieve the intended effect, write instead:
22595 @smallexample @c ada
22598 X, Y : Integer := Init_Func;
22599 Q_Address : constant Address := Compute_Address;
22600 Q : String (X .. Y) := "abc";
22602 for Q'Address use Q_Address;
22608 which will be accepted by GNAT (and other Ada compilers), and is also
22609 compatible with Ada 83. A fuller description of the restrictions
22610 on address specifications is found in @ref{Top, GNAT Reference Manual,
22611 About This Guide, gnat_rm, GNAT Reference Manual}.
22613 @node Other Representation Clauses
22614 @subsection Other Representation Clauses
22617 GNAT implements in a compatible manner all the representation
22618 clauses supported by HP Ada. In addition, GNAT
22619 implements the representation clause forms that were introduced in Ada 95,
22620 including @code{COMPONENT_SIZE} and @code{SIZE} clauses for objects.
22622 @node The Package STANDARD
22623 @section The Package @code{STANDARD}
22626 The package @code{STANDARD}, as implemented by HP Ada, is fully
22627 described in the @cite{Ada Reference Manual} and in the
22628 @cite{HP Ada Language Reference Manual}. As implemented by GNAT, the
22629 package @code{STANDARD} is described in the @cite{Ada Reference Manual}.
22631 In addition, HP Ada supports the Latin-1 character set in
22632 the type @code{CHARACTER}. GNAT supports the Latin-1 character set
22633 in the type @code{CHARACTER} and also Unicode (ISO 10646 BMP) in
22634 the type @code{WIDE_CHARACTER}.
22636 The floating-point types supported by GNAT are those
22637 supported by HP Ada, but the defaults are different, and are controlled by
22638 pragmas. See @ref{Floating-Point Types and Representations}, for details.
22640 @node The Package SYSTEM
22641 @section The Package @code{SYSTEM}
22644 HP Ada provides a specific version of the package
22645 @code{SYSTEM} for each platform on which the language is implemented.
22646 For the complete spec of the package @code{SYSTEM}, see
22647 Appendix F of the @cite{HP Ada Language Reference Manual}.
22649 On HP Ada, the package @code{SYSTEM} includes the following conversion
22652 @item @code{TO_ADDRESS(INTEGER)}
22654 @item @code{TO_ADDRESS(UNSIGNED_LONGWORD)}
22656 @item @code{TO_ADDRESS(}@i{universal_integer}@code{)}
22658 @item @code{TO_INTEGER(ADDRESS)}
22660 @item @code{TO_UNSIGNED_LONGWORD(ADDRESS)}
22662 @item Function @code{IMPORT_VALUE return UNSIGNED_LONGWORD} and the
22663 functions @code{IMPORT_ADDRESS} and @code{IMPORT_LARGEST_VALUE}
22667 By default, GNAT supplies a version of @code{SYSTEM} that matches
22668 the definition given in the @cite{Ada Reference Manual}.
22670 is a subset of the HP system definitions, which is as
22671 close as possible to the original definitions. The only difference
22672 is that the definition of @code{SYSTEM_NAME} is different:
22674 @smallexample @c ada
22676 type Name is (SYSTEM_NAME_GNAT);
22677 System_Name : constant Name := SYSTEM_NAME_GNAT;
22682 Also, GNAT adds the Ada declarations for
22683 @code{BIT_ORDER} and @code{DEFAULT_BIT_ORDER}.
22685 However, the use of the following pragma causes GNAT
22686 to extend the definition of package @code{SYSTEM} so that it
22687 encompasses the full set of HP-specific extensions,
22688 including the functions listed above:
22690 @smallexample @c ada
22692 pragma Extend_System (Aux_DEC);
22697 The pragma @code{Extend_System} is a configuration pragma that
22698 is most conveniently placed in the @file{gnat.adc} file. @xref{Pragma
22699 Extend_System,,, gnat_rm, GNAT Reference Manual}, for further details.
22701 HP Ada does not allow the recompilation of the package
22702 @code{SYSTEM}. Instead HP Ada provides several pragmas
22703 (@code{SYSTEM_NAME}, @code{STORAGE_UNIT}, and @code{MEMORY_SIZE})
22704 to modify values in the package @code{SYSTEM}.
22705 On OpenVMS Alpha systems, the pragma
22706 @code{SYSTEM_NAME} takes the enumeration literal @code{OPENVMS_AXP} as
22707 its single argument.
22709 GNAT does permit the recompilation of package @code{SYSTEM} using
22710 the special switch @option{-gnatg}, and this switch can be used if
22711 it is necessary to modify the definitions in @code{SYSTEM}. GNAT does
22712 not permit the specification of @code{SYSTEM_NAME}, @code{STORAGE_UNIT}
22713 or @code{MEMORY_SIZE} by any other means.
22715 On GNAT systems, the pragma @code{SYSTEM_NAME} takes the
22716 enumeration literal @code{SYSTEM_NAME_GNAT}.
22718 The definitions provided by the use of
22720 @smallexample @c ada
22721 pragma Extend_System (AUX_Dec);
22725 are virtually identical to those provided by the HP Ada 83 package
22726 @code{SYSTEM}. One important difference is that the name of the
22728 function for type @code{UNSIGNED_LONGWORD} is changed to
22729 @code{TO_ADDRESS_LONG}.
22730 @xref{Address Clauses,,, gnat_rm, GNAT Reference Manual}, for a
22731 discussion of why this change was necessary.
22734 The version of @code{TO_ADDRESS} taking a @i{universal_integer} argument
22736 an extension to Ada 83 not strictly compatible with the reference manual.
22737 GNAT, in order to be exactly compatible with the standard,
22738 does not provide this capability. In HP Ada 83, the
22739 point of this definition is to deal with a call like:
22741 @smallexample @c ada
22742 TO_ADDRESS (16#12777#);
22746 Normally, according to Ada 83 semantics, one would expect this to be
22747 ambiguous, since it matches both the @code{INTEGER} and
22748 @code{UNSIGNED_LONGWORD} forms of @code{TO_ADDRESS}.
22749 However, in HP Ada 83, there is no ambiguity, since the
22750 definition using @i{universal_integer} takes precedence.
22752 In GNAT, since the version with @i{universal_integer} cannot be supplied,
22754 not possible to be 100% compatible. Since there are many programs using
22755 numeric constants for the argument to @code{TO_ADDRESS}, the decision in
22757 to change the name of the function in the @code{UNSIGNED_LONGWORD} case,
22758 so the declarations provided in the GNAT version of @code{AUX_Dec} are:
22760 @smallexample @c ada
22761 function To_Address (X : Integer) return Address;
22762 pragma Pure_Function (To_Address);
22764 function To_Address_Long (X : Unsigned_Longword) return Address;
22765 pragma Pure_Function (To_Address_Long);
22769 This means that programs using @code{TO_ADDRESS} for
22770 @code{UNSIGNED_LONGWORD} must change the name to @code{TO_ADDRESS_LONG}.
22772 @node Tasking and Task-Related Features
22773 @section Tasking and Task-Related Features
22776 This section compares the treatment of tasking in GNAT
22777 and in HP Ada for OpenVMS Alpha.
22778 The GNAT description applies to both Alpha and I64 OpenVMS.
22779 For detailed information on tasking in
22780 HP Ada, see the @cite{HP Ada Language Reference Manual} and the
22781 relevant run-time reference manual.
22784 * Implementation of Tasks in HP Ada for OpenVMS Alpha Systems::
22785 * Assigning Task IDs::
22786 * Task IDs and Delays::
22787 * Task-Related Pragmas::
22788 * Scheduling and Task Priority::
22790 * External Interrupts::
22793 @node Implementation of Tasks in HP Ada for OpenVMS Alpha Systems
22794 @subsection Implementation of Tasks in HP Ada for OpenVMS Alpha Systems
22797 On OpenVMS Alpha systems, each Ada task (except a passive
22798 task) is implemented as a single stream of execution
22799 that is created and managed by the kernel. On these
22800 systems, HP Ada tasking support is based on DECthreads,
22801 an implementation of the POSIX standard for threads.
22803 Also, on OpenVMS Alpha systems, HP Ada tasks and foreign
22804 code that calls DECthreads routines can be used together.
22805 The interaction between Ada tasks and DECthreads routines
22806 can have some benefits. For example when on OpenVMS Alpha,
22807 HP Ada can call C code that is already threaded.
22809 GNAT uses the facilities of DECthreads,
22810 and Ada tasks are mapped to threads.
22812 @node Assigning Task IDs
22813 @subsection Assigning Task IDs
22816 The HP Ada Run-Time Library always assigns @code{%TASK 1} to
22817 the environment task that executes the main program. On
22818 OpenVMS Alpha systems, @code{%TASK 0} is often used for tasks
22819 that have been created but are not yet activated.
22821 On OpenVMS Alpha systems, task IDs are assigned at
22822 activation. On GNAT systems, task IDs are also assigned at
22823 task creation but do not have the same form or values as
22824 task ID values in HP Ada. There is no null task, and the
22825 environment task does not have a specific task ID value.
22827 @node Task IDs and Delays
22828 @subsection Task IDs and Delays
22831 On OpenVMS Alpha systems, tasking delays are implemented
22832 using Timer System Services. The Task ID is used for the
22833 identification of the timer request (the @code{REQIDT} parameter).
22834 If Timers are used in the application take care not to use
22835 @code{0} for the identification, because cancelling such a timer
22836 will cancel all timers and may lead to unpredictable results.
22838 @node Task-Related Pragmas
22839 @subsection Task-Related Pragmas
22842 Ada supplies the pragma @code{TASK_STORAGE}, which allows
22843 specification of the size of the guard area for a task
22844 stack. (The guard area forms an area of memory that has no
22845 read or write access and thus helps in the detection of
22846 stack overflow.) On OpenVMS Alpha systems, if the pragma
22847 @code{TASK_STORAGE} specifies a value of zero, a minimal guard
22848 area is created. In the absence of a pragma @code{TASK_STORAGE},
22849 a default guard area is created.
22851 GNAT supplies the following task-related pragma:
22854 @item @code{TASK_STORAGE}
22856 GNAT implements pragma @code{TASK_STORAGE} in the same way as HP Ada.
22857 Both HP Ada and GNAT supply the pragmas @code{PASSIVE},
22858 @code{SUPPRESS}, and @code{VOLATILE}.
22861 @node Scheduling and Task Priority
22862 @subsection Scheduling and Task Priority
22865 HP Ada implements the Ada language requirement that
22866 when two tasks are eligible for execution and they have
22867 different priorities, the lower priority task does not
22868 execute while the higher priority task is waiting. The HP
22869 Ada Run-Time Library keeps a task running until either the
22870 task is suspended or a higher priority task becomes ready.
22872 On OpenVMS Alpha systems, the default strategy is round-
22873 robin with preemption. Tasks of equal priority take turns
22874 at the processor. A task is run for a certain period of
22875 time and then placed at the tail of the ready queue for
22876 its priority level.
22878 HP Ada provides the implementation-defined pragma @code{TIME_SLICE},
22879 which can be used to enable or disable round-robin
22880 scheduling of tasks with the same priority.
22881 See the relevant HP Ada run-time reference manual for
22882 information on using the pragmas to control HP Ada task
22885 GNAT follows the scheduling rules of Annex D (Real-Time
22886 Annex) of the @cite{Ada Reference Manual}. In general, this
22887 scheduling strategy is fully compatible with HP Ada
22888 although it provides some additional constraints (as
22889 fully documented in Annex D).
22890 GNAT implements time slicing control in a manner compatible with
22891 HP Ada 83, by means of the pragma @code{Time_Slice}, whose semantics
22892 are identical to the HP Ada 83 pragma of the same name.
22893 Note that it is not possible to mix GNAT tasking and
22894 HP Ada 83 tasking in the same program, since the two run-time
22895 libraries are not compatible.
22897 @node The Task Stack
22898 @subsection The Task Stack
22901 In HP Ada, a task stack is allocated each time a
22902 non-passive task is activated. As soon as the task is
22903 terminated, the storage for the task stack is deallocated.
22904 If you specify a size of zero (bytes) with @code{T'STORAGE_SIZE},
22905 a default stack size is used. Also, regardless of the size
22906 specified, some additional space is allocated for task
22907 management purposes. On OpenVMS Alpha systems, at least
22908 one page is allocated.
22910 GNAT handles task stacks in a similar manner. In accordance with
22911 the Ada rules, it provides the pragma @code{STORAGE_SIZE} as
22912 an alternative method for controlling the task stack size.
22913 The specification of the attribute @code{T'STORAGE_SIZE} is also
22914 supported in a manner compatible with HP Ada.
22916 @node External Interrupts
22917 @subsection External Interrupts
22920 On HP Ada, external interrupts can be associated with task entries.
22921 GNAT is compatible with HP Ada in its handling of external interrupts.
22923 @node Pragmas and Pragma-Related Features
22924 @section Pragmas and Pragma-Related Features
22927 Both HP Ada and GNAT supply all language-defined pragmas
22928 as specified by the Ada 83 standard. GNAT also supplies all
22929 language-defined pragmas introduced by Ada 95 and Ada 2005.
22930 In addition, GNAT implements the implementation-defined pragmas
22934 @item @code{AST_ENTRY}
22936 @item @code{COMMON_OBJECT}
22938 @item @code{COMPONENT_ALIGNMENT}
22940 @item @code{EXPORT_EXCEPTION}
22942 @item @code{EXPORT_FUNCTION}
22944 @item @code{EXPORT_OBJECT}
22946 @item @code{EXPORT_PROCEDURE}
22948 @item @code{EXPORT_VALUED_PROCEDURE}
22950 @item @code{FLOAT_REPRESENTATION}
22954 @item @code{IMPORT_EXCEPTION}
22956 @item @code{IMPORT_FUNCTION}
22958 @item @code{IMPORT_OBJECT}
22960 @item @code{IMPORT_PROCEDURE}
22962 @item @code{IMPORT_VALUED_PROCEDURE}
22964 @item @code{INLINE_GENERIC}
22966 @item @code{INTERFACE_NAME}
22968 @item @code{LONG_FLOAT}
22970 @item @code{MAIN_STORAGE}
22972 @item @code{PASSIVE}
22974 @item @code{PSECT_OBJECT}
22976 @item @code{SHARE_GENERIC}
22978 @item @code{SUPPRESS_ALL}
22980 @item @code{TASK_STORAGE}
22982 @item @code{TIME_SLICE}
22988 These pragmas are all fully implemented, with the exception of @code{TITLE},
22989 @code{PASSIVE}, and @code{SHARE_GENERIC}, which are
22990 recognized, but which have no
22991 effect in GNAT. The effect of @code{PASSIVE} may be obtained by the
22992 use of Ada protected objects. In GNAT, all generics are inlined.
22994 Unlike HP Ada, the GNAT ``@code{EXPORT_}@i{subprogram}'' pragmas require
22995 a separate subprogram specification which must appear before the
22998 GNAT also supplies a number of implementation-defined pragmas including the
23002 @item @code{ABORT_DEFER}
23004 @item @code{ADA_83}
23006 @item @code{ADA_95}
23008 @item @code{ADA_05}
23010 @item @code{Ada_2005}
23012 @item @code{Ada_12}
23014 @item @code{Ada_2012}
23016 @item @code{ALLOW_INTEGER_ADDRESS}
23018 @item @code{ANNOTATE}
23020 @item @code{ASSERT}
23022 @item @code{C_PASS_BY_COPY}
23024 @item @code{CPP_CLASS}
23026 @item @code{CPP_CONSTRUCTOR}
23028 @item @code{CPP_DESTRUCTOR}
23032 @item @code{EXTEND_SYSTEM}
23034 @item @code{LINKER_ALIAS}
23036 @item @code{LINKER_SECTION}
23038 @item @code{MACHINE_ATTRIBUTE}
23040 @item @code{NO_RETURN}
23042 @item @code{PURE_FUNCTION}
23044 @item @code{SOURCE_FILE_NAME}
23046 @item @code{SOURCE_REFERENCE}
23048 @item @code{UNCHECKED_UNION}
23050 @item @code{UNIMPLEMENTED_UNIT}
23052 @item @code{UNIVERSAL_DATA}
23054 @item @code{UNSUPPRESS}
23056 @item @code{WARNINGS}
23058 @item @code{WEAK_EXTERNAL}
23062 For full details on these and other GNAT implementation-defined pragmas,
23063 see @ref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference
23067 * Restrictions on the Pragma INLINE::
23068 * Restrictions on the Pragma INTERFACE::
23069 * Restrictions on the Pragma SYSTEM_NAME::
23072 @node Restrictions on the Pragma INLINE
23073 @subsection Restrictions on Pragma @code{INLINE}
23076 HP Ada enforces the following restrictions on the pragma @code{INLINE}:
23078 @item Parameters cannot have a task type.
23080 @item Function results cannot be task types, unconstrained
23081 array types, or unconstrained types with discriminants.
23083 @item Bodies cannot declare the following:
23085 @item Subprogram body or stub (imported subprogram is allowed)
23089 @item Generic declarations
23091 @item Instantiations
23095 @item Access types (types derived from access types allowed)
23097 @item Array or record types
23099 @item Dependent tasks
23101 @item Direct recursive calls of subprogram or containing
23102 subprogram, directly or via a renaming
23108 In GNAT, the only restriction on pragma @code{INLINE} is that the
23109 body must occur before the call if both are in the same
23110 unit, and the size must be appropriately small. There are
23111 no other specific restrictions which cause subprograms to
23112 be incapable of being inlined.
23114 @node Restrictions on the Pragma INTERFACE
23115 @subsection Restrictions on Pragma @code{INTERFACE}
23118 The following restrictions on pragma @code{INTERFACE}
23119 are enforced by both HP Ada and GNAT:
23121 @item Languages accepted: Ada, Bliss, C, Fortran, Default.
23122 Default is the default on OpenVMS Alpha systems.
23124 @item Parameter passing: Language specifies default
23125 mechanisms but can be overridden with an @code{EXPORT} pragma.
23128 @item Ada: Use internal Ada rules.
23130 @item Bliss, C: Parameters must be mode @code{in}; cannot be
23131 record or task type. Result cannot be a string, an
23132 array, or a record.
23134 @item Fortran: Parameters cannot have a task type. Result cannot
23135 be a string, an array, or a record.
23140 GNAT is entirely upwards compatible with HP Ada, and in addition allows
23141 record parameters for all languages.
23143 @node Restrictions on the Pragma SYSTEM_NAME
23144 @subsection Restrictions on Pragma @code{SYSTEM_NAME}
23147 For HP Ada for OpenVMS Alpha, the enumeration literal
23148 for the type @code{NAME} is @code{OPENVMS_AXP}.
23149 In GNAT, the enumeration
23150 literal for the type @code{NAME} is @code{SYSTEM_NAME_GNAT}.
23152 @node Library of Predefined Units
23153 @section Library of Predefined Units
23156 A library of predefined units is provided as part of the
23157 HP Ada and GNAT implementations. HP Ada does not provide
23158 the package @code{MACHINE_CODE} but instead recommends importing
23161 The GNAT versions of the HP Ada Run-Time Library (@code{ADA$PREDEFINED:})
23162 units are taken from the OpenVMS Alpha version, not the OpenVMS VAX
23164 The HP Ada Predefined Library units are modified to remove post-Ada 83
23165 incompatibilities and to make them interoperable with GNAT
23166 (@pxref{Changes to DECLIB}, for details).
23167 The units are located in the @file{DECLIB} directory.
23169 The GNAT RTL is contained in
23170 the @file{ADALIB} directory, and
23171 the default search path is set up to find @code{DECLIB} units in preference
23172 to @code{ADALIB} units with the same name (@code{TEXT_IO},
23173 @code{SEQUENTIAL_IO}, and @code{DIRECT_IO}, for example).
23176 * Changes to DECLIB::
23179 @node Changes to DECLIB
23180 @subsection Changes to @code{DECLIB}
23183 The changes made to the HP Ada predefined library for GNAT and post-Ada 83
23184 compatibility are minor and include the following:
23187 @item Adjusting the location of pragmas and record representation
23188 clauses to obey Ada 95 (and thus Ada 2005) rules
23190 @item Adding the proper notation to generic formal parameters
23191 that take unconstrained types in instantiation
23193 @item Adding pragma @code{ELABORATE_BODY} to package specs
23194 that have package bodies not otherwise allowed
23196 @item Replacing occurrences of the identifier ``@code{PROTECTED}'' by
23197 ``@code{PROTECTD}''.
23198 Currently these are found only in the @code{STARLET} package spec.
23200 @item Changing @code{SYSTEM.ADDRESS} to @code{SYSTEM.SHORT_ADDRESS}
23201 where the address size is constrained to 32 bits.
23205 None of the above changes is visible to users.
23211 On OpenVMS Alpha, HP Ada provides the following strongly-typed bindings:
23214 @item Command Language Interpreter (CLI interface)
23216 @item DECtalk Run-Time Library (DTK interface)
23218 @item Librarian utility routines (LBR interface)
23220 @item General Purpose Run-Time Library (LIB interface)
23222 @item Math Run-Time Library (MTH interface)
23224 @item National Character Set Run-Time Library (NCS interface)
23226 @item Compiled Code Support Run-Time Library (OTS interface)
23228 @item Parallel Processing Run-Time Library (PPL interface)
23230 @item Screen Management Run-Time Library (SMG interface)
23232 @item Sort Run-Time Library (SOR interface)
23234 @item String Run-Time Library (STR interface)
23236 @item STARLET System Library
23239 @item X Window System Version 11R4 and 11R5 (X, XLIB interface)
23241 @item X Windows Toolkit (XT interface)
23243 @item X/Motif Version 1.1.3 and 1.2 (XM interface)
23247 GNAT provides implementations of these HP bindings in the @code{DECLIB}
23248 directory, on both the Alpha and I64 OpenVMS platforms.
23250 The X components of DECLIB compatibility package are located in a separate
23251 library, called XDECGNAT, which is not linked with by default; this library
23252 must be explicitly linked with any application that makes use of any X facilities,
23253 with a command similar to
23255 @code{GNAT MAKE USE_X /LINK /LIBRARY=XDECGNAT}
23257 The X/Motif bindings used to build @code{DECLIB} are whatever versions are
23259 HP Ada @file{ADA$PREDEFINED} directory with extension @file{.ADC}.
23260 A pragma @code{Linker_Options} has been added to packages @code{Xm},
23261 @code{Xt}, and @code{X_Lib}
23262 causing the default X/Motif sharable image libraries to be linked in. This
23263 is done via options files named @file{xm.opt}, @file{xt.opt}, and
23264 @file{x_lib.opt} (also located in the @file{DECLIB} directory).
23266 It may be necessary to edit these options files to update or correct the
23267 library names if, for example, the newer X/Motif bindings from
23268 @file{ADA$EXAMPLES}
23269 had been (previous to installing GNAT) copied and renamed to supersede the
23270 default @file{ADA$PREDEFINED} versions.
23273 * Shared Libraries and Options Files::
23274 * Interfaces to C::
23277 @node Shared Libraries and Options Files
23278 @subsection Shared Libraries and Options Files
23281 When using the HP Ada
23282 predefined X and Motif bindings, the linking with their sharable images is
23283 done automatically by @command{GNAT LINK}.
23284 When using other X and Motif bindings, you need
23285 to add the corresponding sharable images to the command line for
23286 @code{GNAT LINK}. When linking with shared libraries, or with
23287 @file{.OPT} files, you must
23288 also add them to the command line for @command{GNAT LINK}.
23290 A shared library to be used with GNAT is built in the same way as other
23291 libraries under VMS. The VMS Link command can be used in standard fashion.
23293 @node Interfaces to C
23294 @subsection Interfaces to C
23298 provides the following Ada types and operations:
23301 @item C types package (@code{C_TYPES})
23303 @item C strings (@code{C_TYPES.NULL_TERMINATED})
23305 @item Other_types (@code{SHORT_INT})
23309 Interfacing to C with GNAT, you can use the above approach
23310 described for HP Ada or the facilities of Annex B of
23311 the @cite{Ada Reference Manual} (packages @code{INTERFACES.C},
23312 @code{INTERFACES.C.STRINGS} and @code{INTERFACES.C.POINTERS}). For more
23313 information, see @ref{Interfacing to C,,, gnat_rm, GNAT Reference Manual}.
23315 The @option{-gnatF} qualifier forces default and explicit
23316 @code{External_Name} parameters in pragmas @code{Import} and @code{Export}
23317 to be uppercased for compatibility with the default behavior
23318 of HP C. The qualifier has no effect on @code{Link_Name} parameters.
23320 @node Main Program Definition
23321 @section Main Program Definition
23324 The following section discusses differences in the
23325 definition of main programs on HP Ada and GNAT.
23326 On HP Ada, main programs are defined to meet the
23327 following conditions:
23329 @item Procedure with no formal parameters (returns @code{0} upon
23332 @item Procedure with no formal parameters (returns @code{42} when
23333 an unhandled exception is raised)
23335 @item Function with no formal parameters whose returned value
23336 is of a discrete type
23338 @item Procedure with one @code{out} formal of a discrete type for
23339 which a specification of pragma @code{EXPORT_VALUED_PROCEDURE} is given.
23344 When declared with the pragma @code{EXPORT_VALUED_PROCEDURE},
23345 a main function or main procedure returns a discrete
23346 value whose size is less than 64 bits (32 on VAX systems),
23347 the value is zero- or sign-extended as appropriate.
23348 On GNAT, main programs are defined as follows:
23350 @item Must be a non-generic, parameterless subprogram that
23351 is either a procedure or function returning an Ada
23352 @code{STANDARD.INTEGER} (the predefined type)
23354 @item Cannot be a generic subprogram or an instantiation of a
23358 @node Implementation-Defined Attributes
23359 @section Implementation-Defined Attributes
23362 GNAT provides all HP Ada implementation-defined
23365 @node Compiler and Run-Time Interfacing
23366 @section Compiler and Run-Time Interfacing
23369 HP Ada provides the following qualifiers to pass options to the linker
23372 @item @option{/WAIT} and @option{/SUBMIT}
23374 @item @option{/COMMAND}
23376 @item @option{/@r{[}NO@r{]}MAP}
23378 @item @option{/OUTPUT=@var{file-spec}}
23380 @item @option{/@r{[}NO@r{]}DEBUG} and @option{/@r{[}NO@r{]}TRACEBACK}
23384 To pass options to the linker, GNAT provides the following
23388 @item @option{/EXECUTABLE=@var{exec-name}}
23390 @item @option{/VERBOSE}
23392 @item @option{/@r{[}NO@r{]}DEBUG} and @option{/@r{[}NO@r{]}TRACEBACK}
23396 For more information on these switches, see
23397 @ref{Switches for gnatlink}.
23398 In HP Ada, the command-line switch @option{/OPTIMIZE} is available
23399 to control optimization. HP Ada also supplies the
23402 @item @code{OPTIMIZE}
23404 @item @code{INLINE}
23406 @item @code{INLINE_GENERIC}
23408 @item @code{SUPPRESS_ALL}
23410 @item @code{PASSIVE}
23414 In GNAT, optimization is controlled strictly by command
23415 line parameters, as described in the corresponding section of this guide.
23416 The HP pragmas for control of optimization are
23417 recognized but ignored.
23419 Note that in GNAT, the default is optimization off, whereas in HP Ada
23420 the default is that optimization is turned on.
23422 @node Program Compilation and Library Management
23423 @section Program Compilation and Library Management
23426 HP Ada and GNAT provide a comparable set of commands to
23427 build programs. HP Ada also provides a program library,
23428 which is a concept that does not exist on GNAT. Instead,
23429 GNAT provides directories of sources that are compiled as
23432 The following table summarizes
23433 the HP Ada commands and provides
23434 equivalent GNAT commands. In this table, some GNAT
23435 equivalents reflect the fact that GNAT does not use the
23436 concept of a program library. Instead, it uses a model
23437 in which collections of source and object files are used
23438 in a manner consistent with other languages like C and
23439 Fortran. Therefore, standard system file commands are used
23440 to manipulate these elements. Those GNAT commands are marked with
23442 Note that, unlike HP Ada, none of the GNAT commands accepts wild cards.
23445 @multitable @columnfractions .35 .65
23447 @item @emph{HP Ada Command}
23448 @tab @emph{GNAT Equivalent / Description}
23450 @item @command{ADA}
23451 @tab @command{GNAT COMPILE}@*
23452 Invokes the compiler to compile one or more Ada source files.
23454 @item @command{ACS ATTACH}@*
23455 @tab [No equivalent]@*
23456 Switches control of terminal from current process running the program
23459 @item @command{ACS CHECK}
23460 @tab @command{GNAT MAKE /DEPENDENCY_LIST}@*
23461 Forms the execution closure of one
23462 or more compiled units and checks completeness and currency.
23464 @item @command{ACS COMPILE}
23465 @tab @command{GNAT MAKE /ACTIONS=COMPILE}@*
23466 Forms the execution closure of one or
23467 more specified units, checks completeness and currency,
23468 identifies units that have revised source files, compiles same,
23469 and recompiles units that are or will become obsolete.
23470 Also completes incomplete generic instantiations.
23472 @item @command{ACS COPY FOREIGN}
23474 Copies a foreign object file into the program library as a
23477 @item @command{ACS COPY UNIT}
23479 Copies a compiled unit from one program library to another.
23481 @item @command{ACS CREATE LIBRARY}
23482 @tab Create /directory (*)@*
23483 Creates a program library.
23485 @item @command{ACS CREATE SUBLIBRARY}
23486 @tab Create /directory (*)@*
23487 Creates a program sublibrary.
23489 @item @command{ACS DELETE LIBRARY}
23491 Deletes a program library and its contents.
23493 @item @command{ACS DELETE SUBLIBRARY}
23495 Deletes a program sublibrary and its contents.
23497 @item @command{ACS DELETE UNIT}
23498 @tab Delete file (*)@*
23499 On OpenVMS systems, deletes one or more compiled units from
23500 the current program library.
23502 @item @command{ACS DIRECTORY}
23503 @tab Directory (*)@*
23504 On OpenVMS systems, lists units contained in the current
23507 @item @command{ACS ENTER FOREIGN}
23509 Allows the import of a foreign body as an Ada library
23510 spec and enters a reference to a pointer.
23512 @item @command{ACS ENTER UNIT}
23514 Enters a reference (pointer) from the current program library to
23515 a unit compiled into another program library.
23517 @item @command{ACS EXIT}
23518 @tab [No equivalent]@*
23519 Exits from the program library manager.
23521 @item @command{ACS EXPORT}
23523 Creates an object file that contains system-specific object code
23524 for one or more units. With GNAT, object files can simply be copied
23525 into the desired directory.
23527 @item @command{ACS EXTRACT SOURCE}
23529 Allows access to the copied source file for each Ada compilation unit
23531 @item @command{ACS HELP}
23532 @tab @command{HELP GNAT}@*
23533 Provides online help.
23535 @item @command{ACS LINK}
23536 @tab @command{GNAT LINK}@*
23537 Links an object file containing Ada units into an executable file.
23539 @item @command{ACS LOAD}
23541 Loads (partially compiles) Ada units into the program library.
23542 Allows loading a program from a collection of files into a library
23543 without knowing the relationship among units.
23545 @item @command{ACS MERGE}
23547 Merges into the current program library, one or more units from
23548 another library where they were modified.
23550 @item @command{ACS RECOMPILE}
23551 @tab @command{GNAT MAKE /ACTIONS=COMPILE}@*
23552 Recompiles from external or copied source files any obsolete
23553 unit in the closure. Also, completes any incomplete generic
23556 @item @command{ACS REENTER}
23557 @tab @command{GNAT MAKE}@*
23558 Reenters current references to units compiled after last entered
23559 with the @command{ACS ENTER UNIT} command.
23561 @item @command{ACS SET LIBRARY}
23562 @tab Set default (*)@*
23563 Defines a program library to be the compilation context as well
23564 as the target library for compiler output and commands in general.
23566 @item @command{ACS SET PRAGMA}
23567 @tab Edit @file{gnat.adc} (*)@*
23568 Redefines specified values of the library characteristics
23569 @code{LONG_ FLOAT}, @code{MEMORY_SIZE}, @code{SYSTEM_NAME},
23570 and @code{Float_Representation}.
23572 @item @command{ACS SET SOURCE}
23573 @tab Define @code{ADA_INCLUDE_PATH} path (*)@*
23574 Defines the source file search list for the @command{ACS COMPILE} command.
23576 @item @command{ACS SHOW LIBRARY}
23577 @tab Directory (*)@*
23578 Lists information about one or more program libraries.
23580 @item @command{ACS SHOW PROGRAM}
23581 @tab [No equivalent]@*
23582 Lists information about the execution closure of one or
23583 more units in the program library.
23585 @item @command{ACS SHOW SOURCE}
23586 @tab Show logical @code{ADA_INCLUDE_PATH}@*
23587 Shows the source file search used when compiling units.
23589 @item @command{ACS SHOW VERSION}
23590 @tab Compile with @option{VERBOSE} option
23591 Displays the version number of the compiler and program library
23594 @item @command{ACS SPAWN}
23595 @tab [No equivalent]@*
23596 Creates a subprocess of the current process (same as @command{DCL SPAWN}
23599 @item @command{ACS VERIFY}
23600 @tab [No equivalent]@*
23601 Performs a series of consistency checks on a program library to
23602 determine whether the library structure and library files are in
23609 @section Input-Output
23612 On OpenVMS Alpha systems, HP Ada uses OpenVMS Record
23613 Management Services (RMS) to perform operations on
23617 HP Ada and GNAT predefine an identical set of input-
23618 output packages. To make the use of the
23619 generic @code{TEXT_IO} operations more convenient, HP Ada
23620 provides predefined library packages that instantiate the
23621 integer and floating-point operations for the predefined
23622 integer and floating-point types as shown in the following table.
23624 @multitable @columnfractions .45 .55
23625 @item @emph{Package Name} @tab Instantiation
23627 @item @code{INTEGER_TEXT_IO}
23628 @tab @code{INTEGER_IO(INTEGER)}
23630 @item @code{SHORT_INTEGER_TEXT_IO}
23631 @tab @code{INTEGER_IO(SHORT_INTEGER)}
23633 @item @code{SHORT_SHORT_INTEGER_TEXT_IO}
23634 @tab @code{INTEGER_IO(SHORT_SHORT_INTEGER)}
23636 @item @code{FLOAT_TEXT_IO}
23637 @tab @code{FLOAT_IO(FLOAT)}
23639 @item @code{LONG_FLOAT_TEXT_IO}
23640 @tab @code{FLOAT_IO(LONG_FLOAT)}
23644 The HP Ada predefined packages and their operations
23645 are implemented using OpenVMS Alpha files and input-output
23646 facilities. HP Ada supports asynchronous input-output on OpenVMS Alpha.
23647 Familiarity with the following is recommended:
23649 @item RMS file organizations and access methods
23651 @item OpenVMS file specifications and directories
23653 @item OpenVMS File Definition Language (FDL)
23657 GNAT provides I/O facilities that are completely
23658 compatible with HP Ada. The distribution includes the
23659 standard HP Ada versions of all I/O packages, operating
23660 in a manner compatible with HP Ada. In particular, the
23661 following packages are by default the HP Ada (Ada 83)
23662 versions of these packages rather than the renamings
23663 suggested in Annex J of the Ada Reference Manual:
23665 @item @code{TEXT_IO}
23667 @item @code{SEQUENTIAL_IO}
23669 @item @code{DIRECT_IO}
23673 The use of the standard child package syntax (for
23674 example, @code{ADA.TEXT_IO}) retrieves the post-Ada 83 versions of these
23676 GNAT provides HP-compatible predefined instantiations
23677 of the @code{TEXT_IO} packages, and also
23678 provides the standard predefined instantiations required
23679 by the @cite{Ada Reference Manual}.
23681 For further information on how GNAT interfaces to the file
23682 system or how I/O is implemented in programs written in
23683 mixed languages, see @ref{Implementation of the Standard I/O,,,
23684 gnat_rm, GNAT Reference Manual}.
23685 This chapter covers the following:
23687 @item Standard I/O packages
23689 @item @code{FORM} strings
23691 @item @code{ADA.DIRECT_IO}
23693 @item @code{ADA.SEQUENTIAL_IO}
23695 @item @code{ADA.TEXT_IO}
23697 @item Stream pointer positioning
23699 @item Reading and writing non-regular files
23701 @item @code{GET_IMMEDIATE}
23703 @item Treating @code{TEXT_IO} files as streams
23710 @node Implementation Limits
23711 @section Implementation Limits
23714 The following table lists implementation limits for HP Ada
23716 @multitable @columnfractions .60 .20 .20
23718 @item @emph{Compilation Parameter}
23723 @item In a subprogram or entry declaration, maximum number of
23724 formal parameters that are of an unconstrained record type
23729 @item Maximum identifier length (number of characters)
23734 @item Maximum number of characters in a source line
23739 @item Maximum collection size (number of bytes)
23744 @item Maximum number of discriminants for a record type
23749 @item Maximum number of formal parameters in an entry or
23750 subprogram declaration
23755 @item Maximum number of dimensions in an array type
23760 @item Maximum number of library units and subunits in a compilation.
23765 @item Maximum number of library units and subunits in an execution.
23770 @item Maximum number of objects declared with the pragma @code{COMMON_OBJECT}
23771 or @code{PSECT_OBJECT}
23776 @item Maximum number of enumeration literals in an enumeration type
23782 @item Maximum number of lines in a source file
23787 @item Maximum number of bits in any object
23792 @item Maximum size of the static portion of a stack frame (approximate)
23797 @node Tools and Utilities
23798 @section Tools and Utilities
23801 The following table lists some of the OpenVMS development tools
23802 available for HP Ada, and the corresponding tools for
23803 use with @value{EDITION} on Alpha and I64 platforms.
23804 Aside from the debugger, all the OpenVMS tools identified are part
23805 of the DECset package.
23808 @c Specify table in TeX since Texinfo does a poor job
23812 \settabs\+Language-Sensitive Editor\quad
23813 &Product with HP Ada\quad
23816 &\it Product with HP Ada
23817 & \it Product with @value{EDITION}\cr
23819 \+Code Management System
23823 \+Language-Sensitive Editor
23825 & emacs or HP LSE (Alpha)\cr
23835 & OpenVMS Debug (I64)\cr
23837 \+Source Code Analyzer /
23854 \+Coverage Analyzer
23858 \+Module Management
23860 & Not applicable\cr
23870 @c This is the Texinfo version of the table. It renders poorly in pdf, hence
23871 @c the TeX version above for the printed version
23873 @c @multitable @columnfractions .3 .4 .4
23874 @multitable {Source Code Analyzer /}{Tool with HP Ada}{Tool with @value{EDITION}}
23876 @tab @i{Tool with HP Ada}
23877 @tab @i{Tool with @value{EDITION}}
23878 @item Code Management@*System
23881 @item Language-Sensitive@*Editor
23883 @tab emacs or HP LSE (Alpha)
23892 @tab OpenVMS Debug (I64)
23893 @item Source Code Analyzer /@*Cross Referencer
23897 @tab HP Digital Test@*Manager (DTM)
23899 @item Performance and@*Coverage Analyzer
23902 @item Module Management@*System
23904 @tab Not applicable
23911 @c **************************************
23912 @node Platform-Specific Information for the Run-Time Libraries
23913 @appendix Platform-Specific Information for the Run-Time Libraries
23914 @cindex Tasking and threads libraries
23915 @cindex Threads libraries and tasking
23916 @cindex Run-time libraries (platform-specific information)
23919 The GNAT run-time implementation may vary with respect to both the
23920 underlying threads library and the exception handling scheme.
23921 For threads support, one or more of the following are supplied:
23923 @item @b{native threads library}, a binding to the thread package from
23924 the underlying operating system
23926 @item @b{pthreads library} (Sparc Solaris only), a binding to the Solaris
23927 POSIX thread package
23931 For exception handling, either or both of two models are supplied:
23933 @item @b{Zero-Cost Exceptions} (``ZCX''),@footnote{
23934 Most programs should experience a substantial speed improvement by
23935 being compiled with a ZCX run-time.
23936 This is especially true for
23937 tasking applications or applications with many exception handlers.}
23938 @cindex Zero-Cost Exceptions
23939 @cindex ZCX (Zero-Cost Exceptions)
23940 which uses binder-generated tables that
23941 are interrogated at run time to locate a handler
23943 @item @b{setjmp / longjmp} (``SJLJ''),
23944 @cindex setjmp/longjmp Exception Model
23945 @cindex SJLJ (setjmp/longjmp Exception Model)
23946 which uses dynamically-set data to establish
23947 the set of handlers
23951 This appendix summarizes which combinations of threads and exception support
23952 are supplied on various GNAT platforms.
23953 It then shows how to select a particular library either
23954 permanently or temporarily,
23955 explains the properties of (and tradeoffs among) the various threads
23956 libraries, and provides some additional
23957 information about several specific platforms.
23960 * Summary of Run-Time Configurations::
23961 * Specifying a Run-Time Library::
23962 * Choosing the Scheduling Policy::
23963 * Solaris-Specific Considerations::
23964 * Linux-Specific Considerations::
23965 * AIX-Specific Considerations::
23966 * RTX-Specific Considerations::
23967 * HP-UX-Specific Considerations::
23970 @node Summary of Run-Time Configurations
23971 @section Summary of Run-Time Configurations
23973 @multitable @columnfractions .30 .70
23974 @item @b{alpha-openvms}
23975 @item @code{@ @ }@i{rts-native (default)}
23976 @item @code{@ @ @ @ }Tasking @tab native VMS threads
23977 @item @code{@ @ @ @ }Exceptions @tab ZCX
23979 @item @code{@ @ }@i{rts-sjlj}
23980 @item @code{@ @ @ @ }Tasking @tab native TRU64 threads
23981 @item @code{@ @ @ @ }Exceptions @tab SJLJ
23983 @item @b{ia64-hp_linux}
23984 @item @code{@ @ }@i{rts-native (default)}
23985 @item @code{@ @ @ @ }Tasking @tab pthread library
23986 @item @code{@ @ @ @ }Exceptions @tab ZCX
23988 @item @b{ia64-hpux}
23989 @item @code{@ @ }@i{rts-native (default)}
23990 @item @code{@ @ @ @ }Tasking @tab native HP-UX threads
23991 @item @code{@ @ @ @ }Exceptions @tab SJLJ
23993 @item @b{ia64-openvms}
23994 @item @code{@ @ }@i{rts-native (default)}
23995 @item @code{@ @ @ @ }Tasking @tab native VMS threads
23996 @item @code{@ @ @ @ }Exceptions @tab ZCX
23998 @item @b{ia64-sgi_linux}
23999 @item @code{@ @ }@i{rts-native (default)}
24000 @item @code{@ @ @ @ }Tasking @tab pthread library
24001 @item @code{@ @ @ @ }Exceptions @tab ZCX
24004 @item @code{@ @ }@i{rts-native (default)}
24005 @item @code{@ @ @ @ }Tasking @tab native HP-UX threads
24006 @item @code{@ @ @ @ }Exceptions @tab ZCX
24008 @item @code{@ @ }@i{rts-sjlj}
24009 @item @code{@ @ @ @ }Tasking @tab native HP-UX threads
24010 @item @code{@ @ @ @ }Exceptions @tab SJLJ
24013 @item @code{@ @ }@i{rts-native (default)}
24014 @item @code{@ @ @ @ }Tasking @tab native AIX threads
24015 @item @code{@ @ @ @ }Exceptions @tab ZCX
24017 @item @code{@ @ }@i{rts-sjlj}
24018 @item @code{@ @ @ @ }Tasking @tab native AIX threads
24019 @item @code{@ @ @ @ }Exceptions @tab SJLJ
24021 @item @b{ppc-darwin}
24022 @item @code{@ @ }@i{rts-native (default)}
24023 @item @code{@ @ @ @ }Tasking @tab native MacOS threads
24024 @item @code{@ @ @ @ }Exceptions @tab ZCX
24026 @item @b{sparc-solaris} @tab
24027 @item @code{@ @ }@i{rts-native (default)}
24028 @item @code{@ @ @ @ }Tasking @tab native Solaris threads library
24029 @item @code{@ @ @ @ }Exceptions @tab ZCX
24031 @item @code{@ @ }@i{rts-pthread}
24032 @item @code{@ @ @ @ }Tasking @tab pthread library
24033 @item @code{@ @ @ @ }Exceptions @tab ZCX
24035 @item @code{@ @ }@i{rts-sjlj}
24036 @item @code{@ @ @ @ }Tasking @tab native Solaris threads library
24037 @item @code{@ @ @ @ }Exceptions @tab SJLJ
24039 @item @b{sparc64-solaris} @tab
24040 @item @code{@ @ }@i{rts-native (default)}
24041 @item @code{@ @ @ @ }Tasking @tab native Solaris threads library
24042 @item @code{@ @ @ @ }Exceptions @tab ZCX
24044 @item @b{x86-linux}
24045 @item @code{@ @ }@i{rts-native (default)}
24046 @item @code{@ @ @ @ }Tasking @tab pthread library
24047 @item @code{@ @ @ @ }Exceptions @tab ZCX
24049 @item @code{@ @ }@i{rts-sjlj}
24050 @item @code{@ @ @ @ }Tasking @tab pthread library
24051 @item @code{@ @ @ @ }Exceptions @tab SJLJ
24054 @item @code{@ @ }@i{rts-native (default)}
24055 @item @code{@ @ @ @ }Tasking @tab native LynxOS threads
24056 @item @code{@ @ @ @ }Exceptions @tab SJLJ
24058 @item @b{x86-solaris}
24059 @item @code{@ @ }@i{rts-native (default)}
24060 @item @code{@ @ @ @ }Tasking @tab native Solaris threads
24061 @item @code{@ @ @ @ }Exceptions @tab ZCX
24063 @item @code{@ @ }@i{rts-sjlj}
24064 @item @code{@ @ @ @ }Tasking @tab native Solaris threads library
24065 @item @code{@ @ @ @ }Exceptions @tab SJLJ
24067 @item @b{x86-windows}
24068 @item @code{@ @ }@i{rts-native (default)}
24069 @item @code{@ @ @ @ }Tasking @tab native Win32 threads
24070 @item @code{@ @ @ @ }Exceptions @tab ZCX
24072 @item @code{@ @ }@i{rts-sjlj}
24073 @item @code{@ @ @ @ }Tasking @tab native Win32 threads
24074 @item @code{@ @ @ @ }Exceptions @tab SJLJ
24076 @item @b{x86-windows-rtx}
24077 @item @code{@ @ }@i{rts-rtx-rtss (default)}
24078 @item @code{@ @ @ @ }Tasking @tab RTX real-time subsystem RTSS threads (kernel mode)
24079 @item @code{@ @ @ @ }Exceptions @tab SJLJ
24081 @item @code{@ @ }@i{rts-rtx-w32}
24082 @item @code{@ @ @ @ }Tasking @tab RTX Win32 threads (user mode)
24083 @item @code{@ @ @ @ }Exceptions @tab ZCX
24085 @item @b{x86_64-linux}
24086 @item @code{@ @ }@i{rts-native (default)}
24087 @item @code{@ @ @ @ }Tasking @tab pthread library
24088 @item @code{@ @ @ @ }Exceptions @tab ZCX
24090 @item @code{@ @ }@i{rts-sjlj}
24091 @item @code{@ @ @ @ }Tasking @tab pthread library
24092 @item @code{@ @ @ @ }Exceptions @tab SJLJ
24096 @node Specifying a Run-Time Library
24097 @section Specifying a Run-Time Library
24100 The @file{adainclude} subdirectory containing the sources of the GNAT
24101 run-time library, and the @file{adalib} subdirectory containing the
24102 @file{ALI} files and the static and/or shared GNAT library, are located
24103 in the gcc target-dependent area:
24106 target=$prefix/lib/gcc/gcc-@i{dumpmachine}/gcc-@i{dumpversion}/
24110 As indicated above, on some platforms several run-time libraries are supplied.
24111 These libraries are installed in the target dependent area and
24112 contain a complete source and binary subdirectory. The detailed description
24113 below explains the differences between the different libraries in terms of
24114 their thread support.
24116 The default run-time library (when GNAT is installed) is @emph{rts-native}.
24117 This default run time is selected by the means of soft links.
24118 For example on x86-linux:
24124 +--- adainclude----------+
24126 +--- adalib-----------+ |
24128 +--- rts-native | |
24130 | +--- adainclude <---+
24132 | +--- adalib <----+
24143 If the @i{rts-sjlj} library is to be selected on a permanent basis,
24144 these soft links can be modified with the following commands:
24148 $ rm -f adainclude adalib
24149 $ ln -s rts-sjlj/adainclude adainclude
24150 $ ln -s rts-sjlj/adalib adalib
24154 Alternatively, you can specify @file{rts-sjlj/adainclude} in the file
24155 @file{$target/ada_source_path} and @file{rts-sjlj/adalib} in
24156 @file{$target/ada_object_path}.
24158 Selecting another run-time library temporarily can be
24159 achieved by using the @option{--RTS} switch, e.g., @option{--RTS=sjlj}
24160 @cindex @option{--RTS} option
24162 @node Choosing the Scheduling Policy
24163 @section Choosing the Scheduling Policy
24166 When using a POSIX threads implementation, you have a choice of several
24167 scheduling policies: @code{SCHED_FIFO},
24168 @cindex @code{SCHED_FIFO} scheduling policy
24170 @cindex @code{SCHED_RR} scheduling policy
24171 and @code{SCHED_OTHER}.
24172 @cindex @code{SCHED_OTHER} scheduling policy
24173 Typically, the default is @code{SCHED_OTHER}, while using @code{SCHED_FIFO}
24174 or @code{SCHED_RR} requires special (e.g., root) privileges.
24176 By default, GNAT uses the @code{SCHED_OTHER} policy. To specify
24178 @cindex @code{SCHED_FIFO} scheduling policy
24179 you can use one of the following:
24183 @code{pragma Time_Slice (0.0)}
24184 @cindex pragma Time_Slice
24186 the corresponding binder option @option{-T0}
24187 @cindex @option{-T0} option
24189 @code{pragma Task_Dispatching_Policy (FIFO_Within_Priorities)}
24190 @cindex pragma Task_Dispatching_Policy
24194 To specify @code{SCHED_RR},
24195 @cindex @code{SCHED_RR} scheduling policy
24196 you should use @code{pragma Time_Slice} with a
24197 value greater than @code{0.0}, or else use the corresponding @option{-T}
24200 @node Solaris-Specific Considerations
24201 @section Solaris-Specific Considerations
24202 @cindex Solaris Sparc threads libraries
24205 This section addresses some topics related to the various threads libraries
24209 * Solaris Threads Issues::
24212 @node Solaris Threads Issues
24213 @subsection Solaris Threads Issues
24216 GNAT under Solaris/Sparc 32 bits comes with an alternate tasking run-time
24217 library based on POSIX threads --- @emph{rts-pthread}.
24218 @cindex rts-pthread threads library
24219 This run-time library has the advantage of being mostly shared across all
24220 POSIX-compliant thread implementations, and it also provides under
24221 @w{Solaris 8} the @code{PTHREAD_PRIO_INHERIT}
24222 @cindex @code{PTHREAD_PRIO_INHERIT} policy (under rts-pthread)
24223 and @code{PTHREAD_PRIO_PROTECT}
24224 @cindex @code{PTHREAD_PRIO_PROTECT} policy (under rts-pthread)
24225 semantics that can be selected using the predefined pragma
24226 @code{Locking_Policy}
24227 @cindex pragma Locking_Policy (under rts-pthread)
24229 @code{Inheritance_Locking} and @code{Ceiling_Locking} as the policy.
24230 @cindex @code{Inheritance_Locking} (under rts-pthread)
24231 @cindex @code{Ceiling_Locking} (under rts-pthread)
24233 As explained above, the native run-time library is based on the Solaris thread
24234 library (@code{libthread}) and is the default library.
24236 When the Solaris threads library is used (this is the default), programs
24237 compiled with GNAT can automatically take advantage of
24238 and can thus execute on multiple processors.
24239 The user can alternatively specify a processor on which the program should run
24240 to emulate a single-processor system. The multiprocessor / uniprocessor choice
24242 setting the environment variable @env{GNAT_PROCESSOR}
24243 @cindex @env{GNAT_PROCESSOR} environment variable (on Sparc Solaris)
24244 to one of the following:
24248 Use the default configuration (run the program on all
24249 available processors) - this is the same as having @code{GNAT_PROCESSOR}
24253 Let the run-time implementation choose one processor and run the program on
24256 @item 0 .. Last_Proc
24257 Run the program on the specified processor.
24258 @code{Last_Proc} is equal to @code{_SC_NPROCESSORS_CONF - 1}
24259 (where @code{_SC_NPROCESSORS_CONF} is a system variable).
24262 @node Linux-Specific Considerations
24263 @section Linux-Specific Considerations
24264 @cindex Linux threads libraries
24267 On GNU/Linux without NPTL support (usually system with GNU C Library
24268 older than 2.3), the signal model is not POSIX compliant, which means
24269 that to send a signal to the process, you need to send the signal to all
24270 threads, e.g.@: by using @code{killpg()}.
24272 @node AIX-Specific Considerations
24273 @section AIX-Specific Considerations
24274 @cindex AIX resolver library
24277 On AIX, the resolver library initializes some internal structure on
24278 the first call to @code{get*by*} functions, which are used to implement
24279 @code{GNAT.Sockets.Get_Host_By_Name} and
24280 @code{GNAT.Sockets.Get_Host_By_Address}.
24281 If such initialization occurs within an Ada task, and the stack size for
24282 the task is the default size, a stack overflow may occur.
24284 To avoid this overflow, the user should either ensure that the first call
24285 to @code{GNAT.Sockets.Get_Host_By_Name} or
24286 @code{GNAT.Sockets.Get_Host_By_Addrss}
24287 occurs in the environment task, or use @code{pragma Storage_Size} to
24288 specify a sufficiently large size for the stack of the task that contains
24291 @node RTX-Specific Considerations
24292 @section RTX-Specific Considerations
24293 @cindex RTX libraries
24296 The Real-time Extension (RTX) to Windows is based on the Windows Win32
24297 API. Applications can be built to work in two different modes:
24301 Windows executables that run in Ring 3 to utilize memory protection
24302 (@emph{rts-rtx-w32}).
24305 Real-time subsystem (RTSS) executables that run in Ring 0, where
24306 performance can be optimized with RTSS applications taking precedent
24307 over all Windows applications (@emph{rts-rtx-rtss}). This mode requires
24308 the Microsoft linker to handle RTSS libraries.
24312 @node HP-UX-Specific Considerations
24313 @section HP-UX-Specific Considerations
24314 @cindex HP-UX Scheduling
24317 On HP-UX, appropriate privileges are required to change the scheduling
24318 parameters of a task. The calling process must have appropriate
24319 privileges or be a member of a group having @code{PRIV_RTSCHED} access to
24320 successfully change the scheduling parameters.
24322 By default, GNAT uses the @code{SCHED_HPUX} policy. To have access to the
24323 priority range 0-31 either the @code{FIFO_Within_Priorities} or the
24324 @code{Round_Robin_Within_Priorities} scheduling policies need to be set.
24326 To specify the @code{FIFO_Within_Priorities} scheduling policy you can use
24327 one of the following:
24331 @code{pragma Time_Slice (0.0)}
24332 @cindex pragma Time_Slice
24334 the corresponding binder option @option{-T0}
24335 @cindex @option{-T0} option
24337 @code{pragma Task_Dispatching_Policy (FIFO_Within_Priorities)}
24338 @cindex pragma Task_Dispatching_Policy
24342 To specify the @code{Round_Robin_Within_Priorities}, scheduling policy
24343 you should use @code{pragma Time_Slice} with a
24344 value greater than @code{0.0}, or use the corresponding @option{-T}
24345 binder option, or set the @code{pragma Task_Dispatching_Policy
24346 (Round_Robin_Within_Priorities)}.
24348 @c *******************************
24349 @node Example of Binder Output File
24350 @appendix Example of Binder Output File
24353 This Appendix displays the source code for @command{gnatbind}'s output
24354 file generated for a simple ``Hello World'' program.
24355 Comments have been added for clarification purposes.
24357 @smallexample @c adanocomment
24361 -- The package is called Ada_Main unless this name is actually used
24362 -- as a unit name in the partition, in which case some other unique
24366 package ada_main is
24368 Elab_Final_Code : Integer;
24369 pragma Import (C, Elab_Final_Code, "__gnat_inside_elab_final_code");
24371 -- The main program saves the parameters (argument count,
24372 -- argument values, environment pointer) in global variables
24373 -- for later access by other units including
24374 -- Ada.Command_Line.
24376 gnat_argc : Integer;
24377 gnat_argv : System.Address;
24378 gnat_envp : System.Address;
24380 -- The actual variables are stored in a library routine. This
24381 -- is useful for some shared library situations, where there
24382 -- are problems if variables are not in the library.
24384 pragma Import (C, gnat_argc);
24385 pragma Import (C, gnat_argv);
24386 pragma Import (C, gnat_envp);
24388 -- The exit status is similarly an external location
24390 gnat_exit_status : Integer;
24391 pragma Import (C, gnat_exit_status);
24393 GNAT_Version : constant String :=
24394 "GNAT Version: 6.0.0w (20061115)";
24395 pragma Export (C, GNAT_Version, "__gnat_version");
24397 -- This is the generated adafinal routine that performs
24398 -- finalization at the end of execution. In the case where
24399 -- Ada is the main program, this main program makes a call
24400 -- to adafinal at program termination.
24402 procedure adafinal;
24403 pragma Export (C, adafinal, "adafinal");
24405 -- This is the generated adainit routine that performs
24406 -- initialization at the start of execution. In the case
24407 -- where Ada is the main program, this main program makes
24408 -- a call to adainit at program startup.
24411 pragma Export (C, adainit, "adainit");
24413 -- This routine is called at the start of execution. It is
24414 -- a dummy routine that is used by the debugger to breakpoint
24415 -- at the start of execution.
24417 procedure Break_Start;
24418 pragma Import (C, Break_Start, "__gnat_break_start");
24420 -- This is the actual generated main program (it would be
24421 -- suppressed if the no main program switch were used). As
24422 -- required by standard system conventions, this program has
24423 -- the external name main.
24427 argv : System.Address;
24428 envp : System.Address)
24430 pragma Export (C, main, "main");
24432 -- The following set of constants give the version
24433 -- identification values for every unit in the bound
24434 -- partition. This identification is computed from all
24435 -- dependent semantic units, and corresponds to the
24436 -- string that would be returned by use of the
24437 -- Body_Version or Version attributes.
24439 type Version_32 is mod 2 ** 32;
24440 u00001 : constant Version_32 := 16#7880BEB3#;
24441 u00002 : constant Version_32 := 16#0D24CBD0#;
24442 u00003 : constant Version_32 := 16#3283DBEB#;
24443 u00004 : constant Version_32 := 16#2359F9ED#;
24444 u00005 : constant Version_32 := 16#664FB847#;
24445 u00006 : constant Version_32 := 16#68E803DF#;
24446 u00007 : constant Version_32 := 16#5572E604#;
24447 u00008 : constant Version_32 := 16#46B173D8#;
24448 u00009 : constant Version_32 := 16#156A40CF#;
24449 u00010 : constant Version_32 := 16#033DABE0#;
24450 u00011 : constant Version_32 := 16#6AB38FEA#;
24451 u00012 : constant Version_32 := 16#22B6217D#;
24452 u00013 : constant Version_32 := 16#68A22947#;
24453 u00014 : constant Version_32 := 16#18CC4A56#;
24454 u00015 : constant Version_32 := 16#08258E1B#;
24455 u00016 : constant Version_32 := 16#367D5222#;
24456 u00017 : constant Version_32 := 16#20C9ECA4#;
24457 u00018 : constant Version_32 := 16#50D32CB6#;
24458 u00019 : constant Version_32 := 16#39A8BB77#;
24459 u00020 : constant Version_32 := 16#5CF8FA2B#;
24460 u00021 : constant Version_32 := 16#2F1EB794#;
24461 u00022 : constant Version_32 := 16#31AB6444#;
24462 u00023 : constant Version_32 := 16#1574B6E9#;
24463 u00024 : constant Version_32 := 16#5109C189#;
24464 u00025 : constant Version_32 := 16#56D770CD#;
24465 u00026 : constant Version_32 := 16#02F9DE3D#;
24466 u00027 : constant Version_32 := 16#08AB6B2C#;
24467 u00028 : constant Version_32 := 16#3FA37670#;
24468 u00029 : constant Version_32 := 16#476457A0#;
24469 u00030 : constant Version_32 := 16#731E1B6E#;
24470 u00031 : constant Version_32 := 16#23C2E789#;
24471 u00032 : constant Version_32 := 16#0F1BD6A1#;
24472 u00033 : constant Version_32 := 16#7C25DE96#;
24473 u00034 : constant Version_32 := 16#39ADFFA2#;
24474 u00035 : constant Version_32 := 16#571DE3E7#;
24475 u00036 : constant Version_32 := 16#5EB646AB#;
24476 u00037 : constant Version_32 := 16#4249379B#;
24477 u00038 : constant Version_32 := 16#0357E00A#;
24478 u00039 : constant Version_32 := 16#3784FB72#;
24479 u00040 : constant Version_32 := 16#2E723019#;
24480 u00041 : constant Version_32 := 16#623358EA#;
24481 u00042 : constant Version_32 := 16#107F9465#;
24482 u00043 : constant Version_32 := 16#6843F68A#;
24483 u00044 : constant Version_32 := 16#63305874#;
24484 u00045 : constant Version_32 := 16#31E56CE1#;
24485 u00046 : constant Version_32 := 16#02917970#;
24486 u00047 : constant Version_32 := 16#6CCBA70E#;
24487 u00048 : constant Version_32 := 16#41CD4204#;
24488 u00049 : constant Version_32 := 16#572E3F58#;
24489 u00050 : constant Version_32 := 16#20729FF5#;
24490 u00051 : constant Version_32 := 16#1D4F93E8#;
24491 u00052 : constant Version_32 := 16#30B2EC3D#;
24492 u00053 : constant Version_32 := 16#34054F96#;
24493 u00054 : constant Version_32 := 16#5A199860#;
24494 u00055 : constant Version_32 := 16#0E7F912B#;
24495 u00056 : constant Version_32 := 16#5760634A#;
24496 u00057 : constant Version_32 := 16#5D851835#;
24498 -- The following Export pragmas export the version numbers
24499 -- with symbolic names ending in B (for body) or S
24500 -- (for spec) so that they can be located in a link. The
24501 -- information provided here is sufficient to track down
24502 -- the exact versions of units used in a given build.
24504 pragma Export (C, u00001, "helloB");
24505 pragma Export (C, u00002, "system__standard_libraryB");
24506 pragma Export (C, u00003, "system__standard_libraryS");
24507 pragma Export (C, u00004, "adaS");
24508 pragma Export (C, u00005, "ada__text_ioB");
24509 pragma Export (C, u00006, "ada__text_ioS");
24510 pragma Export (C, u00007, "ada__exceptionsB");
24511 pragma Export (C, u00008, "ada__exceptionsS");
24512 pragma Export (C, u00009, "gnatS");
24513 pragma Export (C, u00010, "gnat__heap_sort_aB");
24514 pragma Export (C, u00011, "gnat__heap_sort_aS");
24515 pragma Export (C, u00012, "systemS");
24516 pragma Export (C, u00013, "system__exception_tableB");
24517 pragma Export (C, u00014, "system__exception_tableS");
24518 pragma Export (C, u00015, "gnat__htableB");
24519 pragma Export (C, u00016, "gnat__htableS");
24520 pragma Export (C, u00017, "system__exceptionsS");
24521 pragma Export (C, u00018, "system__machine_state_operationsB");
24522 pragma Export (C, u00019, "system__machine_state_operationsS");
24523 pragma Export (C, u00020, "system__machine_codeS");
24524 pragma Export (C, u00021, "system__storage_elementsB");
24525 pragma Export (C, u00022, "system__storage_elementsS");
24526 pragma Export (C, u00023, "system__secondary_stackB");
24527 pragma Export (C, u00024, "system__secondary_stackS");
24528 pragma Export (C, u00025, "system__parametersB");
24529 pragma Export (C, u00026, "system__parametersS");
24530 pragma Export (C, u00027, "system__soft_linksB");
24531 pragma Export (C, u00028, "system__soft_linksS");
24532 pragma Export (C, u00029, "system__stack_checkingB");
24533 pragma Export (C, u00030, "system__stack_checkingS");
24534 pragma Export (C, u00031, "system__tracebackB");
24535 pragma Export (C, u00032, "system__tracebackS");
24536 pragma Export (C, u00033, "ada__streamsS");
24537 pragma Export (C, u00034, "ada__tagsB");
24538 pragma Export (C, u00035, "ada__tagsS");
24539 pragma Export (C, u00036, "system__string_opsB");
24540 pragma Export (C, u00037, "system__string_opsS");
24541 pragma Export (C, u00038, "interfacesS");
24542 pragma Export (C, u00039, "interfaces__c_streamsB");
24543 pragma Export (C, u00040, "interfaces__c_streamsS");
24544 pragma Export (C, u00041, "system__file_ioB");
24545 pragma Export (C, u00042, "system__file_ioS");
24546 pragma Export (C, u00043, "ada__finalizationB");
24547 pragma Export (C, u00044, "ada__finalizationS");
24548 pragma Export (C, u00045, "system__finalization_rootB");
24549 pragma Export (C, u00046, "system__finalization_rootS");
24550 pragma Export (C, u00047, "system__finalization_implementationB");
24551 pragma Export (C, u00048, "system__finalization_implementationS");
24552 pragma Export (C, u00049, "system__string_ops_concat_3B");
24553 pragma Export (C, u00050, "system__string_ops_concat_3S");
24554 pragma Export (C, u00051, "system__stream_attributesB");
24555 pragma Export (C, u00052, "system__stream_attributesS");
24556 pragma Export (C, u00053, "ada__io_exceptionsS");
24557 pragma Export (C, u00054, "system__unsigned_typesS");
24558 pragma Export (C, u00055, "system__file_control_blockS");
24559 pragma Export (C, u00056, "ada__finalization__list_controllerB");
24560 pragma Export (C, u00057, "ada__finalization__list_controllerS");
24562 -- BEGIN ELABORATION ORDER
24565 -- gnat.heap_sort_a (spec)
24566 -- gnat.heap_sort_a (body)
24567 -- gnat.htable (spec)
24568 -- gnat.htable (body)
24569 -- interfaces (spec)
24571 -- system.machine_code (spec)
24572 -- system.parameters (spec)
24573 -- system.parameters (body)
24574 -- interfaces.c_streams (spec)
24575 -- interfaces.c_streams (body)
24576 -- system.standard_library (spec)
24577 -- ada.exceptions (spec)
24578 -- system.exception_table (spec)
24579 -- system.exception_table (body)
24580 -- ada.io_exceptions (spec)
24581 -- system.exceptions (spec)
24582 -- system.storage_elements (spec)
24583 -- system.storage_elements (body)
24584 -- system.machine_state_operations (spec)
24585 -- system.machine_state_operations (body)
24586 -- system.secondary_stack (spec)
24587 -- system.stack_checking (spec)
24588 -- system.soft_links (spec)
24589 -- system.soft_links (body)
24590 -- system.stack_checking (body)
24591 -- system.secondary_stack (body)
24592 -- system.standard_library (body)
24593 -- system.string_ops (spec)
24594 -- system.string_ops (body)
24597 -- ada.streams (spec)
24598 -- system.finalization_root (spec)
24599 -- system.finalization_root (body)
24600 -- system.string_ops_concat_3 (spec)
24601 -- system.string_ops_concat_3 (body)
24602 -- system.traceback (spec)
24603 -- system.traceback (body)
24604 -- ada.exceptions (body)
24605 -- system.unsigned_types (spec)
24606 -- system.stream_attributes (spec)
24607 -- system.stream_attributes (body)
24608 -- system.finalization_implementation (spec)
24609 -- system.finalization_implementation (body)
24610 -- ada.finalization (spec)
24611 -- ada.finalization (body)
24612 -- ada.finalization.list_controller (spec)
24613 -- ada.finalization.list_controller (body)
24614 -- system.file_control_block (spec)
24615 -- system.file_io (spec)
24616 -- system.file_io (body)
24617 -- ada.text_io (spec)
24618 -- ada.text_io (body)
24620 -- END ELABORATION ORDER
24624 -- The following source file name pragmas allow the generated file
24625 -- names to be unique for different main programs. They are needed
24626 -- since the package name will always be Ada_Main.
24628 pragma Source_File_Name (ada_main, Spec_File_Name => "b~hello.ads");
24629 pragma Source_File_Name (ada_main, Body_File_Name => "b~hello.adb");
24631 -- Generated package body for Ada_Main starts here
24633 package body ada_main is
24635 -- The actual finalization is performed by calling the
24636 -- library routine in System.Standard_Library.Adafinal
24638 procedure Do_Finalize;
24639 pragma Import (C, Do_Finalize, "system__standard_library__adafinal");
24646 procedure adainit is
24648 -- These booleans are set to True once the associated unit has
24649 -- been elaborated. It is also used to avoid elaborating the
24650 -- same unit twice.
24653 pragma Import (Ada, E040, "interfaces__c_streams_E");
24656 pragma Import (Ada, E008, "ada__exceptions_E");
24659 pragma Import (Ada, E014, "system__exception_table_E");
24662 pragma Import (Ada, E053, "ada__io_exceptions_E");
24665 pragma Import (Ada, E017, "system__exceptions_E");
24668 pragma Import (Ada, E024, "system__secondary_stack_E");
24671 pragma Import (Ada, E030, "system__stack_checking_E");
24674 pragma Import (Ada, E028, "system__soft_links_E");
24677 pragma Import (Ada, E035, "ada__tags_E");
24680 pragma Import (Ada, E033, "ada__streams_E");
24683 pragma Import (Ada, E046, "system__finalization_root_E");
24686 pragma Import (Ada, E048, "system__finalization_implementation_E");
24689 pragma Import (Ada, E044, "ada__finalization_E");
24692 pragma Import (Ada, E057, "ada__finalization__list_controller_E");
24695 pragma Import (Ada, E055, "system__file_control_block_E");
24698 pragma Import (Ada, E042, "system__file_io_E");
24701 pragma Import (Ada, E006, "ada__text_io_E");
24703 -- Set_Globals is a library routine that stores away the
24704 -- value of the indicated set of global values in global
24705 -- variables within the library.
24707 procedure Set_Globals
24708 (Main_Priority : Integer;
24709 Time_Slice_Value : Integer;
24710 WC_Encoding : Character;
24711 Locking_Policy : Character;
24712 Queuing_Policy : Character;
24713 Task_Dispatching_Policy : Character;
24714 Adafinal : System.Address;
24715 Unreserve_All_Interrupts : Integer;
24716 Exception_Tracebacks : Integer);
24717 @findex __gnat_set_globals
24718 pragma Import (C, Set_Globals, "__gnat_set_globals");
24720 -- SDP_Table_Build is a library routine used to build the
24721 -- exception tables. See unit Ada.Exceptions in files
24722 -- a-except.ads/adb for full details of how zero cost
24723 -- exception handling works. This procedure, the call to
24724 -- it, and the two following tables are all omitted if the
24725 -- build is in longjmp/setjmp exception mode.
24727 @findex SDP_Table_Build
24728 @findex Zero Cost Exceptions
24729 procedure SDP_Table_Build
24730 (SDP_Addresses : System.Address;
24731 SDP_Count : Natural;
24732 Elab_Addresses : System.Address;
24733 Elab_Addr_Count : Natural);
24734 pragma Import (C, SDP_Table_Build, "__gnat_SDP_Table_Build");
24736 -- Table of Unit_Exception_Table addresses. Used for zero
24737 -- cost exception handling to build the top level table.
24739 ST : aliased constant array (1 .. 23) of System.Address := (
24741 Ada.Text_Io'UET_Address,
24742 Ada.Exceptions'UET_Address,
24743 Gnat.Heap_Sort_A'UET_Address,
24744 System.Exception_Table'UET_Address,
24745 System.Machine_State_Operations'UET_Address,
24746 System.Secondary_Stack'UET_Address,
24747 System.Parameters'UET_Address,
24748 System.Soft_Links'UET_Address,
24749 System.Stack_Checking'UET_Address,
24750 System.Traceback'UET_Address,
24751 Ada.Streams'UET_Address,
24752 Ada.Tags'UET_Address,
24753 System.String_Ops'UET_Address,
24754 Interfaces.C_Streams'UET_Address,
24755 System.File_Io'UET_Address,
24756 Ada.Finalization'UET_Address,
24757 System.Finalization_Root'UET_Address,
24758 System.Finalization_Implementation'UET_Address,
24759 System.String_Ops_Concat_3'UET_Address,
24760 System.Stream_Attributes'UET_Address,
24761 System.File_Control_Block'UET_Address,
24762 Ada.Finalization.List_Controller'UET_Address);
24764 -- Table of addresses of elaboration routines. Used for
24765 -- zero cost exception handling to make sure these
24766 -- addresses are included in the top level procedure
24769 EA : aliased constant array (1 .. 23) of System.Address := (
24770 adainit'Code_Address,
24771 Do_Finalize'Code_Address,
24772 Ada.Exceptions'Elab_Spec'Address,
24773 System.Exceptions'Elab_Spec'Address,
24774 Interfaces.C_Streams'Elab_Spec'Address,
24775 System.Exception_Table'Elab_Body'Address,
24776 Ada.Io_Exceptions'Elab_Spec'Address,
24777 System.Stack_Checking'Elab_Spec'Address,
24778 System.Soft_Links'Elab_Body'Address,
24779 System.Secondary_Stack'Elab_Body'Address,
24780 Ada.Tags'Elab_Spec'Address,
24781 Ada.Tags'Elab_Body'Address,
24782 Ada.Streams'Elab_Spec'Address,
24783 System.Finalization_Root'Elab_Spec'Address,
24784 Ada.Exceptions'Elab_Body'Address,
24785 System.Finalization_Implementation'Elab_Spec'Address,
24786 System.Finalization_Implementation'Elab_Body'Address,
24787 Ada.Finalization'Elab_Spec'Address,
24788 Ada.Finalization.List_Controller'Elab_Spec'Address,
24789 System.File_Control_Block'Elab_Spec'Address,
24790 System.File_Io'Elab_Body'Address,
24791 Ada.Text_Io'Elab_Spec'Address,
24792 Ada.Text_Io'Elab_Body'Address);
24794 -- Start of processing for adainit
24798 -- Call SDP_Table_Build to build the top level procedure
24799 -- table for zero cost exception handling (omitted in
24800 -- longjmp/setjmp mode).
24802 SDP_Table_Build (ST'Address, 23, EA'Address, 23);
24804 -- Call Set_Globals to record various information for
24805 -- this partition. The values are derived by the binder
24806 -- from information stored in the ali files by the compiler.
24808 @findex __gnat_set_globals
24810 (Main_Priority => -1,
24811 -- Priority of main program, -1 if no pragma Priority used
24813 Time_Slice_Value => -1,
24814 -- Time slice from Time_Slice pragma, -1 if none used
24816 WC_Encoding => 'b',
24817 -- Wide_Character encoding used, default is brackets
24819 Locking_Policy => ' ',
24820 -- Locking_Policy used, default of space means not
24821 -- specified, otherwise it is the first character of
24822 -- the policy name.
24824 Queuing_Policy => ' ',
24825 -- Queuing_Policy used, default of space means not
24826 -- specified, otherwise it is the first character of
24827 -- the policy name.
24829 Task_Dispatching_Policy => ' ',
24830 -- Task_Dispatching_Policy used, default of space means
24831 -- not specified, otherwise first character of the
24834 Adafinal => System.Null_Address,
24835 -- Address of Adafinal routine, not used anymore
24837 Unreserve_All_Interrupts => 0,
24838 -- Set true if pragma Unreserve_All_Interrupts was used
24840 Exception_Tracebacks => 0);
24841 -- Indicates if exception tracebacks are enabled
24843 Elab_Final_Code := 1;
24845 -- Now we have the elaboration calls for all units in the partition.
24846 -- The Elab_Spec and Elab_Body attributes generate references to the
24847 -- implicit elaboration procedures generated by the compiler for
24848 -- each unit that requires elaboration.
24851 Interfaces.C_Streams'Elab_Spec;
24855 Ada.Exceptions'Elab_Spec;
24858 System.Exception_Table'Elab_Body;
24862 Ada.Io_Exceptions'Elab_Spec;
24866 System.Exceptions'Elab_Spec;
24870 System.Stack_Checking'Elab_Spec;
24873 System.Soft_Links'Elab_Body;
24878 System.Secondary_Stack'Elab_Body;
24882 Ada.Tags'Elab_Spec;
24885 Ada.Tags'Elab_Body;
24889 Ada.Streams'Elab_Spec;
24893 System.Finalization_Root'Elab_Spec;
24897 Ada.Exceptions'Elab_Body;
24901 System.Finalization_Implementation'Elab_Spec;
24904 System.Finalization_Implementation'Elab_Body;
24908 Ada.Finalization'Elab_Spec;
24912 Ada.Finalization.List_Controller'Elab_Spec;
24916 System.File_Control_Block'Elab_Spec;
24920 System.File_Io'Elab_Body;
24924 Ada.Text_Io'Elab_Spec;
24927 Ada.Text_Io'Elab_Body;
24931 Elab_Final_Code := 0;
24939 procedure adafinal is
24948 -- main is actually a function, as in the ANSI C standard,
24949 -- defined to return the exit status. The three parameters
24950 -- are the argument count, argument values and environment
24953 @findex Main Program
24956 argv : System.Address;
24957 envp : System.Address)
24960 -- The initialize routine performs low level system
24961 -- initialization using a standard library routine which
24962 -- sets up signal handling and performs any other
24963 -- required setup. The routine can be found in file
24966 @findex __gnat_initialize
24967 procedure initialize;
24968 pragma Import (C, initialize, "__gnat_initialize");
24970 -- The finalize routine performs low level system
24971 -- finalization using a standard library routine. The
24972 -- routine is found in file a-final.c and in the standard
24973 -- distribution is a dummy routine that does nothing, so
24974 -- really this is a hook for special user finalization.
24976 @findex __gnat_finalize
24977 procedure finalize;
24978 pragma Import (C, finalize, "__gnat_finalize");
24980 -- We get to the main program of the partition by using
24981 -- pragma Import because if we try to with the unit and
24982 -- call it Ada style, then not only do we waste time
24983 -- recompiling it, but also, we don't really know the right
24984 -- switches (e.g.@: identifier character set) to be used
24987 procedure Ada_Main_Program;
24988 pragma Import (Ada, Ada_Main_Program, "_ada_hello");
24990 -- Start of processing for main
24993 -- Save global variables
24999 -- Call low level system initialization
25003 -- Call our generated Ada initialization routine
25007 -- This is the point at which we want the debugger to get
25012 -- Now we call the main program of the partition
25016 -- Perform Ada finalization
25020 -- Perform low level system finalization
25024 -- Return the proper exit status
25025 return (gnat_exit_status);
25028 -- This section is entirely comments, so it has no effect on the
25029 -- compilation of the Ada_Main package. It provides the list of
25030 -- object files and linker options, as well as some standard
25031 -- libraries needed for the link. The gnatlink utility parses
25032 -- this b~hello.adb file to read these comment lines to generate
25033 -- the appropriate command line arguments for the call to the
25034 -- system linker. The BEGIN/END lines are used for sentinels for
25035 -- this parsing operation.
25037 -- The exact file names will of course depend on the environment,
25038 -- host/target and location of files on the host system.
25040 @findex Object file list
25041 -- BEGIN Object file/option list
25044 -- -L/usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/
25045 -- /usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/libgnat.a
25046 -- END Object file/option list
25052 The Ada code in the above example is exactly what is generated by the
25053 binder. We have added comments to more clearly indicate the function
25054 of each part of the generated @code{Ada_Main} package.
25056 The code is standard Ada in all respects, and can be processed by any
25057 tools that handle Ada. In particular, it is possible to use the debugger
25058 in Ada mode to debug the generated @code{Ada_Main} package. For example,
25059 suppose that for reasons that you do not understand, your program is crashing
25060 during elaboration of the body of @code{Ada.Text_IO}. To locate this bug,
25061 you can place a breakpoint on the call:
25063 @smallexample @c ada
25064 Ada.Text_Io'Elab_Body;
25068 and trace the elaboration routine for this package to find out where
25069 the problem might be (more usually of course you would be debugging
25070 elaboration code in your own application).
25072 @node Elaboration Order Handling in GNAT
25073 @appendix Elaboration Order Handling in GNAT
25074 @cindex Order of elaboration
25075 @cindex Elaboration control
25078 * Elaboration Code::
25079 * Checking the Elaboration Order::
25080 * Controlling the Elaboration Order::
25081 * Controlling Elaboration in GNAT - Internal Calls::
25082 * Controlling Elaboration in GNAT - External Calls::
25083 * Default Behavior in GNAT - Ensuring Safety::
25084 * Treatment of Pragma Elaborate::
25085 * Elaboration Issues for Library Tasks::
25086 * Mixing Elaboration Models::
25087 * What to Do If the Default Elaboration Behavior Fails::
25088 * Elaboration for Indirect Calls::
25089 * Summary of Procedures for Elaboration Control::
25090 * Other Elaboration Order Considerations::
25091 * Determining the Chosen Elaboration Order::
25095 This chapter describes the handling of elaboration code in Ada and
25096 in GNAT, and discusses how the order of elaboration of program units can
25097 be controlled in GNAT, either automatically or with explicit programming
25100 @node Elaboration Code
25101 @section Elaboration Code
25104 Ada provides rather general mechanisms for executing code at elaboration
25105 time, that is to say before the main program starts executing. Such code arises
25109 @item Initializers for variables.
25110 Variables declared at the library level, in package specs or bodies, can
25111 require initialization that is performed at elaboration time, as in:
25112 @smallexample @c ada
25114 Sqrt_Half : Float := Sqrt (0.5);
25118 @item Package initialization code
25119 Code in a @code{BEGIN-END} section at the outer level of a package body is
25120 executed as part of the package body elaboration code.
25122 @item Library level task allocators
25123 Tasks that are declared using task allocators at the library level
25124 start executing immediately and hence can execute at elaboration time.
25128 Subprogram calls are possible in any of these contexts, which means that
25129 any arbitrary part of the program may be executed as part of the elaboration
25130 code. It is even possible to write a program which does all its work at
25131 elaboration time, with a null main program, although stylistically this
25132 would usually be considered an inappropriate way to structure
25135 An important concern arises in the context of elaboration code:
25136 we have to be sure that it is executed in an appropriate order. What we
25137 have is a series of elaboration code sections, potentially one section
25138 for each unit in the program. It is important that these execute
25139 in the correct order. Correctness here means that, taking the above
25140 example of the declaration of @code{Sqrt_Half},
25141 if some other piece of
25142 elaboration code references @code{Sqrt_Half},
25143 then it must run after the
25144 section of elaboration code that contains the declaration of
25147 There would never be any order of elaboration problem if we made a rule
25148 that whenever you @code{with} a unit, you must elaborate both the spec and body
25149 of that unit before elaborating the unit doing the @code{with}'ing:
25151 @smallexample @c ada
25155 package Unit_2 is @dots{}
25161 would require that both the body and spec of @code{Unit_1} be elaborated
25162 before the spec of @code{Unit_2}. However, a rule like that would be far too
25163 restrictive. In particular, it would make it impossible to have routines
25164 in separate packages that were mutually recursive.
25166 You might think that a clever enough compiler could look at the actual
25167 elaboration code and determine an appropriate correct order of elaboration,
25168 but in the general case, this is not possible. Consider the following
25171 In the body of @code{Unit_1}, we have a procedure @code{Func_1}
25173 the variable @code{Sqrt_1}, which is declared in the elaboration code
25174 of the body of @code{Unit_1}:
25176 @smallexample @c ada
25178 Sqrt_1 : Float := Sqrt (0.1);
25183 The elaboration code of the body of @code{Unit_1} also contains:
25185 @smallexample @c ada
25188 if expression_1 = 1 then
25189 Q := Unit_2.Func_2;
25196 @code{Unit_2} is exactly parallel,
25197 it has a procedure @code{Func_2} that references
25198 the variable @code{Sqrt_2}, which is declared in the elaboration code of
25199 the body @code{Unit_2}:
25201 @smallexample @c ada
25203 Sqrt_2 : Float := Sqrt (0.1);
25208 The elaboration code of the body of @code{Unit_2} also contains:
25210 @smallexample @c ada
25213 if expression_2 = 2 then
25214 Q := Unit_1.Func_1;
25221 Now the question is, which of the following orders of elaboration is
25246 If you carefully analyze the flow here, you will see that you cannot tell
25247 at compile time the answer to this question.
25248 If @code{expression_1} is not equal to 1,
25249 and @code{expression_2} is not equal to 2,
25250 then either order is acceptable, because neither of the function calls is
25251 executed. If both tests evaluate to true, then neither order is acceptable
25252 and in fact there is no correct order.
25254 If one of the two expressions is true, and the other is false, then one
25255 of the above orders is correct, and the other is incorrect. For example,
25256 if @code{expression_1} /= 1 and @code{expression_2} = 2,
25257 then the call to @code{Func_1}
25258 will occur, but not the call to @code{Func_2.}
25259 This means that it is essential
25260 to elaborate the body of @code{Unit_1} before
25261 the body of @code{Unit_2}, so the first
25262 order of elaboration is correct and the second is wrong.
25264 By making @code{expression_1} and @code{expression_2}
25265 depend on input data, or perhaps
25266 the time of day, we can make it impossible for the compiler or binder
25267 to figure out which of these expressions will be true, and hence it
25268 is impossible to guarantee a safe order of elaboration at run time.
25270 @node Checking the Elaboration Order
25271 @section Checking the Elaboration Order
25274 In some languages that involve the same kind of elaboration problems,
25275 e.g.@: Java and C++, the programmer is expected to worry about these
25276 ordering problems himself, and it is common to
25277 write a program in which an incorrect elaboration order gives
25278 surprising results, because it references variables before they
25280 Ada is designed to be a safe language, and a programmer-beware approach is
25281 clearly not sufficient. Consequently, the language provides three lines
25285 @item Standard rules
25286 Some standard rules restrict the possible choice of elaboration
25287 order. In particular, if you @code{with} a unit, then its spec is always
25288 elaborated before the unit doing the @code{with}. Similarly, a parent
25289 spec is always elaborated before the child spec, and finally
25290 a spec is always elaborated before its corresponding body.
25292 @item Dynamic elaboration checks
25293 @cindex Elaboration checks
25294 @cindex Checks, elaboration
25295 Dynamic checks are made at run time, so that if some entity is accessed
25296 before it is elaborated (typically by means of a subprogram call)
25297 then the exception (@code{Program_Error}) is raised.
25299 @item Elaboration control
25300 Facilities are provided for the programmer to specify the desired order
25304 Let's look at these facilities in more detail. First, the rules for
25305 dynamic checking. One possible rule would be simply to say that the
25306 exception is raised if you access a variable which has not yet been
25307 elaborated. The trouble with this approach is that it could require
25308 expensive checks on every variable reference. Instead Ada has two
25309 rules which are a little more restrictive, but easier to check, and
25313 @item Restrictions on calls
25314 A subprogram can only be called at elaboration time if its body
25315 has been elaborated. The rules for elaboration given above guarantee
25316 that the spec of the subprogram has been elaborated before the
25317 call, but not the body. If this rule is violated, then the
25318 exception @code{Program_Error} is raised.
25320 @item Restrictions on instantiations
25321 A generic unit can only be instantiated if the body of the generic
25322 unit has been elaborated. Again, the rules for elaboration given above
25323 guarantee that the spec of the generic unit has been elaborated
25324 before the instantiation, but not the body. If this rule is
25325 violated, then the exception @code{Program_Error} is raised.
25329 The idea is that if the body has been elaborated, then any variables
25330 it references must have been elaborated; by checking for the body being
25331 elaborated we guarantee that none of its references causes any
25332 trouble. As we noted above, this is a little too restrictive, because a
25333 subprogram that has no non-local references in its body may in fact be safe
25334 to call. However, it really would be unsafe to rely on this, because
25335 it would mean that the caller was aware of details of the implementation
25336 in the body. This goes against the basic tenets of Ada.
25338 A plausible implementation can be described as follows.
25339 A Boolean variable is associated with each subprogram
25340 and each generic unit. This variable is initialized to False, and is set to
25341 True at the point body is elaborated. Every call or instantiation checks the
25342 variable, and raises @code{Program_Error} if the variable is False.
25344 Note that one might think that it would be good enough to have one Boolean
25345 variable for each package, but that would not deal with cases of trying
25346 to call a body in the same package as the call
25347 that has not been elaborated yet.
25348 Of course a compiler may be able to do enough analysis to optimize away
25349 some of the Boolean variables as unnecessary, and @code{GNAT} indeed
25350 does such optimizations, but still the easiest conceptual model is to
25351 think of there being one variable per subprogram.
25353 @node Controlling the Elaboration Order
25354 @section Controlling the Elaboration Order
25357 In the previous section we discussed the rules in Ada which ensure
25358 that @code{Program_Error} is raised if an incorrect elaboration order is
25359 chosen. This prevents erroneous executions, but we need mechanisms to
25360 specify a correct execution and avoid the exception altogether.
25361 To achieve this, Ada provides a number of features for controlling
25362 the order of elaboration. We discuss these features in this section.
25364 First, there are several ways of indicating to the compiler that a given
25365 unit has no elaboration problems:
25368 @item packages that do not require a body
25369 A library package that does not require a body does not permit
25370 a body (this rule was introduced in Ada 95).
25371 Thus if we have a such a package, as in:
25373 @smallexample @c ada
25376 package Definitions is
25378 type m is new integer;
25380 type a is array (1 .. 10) of m;
25381 type b is array (1 .. 20) of m;
25389 A package that @code{with}'s @code{Definitions} may safely instantiate
25390 @code{Definitions.Subp} because the compiler can determine that there
25391 definitely is no package body to worry about in this case
25394 @cindex pragma Pure
25396 Places sufficient restrictions on a unit to guarantee that
25397 no call to any subprogram in the unit can result in an
25398 elaboration problem. This means that the compiler does not need
25399 to worry about the point of elaboration of such units, and in
25400 particular, does not need to check any calls to any subprograms
25403 @item pragma Preelaborate
25404 @findex Preelaborate
25405 @cindex pragma Preelaborate
25406 This pragma places slightly less stringent restrictions on a unit than
25408 but these restrictions are still sufficient to ensure that there
25409 are no elaboration problems with any calls to the unit.
25411 @item pragma Elaborate_Body
25412 @findex Elaborate_Body
25413 @cindex pragma Elaborate_Body
25414 This pragma requires that the body of a unit be elaborated immediately
25415 after its spec. Suppose a unit @code{A} has such a pragma,
25416 and unit @code{B} does
25417 a @code{with} of unit @code{A}. Recall that the standard rules require
25418 the spec of unit @code{A}
25419 to be elaborated before the @code{with}'ing unit; given the pragma in
25420 @code{A}, we also know that the body of @code{A}
25421 will be elaborated before @code{B}, so
25422 that calls to @code{A} are safe and do not need a check.
25427 unlike pragma @code{Pure} and pragma @code{Preelaborate},
25429 @code{Elaborate_Body} does not guarantee that the program is
25430 free of elaboration problems, because it may not be possible
25431 to satisfy the requested elaboration order.
25432 Let's go back to the example with @code{Unit_1} and @code{Unit_2}.
25434 marks @code{Unit_1} as @code{Elaborate_Body},
25435 and not @code{Unit_2,} then the order of
25436 elaboration will be:
25448 Now that means that the call to @code{Func_1} in @code{Unit_2}
25449 need not be checked,
25450 it must be safe. But the call to @code{Func_2} in
25451 @code{Unit_1} may still fail if
25452 @code{Expression_1} is equal to 1,
25453 and the programmer must still take
25454 responsibility for this not being the case.
25456 If all units carry a pragma @code{Elaborate_Body}, then all problems are
25457 eliminated, except for calls entirely within a body, which are
25458 in any case fully under programmer control. However, using the pragma
25459 everywhere is not always possible.
25460 In particular, for our @code{Unit_1}/@code{Unit_2} example, if
25461 we marked both of them as having pragma @code{Elaborate_Body}, then
25462 clearly there would be no possible elaboration order.
25464 The above pragmas allow a server to guarantee safe use by clients, and
25465 clearly this is the preferable approach. Consequently a good rule
25466 is to mark units as @code{Pure} or @code{Preelaborate} if possible,
25467 and if this is not possible,
25468 mark them as @code{Elaborate_Body} if possible.
25469 As we have seen, there are situations where neither of these
25470 three pragmas can be used.
25471 So we also provide methods for clients to control the
25472 order of elaboration of the servers on which they depend:
25475 @item pragma Elaborate (unit)
25477 @cindex pragma Elaborate
25478 This pragma is placed in the context clause, after a @code{with} clause,
25479 and it requires that the body of the named unit be elaborated before
25480 the unit in which the pragma occurs. The idea is to use this pragma
25481 if the current unit calls at elaboration time, directly or indirectly,
25482 some subprogram in the named unit.
25484 @item pragma Elaborate_All (unit)
25485 @findex Elaborate_All
25486 @cindex pragma Elaborate_All
25487 This is a stronger version of the Elaborate pragma. Consider the
25491 Unit A @code{with}'s unit B and calls B.Func in elab code
25492 Unit B @code{with}'s unit C, and B.Func calls C.Func
25496 Now if we put a pragma @code{Elaborate (B)}
25497 in unit @code{A}, this ensures that the
25498 body of @code{B} is elaborated before the call, but not the
25499 body of @code{C}, so
25500 the call to @code{C.Func} could still cause @code{Program_Error} to
25503 The effect of a pragma @code{Elaborate_All} is stronger, it requires
25504 not only that the body of the named unit be elaborated before the
25505 unit doing the @code{with}, but also the bodies of all units that the
25506 named unit uses, following @code{with} links transitively. For example,
25507 if we put a pragma @code{Elaborate_All (B)} in unit @code{A},
25509 not only that the body of @code{B} be elaborated before @code{A},
25511 body of @code{C}, because @code{B} @code{with}'s @code{C}.
25515 We are now in a position to give a usage rule in Ada for avoiding
25516 elaboration problems, at least if dynamic dispatching and access to
25517 subprogram values are not used. We will handle these cases separately
25520 The rule is simple. If a unit has elaboration code that can directly or
25521 indirectly make a call to a subprogram in a @code{with}'ed unit, or instantiate
25522 a generic package in a @code{with}'ed unit,
25523 then if the @code{with}'ed unit does not have
25524 pragma @code{Pure} or @code{Preelaborate}, then the client should have
25525 a pragma @code{Elaborate_All}
25526 for the @code{with}'ed unit. By following this rule a client is
25527 assured that calls can be made without risk of an exception.
25529 For generic subprogram instantiations, the rule can be relaxed to
25530 require only a pragma @code{Elaborate} since elaborating the body
25531 of a subprogram cannot cause any transitive elaboration (we are
25532 not calling the subprogram in this case, just elaborating its
25535 If this rule is not followed, then a program may be in one of four
25539 @item No order exists
25540 No order of elaboration exists which follows the rules, taking into
25541 account any @code{Elaborate}, @code{Elaborate_All},
25542 or @code{Elaborate_Body} pragmas. In
25543 this case, an Ada compiler must diagnose the situation at bind
25544 time, and refuse to build an executable program.
25546 @item One or more orders exist, all incorrect
25547 One or more acceptable elaboration orders exist, and all of them
25548 generate an elaboration order problem. In this case, the binder
25549 can build an executable program, but @code{Program_Error} will be raised
25550 when the program is run.
25552 @item Several orders exist, some right, some incorrect
25553 One or more acceptable elaboration orders exists, and some of them
25554 work, and some do not. The programmer has not controlled
25555 the order of elaboration, so the binder may or may not pick one of
25556 the correct orders, and the program may or may not raise an
25557 exception when it is run. This is the worst case, because it means
25558 that the program may fail when moved to another compiler, or even
25559 another version of the same compiler.
25561 @item One or more orders exists, all correct
25562 One ore more acceptable elaboration orders exist, and all of them
25563 work. In this case the program runs successfully. This state of
25564 affairs can be guaranteed by following the rule we gave above, but
25565 may be true even if the rule is not followed.
25569 Note that one additional advantage of following our rules on the use
25570 of @code{Elaborate} and @code{Elaborate_All}
25571 is that the program continues to stay in the ideal (all orders OK) state
25572 even if maintenance
25573 changes some bodies of some units. Conversely, if a program that does
25574 not follow this rule happens to be safe at some point, this state of affairs
25575 may deteriorate silently as a result of maintenance changes.
25577 You may have noticed that the above discussion did not mention
25578 the use of @code{Elaborate_Body}. This was a deliberate omission. If you
25579 @code{with} an @code{Elaborate_Body} unit, it still may be the case that
25580 code in the body makes calls to some other unit, so it is still necessary
25581 to use @code{Elaborate_All} on such units.
25583 @node Controlling Elaboration in GNAT - Internal Calls
25584 @section Controlling Elaboration in GNAT - Internal Calls
25587 In the case of internal calls, i.e., calls within a single package, the
25588 programmer has full control over the order of elaboration, and it is up
25589 to the programmer to elaborate declarations in an appropriate order. For
25592 @smallexample @c ada
25595 function One return Float;
25599 function One return Float is
25608 will obviously raise @code{Program_Error} at run time, because function
25609 One will be called before its body is elaborated. In this case GNAT will
25610 generate a warning that the call will raise @code{Program_Error}:
25616 2. function One return Float;
25618 4. Q : Float := One;
25620 >>> warning: cannot call "One" before body is elaborated
25621 >>> warning: Program_Error will be raised at run time
25624 6. function One return Float is
25637 Note that in this particular case, it is likely that the call is safe, because
25638 the function @code{One} does not access any global variables.
25639 Nevertheless in Ada, we do not want the validity of the check to depend on
25640 the contents of the body (think about the separate compilation case), so this
25641 is still wrong, as we discussed in the previous sections.
25643 The error is easily corrected by rearranging the declarations so that the
25644 body of @code{One} appears before the declaration containing the call
25645 (note that in Ada 95 and Ada 2005,
25646 declarations can appear in any order, so there is no restriction that
25647 would prevent this reordering, and if we write:
25649 @smallexample @c ada
25652 function One return Float;
25654 function One return Float is
25665 then all is well, no warning is generated, and no
25666 @code{Program_Error} exception
25668 Things are more complicated when a chain of subprograms is executed:
25670 @smallexample @c ada
25673 function A return Integer;
25674 function B return Integer;
25675 function C return Integer;
25677 function B return Integer is begin return A; end;
25678 function C return Integer is begin return B; end;
25682 function A return Integer is begin return 1; end;
25688 Now the call to @code{C}
25689 at elaboration time in the declaration of @code{X} is correct, because
25690 the body of @code{C} is already elaborated,
25691 and the call to @code{B} within the body of
25692 @code{C} is correct, but the call
25693 to @code{A} within the body of @code{B} is incorrect, because the body
25694 of @code{A} has not been elaborated, so @code{Program_Error}
25695 will be raised on the call to @code{A}.
25696 In this case GNAT will generate a
25697 warning that @code{Program_Error} may be
25698 raised at the point of the call. Let's look at the warning:
25704 2. function A return Integer;
25705 3. function B return Integer;
25706 4. function C return Integer;
25708 6. function B return Integer is begin return A; end;
25710 >>> warning: call to "A" before body is elaborated may
25711 raise Program_Error
25712 >>> warning: "B" called at line 7
25713 >>> warning: "C" called at line 9
25715 7. function C return Integer is begin return B; end;
25717 9. X : Integer := C;
25719 11. function A return Integer is begin return 1; end;
25729 Note that the message here says ``may raise'', instead of the direct case,
25730 where the message says ``will be raised''. That's because whether
25732 actually called depends in general on run-time flow of control.
25733 For example, if the body of @code{B} said
25735 @smallexample @c ada
25738 function B return Integer is
25740 if some-condition-depending-on-input-data then
25751 then we could not know until run time whether the incorrect call to A would
25752 actually occur, so @code{Program_Error} might
25753 or might not be raised. It is possible for a compiler to
25754 do a better job of analyzing bodies, to
25755 determine whether or not @code{Program_Error}
25756 might be raised, but it certainly
25757 couldn't do a perfect job (that would require solving the halting problem
25758 and is provably impossible), and because this is a warning anyway, it does
25759 not seem worth the effort to do the analysis. Cases in which it
25760 would be relevant are rare.
25762 In practice, warnings of either of the forms given
25763 above will usually correspond to
25764 real errors, and should be examined carefully and eliminated.
25765 In the rare case where a warning is bogus, it can be suppressed by any of
25766 the following methods:
25770 Compile with the @option{-gnatws} switch set
25773 Suppress @code{Elaboration_Check} for the called subprogram
25776 Use pragma @code{Warnings_Off} to turn warnings off for the call
25780 For the internal elaboration check case,
25781 GNAT by default generates the
25782 necessary run-time checks to ensure
25783 that @code{Program_Error} is raised if any
25784 call fails an elaboration check. Of course this can only happen if a
25785 warning has been issued as described above. The use of pragma
25786 @code{Suppress (Elaboration_Check)} may (but is not guaranteed to) suppress
25787 some of these checks, meaning that it may be possible (but is not
25788 guaranteed) for a program to be able to call a subprogram whose body
25789 is not yet elaborated, without raising a @code{Program_Error} exception.
25791 @node Controlling Elaboration in GNAT - External Calls
25792 @section Controlling Elaboration in GNAT - External Calls
25795 The previous section discussed the case in which the execution of a
25796 particular thread of elaboration code occurred entirely within a
25797 single unit. This is the easy case to handle, because a programmer
25798 has direct and total control over the order of elaboration, and
25799 furthermore, checks need only be generated in cases which are rare
25800 and which the compiler can easily detect.
25801 The situation is more complex when separate compilation is taken into account.
25802 Consider the following:
25804 @smallexample @c ada
25808 function Sqrt (Arg : Float) return Float;
25811 package body Math is
25812 function Sqrt (Arg : Float) return Float is
25821 X : Float := Math.Sqrt (0.5);
25834 where @code{Main} is the main program. When this program is executed, the
25835 elaboration code must first be executed, and one of the jobs of the
25836 binder is to determine the order in which the units of a program are
25837 to be elaborated. In this case we have four units: the spec and body
25839 the spec of @code{Stuff} and the body of @code{Main}).
25840 In what order should the four separate sections of elaboration code
25843 There are some restrictions in the order of elaboration that the binder
25844 can choose. In particular, if unit U has a @code{with}
25845 for a package @code{X}, then you
25846 are assured that the spec of @code{X}
25847 is elaborated before U , but you are
25848 not assured that the body of @code{X}
25849 is elaborated before U.
25850 This means that in the above case, the binder is allowed to choose the
25861 but that's not good, because now the call to @code{Math.Sqrt}
25862 that happens during
25863 the elaboration of the @code{Stuff}
25864 spec happens before the body of @code{Math.Sqrt} is
25865 elaborated, and hence causes @code{Program_Error} exception to be raised.
25866 At first glance, one might say that the binder is misbehaving, because
25867 obviously you want to elaborate the body of something you @code{with}
25869 that is not a general rule that can be followed in all cases. Consider
25871 @smallexample @c ada
25874 package X is @dots{}
25876 package Y is @dots{}
25879 package body Y is @dots{}
25882 package body X is @dots{}
25888 This is a common arrangement, and, apart from the order of elaboration
25889 problems that might arise in connection with elaboration code, this works fine.
25890 A rule that says that you must first elaborate the body of anything you
25891 @code{with} cannot work in this case:
25892 the body of @code{X} @code{with}'s @code{Y},
25893 which means you would have to
25894 elaborate the body of @code{Y} first, but that @code{with}'s @code{X},
25896 you have to elaborate the body of @code{X} first, but @dots{} and we have a
25897 loop that cannot be broken.
25899 It is true that the binder can in many cases guess an order of elaboration
25900 that is unlikely to cause a @code{Program_Error}
25901 exception to be raised, and it tries to do so (in the
25902 above example of @code{Math/Stuff/Spec}, the GNAT binder will
25904 elaborate the body of @code{Math} right after its spec, so all will be well).
25906 However, a program that blindly relies on the binder to be helpful can
25907 get into trouble, as we discussed in the previous sections, so
25909 provides a number of facilities for assisting the programmer in
25910 developing programs that are robust with respect to elaboration order.
25912 @node Default Behavior in GNAT - Ensuring Safety
25913 @section Default Behavior in GNAT - Ensuring Safety
25916 The default behavior in GNAT ensures elaboration safety. In its
25917 default mode GNAT implements the
25918 rule we previously described as the right approach. Let's restate it:
25922 @emph{If a unit has elaboration code that can directly or indirectly make a
25923 call to a subprogram in a @code{with}'ed unit, or instantiate a generic
25924 package in a @code{with}'ed unit, then if the @code{with}'ed unit
25925 does not have pragma @code{Pure} or
25926 @code{Preelaborate}, then the client should have an
25927 @code{Elaborate_All} pragma for the @code{with}'ed unit.}
25929 @emph{In the case of instantiating a generic subprogram, it is always
25930 sufficient to have only an @code{Elaborate} pragma for the
25931 @code{with}'ed unit.}
25935 By following this rule a client is assured that calls and instantiations
25936 can be made without risk of an exception.
25938 In this mode GNAT traces all calls that are potentially made from
25939 elaboration code, and puts in any missing implicit @code{Elaborate}
25940 and @code{Elaborate_All} pragmas.
25941 The advantage of this approach is that no elaboration problems
25942 are possible if the binder can find an elaboration order that is
25943 consistent with these implicit @code{Elaborate} and
25944 @code{Elaborate_All} pragmas. The
25945 disadvantage of this approach is that no such order may exist.
25947 If the binder does not generate any diagnostics, then it means that it has
25948 found an elaboration order that is guaranteed to be safe. However, the binder
25949 may still be relying on implicitly generated @code{Elaborate} and
25950 @code{Elaborate_All} pragmas so portability to other compilers than GNAT is not
25953 If it is important to guarantee portability, then the compilations should
25956 (info messages for elaboration prag mas) switch. This will cause info messages
25957 to be generated indicating the missing @code{Elaborate} and
25958 @code{Elaborate_All} pragmas.
25959 Consider the following source program:
25961 @smallexample @c ada
25966 m : integer := k.r;
25973 where it is clear that there
25974 should be a pragma @code{Elaborate_All}
25975 for unit @code{k}. An implicit pragma will be generated, and it is
25976 likely that the binder will be able to honor it. However, if you want
25977 to port this program to some other Ada compiler than GNAT.
25978 it is safer to include the pragma explicitly in the source. If this
25979 unit is compiled with the
25981 switch, then the compiler outputs an information message:
25988 3. m : integer := k.r;
25990 >>> info: call to "r" may raise Program_Error
25991 >>> info: missing pragma Elaborate_All for "k"
25999 and these messages can be used as a guide for supplying manually
26000 the missing pragmas. It is usually a bad idea to use this
26001 option during development. That's because it will tell you when
26002 you need to put in a pragma, but cannot tell you when it is time
26003 to take it out. So the use of pragma @code{Elaborate_All} may lead to
26004 unnecessary dependencies and even false circularities.
26006 This default mode is more restrictive than the Ada Reference
26007 Manual, and it is possible to construct programs which will compile
26008 using the dynamic model described there, but will run into a
26009 circularity using the safer static model we have described.
26011 Of course any Ada compiler must be able to operate in a mode
26012 consistent with the requirements of the Ada Reference Manual,
26013 and in particular must have the capability of implementing the
26014 standard dynamic model of elaboration with run-time checks.
26016 In GNAT, this standard mode can be achieved either by the use of
26017 the @option{-gnatE} switch on the compiler (@command{gcc} or
26018 @command{gnatmake}) command, or by the use of the configuration pragma:
26020 @smallexample @c ada
26021 pragma Elaboration_Checks (DYNAMIC);
26025 Either approach will cause the unit affected to be compiled using the
26026 standard dynamic run-time elaboration checks described in the Ada
26027 Reference Manual. The static model is generally preferable, since it
26028 is clearly safer to rely on compile and link time checks rather than
26029 run-time checks. However, in the case of legacy code, it may be
26030 difficult to meet the requirements of the static model. This
26031 issue is further discussed in
26032 @ref{What to Do If the Default Elaboration Behavior Fails}.
26034 Note that the static model provides a strict subset of the allowed
26035 behavior and programs of the Ada Reference Manual, so if you do
26036 adhere to the static model and no circularities exist,
26037 then you are assured that your program will
26038 work using the dynamic model, providing that you remove any
26039 pragma Elaborate statements from the source.
26041 @node Treatment of Pragma Elaborate
26042 @section Treatment of Pragma Elaborate
26043 @cindex Pragma Elaborate
26046 The use of @code{pragma Elaborate}
26047 should generally be avoided in Ada 95 and Ada 2005 programs,
26048 since there is no guarantee that transitive calls
26049 will be properly handled. Indeed at one point, this pragma was placed
26050 in Annex J (Obsolescent Features), on the grounds that it is never useful.
26052 Now that's a bit restrictive. In practice, the case in which
26053 @code{pragma Elaborate} is useful is when the caller knows that there
26054 are no transitive calls, or that the called unit contains all necessary
26055 transitive @code{pragma Elaborate} statements, and legacy code often
26056 contains such uses.
26058 Strictly speaking the static mode in GNAT should ignore such pragmas,
26059 since there is no assurance at compile time that the necessary safety
26060 conditions are met. In practice, this would cause GNAT to be incompatible
26061 with correctly written Ada 83 code that had all necessary
26062 @code{pragma Elaborate} statements in place. Consequently, we made the
26063 decision that GNAT in its default mode will believe that if it encounters
26064 a @code{pragma Elaborate} then the programmer knows what they are doing,
26065 and it will trust that no elaboration errors can occur.
26067 The result of this decision is two-fold. First to be safe using the
26068 static mode, you should remove all @code{pragma Elaborate} statements.
26069 Second, when fixing circularities in existing code, you can selectively
26070 use @code{pragma Elaborate} statements to convince the static mode of
26071 GNAT that it need not generate an implicit @code{pragma Elaborate_All}
26074 When using the static mode with @option{-gnatwl}, any use of
26075 @code{pragma Elaborate} will generate a warning about possible
26078 @node Elaboration Issues for Library Tasks
26079 @section Elaboration Issues for Library Tasks
26080 @cindex Library tasks, elaboration issues
26081 @cindex Elaboration of library tasks
26084 In this section we examine special elaboration issues that arise for
26085 programs that declare library level tasks.
26087 Generally the model of execution of an Ada program is that all units are
26088 elaborated, and then execution of the program starts. However, the
26089 declaration of library tasks definitely does not fit this model. The
26090 reason for this is that library tasks start as soon as they are declared
26091 (more precisely, as soon as the statement part of the enclosing package
26092 body is reached), that is to say before elaboration
26093 of the program is complete. This means that if such a task calls a
26094 subprogram, or an entry in another task, the callee may or may not be
26095 elaborated yet, and in the standard
26096 Reference Manual model of dynamic elaboration checks, you can even
26097 get timing dependent Program_Error exceptions, since there can be
26098 a race between the elaboration code and the task code.
26100 The static model of elaboration in GNAT seeks to avoid all such
26101 dynamic behavior, by being conservative, and the conservative
26102 approach in this particular case is to assume that all the code
26103 in a task body is potentially executed at elaboration time if
26104 a task is declared at the library level.
26106 This can definitely result in unexpected circularities. Consider
26107 the following example
26109 @smallexample @c ada
26115 type My_Int is new Integer;
26117 function Ident (M : My_Int) return My_Int;
26121 package body Decls is
26122 task body Lib_Task is
26128 function Ident (M : My_Int) return My_Int is
26136 procedure Put_Val (Arg : Decls.My_Int);
26140 package body Utils is
26141 procedure Put_Val (Arg : Decls.My_Int) is
26143 Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
26150 Decls.Lib_Task.Start;
26155 If the above example is compiled in the default static elaboration
26156 mode, then a circularity occurs. The circularity comes from the call
26157 @code{Utils.Put_Val} in the task body of @code{Decls.Lib_Task}. Since
26158 this call occurs in elaboration code, we need an implicit pragma
26159 @code{Elaborate_All} for @code{Utils}. This means that not only must
26160 the spec and body of @code{Utils} be elaborated before the body
26161 of @code{Decls}, but also the spec and body of any unit that is
26162 @code{with'ed} by the body of @code{Utils} must also be elaborated before
26163 the body of @code{Decls}. This is the transitive implication of
26164 pragma @code{Elaborate_All} and it makes sense, because in general
26165 the body of @code{Put_Val} might have a call to something in a
26166 @code{with'ed} unit.
26168 In this case, the body of Utils (actually its spec) @code{with's}
26169 @code{Decls}. Unfortunately this means that the body of @code{Decls}
26170 must be elaborated before itself, in case there is a call from the
26171 body of @code{Utils}.
26173 Here is the exact chain of events we are worrying about:
26177 In the body of @code{Decls} a call is made from within the body of a library
26178 task to a subprogram in the package @code{Utils}. Since this call may
26179 occur at elaboration time (given that the task is activated at elaboration
26180 time), we have to assume the worst, i.e., that the
26181 call does happen at elaboration time.
26184 This means that the body and spec of @code{Util} must be elaborated before
26185 the body of @code{Decls} so that this call does not cause an access before
26189 Within the body of @code{Util}, specifically within the body of
26190 @code{Util.Put_Val} there may be calls to any unit @code{with}'ed
26194 One such @code{with}'ed package is package @code{Decls}, so there
26195 might be a call to a subprogram in @code{Decls} in @code{Put_Val}.
26196 In fact there is such a call in this example, but we would have to
26197 assume that there was such a call even if it were not there, since
26198 we are not supposed to write the body of @code{Decls} knowing what
26199 is in the body of @code{Utils}; certainly in the case of the
26200 static elaboration model, the compiler does not know what is in
26201 other bodies and must assume the worst.
26204 This means that the spec and body of @code{Decls} must also be
26205 elaborated before we elaborate the unit containing the call, but
26206 that unit is @code{Decls}! This means that the body of @code{Decls}
26207 must be elaborated before itself, and that's a circularity.
26211 Indeed, if you add an explicit pragma @code{Elaborate_All} for @code{Utils} in
26212 the body of @code{Decls} you will get a true Ada Reference Manual
26213 circularity that makes the program illegal.
26215 In practice, we have found that problems with the static model of
26216 elaboration in existing code often arise from library tasks, so
26217 we must address this particular situation.
26219 Note that if we compile and run the program above, using the dynamic model of
26220 elaboration (that is to say use the @option{-gnatE} switch),
26221 then it compiles, binds,
26222 links, and runs, printing the expected result of 2. Therefore in some sense
26223 the circularity here is only apparent, and we need to capture
26224 the properties of this program that distinguish it from other library-level
26225 tasks that have real elaboration problems.
26227 We have four possible answers to this question:
26232 Use the dynamic model of elaboration.
26234 If we use the @option{-gnatE} switch, then as noted above, the program works.
26235 Why is this? If we examine the task body, it is apparent that the task cannot
26237 @code{accept} statement until after elaboration has been completed, because
26238 the corresponding entry call comes from the main program, not earlier.
26239 This is why the dynamic model works here. But that's really giving
26240 up on a precise analysis, and we prefer to take this approach only if we cannot
26242 problem in any other manner. So let us examine two ways to reorganize
26243 the program to avoid the potential elaboration problem.
26246 Split library tasks into separate packages.
26248 Write separate packages, so that library tasks are isolated from
26249 other declarations as much as possible. Let us look at a variation on
26252 @smallexample @c ada
26260 package body Decls1 is
26261 task body Lib_Task is
26269 type My_Int is new Integer;
26270 function Ident (M : My_Int) return My_Int;
26274 package body Decls2 is
26275 function Ident (M : My_Int) return My_Int is
26283 procedure Put_Val (Arg : Decls2.My_Int);
26287 package body Utils is
26288 procedure Put_Val (Arg : Decls2.My_Int) is
26290 Text_IO.Put_Line (Decls2.My_Int'Image (Decls2.Ident (Arg)));
26297 Decls1.Lib_Task.Start;
26302 All we have done is to split @code{Decls} into two packages, one
26303 containing the library task, and one containing everything else. Now
26304 there is no cycle, and the program compiles, binds, links and executes
26305 using the default static model of elaboration.
26308 Declare separate task types.
26310 A significant part of the problem arises because of the use of the
26311 single task declaration form. This means that the elaboration of
26312 the task type, and the elaboration of the task itself (i.e.@: the
26313 creation of the task) happen at the same time. A good rule
26314 of style in Ada is to always create explicit task types. By
26315 following the additional step of placing task objects in separate
26316 packages from the task type declaration, many elaboration problems
26317 are avoided. Here is another modified example of the example program:
26319 @smallexample @c ada
26321 task type Lib_Task_Type is
26325 type My_Int is new Integer;
26327 function Ident (M : My_Int) return My_Int;
26331 package body Decls is
26332 task body Lib_Task_Type is
26338 function Ident (M : My_Int) return My_Int is
26346 procedure Put_Val (Arg : Decls.My_Int);
26350 package body Utils is
26351 procedure Put_Val (Arg : Decls.My_Int) is
26353 Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
26359 Lib_Task : Decls.Lib_Task_Type;
26365 Declst.Lib_Task.Start;
26370 What we have done here is to replace the @code{task} declaration in
26371 package @code{Decls} with a @code{task type} declaration. Then we
26372 introduce a separate package @code{Declst} to contain the actual
26373 task object. This separates the elaboration issues for
26374 the @code{task type}
26375 declaration, which causes no trouble, from the elaboration issues
26376 of the task object, which is also unproblematic, since it is now independent
26377 of the elaboration of @code{Utils}.
26378 This separation of concerns also corresponds to
26379 a generally sound engineering principle of separating declarations
26380 from instances. This version of the program also compiles, binds, links,
26381 and executes, generating the expected output.
26384 Use No_Entry_Calls_In_Elaboration_Code restriction.
26385 @cindex No_Entry_Calls_In_Elaboration_Code
26387 The previous two approaches described how a program can be restructured
26388 to avoid the special problems caused by library task bodies. in practice,
26389 however, such restructuring may be difficult to apply to existing legacy code,
26390 so we must consider solutions that do not require massive rewriting.
26392 Let us consider more carefully why our original sample program works
26393 under the dynamic model of elaboration. The reason is that the code
26394 in the task body blocks immediately on the @code{accept}
26395 statement. Now of course there is nothing to prohibit elaboration
26396 code from making entry calls (for example from another library level task),
26397 so we cannot tell in isolation that
26398 the task will not execute the accept statement during elaboration.
26400 However, in practice it is very unusual to see elaboration code
26401 make any entry calls, and the pattern of tasks starting
26402 at elaboration time and then immediately blocking on @code{accept} or
26403 @code{select} statements is very common. What this means is that
26404 the compiler is being too pessimistic when it analyzes the
26405 whole package body as though it might be executed at elaboration
26408 If we know that the elaboration code contains no entry calls, (a very safe
26409 assumption most of the time, that could almost be made the default
26410 behavior), then we can compile all units of the program under control
26411 of the following configuration pragma:
26414 pragma Restrictions (No_Entry_Calls_In_Elaboration_Code);
26418 This pragma can be placed in the @file{gnat.adc} file in the usual
26419 manner. If we take our original unmodified program and compile it
26420 in the presence of a @file{gnat.adc} containing the above pragma,
26421 then once again, we can compile, bind, link, and execute, obtaining
26422 the expected result. In the presence of this pragma, the compiler does
26423 not trace calls in a task body, that appear after the first @code{accept}
26424 or @code{select} statement, and therefore does not report a potential
26425 circularity in the original program.
26427 The compiler will check to the extent it can that the above
26428 restriction is not violated, but it is not always possible to do a
26429 complete check at compile time, so it is important to use this
26430 pragma only if the stated restriction is in fact met, that is to say
26431 no task receives an entry call before elaboration of all units is completed.
26435 @node Mixing Elaboration Models
26436 @section Mixing Elaboration Models
26438 So far, we have assumed that the entire program is either compiled
26439 using the dynamic model or static model, ensuring consistency. It
26440 is possible to mix the two models, but rules have to be followed
26441 if this mixing is done to ensure that elaboration checks are not
26444 The basic rule is that @emph{a unit compiled with the static model cannot
26445 be @code{with'ed} by a unit compiled with the dynamic model}. The
26446 reason for this is that in the static model, a unit assumes that
26447 its clients guarantee to use (the equivalent of) pragma
26448 @code{Elaborate_All} so that no elaboration checks are required
26449 in inner subprograms, and this assumption is violated if the
26450 client is compiled with dynamic checks.
26452 The precise rule is as follows. A unit that is compiled with dynamic
26453 checks can only @code{with} a unit that meets at least one of the
26454 following criteria:
26459 The @code{with'ed} unit is itself compiled with dynamic elaboration
26460 checks (that is with the @option{-gnatE} switch.
26463 The @code{with'ed} unit is an internal GNAT implementation unit from
26464 the System, Interfaces, Ada, or GNAT hierarchies.
26467 The @code{with'ed} unit has pragma Preelaborate or pragma Pure.
26470 The @code{with'ing} unit (that is the client) has an explicit pragma
26471 @code{Elaborate_All} for the @code{with'ed} unit.
26476 If this rule is violated, that is if a unit with dynamic elaboration
26477 checks @code{with's} a unit that does not meet one of the above four
26478 criteria, then the binder (@code{gnatbind}) will issue a warning
26479 similar to that in the following example:
26482 warning: "x.ads" has dynamic elaboration checks and with's
26483 warning: "y.ads" which has static elaboration checks
26487 These warnings indicate that the rule has been violated, and that as a result
26488 elaboration checks may be missed in the resulting executable file.
26489 This warning may be suppressed using the @option{-ws} binder switch
26490 in the usual manner.
26492 One useful application of this mixing rule is in the case of a subsystem
26493 which does not itself @code{with} units from the remainder of the
26494 application. In this case, the entire subsystem can be compiled with
26495 dynamic checks to resolve a circularity in the subsystem, while
26496 allowing the main application that uses this subsystem to be compiled
26497 using the more reliable default static model.
26499 @node What to Do If the Default Elaboration Behavior Fails
26500 @section What to Do If the Default Elaboration Behavior Fails
26503 If the binder cannot find an acceptable order, it outputs detailed
26504 diagnostics. For example:
26510 error: elaboration circularity detected
26511 info: "proc (body)" must be elaborated before "pack (body)"
26512 info: reason: Elaborate_All probably needed in unit "pack (body)"
26513 info: recompile "pack (body)" with -gnatel
26514 info: for full details
26515 info: "proc (body)"
26516 info: is needed by its spec:
26517 info: "proc (spec)"
26518 info: which is withed by:
26519 info: "pack (body)"
26520 info: "pack (body)" must be elaborated before "proc (body)"
26521 info: reason: pragma Elaborate in unit "proc (body)"
26527 In this case we have a cycle that the binder cannot break. On the one
26528 hand, there is an explicit pragma Elaborate in @code{proc} for
26529 @code{pack}. This means that the body of @code{pack} must be elaborated
26530 before the body of @code{proc}. On the other hand, there is elaboration
26531 code in @code{pack} that calls a subprogram in @code{proc}. This means
26532 that for maximum safety, there should really be a pragma
26533 Elaborate_All in @code{pack} for @code{proc} which would require that
26534 the body of @code{proc} be elaborated before the body of
26535 @code{pack}. Clearly both requirements cannot be satisfied.
26536 Faced with a circularity of this kind, you have three different options.
26539 @item Fix the program
26540 The most desirable option from the point of view of long-term maintenance
26541 is to rearrange the program so that the elaboration problems are avoided.
26542 One useful technique is to place the elaboration code into separate
26543 child packages. Another is to move some of the initialization code to
26544 explicitly called subprograms, where the program controls the order
26545 of initialization explicitly. Although this is the most desirable option,
26546 it may be impractical and involve too much modification, especially in
26547 the case of complex legacy code.
26549 @item Perform dynamic checks
26550 If the compilations are done using the
26552 (dynamic elaboration check) switch, then GNAT behaves in a quite different
26553 manner. Dynamic checks are generated for all calls that could possibly result
26554 in raising an exception. With this switch, the compiler does not generate
26555 implicit @code{Elaborate} or @code{Elaborate_All} pragmas. The behavior then is
26556 exactly as specified in the @cite{Ada Reference Manual}.
26557 The binder will generate
26558 an executable program that may or may not raise @code{Program_Error}, and then
26559 it is the programmer's job to ensure that it does not raise an exception. Note
26560 that it is important to compile all units with the switch, it cannot be used
26563 @item Suppress checks
26564 The drawback of dynamic checks is that they generate a
26565 significant overhead at run time, both in space and time. If you
26566 are absolutely sure that your program cannot raise any elaboration
26567 exceptions, and you still want to use the dynamic elaboration model,
26568 then you can use the configuration pragma
26569 @code{Suppress (Elaboration_Check)} to suppress all such checks. For
26570 example this pragma could be placed in the @file{gnat.adc} file.
26572 @item Suppress checks selectively
26573 When you know that certain calls or instantiations in elaboration code cannot
26574 possibly lead to an elaboration error, and the binder nevertheless complains
26575 about implicit @code{Elaborate} and @code{Elaborate_All} pragmas that lead to
26576 elaboration circularities, it is possible to remove those warnings locally and
26577 obtain a program that will bind. Clearly this can be unsafe, and it is the
26578 responsibility of the programmer to make sure that the resulting program has no
26579 elaboration anomalies. The pragma @code{Suppress (Elaboration_Check)} can be
26580 used with different granularity to suppress warnings and break elaboration
26585 Place the pragma that names the called subprogram in the declarative part
26586 that contains the call.
26589 Place the pragma in the declarative part, without naming an entity. This
26590 disables warnings on all calls in the corresponding declarative region.
26593 Place the pragma in the package spec that declares the called subprogram,
26594 and name the subprogram. This disables warnings on all elaboration calls to
26598 Place the pragma in the package spec that declares the called subprogram,
26599 without naming any entity. This disables warnings on all elaboration calls to
26600 all subprograms declared in this spec.
26602 @item Use Pragma Elaborate
26603 As previously described in section @xref{Treatment of Pragma Elaborate},
26604 GNAT in static mode assumes that a @code{pragma} Elaborate indicates correctly
26605 that no elaboration checks are required on calls to the designated unit.
26606 There may be cases in which the caller knows that no transitive calls
26607 can occur, so that a @code{pragma Elaborate} will be sufficient in a
26608 case where @code{pragma Elaborate_All} would cause a circularity.
26612 These five cases are listed in order of decreasing safety, and therefore
26613 require increasing programmer care in their application. Consider the
26616 @smallexample @c adanocomment
26618 function F1 return Integer;
26623 function F2 return Integer;
26624 function Pure (x : integer) return integer;
26625 -- pragma Suppress (Elaboration_Check, On => Pure); -- (3)
26626 -- pragma Suppress (Elaboration_Check); -- (4)
26630 package body Pack1 is
26631 function F1 return Integer is
26635 Val : integer := Pack2.Pure (11); -- Elab. call (1)
26638 -- pragma Suppress(Elaboration_Check, Pack2.F2); -- (1)
26639 -- pragma Suppress(Elaboration_Check); -- (2)
26641 X1 := Pack2.F2 + 1; -- Elab. call (2)
26646 package body Pack2 is
26647 function F2 return Integer is
26651 function Pure (x : integer) return integer is
26653 return x ** 3 - 3 * x;
26657 with Pack1, Ada.Text_IO;
26660 Ada.Text_IO.Put_Line(Pack1.X1'Img); -- 101
26663 In the absence of any pragmas, an attempt to bind this program produces
26664 the following diagnostics:
26670 error: elaboration circularity detected
26671 info: "pack1 (body)" must be elaborated before "pack1 (body)"
26672 info: reason: Elaborate_All probably needed in unit "pack1 (body)"
26673 info: recompile "pack1 (body)" with -gnatel for full details
26674 info: "pack1 (body)"
26675 info: must be elaborated along with its spec:
26676 info: "pack1 (spec)"
26677 info: which is withed by:
26678 info: "pack2 (body)"
26679 info: which must be elaborated along with its spec:
26680 info: "pack2 (spec)"
26681 info: which is withed by:
26682 info: "pack1 (body)"
26685 The sources of the circularity are the two calls to @code{Pack2.Pure} and
26686 @code{Pack2.F2} in the body of @code{Pack1}. We can see that the call to
26687 F2 is safe, even though F2 calls F1, because the call appears after the
26688 elaboration of the body of F1. Therefore the pragma (1) is safe, and will
26689 remove the warning on the call. It is also possible to use pragma (2)
26690 because there are no other potentially unsafe calls in the block.
26693 The call to @code{Pure} is safe because this function does not depend on the
26694 state of @code{Pack2}. Therefore any call to this function is safe, and it
26695 is correct to place pragma (3) in the corresponding package spec.
26698 Finally, we could place pragma (4) in the spec of @code{Pack2} to disable
26699 warnings on all calls to functions declared therein. Note that this is not
26700 necessarily safe, and requires more detailed examination of the subprogram
26701 bodies involved. In particular, a call to @code{F2} requires that @code{F1}
26702 be already elaborated.
26706 It is hard to generalize on which of these four approaches should be
26707 taken. Obviously if it is possible to fix the program so that the default
26708 treatment works, this is preferable, but this may not always be practical.
26709 It is certainly simple enough to use
26711 but the danger in this case is that, even if the GNAT binder
26712 finds a correct elaboration order, it may not always do so,
26713 and certainly a binder from another Ada compiler might not. A
26714 combination of testing and analysis (for which the
26715 information messages generated with the
26717 switch can be useful) must be used to ensure that the program is free
26718 of errors. One switch that is useful in this testing is the
26719 @option{^-p (pessimistic elaboration order)^/PESSIMISTIC_ELABORATION_ORDER^}
26722 Normally the binder tries to find an order that has the best chance
26723 of avoiding elaboration problems. However, if this switch is used, the binder
26724 plays a devil's advocate role, and tries to choose the order that
26725 has the best chance of failing. If your program works even with this
26726 switch, then it has a better chance of being error free, but this is still
26729 For an example of this approach in action, consider the C-tests (executable
26730 tests) from the ACVC suite. If these are compiled and run with the default
26731 treatment, then all but one of them succeed without generating any error
26732 diagnostics from the binder. However, there is one test that fails, and
26733 this is not surprising, because the whole point of this test is to ensure
26734 that the compiler can handle cases where it is impossible to determine
26735 a correct order statically, and it checks that an exception is indeed
26736 raised at run time.
26738 This one test must be compiled and run using the
26740 switch, and then it passes. Alternatively, the entire suite can
26741 be run using this switch. It is never wrong to run with the dynamic
26742 elaboration switch if your code is correct, and we assume that the
26743 C-tests are indeed correct (it is less efficient, but efficiency is
26744 not a factor in running the ACVC tests.)
26746 @node Elaboration for Indirect Calls
26747 @section Elaboration for Indirect Calls
26748 @cindex Dispatching calls
26749 @cindex Indirect calls
26752 In rare cases, the static elaboration model fails to prevent
26753 dispatching calls to not-yet-elaborated subprograms. In such cases, we
26754 fall back to run-time checks; premature calls to any primitive
26755 operation of a tagged type before the body of the operation has been
26756 elaborated will raise @code{Program_Error}.
26758 Access-to-subprogram types, however, are handled conservatively, and
26759 do not require run-time checks. This was not true in earlier versions
26760 of the compiler; you can use the @option{-gnatd.U} debug switch to
26761 revert to the old behavior if the new conservative behavior causes
26762 elaboration cycles. Here, ``conservative'' means that if you do
26763 @code{P'Access} during elaboration, the compiler will assume that you
26764 might call @code{P} indirectly during elaboration, so it adds an
26765 implicit @code{pragma Elaborate_All} on the library unit containing
26766 @code{P}. The @option{-gnatd.U} switch is safe if you know there are
26767 no such calls. If the program worked before, it will continue to work
26768 with @option{-gnatd.U}. But beware that code modifications such as
26769 adding an indirect call can cause erroneous behavior in the presence
26770 of @option{-gnatd.U}.
26772 @node Summary of Procedures for Elaboration Control
26773 @section Summary of Procedures for Elaboration Control
26774 @cindex Elaboration control
26777 First, compile your program with the default options, using none of
26778 the special elaboration control switches. If the binder successfully
26779 binds your program, then you can be confident that, apart from issues
26780 raised by the use of access-to-subprogram types and dynamic dispatching,
26781 the program is free of elaboration errors. If it is important that the
26782 program be portable to other compilers than GNAT, then use the
26784 switch to generate messages about missing @code{Elaborate} or
26785 @code{Elaborate_All} pragmas, and supply the missing pragmas.
26787 If the program fails to bind using the default static elaboration
26788 handling, then you can fix the program to eliminate the binder
26789 message, or recompile the entire program with the
26790 @option{-gnatE} switch to generate dynamic elaboration checks,
26791 and, if you are sure there really are no elaboration problems,
26792 use a global pragma @code{Suppress (Elaboration_Check)}.
26794 @node Other Elaboration Order Considerations
26795 @section Other Elaboration Order Considerations
26797 This section has been entirely concerned with the issue of finding a valid
26798 elaboration order, as defined by the Ada Reference Manual. In a case
26799 where several elaboration orders are valid, the task is to find one
26800 of the possible valid elaboration orders (and the static model in GNAT
26801 will ensure that this is achieved).
26803 The purpose of the elaboration rules in the Ada Reference Manual is to
26804 make sure that no entity is accessed before it has been elaborated. For
26805 a subprogram, this means that the spec and body must have been elaborated
26806 before the subprogram is called. For an object, this means that the object
26807 must have been elaborated before its value is read or written. A violation
26808 of either of these two requirements is an access before elaboration order,
26809 and this section has been all about avoiding such errors.
26811 In the case where more than one order of elaboration is possible, in the
26812 sense that access before elaboration errors are avoided, then any one of
26813 the orders is ``correct'' in the sense that it meets the requirements of
26814 the Ada Reference Manual, and no such error occurs.
26816 However, it may be the case for a given program, that there are
26817 constraints on the order of elaboration that come not from consideration
26818 of avoiding elaboration errors, but rather from extra-lingual logic
26819 requirements. Consider this example:
26821 @smallexample @c ada
26822 with Init_Constants;
26823 package Constants is
26828 package Init_Constants is
26829 procedure P; -- require a body
26830 end Init_Constants;
26833 package body Init_Constants is
26834 procedure P is begin null; end;
26838 end Init_Constants;
26842 Z : Integer := Constants.X + Constants.Y;
26846 with Text_IO; use Text_IO;
26849 Put_Line (Calc.Z'Img);
26854 In this example, there is more than one valid order of elaboration. For
26855 example both the following are correct orders:
26858 Init_Constants spec
26861 Init_Constants body
26866 Init_Constants spec
26867 Init_Constants body
26874 There is no language rule to prefer one or the other, both are correct
26875 from an order of elaboration point of view. But the programmatic effects
26876 of the two orders are very different. In the first, the elaboration routine
26877 of @code{Calc} initializes @code{Z} to zero, and then the main program
26878 runs with this value of zero. But in the second order, the elaboration
26879 routine of @code{Calc} runs after the body of Init_Constants has set
26880 @code{X} and @code{Y} and thus @code{Z} is set to 7 before @code{Main}
26883 One could perhaps by applying pretty clever non-artificial intelligence
26884 to the situation guess that it is more likely that the second order of
26885 elaboration is the one desired, but there is no formal linguistic reason
26886 to prefer one over the other. In fact in this particular case, GNAT will
26887 prefer the second order, because of the rule that bodies are elaborated
26888 as soon as possible, but it's just luck that this is what was wanted
26889 (if indeed the second order was preferred).
26891 If the program cares about the order of elaboration routines in a case like
26892 this, it is important to specify the order required. In this particular
26893 case, that could have been achieved by adding to the spec of Calc:
26895 @smallexample @c ada
26896 pragma Elaborate_All (Constants);
26900 which requires that the body (if any) and spec of @code{Constants},
26901 as well as the body and spec of any unit @code{with}'ed by
26902 @code{Constants} be elaborated before @code{Calc} is elaborated.
26904 Clearly no automatic method can always guess which alternative you require,
26905 and if you are working with legacy code that had constraints of this kind
26906 which were not properly specified by adding @code{Elaborate} or
26907 @code{Elaborate_All} pragmas, then indeed it is possible that two different
26908 compilers can choose different orders.
26910 However, GNAT does attempt to diagnose the common situation where there
26911 are uninitialized variables in the visible part of a package spec, and the
26912 corresponding package body has an elaboration block that directly or
26913 indirectly initialized one or more of these variables. This is the situation
26914 in which a pragma Elaborate_Body is usually desirable, and GNAT will generate
26915 a warning that suggests this addition if it detects this situation.
26917 The @code{gnatbind}
26918 @option{^-p^/PESSIMISTIC_ELABORATION^} switch may be useful in smoking
26919 out problems. This switch causes bodies to be elaborated as late as possible
26920 instead of as early as possible. In the example above, it would have forced
26921 the choice of the first elaboration order. If you get different results
26922 when using this switch, and particularly if one set of results is right,
26923 and one is wrong as far as you are concerned, it shows that you have some
26924 missing @code{Elaborate} pragmas. For the example above, we have the
26928 gnatmake -f -q main
26931 gnatmake -f -q main -bargs -p
26937 It is of course quite unlikely that both these results are correct, so
26938 it is up to you in a case like this to investigate the source of the
26939 difference, by looking at the two elaboration orders that are chosen,
26940 and figuring out which is correct, and then adding the necessary
26941 @code{Elaborate} or @code{Elaborate_All} pragmas to ensure the desired order.
26943 @node Determining the Chosen Elaboration Order
26944 @section Determining the Chosen Elaboration Order
26947 To see the elaboration order that the binder chooses, you can look at
26948 the last part of the b~xxx.adb binder output file. Here is an example:
26950 @smallexample @c ada
26951 System.Soft_Links'Elab_Body;
26953 System.Secondary_Stack'Elab_Body;
26955 System.Exception_Table'Elab_Body;
26957 Ada.Io_Exceptions'Elab_Spec;
26959 Ada.Tags'Elab_Spec;
26960 Ada.Streams'Elab_Spec;
26962 Interfaces.C'Elab_Spec;
26964 System.Finalization_Root'Elab_Spec;
26966 System.Os_Lib'Elab_Body;
26968 System.Finalization_Implementation'Elab_Spec;
26969 System.Finalization_Implementation'Elab_Body;
26971 Ada.Finalization'Elab_Spec;
26973 Ada.Finalization.List_Controller'Elab_Spec;
26975 System.File_Control_Block'Elab_Spec;
26977 System.File_Io'Elab_Body;
26979 Ada.Tags'Elab_Body;
26981 Ada.Text_Io'Elab_Spec;
26982 Ada.Text_Io'Elab_Body;
26987 Here Elab_Spec elaborates the spec
26988 and Elab_Body elaborates the body. The assignments to the Exx flags
26989 flag that the corresponding body is now elaborated.
26991 You can also ask the binder to generate a more
26992 readable list of the elaboration order using the
26993 @code{-l} switch when invoking the binder. Here is
26994 an example of the output generated by this switch:
27000 system.case_util (spec)
27001 system.case_util (body)
27002 system.concat_2 (spec)
27003 system.concat_2 (body)
27004 system.concat_3 (spec)
27005 system.concat_3 (body)
27006 system.htable (spec)
27007 system.parameters (spec)
27008 system.parameters (body)
27010 interfaces.c_streams (spec)
27011 interfaces.c_streams (body)
27012 system.restrictions (spec)
27013 system.restrictions (body)
27014 system.standard_library (spec)
27015 system.exceptions (spec)
27016 system.exceptions (body)
27017 system.storage_elements (spec)
27018 system.storage_elements (body)
27019 system.secondary_stack (spec)
27020 system.stack_checking (spec)
27021 system.stack_checking (body)
27022 system.string_hash (spec)
27023 system.string_hash (body)
27024 system.htable (body)
27025 system.strings (spec)
27026 system.strings (body)
27027 system.traceback (spec)
27028 system.traceback (body)
27029 system.traceback_entries (spec)
27030 system.traceback_entries (body)
27031 ada.exceptions (spec)
27032 ada.exceptions.last_chance_handler (spec)
27033 system.soft_links (spec)
27034 system.soft_links (body)
27035 ada.exceptions.last_chance_handler (body)
27036 system.secondary_stack (body)
27037 system.exception_table (spec)
27038 system.exception_table (body)
27039 ada.io_exceptions (spec)
27042 interfaces.c (spec)
27043 interfaces.c (body)
27044 system.finalization_root (spec)
27045 system.finalization_root (body)
27046 system.memory (spec)
27047 system.memory (body)
27048 system.standard_library (body)
27049 system.os_lib (spec)
27050 system.os_lib (body)
27051 system.unsigned_types (spec)
27052 system.stream_attributes (spec)
27053 system.stream_attributes (body)
27054 system.finalization_implementation (spec)
27055 system.finalization_implementation (body)
27056 ada.finalization (spec)
27057 ada.finalization (body)
27058 ada.finalization.list_controller (spec)
27059 ada.finalization.list_controller (body)
27060 system.file_control_block (spec)
27061 system.file_io (spec)
27062 system.file_io (body)
27063 system.val_uns (spec)
27064 system.val_util (spec)
27065 system.val_util (body)
27066 system.val_uns (body)
27067 system.wch_con (spec)
27068 system.wch_con (body)
27069 system.wch_cnv (spec)
27070 system.wch_jis (spec)
27071 system.wch_jis (body)
27072 system.wch_cnv (body)
27073 system.wch_stw (spec)
27074 system.wch_stw (body)
27076 ada.exceptions (body)
27083 @c **********************************
27084 @node Overflow Check Handling in GNAT
27085 @appendix Overflow Check Handling in GNAT
27086 @cindex Overflow checks
27087 @cindex Checks (overflow)
27088 @c **********************************
27092 * Overflow Checking Modes in GNAT::
27093 * Specifying the Desired Mode::
27094 * Default Settings::
27095 * Implementation Notes::
27100 @section Background
27103 Overflow checks are checks that the compiler may make to ensure
27104 that intermediate results are not out of range. For example:
27106 @smallexample @c ada
27113 if @code{A} has the value @code{Integer'Last}, then the addition may cause
27114 overflow since the result is out of range of the type @code{Integer}.
27115 In this case @code{Constraint_Error} will be raised if checks are
27118 A trickier situation arises in examples like the following:
27120 @smallexample @c ada
27127 where @code{A} is @code{Integer'Last} and @code{C} is @code{-1}.
27128 Now the final result of the expression on the right hand side is
27129 @code{Integer'Last} which is in range, but the question arises whether the
27130 intermediate addition of @code{(A + 1)} raises an overflow error.
27132 The (perhaps surprising) answer is that the Ada language
27133 definition does not answer this question. Instead it leaves
27134 it up to the implementation to do one of two things if overflow
27135 checks are enabled.
27139 raise an exception (@code{Constraint_Error}), or
27142 yield the correct mathematical result which is then used in
27143 subsequent operations.
27147 If the compiler chooses the first approach, then the assignment of this
27148 example will indeed raise @code{Constraint_Error} if overflow checking is
27149 enabled, or result in erroneous execution if overflow checks are suppressed.
27151 But if the compiler
27152 chooses the second approach, then it can perform both additions yielding
27153 the correct mathematical result, which is in range, so no exception
27154 will be raised, and the right result is obtained, regardless of whether
27155 overflow checks are suppressed.
27157 Note that in the first example an
27158 exception will be raised in either case, since if the compiler
27159 gives the correct mathematical result for the addition, it will
27160 be out of range of the target type of the assignment, and thus
27161 fails the range check.
27163 This lack of specified behavior in the handling of overflow for
27164 intermediate results is a source of non-portability, and can thus
27165 be problematic when programs are ported. Most typically this arises
27166 in a situation where the original compiler did not raise an exception,
27167 and then the application is moved to a compiler where the check is
27168 performed on the intermediate result and an unexpected exception is
27171 Furthermore, when using Ada 2012's preconditions and other
27172 assertion forms, another issue arises. Consider:
27174 @smallexample @c ada
27175 procedure P (A, B : Integer) with
27176 Pre => A + B <= Integer'Last;
27180 One often wants to regard arithmetic in a context like this from
27181 a mathematical point of view. So for example, if the two actual parameters
27182 for a call to @code{P} are both @code{Integer'Last}, then
27183 the precondition should be regarded as False. If we are executing
27184 in a mode with run-time checks enabled for preconditions, then we would
27185 like this precondition to fail, rather than raising an exception
27186 because of the intermediate overflow.
27188 However, the language definition leaves the specification of
27189 whether the above condition fails (raising @code{Assert_Error}) or
27190 causes an intermediate overflow (raising @code{Constraint_Error})
27191 up to the implementation.
27193 The situation is worse in a case such as the following:
27195 @smallexample @c ada
27196 procedure Q (A, B, C : Integer) with
27197 Pre => A + B + C <= Integer'Last;
27203 @smallexample @c ada
27204 Q (A => Integer'Last, B => 1, C => -1);
27208 From a mathematical point of view the precondition
27209 is True, but at run time we may (but are not guaranteed to) get an
27210 exception raised because of the intermediate overflow (and we really
27211 would prefer this precondition to be considered True at run time).
27213 @node Overflow Checking Modes in GNAT
27214 @section Overflow Checking Modes in GNAT
27217 To deal with the portability issue, and with the problem of
27218 mathematical versus run-time interpretation of the expressions in
27219 assertions, GNAT provides comprehensive control over the handling
27220 of intermediate overflow. GNAT can operate in three modes, and
27221 furthemore, permits separate selection of operating modes for
27222 the expressions within assertions (here the term ``assertions''
27223 is used in the technical sense, which includes preconditions and so forth)
27224 and for expressions appearing outside assertions.
27226 The three modes are:
27229 @item @i{Use base type for intermediate operations} (@code{STRICT})
27231 In this mode, all intermediate results for predefined arithmetic
27232 operators are computed using the base type, and the result must
27233 be in range of the base type. If this is not the
27234 case then either an exception is raised (if overflow checks are
27235 enabled) or the execution is erroneous (if overflow checks are suppressed).
27236 This is the normal default mode.
27238 @item @i{Most intermediate overflows avoided} (@code{MINIMIZED})
27240 In this mode, the compiler attempts to avoid intermediate overflows by
27241 using a larger integer type, typically @code{Long_Long_Integer},
27242 as the type in which arithmetic is
27243 performed for predefined arithmetic operators. This may be slightly more
27245 run time (compared to suppressing intermediate overflow checks), though
27246 the cost is negligible on modern 64-bit machines. For the examples given
27247 earlier, no intermediate overflows would have resulted in exceptions,
27248 since the intermediate results are all in the range of
27249 @code{Long_Long_Integer} (typically 64-bits on nearly all implementations
27250 of GNAT). In addition, if checks are enabled, this reduces the number of
27251 checks that must be made, so this choice may actually result in an
27252 improvement in space and time behavior.
27254 However, there are cases where @code{Long_Long_Integer} is not large
27255 enough, consider the following example:
27257 @smallexample @c ada
27258 procedure R (A, B, C, D : Integer) with
27259 Pre => (A**2 * B**2) / (C**2 * D**2) <= 10;
27262 where @code{A} = @code{B} = @code{C} = @code{D} = @code{Integer'Last}.
27263 Now the intermediate results are
27264 out of the range of @code{Long_Long_Integer} even though the final result
27265 is in range and the precondition is True (from a mathematical point
27266 of view). In such a case, operating in this mode, an overflow occurs
27267 for the intermediate computation (which is why this mode
27268 says @i{most} intermediate overflows are avoided). In this case,
27269 an exception is raised if overflow checks are enabled, and the
27270 execution is erroneous if overflow checks are suppressed.
27272 @item @i{All intermediate overflows avoided} (@code{ELIMINATED})
27274 In this mode, the compiler avoids all intermediate overflows
27275 by using arbitrary precision arithmetic as required. In this
27276 mode, the above example with @code{A**2 * B**2} would
27277 not cause intermediate overflow, because the intermediate result
27278 would be evaluated using sufficient precision, and the result
27279 of evaluating the precondition would be True.
27281 This mode has the advantage of avoiding any intermediate
27282 overflows, but at the expense of significant run-time overhead,
27283 including the use of a library (included automatically in this
27284 mode) for multiple-precision arithmetic.
27286 This mode provides cleaner semantics for assertions, since now
27287 the run-time behavior emulates true arithmetic behavior for the
27288 predefined arithmetic operators, meaning that there is never a
27289 conflict between the mathematical view of the assertion, and its
27292 Note that in this mode, the behavior is unaffected by whether or
27293 not overflow checks are suppressed, since overflow does not occur.
27294 It is possible for gigantic intermediate expressions to raise
27295 @code{Storage_Error} as a result of attempting to compute the
27296 results of such expressions (e.g. @code{Integer'Last ** Integer'Last})
27297 but overflow is impossible.
27303 Note that these modes apply only to the evaluation of predefined
27304 arithmetic, membership, and comparison operators for signed integer
27307 For fixed-point arithmetic, checks can be suppressed. But if checks
27309 then fixed-point values are always checked for overflow against the
27310 base type for intermediate expressions (that is such checks always
27311 operate in the equivalent of @code{STRICT} mode).
27313 For floating-point, on nearly all architectures, @code{Machine_Overflows}
27314 is False, and IEEE infinities are generated, so overflow exceptions
27315 are never raised. If you want to avoid infinities, and check that
27316 final results of expressions are in range, then you can declare a
27317 constrained floating-point type, and range checks will be carried
27318 out in the normal manner (with infinite values always failing all
27322 @c -------------------------
27323 @node Specifying the Desired Mode
27324 @section Specifying the Desired Mode
27327 The desired mode of for handling intermediate overflow can be specified using
27328 either the @code{Overflow_Mode} pragma or an equivalent compiler switch.
27329 The pragma has the form
27330 @cindex pragma @code{Overflow_Mode}
27332 @smallexample @c ada
27333 pragma Overflow_Mode ([General =>] MODE [, [Assertions =>] MODE]);
27337 where @code{MODE} is one of
27340 @item @code{STRICT}: intermediate overflows checked (using base type)
27341 @item @code{MINIMIZED}: minimize intermediate overflows
27342 @item @code{ELIMINATED}: eliminate intermediate overflows
27346 The case is ignored, so @code{MINIMIZED}, @code{Minimized} and
27347 @code{minimized} all have the same effect.
27349 If only the @code{General} parameter is present, then the given @code{MODE}
27351 to expressions both within and outside assertions. If both arguments
27352 are present, then @code{General} applies to expressions outside assertions,
27353 and @code{Assertions} applies to expressions within assertions. For example:
27355 @smallexample @c ada
27356 pragma Overflow_Mode
27357 (General => Minimized, Assertions => Eliminated);
27361 specifies that general expressions outside assertions be evaluated
27362 in ``minimize intermediate overflows'' mode, and expressions within
27363 assertions be evaluated in ``eliminate intermediate overflows'' mode.
27364 This is often a reasonable choice, avoiding excessive overhead
27365 outside assertions, but assuring a high degree of portability
27366 when importing code from another compiler, while incurring
27367 the extra overhead for assertion expressions to ensure that
27368 the behavior at run time matches the expected mathematical
27371 The @code{Overflow_Mode} pragma has the same scoping and placement
27372 rules as pragma @code{Suppress}, so it can occur either as a
27373 configuration pragma, specifying a default for the whole
27374 program, or in a declarative scope, where it applies to the
27375 remaining declarations and statements in that scope.
27377 Note that pragma @code{Overflow_Mode} does not affect whether
27378 overflow checks are enabled or suppressed. It only controls the
27379 method used to compute intermediate values. To control whether
27380 overflow checking is enabled or suppressed, use pragma @code{Suppress}
27381 or @code{Unsuppress} in the usual manner
27383 Additionally, a compiler switch @option{-gnato?} or @option{-gnato??}
27384 can be used to control the checking mode default (which can be subsequently
27385 overridden using pragmas).
27386 @cindex @option{-gnato?} (gcc)
27387 @cindex @option{-gnato??} (gcc)
27389 Here `@code{?}' is one of the digits `@code{1}' through `@code{3}':
27393 use base type for intermediate operations (@code{STRICT})
27395 minimize intermediate overflows (@code{MINIMIZED})
27397 eliminate intermediate overflows (@code{ELIMINATED})
27401 As with the pragma, if only one digit appears then it applies to all
27402 cases; if two digits are given, then the first applies outside
27403 assertions, and the second within assertions. Thus the equivalent
27404 of the example pragma above would be
27405 @option{^-gnato23^/OVERFLOW_CHECKS=23^}.
27407 If no digits follow the @option{-gnato}, then it is equivalent to
27408 @option{^-gnato11^/OVERFLOW_CHECKS=11^},
27409 causing all intermediate operations to be computed using the base
27410 type (@code{STRICT} mode).
27412 In addition to setting the mode used for computation of intermediate
27413 results, the @code{-gnato} switch also enables overflow checking (which
27414 is suppressed by default). It thus combines the effect of using
27415 a pragma @code{Overflow_Mode} and pragma @code{Unsuppress}.
27418 @c -------------------------
27419 @node Default Settings
27420 @section Default Settings
27422 The default mode for overflow checks is
27429 which causes all computations both inside and outside assertions to use
27430 the base type. In addition overflow checks are suppressed.
27432 This retains compatibility with previous versions of
27433 GNAT which suppressed overflow checks by default and always
27434 used the base type for computation of intermediate results.
27436 The switch @option{-gnato} (with no digits following) is equivalent to
27437 @cindex @option{-gnato} (gcc)
27444 which causes overflow checking of all intermediate overflows
27445 both inside and outside assertions against the base type.
27446 This provides compatibility
27447 with this switch as implemented in previous versions of GNAT.
27449 The pragma @code{Suppress (Overflow_Check)} disables overflow
27450 checking, but it has no effect on the method used for computing
27451 intermediate results.
27453 The pragma @code{Unsuppress (Overflow_Check)} enables overflow
27454 checking, but it has no effect on the method used for computing
27455 intermediate results.
27457 @c -------------------------
27458 @node Implementation Notes
27459 @section Implementation Notes
27461 In practice on typical 64-bit machines, the @code{MINIMIZED} mode is
27462 reasonably efficient, and can be generally used. It also helps
27463 to ensure compatibility with code imported from some other
27466 Setting all intermediate overflows checking (@code{CHECKED} mode)
27467 makes sense if you want to
27468 make sure that your code is compatible with any other possible
27469 Ada implementation. This may be useful in ensuring portability
27470 for code that is to be exported to some other compiler than GNAT.
27473 The Ada standard allows the reassociation of expressions at
27474 the same precedence level if no parentheses are present. For
27475 example, @w{@code{A+B+C}} parses as though it were @w{@code{(A+B)+C}}, but
27476 the compiler can reintepret this as @w{@code{A+(B+C)}}, possibly
27477 introducing or eliminating an overflow exception. The GNAT
27478 compiler never takes advantage of this freedom, and the
27479 expression @w{@code{A+B+C}} will be evaluated as @w{@code{(A+B)+C}}.
27480 If you need the other order, you can write the parentheses
27481 explicitly @w{@code{A+(B+C)}} and GNAT will respect this order.
27483 The use of @code{ELIMINATED} mode will cause the compiler to
27484 automatically include an appropriate arbitrary precision
27485 integer arithmetic package. The compiler will make calls
27486 to this package, though only in cases where it cannot be
27487 sure that @code{Long_Long_Integer} is sufficient to guard against
27488 intermediate overflows. This package does not use dynamic
27489 alllocation, but it does use the secondary stack, so an
27490 appropriate secondary stack package must be present (this
27491 is always true for standard full Ada, but may require
27492 specific steps for restricted run times such as ZFP).
27494 Although @code{ELIMINATED} mode causes expressions to use arbitrary
27495 precision arithmetic, avoiding overflow, the final result
27496 must be in an appropriate range. This is true even if the
27497 final result is of type @code{[Long_[Long_]]Integer'Base}, which
27498 still has the same bounds as its associated constrained
27501 Currently, the @code{ELIMINATED} mode is only available on target
27502 platforms for which @code{Long_Long_Integer} is 64-bits (nearly all GNAT
27505 @c *******************************
27506 @node Conditional Compilation
27507 @appendix Conditional Compilation
27508 @c *******************************
27509 @cindex Conditional compilation
27512 It is often necessary to arrange for a single source program
27513 to serve multiple purposes, where it is compiled in different
27514 ways to achieve these different goals. Some examples of the
27515 need for this feature are
27518 @item Adapting a program to a different hardware environment
27519 @item Adapting a program to a different target architecture
27520 @item Turning debugging features on and off
27521 @item Arranging for a program to compile with different compilers
27525 In C, or C++, the typical approach would be to use the preprocessor
27526 that is defined as part of the language. The Ada language does not
27527 contain such a feature. This is not an oversight, but rather a very
27528 deliberate design decision, based on the experience that overuse of
27529 the preprocessing features in C and C++ can result in programs that
27530 are extremely difficult to maintain. For example, if we have ten
27531 switches that can be on or off, this means that there are a thousand
27532 separate programs, any one of which might not even be syntactically
27533 correct, and even if syntactically correct, the resulting program
27534 might not work correctly. Testing all combinations can quickly become
27537 Nevertheless, the need to tailor programs certainly exists, and in
27538 this Appendix we will discuss how this can
27539 be achieved using Ada in general, and GNAT in particular.
27542 * Use of Boolean Constants::
27543 * Debugging - A Special Case::
27544 * Conditionalizing Declarations::
27545 * Use of Alternative Implementations::
27549 @node Use of Boolean Constants
27550 @section Use of Boolean Constants
27553 In the case where the difference is simply which code
27554 sequence is executed, the cleanest solution is to use Boolean
27555 constants to control which code is executed.
27557 @smallexample @c ada
27559 FP_Initialize_Required : constant Boolean := True;
27561 if FP_Initialize_Required then
27568 Not only will the code inside the @code{if} statement not be executed if
27569 the constant Boolean is @code{False}, but it will also be completely
27570 deleted from the program.
27571 However, the code is only deleted after the @code{if} statement
27572 has been checked for syntactic and semantic correctness.
27573 (In contrast, with preprocessors the code is deleted before the
27574 compiler ever gets to see it, so it is not checked until the switch
27576 @cindex Preprocessors (contrasted with conditional compilation)
27578 Typically the Boolean constants will be in a separate package,
27581 @smallexample @c ada
27584 FP_Initialize_Required : constant Boolean := True;
27585 Reset_Available : constant Boolean := False;
27592 The @code{Config} package exists in multiple forms for the various targets,
27593 with an appropriate script selecting the version of @code{Config} needed.
27594 Then any other unit requiring conditional compilation can do a @code{with}
27595 of @code{Config} to make the constants visible.
27598 @node Debugging - A Special Case
27599 @section Debugging - A Special Case
27602 A common use of conditional code is to execute statements (for example
27603 dynamic checks, or output of intermediate results) under control of a
27604 debug switch, so that the debugging behavior can be turned on and off.
27605 This can be done using a Boolean constant to control whether the code
27608 @smallexample @c ada
27611 Put_Line ("got to the first stage!");
27619 @smallexample @c ada
27621 if Debugging and then Temperature > 999.0 then
27622 raise Temperature_Crazy;
27628 Since this is a common case, there are special features to deal with
27629 this in a convenient manner. For the case of tests, Ada 2005 has added
27630 a pragma @code{Assert} that can be used for such tests. This pragma is modeled
27631 @cindex pragma @code{Assert}
27632 on the @code{Assert} pragma that has always been available in GNAT, so this
27633 feature may be used with GNAT even if you are not using Ada 2005 features.
27634 The use of pragma @code{Assert} is described in
27635 @ref{Pragma Assert,,, gnat_rm, GNAT Reference Manual}, but as an
27636 example, the last test could be written:
27638 @smallexample @c ada
27639 pragma Assert (Temperature <= 999.0, "Temperature Crazy");
27645 @smallexample @c ada
27646 pragma Assert (Temperature <= 999.0);
27650 In both cases, if assertions are active and the temperature is excessive,
27651 the exception @code{Assert_Failure} will be raised, with the given string in
27652 the first case or a string indicating the location of the pragma in the second
27653 case used as the exception message.
27655 You can turn assertions on and off by using the @code{Assertion_Policy}
27657 @cindex pragma @code{Assertion_Policy}
27658 This is an Ada 2005 pragma which is implemented in all modes by
27659 GNAT, but only in the latest versions of GNAT which include Ada 2005
27660 capability. Alternatively, you can use the @option{-gnata} switch
27661 @cindex @option{-gnata} switch
27662 to enable assertions from the command line (this is recognized by all versions
27665 For the example above with the @code{Put_Line}, the GNAT-specific pragma
27666 @code{Debug} can be used:
27667 @cindex pragma @code{Debug}
27669 @smallexample @c ada
27670 pragma Debug (Put_Line ("got to the first stage!"));
27674 If debug pragmas are enabled, the argument, which must be of the form of
27675 a procedure call, is executed (in this case, @code{Put_Line} will be called).
27676 Only one call can be present, but of course a special debugging procedure
27677 containing any code you like can be included in the program and then
27678 called in a pragma @code{Debug} argument as needed.
27680 One advantage of pragma @code{Debug} over the @code{if Debugging then}
27681 construct is that pragma @code{Debug} can appear in declarative contexts,
27682 such as at the very beginning of a procedure, before local declarations have
27685 Debug pragmas are enabled using either the @option{-gnata} switch that also
27686 controls assertions, or with a separate Debug_Policy pragma.
27687 @cindex pragma @code{Debug_Policy}
27688 The latter pragma is new in the Ada 2005 versions of GNAT (but it can be used
27689 in Ada 95 and Ada 83 programs as well), and is analogous to
27690 pragma @code{Assertion_Policy} to control assertions.
27692 @code{Assertion_Policy} and @code{Debug_Policy} are configuration pragmas,
27693 and thus they can appear in @file{gnat.adc} if you are not using a
27694 project file, or in the file designated to contain configuration pragmas
27696 They then apply to all subsequent compilations. In practice the use of
27697 the @option{-gnata} switch is often the most convenient method of controlling
27698 the status of these pragmas.
27700 Note that a pragma is not a statement, so in contexts where a statement
27701 sequence is required, you can't just write a pragma on its own. You have
27702 to add a @code{null} statement.
27704 @smallexample @c ada
27707 @dots{} -- some statements
27709 pragma Assert (Num_Cases < 10);
27716 @node Conditionalizing Declarations
27717 @section Conditionalizing Declarations
27720 In some cases, it may be necessary to conditionalize declarations to meet
27721 different requirements. For example we might want a bit string whose length
27722 is set to meet some hardware message requirement.
27724 In some cases, it may be possible to do this using declare blocks controlled
27725 by conditional constants:
27727 @smallexample @c ada
27729 if Small_Machine then
27731 X : Bit_String (1 .. 10);
27737 X : Large_Bit_String (1 .. 1000);
27746 Note that in this approach, both declarations are analyzed by the
27747 compiler so this can only be used where both declarations are legal,
27748 even though one of them will not be used.
27750 Another approach is to define integer constants, e.g.@: @code{Bits_Per_Word},
27751 or Boolean constants, e.g.@: @code{Little_Endian}, and then write declarations
27752 that are parameterized by these constants. For example
27754 @smallexample @c ada
27757 Field1 at 0 range Boolean'Pos (Little_Endian) * 10 .. Bits_Per_Word;
27763 If @code{Bits_Per_Word} is set to 32, this generates either
27765 @smallexample @c ada
27768 Field1 at 0 range 0 .. 32;
27774 for the big endian case, or
27776 @smallexample @c ada
27779 Field1 at 0 range 10 .. 32;
27785 for the little endian case. Since a powerful subset of Ada expression
27786 notation is usable for creating static constants, clever use of this
27787 feature can often solve quite difficult problems in conditionalizing
27788 compilation (note incidentally that in Ada 95, the little endian
27789 constant was introduced as @code{System.Default_Bit_Order}, so you do not
27790 need to define this one yourself).
27793 @node Use of Alternative Implementations
27794 @section Use of Alternative Implementations
27797 In some cases, none of the approaches described above are adequate. This
27798 can occur for example if the set of declarations required is radically
27799 different for two different configurations.
27801 In this situation, the official Ada way of dealing with conditionalizing
27802 such code is to write separate units for the different cases. As long as
27803 this does not result in excessive duplication of code, this can be done
27804 without creating maintenance problems. The approach is to share common
27805 code as far as possible, and then isolate the code and declarations
27806 that are different. Subunits are often a convenient method for breaking
27807 out a piece of a unit that is to be conditionalized, with separate files
27808 for different versions of the subunit for different targets, where the
27809 build script selects the right one to give to the compiler.
27810 @cindex Subunits (and conditional compilation)
27812 As an example, consider a situation where a new feature in Ada 2005
27813 allows something to be done in a really nice way. But your code must be able
27814 to compile with an Ada 95 compiler. Conceptually you want to say:
27816 @smallexample @c ada
27819 @dots{} neat Ada 2005 code
27821 @dots{} not quite as neat Ada 95 code
27827 where @code{Ada_2005} is a Boolean constant.
27829 But this won't work when @code{Ada_2005} is set to @code{False},
27830 since the @code{then} clause will be illegal for an Ada 95 compiler.
27831 (Recall that although such unreachable code would eventually be deleted
27832 by the compiler, it still needs to be legal. If it uses features
27833 introduced in Ada 2005, it will be illegal in Ada 95.)
27835 So instead we write
27837 @smallexample @c ada
27838 procedure Insert is separate;
27842 Then we have two files for the subunit @code{Insert}, with the two sets of
27844 If the package containing this is called @code{File_Queries}, then we might
27848 @item @file{file_queries-insert-2005.adb}
27849 @item @file{file_queries-insert-95.adb}
27853 and the build script renames the appropriate file to
27856 file_queries-insert.adb
27860 and then carries out the compilation.
27862 This can also be done with project files' naming schemes. For example:
27864 @smallexample @c project
27865 For Body ("File_Queries.Insert") use "file_queries-insert-2005.ada";
27869 Note also that with project files it is desirable to use a different extension
27870 than @file{ads} / @file{adb} for alternative versions. Otherwise a naming
27871 conflict may arise through another commonly used feature: to declare as part
27872 of the project a set of directories containing all the sources obeying the
27873 default naming scheme.
27875 The use of alternative units is certainly feasible in all situations,
27876 and for example the Ada part of the GNAT run-time is conditionalized
27877 based on the target architecture using this approach. As a specific example,
27878 consider the implementation of the AST feature in VMS. There is one
27886 which is the same for all architectures, and three bodies:
27890 used for all non-VMS operating systems
27891 @item s-asthan-vms-alpha.adb
27892 used for VMS on the Alpha
27893 @item s-asthan-vms-ia64.adb
27894 used for VMS on the ia64
27898 The dummy version @file{s-asthan.adb} simply raises exceptions noting that
27899 this operating system feature is not available, and the two remaining
27900 versions interface with the corresponding versions of VMS to provide
27901 VMS-compatible AST handling. The GNAT build script knows the architecture
27902 and operating system, and automatically selects the right version,
27903 renaming it if necessary to @file{s-asthan.adb} before the run-time build.
27905 Another style for arranging alternative implementations is through Ada's
27906 access-to-subprogram facility.
27907 In case some functionality is to be conditionally included,
27908 you can declare an access-to-procedure variable @code{Ref} that is initialized
27909 to designate a ``do nothing'' procedure, and then invoke @code{Ref.all}
27911 In some library package, set @code{Ref} to @code{Proc'Access} for some
27912 procedure @code{Proc} that performs the relevant processing.
27913 The initialization only occurs if the library package is included in the
27915 The same idea can also be implemented using tagged types and dispatching
27919 @node Preprocessing
27920 @section Preprocessing
27921 @cindex Preprocessing
27924 Although it is quite possible to conditionalize code without the use of
27925 C-style preprocessing, as described earlier in this section, it is
27926 nevertheless convenient in some cases to use the C approach. Moreover,
27927 older Ada compilers have often provided some preprocessing capability,
27928 so legacy code may depend on this approach, even though it is not
27931 To accommodate such use, GNAT provides a preprocessor (modeled to a large
27932 extent on the various preprocessors that have been used
27933 with legacy code on other compilers, to enable easier transition).
27935 The preprocessor may be used in two separate modes. It can be used quite
27936 separately from the compiler, to generate a separate output source file
27937 that is then fed to the compiler as a separate step. This is the
27938 @code{gnatprep} utility, whose use is fully described in
27939 @ref{Preprocessing with gnatprep}.
27940 @cindex @code{gnatprep}
27942 The preprocessing language allows such constructs as
27946 #if DEBUG or else (PRIORITY > 4) then
27947 bunch of declarations
27949 completely different bunch of declarations
27955 The values of the symbols @code{DEBUG} and @code{PRIORITY} can be
27956 defined either on the command line or in a separate file.
27958 The other way of running the preprocessor is even closer to the C style and
27959 often more convenient. In this approach the preprocessing is integrated into
27960 the compilation process. The compiler is fed the preprocessor input which
27961 includes @code{#if} lines etc, and then the compiler carries out the
27962 preprocessing internally and processes the resulting output.
27963 For more details on this approach, see @ref{Integrated Preprocessing}.
27966 @c *******************************
27967 @node Inline Assembler
27968 @appendix Inline Assembler
27969 @c *******************************
27972 If you need to write low-level software that interacts directly
27973 with the hardware, Ada provides two ways to incorporate assembly
27974 language code into your program. First, you can import and invoke
27975 external routines written in assembly language, an Ada feature fully
27976 supported by GNAT@. However, for small sections of code it may be simpler
27977 or more efficient to include assembly language statements directly
27978 in your Ada source program, using the facilities of the implementation-defined
27979 package @code{System.Machine_Code}, which incorporates the gcc
27980 Inline Assembler. The Inline Assembler approach offers a number of advantages,
27981 including the following:
27984 @item No need to use non-Ada tools
27985 @item Consistent interface over different targets
27986 @item Automatic usage of the proper calling conventions
27987 @item Access to Ada constants and variables
27988 @item Definition of intrinsic routines
27989 @item Possibility of inlining a subprogram comprising assembler code
27990 @item Code optimizer can take Inline Assembler code into account
27993 This chapter presents a series of examples to show you how to use
27994 the Inline Assembler. Although it focuses on the Intel x86,
27995 the general approach applies also to other processors.
27996 It is assumed that you are familiar with Ada
27997 and with assembly language programming.
28000 * Basic Assembler Syntax::
28001 * A Simple Example of Inline Assembler::
28002 * Output Variables in Inline Assembler::
28003 * Input Variables in Inline Assembler::
28004 * Inlining Inline Assembler Code::
28005 * Other Asm Functionality::
28008 @c ---------------------------------------------------------------------------
28009 @node Basic Assembler Syntax
28010 @section Basic Assembler Syntax
28013 The assembler used by GNAT and gcc is based not on the Intel assembly
28014 language, but rather on a language that descends from the AT&T Unix
28015 assembler @emph{as} (and which is often referred to as ``AT&T syntax'').
28016 The following table summarizes the main features of @emph{as} syntax
28017 and points out the differences from the Intel conventions.
28018 See the gcc @emph{as} and @emph{gas} (an @emph{as} macro
28019 pre-processor) documentation for further information.
28022 @item Register names
28023 gcc / @emph{as}: Prefix with ``%''; for example @code{%eax}
28025 Intel: No extra punctuation; for example @code{eax}
28027 @item Immediate operand
28028 gcc / @emph{as}: Prefix with ``$''; for example @code{$4}
28030 Intel: No extra punctuation; for example @code{4}
28033 gcc / @emph{as}: Prefix with ``$''; for example @code{$loc}
28035 Intel: No extra punctuation; for example @code{loc}
28037 @item Memory contents
28038 gcc / @emph{as}: No extra punctuation; for example @code{loc}
28040 Intel: Square brackets; for example @code{[loc]}
28042 @item Register contents
28043 gcc / @emph{as}: Parentheses; for example @code{(%eax)}
28045 Intel: Square brackets; for example @code{[eax]}
28047 @item Hexadecimal numbers
28048 gcc / @emph{as}: Leading ``0x'' (C language syntax); for example @code{0xA0}
28050 Intel: Trailing ``h''; for example @code{A0h}
28053 gcc / @emph{as}: Explicit in op code; for example @code{movw} to move
28056 Intel: Implicit, deduced by assembler; for example @code{mov}
28058 @item Instruction repetition
28059 gcc / @emph{as}: Split into two lines; for example
28065 Intel: Keep on one line; for example @code{rep stosl}
28067 @item Order of operands
28068 gcc / @emph{as}: Source first; for example @code{movw $4, %eax}
28070 Intel: Destination first; for example @code{mov eax, 4}
28073 @c ---------------------------------------------------------------------------
28074 @node A Simple Example of Inline Assembler
28075 @section A Simple Example of Inline Assembler
28078 The following example will generate a single assembly language statement,
28079 @code{nop}, which does nothing. Despite its lack of run-time effect,
28080 the example will be useful in illustrating the basics of
28081 the Inline Assembler facility.
28083 @smallexample @c ada
28085 with System.Machine_Code; use System.Machine_Code;
28086 procedure Nothing is
28093 @code{Asm} is a procedure declared in package @code{System.Machine_Code};
28094 here it takes one parameter, a @emph{template string} that must be a static
28095 expression and that will form the generated instruction.
28096 @code{Asm} may be regarded as a compile-time procedure that parses
28097 the template string and additional parameters (none here),
28098 from which it generates a sequence of assembly language instructions.
28100 The examples in this chapter will illustrate several of the forms
28101 for invoking @code{Asm}; a complete specification of the syntax
28102 is found in @ref{Machine Code Insertions,,, gnat_rm, GNAT Reference
28105 Under the standard GNAT conventions, the @code{Nothing} procedure
28106 should be in a file named @file{nothing.adb}.
28107 You can build the executable in the usual way:
28111 However, the interesting aspect of this example is not its run-time behavior
28112 but rather the generated assembly code.
28113 To see this output, invoke the compiler as follows:
28115 gcc -c -S -fomit-frame-pointer -gnatp @file{nothing.adb}
28117 where the options are:
28121 compile only (no bind or link)
28123 generate assembler listing
28124 @item -fomit-frame-pointer
28125 do not set up separate stack frames
28127 do not add runtime checks
28130 This gives a human-readable assembler version of the code. The resulting
28131 file will have the same name as the Ada source file, but with a @code{.s}
28132 extension. In our example, the file @file{nothing.s} has the following
28137 .file "nothing.adb"
28139 ___gnu_compiled_ada:
28142 .globl __ada_nothing
28154 The assembly code you included is clearly indicated by
28155 the compiler, between the @code{#APP} and @code{#NO_APP}
28156 delimiters. The character before the 'APP' and 'NOAPP'
28157 can differ on different targets. For example, GNU/Linux uses '#APP' while
28158 on NT you will see '/APP'.
28160 If you make a mistake in your assembler code (such as using the
28161 wrong size modifier, or using a wrong operand for the instruction) GNAT
28162 will report this error in a temporary file, which will be deleted when
28163 the compilation is finished. Generating an assembler file will help
28164 in such cases, since you can assemble this file separately using the
28165 @emph{as} assembler that comes with gcc.
28167 Assembling the file using the command
28170 as @file{nothing.s}
28173 will give you error messages whose lines correspond to the assembler
28174 input file, so you can easily find and correct any mistakes you made.
28175 If there are no errors, @emph{as} will generate an object file
28176 @file{nothing.out}.
28178 @c ---------------------------------------------------------------------------
28179 @node Output Variables in Inline Assembler
28180 @section Output Variables in Inline Assembler
28183 The examples in this section, showing how to access the processor flags,
28184 illustrate how to specify the destination operands for assembly language
28187 @smallexample @c ada
28189 with Interfaces; use Interfaces;
28190 with Ada.Text_IO; use Ada.Text_IO;
28191 with System.Machine_Code; use System.Machine_Code;
28192 procedure Get_Flags is
28193 Flags : Unsigned_32;
28196 Asm ("pushfl" & LF & HT & -- push flags on stack
28197 "popl %%eax" & LF & HT & -- load eax with flags
28198 "movl %%eax, %0", -- store flags in variable
28199 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
28200 Put_Line ("Flags register:" & Flags'Img);
28205 In order to have a nicely aligned assembly listing, we have separated
28206 multiple assembler statements in the Asm template string with linefeed
28207 (ASCII.LF) and horizontal tab (ASCII.HT) characters.
28208 The resulting section of the assembly output file is:
28215 movl %eax, -40(%ebp)
28220 It would have been legal to write the Asm invocation as:
28223 Asm ("pushfl popl %%eax movl %%eax, %0")
28226 but in the generated assembler file, this would come out as:
28230 pushfl popl %eax movl %eax, -40(%ebp)
28234 which is not so convenient for the human reader.
28236 We use Ada comments
28237 at the end of each line to explain what the assembler instructions
28238 actually do. This is a useful convention.
28240 When writing Inline Assembler instructions, you need to precede each register
28241 and variable name with a percent sign. Since the assembler already requires
28242 a percent sign at the beginning of a register name, you need two consecutive
28243 percent signs for such names in the Asm template string, thus @code{%%eax}.
28244 In the generated assembly code, one of the percent signs will be stripped off.
28246 Names such as @code{%0}, @code{%1}, @code{%2}, etc., denote input or output
28247 variables: operands you later define using @code{Input} or @code{Output}
28248 parameters to @code{Asm}.
28249 An output variable is illustrated in
28250 the third statement in the Asm template string:
28254 The intent is to store the contents of the eax register in a variable that can
28255 be accessed in Ada. Simply writing @code{movl %%eax, Flags} would not
28256 necessarily work, since the compiler might optimize by using a register
28257 to hold Flags, and the expansion of the @code{movl} instruction would not be
28258 aware of this optimization. The solution is not to store the result directly
28259 but rather to advise the compiler to choose the correct operand form;
28260 that is the purpose of the @code{%0} output variable.
28262 Information about the output variable is supplied in the @code{Outputs}
28263 parameter to @code{Asm}:
28265 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
28268 The output is defined by the @code{Asm_Output} attribute of the target type;
28269 the general format is
28271 Type'Asm_Output (constraint_string, variable_name)
28274 The constraint string directs the compiler how
28275 to store/access the associated variable. In the example
28277 Unsigned_32'Asm_Output ("=m", Flags);
28279 the @code{"m"} (memory) constraint tells the compiler that the variable
28280 @code{Flags} should be stored in a memory variable, thus preventing
28281 the optimizer from keeping it in a register. In contrast,
28283 Unsigned_32'Asm_Output ("=r", Flags);
28285 uses the @code{"r"} (register) constraint, telling the compiler to
28286 store the variable in a register.
28288 If the constraint is preceded by the equal character (@strong{=}), it tells
28289 the compiler that the variable will be used to store data into it.
28291 In the @code{Get_Flags} example, we used the @code{"g"} (global) constraint,
28292 allowing the optimizer to choose whatever it deems best.
28294 There are a fairly large number of constraints, but the ones that are
28295 most useful (for the Intel x86 processor) are the following:
28301 global (i.e.@: can be stored anywhere)
28319 use one of eax, ebx, ecx or edx
28321 use one of eax, ebx, ecx, edx, esi or edi
28324 The full set of constraints is described in the gcc and @emph{as}
28325 documentation; note that it is possible to combine certain constraints
28326 in one constraint string.
28328 You specify the association of an output variable with an assembler operand
28329 through the @code{%}@emph{n} notation, where @emph{n} is a non-negative
28331 @smallexample @c ada
28333 Asm ("pushfl" & LF & HT & -- push flags on stack
28334 "popl %%eax" & LF & HT & -- load eax with flags
28335 "movl %%eax, %0", -- store flags in variable
28336 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
28340 @code{%0} will be replaced in the expanded code by the appropriate operand,
28342 the compiler decided for the @code{Flags} variable.
28344 In general, you may have any number of output variables:
28347 Count the operands starting at 0; thus @code{%0}, @code{%1}, etc.
28349 Specify the @code{Outputs} parameter as a parenthesized comma-separated list
28350 of @code{Asm_Output} attributes
28354 @smallexample @c ada
28356 Asm ("movl %%eax, %0" & LF & HT &
28357 "movl %%ebx, %1" & LF & HT &
28359 Outputs => (Unsigned_32'Asm_Output ("=g", Var_A), -- %0 = Var_A
28360 Unsigned_32'Asm_Output ("=g", Var_B), -- %1 = Var_B
28361 Unsigned_32'Asm_Output ("=g", Var_C))); -- %2 = Var_C
28365 where @code{Var_A}, @code{Var_B}, and @code{Var_C} are variables
28366 in the Ada program.
28368 As a variation on the @code{Get_Flags} example, we can use the constraints
28369 string to direct the compiler to store the eax register into the @code{Flags}
28370 variable, instead of including the store instruction explicitly in the
28371 @code{Asm} template string:
28373 @smallexample @c ada
28375 with Interfaces; use Interfaces;
28376 with Ada.Text_IO; use Ada.Text_IO;
28377 with System.Machine_Code; use System.Machine_Code;
28378 procedure Get_Flags_2 is
28379 Flags : Unsigned_32;
28382 Asm ("pushfl" & LF & HT & -- push flags on stack
28383 "popl %%eax", -- save flags in eax
28384 Outputs => Unsigned_32'Asm_Output ("=a", Flags));
28385 Put_Line ("Flags register:" & Flags'Img);
28391 The @code{"a"} constraint tells the compiler that the @code{Flags}
28392 variable will come from the eax register. Here is the resulting code:
28400 movl %eax,-40(%ebp)
28405 The compiler generated the store of eax into Flags after
28406 expanding the assembler code.
28408 Actually, there was no need to pop the flags into the eax register;
28409 more simply, we could just pop the flags directly into the program variable:
28411 @smallexample @c ada
28413 with Interfaces; use Interfaces;
28414 with Ada.Text_IO; use Ada.Text_IO;
28415 with System.Machine_Code; use System.Machine_Code;
28416 procedure Get_Flags_3 is
28417 Flags : Unsigned_32;
28420 Asm ("pushfl" & LF & HT & -- push flags on stack
28421 "pop %0", -- save flags in Flags
28422 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
28423 Put_Line ("Flags register:" & Flags'Img);
28428 @c ---------------------------------------------------------------------------
28429 @node Input Variables in Inline Assembler
28430 @section Input Variables in Inline Assembler
28433 The example in this section illustrates how to specify the source operands
28434 for assembly language statements.
28435 The program simply increments its input value by 1:
28437 @smallexample @c ada
28439 with Interfaces; use Interfaces;
28440 with Ada.Text_IO; use Ada.Text_IO;
28441 with System.Machine_Code; use System.Machine_Code;
28442 procedure Increment is
28444 function Incr (Value : Unsigned_32) return Unsigned_32 is
28445 Result : Unsigned_32;
28448 Outputs => Unsigned_32'Asm_Output ("=a", Result),
28449 Inputs => Unsigned_32'Asm_Input ("a", Value));
28453 Value : Unsigned_32;
28457 Put_Line ("Value before is" & Value'Img);
28458 Value := Incr (Value);
28459 Put_Line ("Value after is" & Value'Img);
28464 The @code{Outputs} parameter to @code{Asm} specifies
28465 that the result will be in the eax register and that it is to be stored
28466 in the @code{Result} variable.
28468 The @code{Inputs} parameter looks much like the @code{Outputs} parameter,
28469 but with an @code{Asm_Input} attribute.
28470 The @code{"="} constraint, indicating an output value, is not present.
28472 You can have multiple input variables, in the same way that you can have more
28473 than one output variable.
28475 The parameter count (%0, %1) etc, still starts at the first output statement,
28476 and continues with the input statements.
28478 Just as the @code{Outputs} parameter causes the register to be stored into the
28479 target variable after execution of the assembler statements, so does the
28480 @code{Inputs} parameter cause its variable to be loaded into the register
28481 before execution of the assembler statements.
28483 Thus the effect of the @code{Asm} invocation is:
28485 @item load the 32-bit value of @code{Value} into eax
28486 @item execute the @code{incl %eax} instruction
28487 @item store the contents of eax into the @code{Result} variable
28490 The resulting assembler file (with @option{-O2} optimization) contains:
28493 _increment__incr.1:
28506 @c ---------------------------------------------------------------------------
28507 @node Inlining Inline Assembler Code
28508 @section Inlining Inline Assembler Code
28511 For a short subprogram such as the @code{Incr} function in the previous
28512 section, the overhead of the call and return (creating / deleting the stack
28513 frame) can be significant, compared to the amount of code in the subprogram
28514 body. A solution is to apply Ada's @code{Inline} pragma to the subprogram,
28515 which directs the compiler to expand invocations of the subprogram at the
28516 point(s) of call, instead of setting up a stack frame for out-of-line calls.
28517 Here is the resulting program:
28519 @smallexample @c ada
28521 with Interfaces; use Interfaces;
28522 with Ada.Text_IO; use Ada.Text_IO;
28523 with System.Machine_Code; use System.Machine_Code;
28524 procedure Increment_2 is
28526 function Incr (Value : Unsigned_32) return Unsigned_32 is
28527 Result : Unsigned_32;
28530 Outputs => Unsigned_32'Asm_Output ("=a", Result),
28531 Inputs => Unsigned_32'Asm_Input ("a", Value));
28534 pragma Inline (Increment);
28536 Value : Unsigned_32;
28540 Put_Line ("Value before is" & Value'Img);
28541 Value := Increment (Value);
28542 Put_Line ("Value after is" & Value'Img);
28547 Compile the program with both optimization (@option{-O2}) and inlining
28548 (@option{-gnatn}) enabled.
28550 The @code{Incr} function is still compiled as usual, but at the
28551 point in @code{Increment} where our function used to be called:
28556 call _increment__incr.1
28561 the code for the function body directly appears:
28574 thus saving the overhead of stack frame setup and an out-of-line call.
28576 @c ---------------------------------------------------------------------------
28577 @node Other Asm Functionality
28578 @section Other @code{Asm} Functionality
28581 This section describes two important parameters to the @code{Asm}
28582 procedure: @code{Clobber}, which identifies register usage;
28583 and @code{Volatile}, which inhibits unwanted optimizations.
28586 * The Clobber Parameter::
28587 * The Volatile Parameter::
28590 @c ---------------------------------------------------------------------------
28591 @node The Clobber Parameter
28592 @subsection The @code{Clobber} Parameter
28595 One of the dangers of intermixing assembly language and a compiled language
28596 such as Ada is that the compiler needs to be aware of which registers are
28597 being used by the assembly code. In some cases, such as the earlier examples,
28598 the constraint string is sufficient to indicate register usage (e.g.,
28600 the eax register). But more generally, the compiler needs an explicit
28601 identification of the registers that are used by the Inline Assembly
28604 Using a register that the compiler doesn't know about
28605 could be a side effect of an instruction (like @code{mull}
28606 storing its result in both eax and edx).
28607 It can also arise from explicit register usage in your
28608 assembly code; for example:
28611 Asm ("movl %0, %%ebx" & LF & HT &
28613 Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
28614 Inputs => Unsigned_32'Asm_Input ("g", Var_In));
28618 where the compiler (since it does not analyze the @code{Asm} template string)
28619 does not know you are using the ebx register.
28621 In such cases you need to supply the @code{Clobber} parameter to @code{Asm},
28622 to identify the registers that will be used by your assembly code:
28626 Asm ("movl %0, %%ebx" & LF & HT &
28628 Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
28629 Inputs => Unsigned_32'Asm_Input ("g", Var_In),
28634 The Clobber parameter is a static string expression specifying the
28635 register(s) you are using. Note that register names are @emph{not} prefixed
28636 by a percent sign. Also, if more than one register is used then their names
28637 are separated by commas; e.g., @code{"eax, ebx"}
28639 The @code{Clobber} parameter has several additional uses:
28641 @item Use ``register'' name @code{cc} to indicate that flags might have changed
28642 @item Use ``register'' name @code{memory} if you changed a memory location
28645 @c ---------------------------------------------------------------------------
28646 @node The Volatile Parameter
28647 @subsection The @code{Volatile} Parameter
28648 @cindex Volatile parameter
28651 Compiler optimizations in the presence of Inline Assembler may sometimes have
28652 unwanted effects. For example, when an @code{Asm} invocation with an input
28653 variable is inside a loop, the compiler might move the loading of the input
28654 variable outside the loop, regarding it as a one-time initialization.
28656 If this effect is not desired, you can disable such optimizations by setting
28657 the @code{Volatile} parameter to @code{True}; for example:
28659 @smallexample @c ada
28661 Asm ("movl %0, %%ebx" & LF & HT &
28663 Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
28664 Inputs => Unsigned_32'Asm_Input ("g", Var_In),
28670 By default, @code{Volatile} is set to @code{False} unless there is no
28671 @code{Outputs} parameter.
28673 Although setting @code{Volatile} to @code{True} prevents unwanted
28674 optimizations, it will also disable other optimizations that might be
28675 important for efficiency. In general, you should set @code{Volatile}
28676 to @code{True} only if the compiler's optimizations have created
28678 @c END OF INLINE ASSEMBLER CHAPTER
28679 @c ===============================
28681 @c ***********************************
28682 @c * Compatibility and Porting Guide *
28683 @c ***********************************
28684 @node Compatibility and Porting Guide
28685 @appendix Compatibility and Porting Guide
28688 This chapter describes the compatibility issues that may arise between
28689 GNAT and other Ada compilation systems (including those for Ada 83),
28690 and shows how GNAT can expedite porting
28691 applications developed in other Ada environments.
28694 * Compatibility with Ada 83::
28695 * Compatibility between Ada 95 and Ada 2005::
28696 * Implementation-dependent characteristics::
28697 * Compatibility with Other Ada Systems::
28698 * Representation Clauses::
28700 @c Brief section is only in non-VMS version
28701 @c Full chapter is in VMS version
28702 * Compatibility with HP Ada 83::
28705 * Transitioning to 64-Bit GNAT for OpenVMS::
28709 @node Compatibility with Ada 83
28710 @section Compatibility with Ada 83
28711 @cindex Compatibility (between Ada 83 and Ada 95 / Ada 2005)
28714 Ada 95 and Ada 2005 are highly upwards compatible with Ada 83. In
28715 particular, the design intention was that the difficulties associated
28716 with moving from Ada 83 to Ada 95 or Ada 2005 should be no greater than those
28717 that occur when moving from one Ada 83 system to another.
28719 However, there are a number of points at which there are minor
28720 incompatibilities. The @cite{Ada 95 Annotated Reference Manual} contains
28721 full details of these issues,
28722 and should be consulted for a complete treatment.
28724 following subsections treat the most likely issues to be encountered.
28727 * Legal Ada 83 programs that are illegal in Ada 95::
28728 * More deterministic semantics::
28729 * Changed semantics::
28730 * Other language compatibility issues::
28733 @node Legal Ada 83 programs that are illegal in Ada 95
28734 @subsection Legal Ada 83 programs that are illegal in Ada 95
28736 Some legal Ada 83 programs are illegal (i.e., they will fail to compile) in
28737 Ada 95 and thus also in Ada 2005:
28740 @item Character literals
28741 Some uses of character literals are ambiguous. Since Ada 95 has introduced
28742 @code{Wide_Character} as a new predefined character type, some uses of
28743 character literals that were legal in Ada 83 are illegal in Ada 95.
28745 @smallexample @c ada
28746 for Char in 'A' .. 'Z' loop @dots{} end loop;
28750 The problem is that @code{'A'} and @code{'Z'} could be from either
28751 @code{Character} or @code{Wide_Character}. The simplest correction
28752 is to make the type explicit; e.g.:
28753 @smallexample @c ada
28754 for Char in Character range 'A' .. 'Z' loop @dots{} end loop;
28757 @item New reserved words
28758 The identifiers @code{abstract}, @code{aliased}, @code{protected},
28759 @code{requeue}, @code{tagged}, and @code{until} are reserved in Ada 95.
28760 Existing Ada 83 code using any of these identifiers must be edited to
28761 use some alternative name.
28763 @item Freezing rules
28764 The rules in Ada 95 are slightly different with regard to the point at
28765 which entities are frozen, and representation pragmas and clauses are
28766 not permitted past the freeze point. This shows up most typically in
28767 the form of an error message complaining that a representation item
28768 appears too late, and the appropriate corrective action is to move
28769 the item nearer to the declaration of the entity to which it refers.
28771 A particular case is that representation pragmas
28774 extended HP Ada 83 compatibility pragmas such as @code{Export_Procedure})
28776 cannot be applied to a subprogram body. If necessary, a separate subprogram
28777 declaration must be introduced to which the pragma can be applied.
28779 @item Optional bodies for library packages
28780 In Ada 83, a package that did not require a package body was nevertheless
28781 allowed to have one. This lead to certain surprises in compiling large
28782 systems (situations in which the body could be unexpectedly ignored by the
28783 binder). In Ada 95, if a package does not require a body then it is not
28784 permitted to have a body. To fix this problem, simply remove a redundant
28785 body if it is empty, or, if it is non-empty, introduce a dummy declaration
28786 into the spec that makes the body required. One approach is to add a private
28787 part to the package declaration (if necessary), and define a parameterless
28788 procedure called @code{Requires_Body}, which must then be given a dummy
28789 procedure body in the package body, which then becomes required.
28790 Another approach (assuming that this does not introduce elaboration
28791 circularities) is to add an @code{Elaborate_Body} pragma to the package spec,
28792 since one effect of this pragma is to require the presence of a package body.
28794 @item @code{Numeric_Error} is now the same as @code{Constraint_Error}
28795 In Ada 95, the exception @code{Numeric_Error} is a renaming of
28796 @code{Constraint_Error}.
28797 This means that it is illegal to have separate exception handlers for
28798 the two exceptions. The fix is simply to remove the handler for the
28799 @code{Numeric_Error} case (since even in Ada 83, a compiler was free to raise
28800 @code{Constraint_Error} in place of @code{Numeric_Error} in all cases).
28802 @item Indefinite subtypes in generics
28803 In Ada 83, it was permissible to pass an indefinite type (e.g.@: @code{String})
28804 as the actual for a generic formal private type, but then the instantiation
28805 would be illegal if there were any instances of declarations of variables
28806 of this type in the generic body. In Ada 95, to avoid this clear violation
28807 of the methodological principle known as the ``contract model'',
28808 the generic declaration explicitly indicates whether
28809 or not such instantiations are permitted. If a generic formal parameter
28810 has explicit unknown discriminants, indicated by using @code{(<>)} after the
28811 subtype name, then it can be instantiated with indefinite types, but no
28812 stand-alone variables can be declared of this type. Any attempt to declare
28813 such a variable will result in an illegality at the time the generic is
28814 declared. If the @code{(<>)} notation is not used, then it is illegal
28815 to instantiate the generic with an indefinite type.
28816 This is the potential incompatibility issue when porting Ada 83 code to Ada 95.
28817 It will show up as a compile time error, and
28818 the fix is usually simply to add the @code{(<>)} to the generic declaration.
28821 @node More deterministic semantics
28822 @subsection More deterministic semantics
28826 Conversions from real types to integer types round away from 0. In Ada 83
28827 the conversion Integer(2.5) could deliver either 2 or 3 as its value. This
28828 implementation freedom was intended to support unbiased rounding in
28829 statistical applications, but in practice it interfered with portability.
28830 In Ada 95 the conversion semantics are unambiguous, and rounding away from 0
28831 is required. Numeric code may be affected by this change in semantics.
28832 Note, though, that this issue is no worse than already existed in Ada 83
28833 when porting code from one vendor to another.
28836 The Real-Time Annex introduces a set of policies that define the behavior of
28837 features that were implementation dependent in Ada 83, such as the order in
28838 which open select branches are executed.
28841 @node Changed semantics
28842 @subsection Changed semantics
28845 The worst kind of incompatibility is one where a program that is legal in
28846 Ada 83 is also legal in Ada 95 but can have an effect in Ada 95 that was not
28847 possible in Ada 83. Fortunately this is extremely rare, but the one
28848 situation that you should be alert to is the change in the predefined type
28849 @code{Character} from 7-bit ASCII to 8-bit Latin-1.
28852 @item Range of type @code{Character}
28853 The range of @code{Standard.Character} is now the full 256 characters
28854 of Latin-1, whereas in most Ada 83 implementations it was restricted
28855 to 128 characters. Although some of the effects of
28856 this change will be manifest in compile-time rejection of legal
28857 Ada 83 programs it is possible for a working Ada 83 program to have
28858 a different effect in Ada 95, one that was not permitted in Ada 83.
28859 As an example, the expression
28860 @code{Character'Pos(Character'Last)} returned @code{127} in Ada 83 and now
28861 delivers @code{255} as its value.
28862 In general, you should look at the logic of any
28863 character-processing Ada 83 program and see whether it needs to be adapted
28864 to work correctly with Latin-1. Note that the predefined Ada 95 API has a
28865 character handling package that may be relevant if code needs to be adapted
28866 to account for the additional Latin-1 elements.
28867 The desirable fix is to
28868 modify the program to accommodate the full character set, but in some cases
28869 it may be convenient to define a subtype or derived type of Character that
28870 covers only the restricted range.
28874 @node Other language compatibility issues
28875 @subsection Other language compatibility issues
28878 @item @option{-gnat83} switch
28879 All implementations of GNAT provide a switch that causes GNAT to operate
28880 in Ada 83 mode. In this mode, some but not all compatibility problems
28881 of the type described above are handled automatically. For example, the
28882 new reserved words introduced in Ada 95 and Ada 2005 are treated simply
28883 as identifiers as in Ada 83.
28885 in practice, it is usually advisable to make the necessary modifications
28886 to the program to remove the need for using this switch.
28887 See @ref{Compiling Different Versions of Ada}.
28889 @item Support for removed Ada 83 pragmas and attributes
28890 A number of pragmas and attributes from Ada 83 were removed from Ada 95,
28891 generally because they were replaced by other mechanisms. Ada 95 and Ada 2005
28892 compilers are allowed, but not required, to implement these missing
28893 elements. In contrast with some other compilers, GNAT implements all
28894 such pragmas and attributes, eliminating this compatibility concern. These
28895 include @code{pragma Interface} and the floating point type attributes
28896 (@code{Emax}, @code{Mantissa}, etc.), among other items.
28900 @node Compatibility between Ada 95 and Ada 2005
28901 @section Compatibility between Ada 95 and Ada 2005
28902 @cindex Compatibility between Ada 95 and Ada 2005
28905 Although Ada 2005 was designed to be upwards compatible with Ada 95, there are
28906 a number of incompatibilities. Several are enumerated below;
28907 for a complete description please see the
28908 Annotated Ada 2005 Reference Manual, or section 9.1.1 in
28909 @cite{Rationale for Ada 2005}.
28912 @item New reserved words.
28913 The words @code{interface}, @code{overriding} and @code{synchronized} are
28914 reserved in Ada 2005.
28915 A pre-Ada 2005 program that uses any of these as an identifier will be
28918 @item New declarations in predefined packages.
28919 A number of packages in the predefined environment contain new declarations:
28920 @code{Ada.Exceptions}, @code{Ada.Real_Time}, @code{Ada.Strings},
28921 @code{Ada.Strings.Fixed}, @code{Ada.Strings.Bounded},
28922 @code{Ada.Strings.Unbounded}, @code{Ada.Strings.Wide_Fixed},
28923 @code{Ada.Strings.Wide_Bounded}, @code{Ada.Strings.Wide_Unbounded},
28924 @code{Ada.Tags}, @code{Ada.Text_IO}, and @code{Interfaces.C}.
28925 If an Ada 95 program does a @code{with} and @code{use} of any of these
28926 packages, the new declarations may cause name clashes.
28928 @item Access parameters.
28929 A nondispatching subprogram with an access parameter cannot be renamed
28930 as a dispatching operation. This was permitted in Ada 95.
28932 @item Access types, discriminants, and constraints.
28933 Rule changes in this area have led to some incompatibilities; for example,
28934 constrained subtypes of some access types are not permitted in Ada 2005.
28936 @item Aggregates for limited types.
28937 The allowance of aggregates for limited types in Ada 2005 raises the
28938 possibility of ambiguities in legal Ada 95 programs, since additional types
28939 now need to be considered in expression resolution.
28941 @item Fixed-point multiplication and division.
28942 Certain expressions involving ``*'' or ``/'' for a fixed-point type, which
28943 were legal in Ada 95 and invoked the predefined versions of these operations,
28945 The ambiguity may be resolved either by applying a type conversion to the
28946 expression, or by explicitly invoking the operation from package
28949 @item Return-by-reference types.
28950 The Ada 95 return-by-reference mechanism has been removed. Instead, the user
28951 can declare a function returning a value from an anonymous access type.
28955 @node Implementation-dependent characteristics
28956 @section Implementation-dependent characteristics
28958 Although the Ada language defines the semantics of each construct as
28959 precisely as practical, in some situations (for example for reasons of
28960 efficiency, or where the effect is heavily dependent on the host or target
28961 platform) the implementation is allowed some freedom. In porting Ada 83
28962 code to GNAT, you need to be aware of whether / how the existing code
28963 exercised such implementation dependencies. Such characteristics fall into
28964 several categories, and GNAT offers specific support in assisting the
28965 transition from certain Ada 83 compilers.
28968 * Implementation-defined pragmas::
28969 * Implementation-defined attributes::
28971 * Elaboration order::
28972 * Target-specific aspects::
28975 @node Implementation-defined pragmas
28976 @subsection Implementation-defined pragmas
28979 Ada compilers are allowed to supplement the language-defined pragmas, and
28980 these are a potential source of non-portability. All GNAT-defined pragmas
28981 are described in @ref{Implementation Defined Pragmas,,, gnat_rm, GNAT
28982 Reference Manual}, and these include several that are specifically
28983 intended to correspond to other vendors' Ada 83 pragmas.
28984 For migrating from VADS, the pragma @code{Use_VADS_Size} may be useful.
28985 For compatibility with HP Ada 83, GNAT supplies the pragmas
28986 @code{Extend_System}, @code{Ident}, @code{Inline_Generic},
28987 @code{Interface_Name}, @code{Passive}, @code{Suppress_All},
28988 and @code{Volatile}.
28989 Other relevant pragmas include @code{External} and @code{Link_With}.
28990 Some vendor-specific
28991 Ada 83 pragmas (@code{Share_Generic}, @code{Subtitle}, and @code{Title}) are
28993 avoiding compiler rejection of units that contain such pragmas; they are not
28994 relevant in a GNAT context and hence are not otherwise implemented.
28996 @node Implementation-defined attributes
28997 @subsection Implementation-defined attributes
28999 Analogous to pragmas, the set of attributes may be extended by an
29000 implementation. All GNAT-defined attributes are described in
29001 @ref{Implementation Defined Attributes,,, gnat_rm, GNAT Reference
29002 Manual}, and these include several that are specifically intended
29003 to correspond to other vendors' Ada 83 attributes. For migrating from VADS,
29004 the attribute @code{VADS_Size} may be useful. For compatibility with HP
29005 Ada 83, GNAT supplies the attributes @code{Bit}, @code{Machine_Size} and
29009 @subsection Libraries
29011 Vendors may supply libraries to supplement the standard Ada API. If Ada 83
29012 code uses vendor-specific libraries then there are several ways to manage
29013 this in Ada 95 or Ada 2005:
29016 If the source code for the libraries (specs and bodies) are
29017 available, then the libraries can be migrated in the same way as the
29020 If the source code for the specs but not the bodies are
29021 available, then you can reimplement the bodies.
29023 Some features introduced by Ada 95 obviate the need for library support. For
29024 example most Ada 83 vendors supplied a package for unsigned integers. The
29025 Ada 95 modular type feature is the preferred way to handle this need, so
29026 instead of migrating or reimplementing the unsigned integer package it may
29027 be preferable to retrofit the application using modular types.
29030 @node Elaboration order
29031 @subsection Elaboration order
29033 The implementation can choose any elaboration order consistent with the unit
29034 dependency relationship. This freedom means that some orders can result in
29035 Program_Error being raised due to an ``Access Before Elaboration'': an attempt
29036 to invoke a subprogram its body has been elaborated, or to instantiate a
29037 generic before the generic body has been elaborated. By default GNAT
29038 attempts to choose a safe order (one that will not encounter access before
29039 elaboration problems) by implicitly inserting @code{Elaborate} or
29040 @code{Elaborate_All} pragmas where
29041 needed. However, this can lead to the creation of elaboration circularities
29042 and a resulting rejection of the program by gnatbind. This issue is
29043 thoroughly described in @ref{Elaboration Order Handling in GNAT}.
29044 In brief, there are several
29045 ways to deal with this situation:
29049 Modify the program to eliminate the circularities, e.g.@: by moving
29050 elaboration-time code into explicitly-invoked procedures
29052 Constrain the elaboration order by including explicit @code{Elaborate_Body} or
29053 @code{Elaborate} pragmas, and then inhibit the generation of implicit
29054 @code{Elaborate_All}
29055 pragmas either globally (as an effect of the @option{-gnatE} switch) or locally
29056 (by selectively suppressing elaboration checks via pragma
29057 @code{Suppress(Elaboration_Check)} when it is safe to do so).
29060 @node Target-specific aspects
29061 @subsection Target-specific aspects
29063 Low-level applications need to deal with machine addresses, data
29064 representations, interfacing with assembler code, and similar issues. If
29065 such an Ada 83 application is being ported to different target hardware (for
29066 example where the byte endianness has changed) then you will need to
29067 carefully examine the program logic; the porting effort will heavily depend
29068 on the robustness of the original design. Moreover, Ada 95 (and thus
29069 Ada 2005) are sometimes
29070 incompatible with typical Ada 83 compiler practices regarding implicit
29071 packing, the meaning of the Size attribute, and the size of access values.
29072 GNAT's approach to these issues is described in @ref{Representation Clauses}.
29074 @node Compatibility with Other Ada Systems
29075 @section Compatibility with Other Ada Systems
29078 If programs avoid the use of implementation dependent and
29079 implementation defined features, as documented in the @cite{Ada
29080 Reference Manual}, there should be a high degree of portability between
29081 GNAT and other Ada systems. The following are specific items which
29082 have proved troublesome in moving Ada 95 programs from GNAT to other Ada 95
29083 compilers, but do not affect porting code to GNAT@.
29084 (As of @value{NOW}, GNAT is the only compiler available for Ada 2005;
29085 the following issues may or may not arise for Ada 2005 programs
29086 when other compilers appear.)
29089 @item Ada 83 Pragmas and Attributes
29090 Ada 95 compilers are allowed, but not required, to implement the missing
29091 Ada 83 pragmas and attributes that are no longer defined in Ada 95.
29092 GNAT implements all such pragmas and attributes, eliminating this as
29093 a compatibility concern, but some other Ada 95 compilers reject these
29094 pragmas and attributes.
29096 @item Specialized Needs Annexes
29097 GNAT implements the full set of special needs annexes. At the
29098 current time, it is the only Ada 95 compiler to do so. This means that
29099 programs making use of these features may not be portable to other Ada
29100 95 compilation systems.
29102 @item Representation Clauses
29103 Some other Ada 95 compilers implement only the minimal set of
29104 representation clauses required by the Ada 95 reference manual. GNAT goes
29105 far beyond this minimal set, as described in the next section.
29108 @node Representation Clauses
29109 @section Representation Clauses
29112 The Ada 83 reference manual was quite vague in describing both the minimal
29113 required implementation of representation clauses, and also their precise
29114 effects. Ada 95 (and thus also Ada 2005) are much more explicit, but the
29115 minimal set of capabilities required is still quite limited.
29117 GNAT implements the full required set of capabilities in
29118 Ada 95 and Ada 2005, but also goes much further, and in particular
29119 an effort has been made to be compatible with existing Ada 83 usage to the
29120 greatest extent possible.
29122 A few cases exist in which Ada 83 compiler behavior is incompatible with
29123 the requirements in Ada 95 (and thus also Ada 2005). These are instances of
29124 intentional or accidental dependence on specific implementation dependent
29125 characteristics of these Ada 83 compilers. The following is a list of
29126 the cases most likely to arise in existing Ada 83 code.
29129 @item Implicit Packing
29130 Some Ada 83 compilers allowed a Size specification to cause implicit
29131 packing of an array or record. This could cause expensive implicit
29132 conversions for change of representation in the presence of derived
29133 types, and the Ada design intends to avoid this possibility.
29134 Subsequent AI's were issued to make it clear that such implicit
29135 change of representation in response to a Size clause is inadvisable,
29136 and this recommendation is represented explicitly in the Ada 95 (and Ada 2005)
29137 Reference Manuals as implementation advice that is followed by GNAT@.
29138 The problem will show up as an error
29139 message rejecting the size clause. The fix is simply to provide
29140 the explicit pragma @code{Pack}, or for more fine tuned control, provide
29141 a Component_Size clause.
29143 @item Meaning of Size Attribute
29144 The Size attribute in Ada 95 (and Ada 2005) for discrete types is defined as
29145 the minimal number of bits required to hold values of the type. For example,
29146 on a 32-bit machine, the size of @code{Natural} will typically be 31 and not
29147 32 (since no sign bit is required). Some Ada 83 compilers gave 31, and
29148 some 32 in this situation. This problem will usually show up as a compile
29149 time error, but not always. It is a good idea to check all uses of the
29150 'Size attribute when porting Ada 83 code. The GNAT specific attribute
29151 Object_Size can provide a useful way of duplicating the behavior of
29152 some Ada 83 compiler systems.
29154 @item Size of Access Types
29155 A common assumption in Ada 83 code is that an access type is in fact a pointer,
29156 and that therefore it will be the same size as a System.Address value. This
29157 assumption is true for GNAT in most cases with one exception. For the case of
29158 a pointer to an unconstrained array type (where the bounds may vary from one
29159 value of the access type to another), the default is to use a ``fat pointer'',
29160 which is represented as two separate pointers, one to the bounds, and one to
29161 the array. This representation has a number of advantages, including improved
29162 efficiency. However, it may cause some difficulties in porting existing Ada 83
29163 code which makes the assumption that, for example, pointers fit in 32 bits on
29164 a machine with 32-bit addressing.
29166 To get around this problem, GNAT also permits the use of ``thin pointers'' for
29167 access types in this case (where the designated type is an unconstrained array
29168 type). These thin pointers are indeed the same size as a System.Address value.
29169 To specify a thin pointer, use a size clause for the type, for example:
29171 @smallexample @c ada
29172 type X is access all String;
29173 for X'Size use Standard'Address_Size;
29177 which will cause the type X to be represented using a single pointer.
29178 When using this representation, the bounds are right behind the array.
29179 This representation is slightly less efficient, and does not allow quite
29180 such flexibility in the use of foreign pointers or in using the
29181 Unrestricted_Access attribute to create pointers to non-aliased objects.
29182 But for any standard portable use of the access type it will work in
29183 a functionally correct manner and allow porting of existing code.
29184 Note that another way of forcing a thin pointer representation
29185 is to use a component size clause for the element size in an array,
29186 or a record representation clause for an access field in a record.
29190 @c This brief section is only in the non-VMS version
29191 @c The complete chapter on HP Ada is in the VMS version
29192 @node Compatibility with HP Ada 83
29193 @section Compatibility with HP Ada 83
29196 The VMS version of GNAT fully implements all the pragmas and attributes
29197 provided by HP Ada 83, as well as providing the standard HP Ada 83
29198 libraries, including Starlet. In addition, data layouts and parameter
29199 passing conventions are highly compatible. This means that porting
29200 existing HP Ada 83 code to GNAT in VMS systems should be easier than
29201 most other porting efforts. The following are some of the most
29202 significant differences between GNAT and HP Ada 83.
29205 @item Default floating-point representation
29206 In GNAT, the default floating-point format is IEEE, whereas in HP Ada 83,
29207 it is VMS format. GNAT does implement the necessary pragmas
29208 (Long_Float, Float_Representation) for changing this default.
29211 The package System in GNAT exactly corresponds to the definition in the
29212 Ada 95 reference manual, which means that it excludes many of the
29213 HP Ada 83 extensions. However, a separate package Aux_DEC is provided
29214 that contains the additional definitions, and a special pragma,
29215 Extend_System allows this package to be treated transparently as an
29216 extension of package System.
29219 The definitions provided by Aux_DEC are exactly compatible with those
29220 in the HP Ada 83 version of System, with one exception.
29221 HP Ada provides the following declarations:
29223 @smallexample @c ada
29224 TO_ADDRESS (INTEGER)
29225 TO_ADDRESS (UNSIGNED_LONGWORD)
29226 TO_ADDRESS (@i{universal_integer})
29230 The version of TO_ADDRESS taking a @i{universal integer} argument is in fact
29231 an extension to Ada 83 not strictly compatible with the reference manual.
29232 In GNAT, we are constrained to be exactly compatible with the standard,
29233 and this means we cannot provide this capability. In HP Ada 83, the
29234 point of this definition is to deal with a call like:
29236 @smallexample @c ada
29237 TO_ADDRESS (16#12777#);
29241 Normally, according to the Ada 83 standard, one would expect this to be
29242 ambiguous, since it matches both the INTEGER and UNSIGNED_LONGWORD forms
29243 of TO_ADDRESS@. However, in HP Ada 83, there is no ambiguity, since the
29244 definition using @i{universal_integer} takes precedence.
29246 In GNAT, since the version with @i{universal_integer} cannot be supplied, it
29247 is not possible to be 100% compatible. Since there are many programs using
29248 numeric constants for the argument to TO_ADDRESS, the decision in GNAT was
29249 to change the name of the function in the UNSIGNED_LONGWORD case, so the
29250 declarations provided in the GNAT version of AUX_Dec are:
29252 @smallexample @c ada
29253 function To_Address (X : Integer) return Address;
29254 pragma Pure_Function (To_Address);
29256 function To_Address_Long (X : Unsigned_Longword)
29258 pragma Pure_Function (To_Address_Long);
29262 This means that programs using TO_ADDRESS for UNSIGNED_LONGWORD must
29263 change the name to TO_ADDRESS_LONG@.
29265 @item Task_Id values
29266 The Task_Id values assigned will be different in the two systems, and GNAT
29267 does not provide a specified value for the Task_Id of the environment task,
29268 which in GNAT is treated like any other declared task.
29272 For full details on these and other less significant compatibility issues,
29273 see appendix E of the HP publication entitled @cite{HP Ada, Technical
29274 Overview and Comparison on HP Platforms}.
29276 For GNAT running on other than VMS systems, all the HP Ada 83 pragmas and
29277 attributes are recognized, although only a subset of them can sensibly
29278 be implemented. The description of pragmas in @ref{Implementation
29279 Defined Pragmas,,, gnat_rm, GNAT Reference Manual}
29280 indicates whether or not they are applicable to non-VMS systems.
29284 @node Transitioning to 64-Bit GNAT for OpenVMS
29285 @section Transitioning to 64-Bit @value{EDITION} for OpenVMS
29288 This section is meant to assist users of pre-2006 @value{EDITION}
29289 for Alpha OpenVMS who are transitioning to 64-bit @value{EDITION},
29290 the version of the GNAT technology supplied in 2006 and later for
29291 OpenVMS on both Alpha and I64.
29294 * Introduction to transitioning::
29295 * Migration of 32 bit code::
29296 * Taking advantage of 64 bit addressing::
29297 * Technical details::
29300 @node Introduction to transitioning
29301 @subsection Introduction
29304 64-bit @value{EDITION} for Open VMS has been designed to meet
29309 Providing a full conforming implementation of Ada 95 and Ada 2005
29312 Allowing maximum backward compatibility, thus easing migration of existing
29316 Supplying a path for exploiting the full 64-bit address range
29320 Ada's strong typing semantics has made it
29321 impractical to have different 32-bit and 64-bit modes. As soon as
29322 one object could possibly be outside the 32-bit address space, this
29323 would make it necessary for the @code{System.Address} type to be 64 bits.
29324 In particular, this would cause inconsistencies if 32-bit code is
29325 called from 64-bit code that raises an exception.
29327 This issue has been resolved by always using 64-bit addressing
29328 at the system level, but allowing for automatic conversions between
29329 32-bit and 64-bit addresses where required. Thus users who
29330 do not currently require 64-bit addressing capabilities, can
29331 recompile their code with only minimal changes (and indeed
29332 if the code is written in portable Ada, with no assumptions about
29333 the size of the @code{Address} type, then no changes at all are necessary).
29335 this approach provides a simple, gradual upgrade path to future
29336 use of larger memories than available for 32-bit systems.
29337 Also, newly written applications or libraries will by default
29338 be fully compatible with future systems exploiting 64-bit
29339 addressing capabilities.
29341 @ref{Migration of 32 bit code}, will focus on porting applications
29342 that do not require more than 2 GB of
29343 addressable memory. This code will be referred to as
29344 @emph{32-bit code}.
29345 For applications intending to exploit the full 64-bit address space,
29346 @ref{Taking advantage of 64 bit addressing},
29347 will consider further changes that may be required.
29348 Such code will be referred to below as @emph{64-bit code}.
29350 @node Migration of 32 bit code
29351 @subsection Migration of 32-bit code
29355 * Access types and 32/64-bit allocation::
29356 * Unchecked conversions::
29357 * Predefined constants::
29358 * Interfacing with C::
29359 * 32/64-bit descriptors::
29360 * Experience with source compatibility::
29363 @node Address types
29364 @subsubsection Address types
29367 To solve the problem of mixing 64-bit and 32-bit addressing,
29368 while maintaining maximum backward compatibility, the following
29369 approach has been taken:
29373 @code{System.Address} always has a size of 64 bits
29374 @cindex @code{System.Address} size
29375 @cindex @code{Address} size
29378 @code{System.Short_Address} is a 32-bit subtype of @code{System.Address}
29379 @cindex @code{System.Short_Address} size
29380 @cindex @code{Short_Address} size
29384 Since @code{System.Short_Address} is a subtype of @code{System.Address},
29385 a @code{Short_Address}
29386 may be used where an @code{Address} is required, and vice versa, without
29387 needing explicit type conversions.
29388 By virtue of the Open VMS parameter passing conventions,
29390 and exported subprograms that have 32-bit address parameters are
29391 compatible with those that have 64-bit address parameters.
29392 (See @ref{Making code 64 bit clean} for details.)
29394 The areas that may need attention are those where record types have
29395 been defined that contain components of the type @code{System.Address}, and
29396 where objects of this type are passed to code expecting a record layout with
29399 Different compilers on different platforms cannot be
29400 expected to represent the same type in the same way,
29401 since alignment constraints
29402 and other system-dependent properties affect the compiler's decision.
29403 For that reason, Ada code
29404 generally uses representation clauses to specify the expected
29405 layout where required.
29407 If such a representation clause uses 32 bits for a component having
29408 the type @code{System.Address}, 64-bit @value{EDITION} for OpenVMS
29409 will detect that error and produce a specific diagnostic message.
29410 The developer should then determine whether the representation
29411 should be 64 bits or not and make either of two changes:
29412 change the size to 64 bits and leave the type as @code{System.Address}, or
29413 leave the size as 32 bits and change the type to @code{System.Short_Address}.
29414 Since @code{Short_Address} is a subtype of @code{Address}, no changes are
29415 required in any code setting or accessing the field; the compiler will
29416 automatically perform any needed conversions between address
29419 @node Access types and 32/64-bit allocation
29420 @subsubsection Access types and 32/64-bit allocation
29421 @cindex 32-bit allocation
29422 @cindex 64-bit allocation
29425 By default, objects designated by access values are always allocated in
29426 the 64-bit address space, and access values themselves are represented
29427 in 64 bits. If these defaults are not appropriate, and 32-bit allocation
29428 is required (for example if the address of an allocated object is assigned
29429 to a @code{Short_Address} variable), then several alternatives are available:
29433 A pool-specific access type (ie, an @w{Ada 83} access type, whose
29434 definition is @code{access T} versus @code{access all T} or
29435 @code{access constant T}), may be declared with a @code{'Size} representation
29436 clause that establishes the size as 32 bits.
29437 In such circumstances allocations for that type will
29438 be from the 32-bit heap. Such a clause is not permitted
29439 for a general access type (declared with @code{access all} or
29440 @code{access constant}) as values of such types must be able to refer
29441 to any object of the designated type, including objects residing outside
29442 the 32-bit address range. Existing @w{Ada 83} code will not contain such
29443 type definitions, however, since general access types were introduced
29447 Switches for @command{GNAT BIND} control whether the internal GNAT
29448 allocation routine @code{__gnat_malloc} uses 64-bit or 32-bit allocations.
29449 @cindex @code{__gnat_malloc}
29450 The switches are respectively @option{-H64} (the default) and
29452 @cindex @option{-H32} (@command{gnatbind})
29453 @cindex @option{-H64} (@command{gnatbind})
29456 The environment variable (logical name) @code{GNAT$NO_MALLOC_64}
29457 @cindex @code{GNAT$NO_MALLOC_64} environment variable
29458 may be used to force @code{__gnat_malloc} to use 32-bit allocation.
29459 If this variable is left
29460 undefined, or defined as @code{"DISABLE"}, @code{"FALSE"}, or @code{"0"},
29461 then the default (64-bit) allocation is used.
29462 If defined as @code{"ENABLE"}, @code{"TRUE"}, or @code{"1"},
29463 then 32-bit allocation is used. The gnatbind qualifiers described above
29464 override this logical name.
29467 A ^gcc switch^gcc switch^ for OpenVMS, @option{-mno-malloc64}, operates
29468 @cindex @option{-mno-malloc64} (^gcc^gcc^)
29469 at a low level to convert explicit calls to @code{malloc} and related
29470 functions from the C run-time library so that they perform allocations
29471 in the 32-bit heap.
29472 Since all internal allocations from GNAT use @code{__gnat_malloc},
29473 this switch is not required unless the program makes explicit calls on
29474 @code{malloc} (or related functions) from interfaced C code.
29478 @node Unchecked conversions
29479 @subsubsection Unchecked conversions
29482 In the case of an @code{Unchecked_Conversion} where the source type is a
29483 64-bit access type or the type @code{System.Address}, and the target
29484 type is a 32-bit type, the compiler will generate a warning.
29485 Even though the generated code will still perform the required
29486 conversions, it is highly recommended in these cases to use
29487 respectively a 32-bit access type or @code{System.Short_Address}
29488 as the source type.
29490 @node Predefined constants
29491 @subsubsection Predefined constants
29494 The following table shows the correspondence between pre-2006 versions of
29495 @value{EDITION} on Alpha OpenVMS (``Old'') and 64-bit @value{EDITION}
29498 @multitable {@code{System.Short_Memory_Size}} {2**32} {2**64}
29499 @item @b{Constant} @tab @b{Old} @tab @b{New}
29500 @item @code{System.Word_Size} @tab 32 @tab 64
29501 @item @code{System.Memory_Size} @tab 2**32 @tab 2**64
29502 @item @code{System.Short_Memory_Size} @tab 2**32 @tab 2**32
29503 @item @code{System.Address_Size} @tab 32 @tab 64
29507 If you need to refer to the specific
29508 memory size of a 32-bit implementation, instead of the
29509 actual memory size, use @code{System.Short_Memory_Size}
29510 rather than @code{System.Memory_Size}.
29511 Similarly, references to @code{System.Address_Size} may need
29512 to be replaced by @code{System.Short_Address'Size}.
29513 The program @command{gnatfind} may be useful for locating
29514 references to the above constants, so that you can verify that they
29517 @node Interfacing with C
29518 @subsubsection Interfacing with C
29521 In order to minimize the impact of the transition to 64-bit addresses on
29522 legacy programs, some fundamental types in the @code{Interfaces.C}
29523 package hierarchy continue to be represented in 32 bits.
29524 These types are: @code{ptrdiff_t}, @code{size_t}, and @code{chars_ptr}.
29525 This eases integration with the default HP C layout choices, for example
29526 as found in the system routines in @code{DECC$SHR.EXE}.
29527 Because of this implementation choice, the type fully compatible with
29528 @code{chars_ptr} is now @code{Short_Address} and not @code{Address}.
29529 Depending on the context the compiler will issue a
29530 warning or an error when type @code{Address} is used, alerting the user to a
29531 potential problem. Otherwise 32-bit programs that use
29532 @code{Interfaces.C} should normally not require code modifications
29534 The other issue arising with C interfacing concerns pragma @code{Convention}.
29535 For VMS 64-bit systems, there is an issue of the appropriate default size
29536 of C convention pointers in the absence of an explicit size clause. The HP
29537 C compiler can choose either 32 or 64 bits depending on compiler options.
29538 GNAT chooses 32-bits rather than 64-bits in the default case where no size
29539 clause is given. This proves a better choice for porting 32-bit legacy
29540 applications. In order to have a 64-bit representation, it is necessary to
29541 specify a size representation clause. For example:
29543 @smallexample @c ada
29544 type int_star is access Interfaces.C.int;
29545 pragma Convention(C, int_star);
29546 for int_star'Size use 64; -- Necessary to get 64 and not 32 bits
29549 @node 32/64-bit descriptors
29550 @subsubsection 32/64-bit descriptors
29553 By default, GNAT uses a 64-bit descriptor mechanism. For an imported
29554 subprogram (i.e., a subprogram identified by pragma @code{Import_Function},
29555 @code{Import_Procedure}, or @code{Import_Valued_Procedure}) that specifies
29556 @code{Short_Descriptor} as its mechanism, a 32-bit descriptor is used.
29557 @cindex @code{Short_Descriptor} mechanism for imported subprograms
29559 If the configuration pragma @code{Short_Descriptors} is supplied, then
29560 all descriptors will be 32 bits.
29561 @cindex pragma @code{Short_Descriptors}
29563 @node Experience with source compatibility
29564 @subsubsection Experience with source compatibility
29567 The Security Server and STARLET on I64 provide an interesting ``test case''
29568 for source compatibility issues, since it is in such system code
29569 where assumptions about @code{Address} size might be expected to occur.
29570 Indeed, there were a small number of occasions in the Security Server
29571 file @file{jibdef.ads}
29572 where a representation clause for a record type specified
29573 32 bits for a component of type @code{Address}.
29574 All of these errors were detected by the compiler.
29575 The repair was obvious and immediate; to simply replace @code{Address} by
29576 @code{Short_Address}.
29578 In the case of STARLET, there were several record types that should
29579 have had representation clauses but did not. In these record types
29580 there was an implicit assumption that an @code{Address} value occupied
29582 These compiled without error, but their usage resulted in run-time error
29583 returns from STARLET system calls.
29584 Future GNAT technology enhancements may include a tool that detects and flags
29585 these sorts of potential source code porting problems.
29587 @c ****************************************
29588 @node Taking advantage of 64 bit addressing
29589 @subsection Taking advantage of 64-bit addressing
29592 * Making code 64 bit clean::
29593 * Allocating memory from the 64 bit storage pool::
29594 * Restrictions on use of 64 bit objects::
29595 * STARLET and other predefined libraries::
29598 @node Making code 64 bit clean
29599 @subsubsection Making code 64-bit clean
29602 In order to prevent problems that may occur when (parts of) a
29603 system start using memory outside the 32-bit address range,
29604 we recommend some additional guidelines:
29608 For imported subprograms that take parameters of the
29609 type @code{System.Address}, ensure that these subprograms can
29610 indeed handle 64-bit addresses. If not, or when in doubt,
29611 change the subprogram declaration to specify
29612 @code{System.Short_Address} instead.
29615 Resolve all warnings related to size mismatches in
29616 unchecked conversions. Failing to do so causes
29617 erroneous execution if the source object is outside
29618 the 32-bit address space.
29621 (optional) Explicitly use the 32-bit storage pool
29622 for access types used in a 32-bit context, or use
29623 generic access types where possible
29624 (@pxref{Restrictions on use of 64 bit objects}).
29628 If these rules are followed, the compiler will automatically insert
29629 any necessary checks to ensure that no addresses or access values
29630 passed to 32-bit code ever refer to objects outside the 32-bit
29632 Any attempt to do this will raise @code{Constraint_Error}.
29634 @node Allocating memory from the 64 bit storage pool
29635 @subsubsection Allocating memory from the 64-bit storage pool
29638 By default, all allocations -- for both pool-specific and general
29639 access types -- use the 64-bit storage pool. To override
29640 this default, for an individual access type or globally, see
29641 @ref{Access types and 32/64-bit allocation}.
29643 @node Restrictions on use of 64 bit objects
29644 @subsubsection Restrictions on use of 64-bit objects
29647 Taking the address of an object allocated from a 64-bit storage pool,
29648 and then passing this address to a subprogram expecting
29649 @code{System.Short_Address},
29650 or assigning it to a variable of type @code{Short_Address}, will cause
29651 @code{Constraint_Error} to be raised. In case the code is not 64-bit clean
29652 (@pxref{Making code 64 bit clean}), or checks are suppressed,
29653 no exception is raised and execution
29654 will become erroneous.
29656 @node STARLET and other predefined libraries
29657 @subsubsection STARLET and other predefined libraries
29660 All code that comes as part of GNAT is 64-bit clean, but the
29661 restrictions given in @ref{Restrictions on use of 64 bit objects},
29662 still apply. Look at the package
29663 specs to see in which contexts objects allocated
29664 in 64-bit address space are acceptable.
29666 @node Technical details
29667 @subsection Technical details
29670 64-bit @value{EDITION} for Open VMS takes advantage of the freedom given in the
29671 Ada standard with respect to the type of @code{System.Address}. Previous
29672 versions of @value{EDITION} have defined this type as private and implemented it as a
29675 In order to allow defining @code{System.Short_Address} as a proper subtype,
29676 and to match the implicit sign extension in parameter passing,
29677 in 64-bit @value{EDITION} for Open VMS, @code{System.Address} is defined as a
29678 visible (i.e., non-private) integer type.
29679 Standard operations on the type, such as the binary operators ``+'', ``-'',
29680 etc., that take @code{Address} operands and return an @code{Address} result,
29681 have been hidden by declaring these
29682 @code{abstract}, a feature introduced in Ada 95 that helps avoid the potential
29683 ambiguities that would otherwise result from overloading.
29684 (Note that, although @code{Address} is a visible integer type,
29685 good programming practice dictates against exploiting the type's
29686 integer properties such as literals, since this will compromise
29689 Defining @code{Address} as a visible integer type helps achieve
29690 maximum compatibility for existing Ada code,
29691 without sacrificing the capabilities of the 64-bit architecture.
29694 @c ************************************************
29695 @node Microsoft Windows Topics
29696 @appendix Microsoft Windows Topics
29702 This chapter describes topics that are specific to the Microsoft Windows
29703 platforms (NT, 2000, and XP Professional).
29706 @ifclear FSFEDITION
29707 * Installing from the Command Line::
29709 * Using GNAT on Windows::
29710 * Using a network installation of GNAT::
29711 * CONSOLE and WINDOWS subsystems::
29712 * Temporary Files::
29713 * Mixed-Language Programming on Windows::
29714 * Windows Calling Conventions::
29715 * Introduction to Dynamic Link Libraries (DLLs)::
29716 * Using DLLs with GNAT::
29717 * Building DLLs with GNAT Project files::
29718 * Building DLLs with GNAT::
29719 * Building DLLs with gnatdll::
29720 * GNAT and Windows Resources::
29721 * Debugging a DLL::
29722 * Setting Stack Size from gnatlink::
29723 * Setting Heap Size from gnatlink::
29726 @ifclear FSFEDITION
29727 @node Installing from the Command Line
29728 @section Installing from the Command Line
29729 @cindex Batch installation
29730 @cindex Silent installation
29731 @cindex Unassisted installation
29734 By default the @value{EDITION} installers display a GUI that prompts the user
29735 to enter installation path and similar information, and guide him through the
29736 installation process. It is also possible to perform silent installations
29737 using the command-line interface.
29739 In order to install one of the @value{EDITION} installers from the command
29740 line you should pass parameter @code{/S} (and, optionally,
29741 @code{/D=<directory>}) as command-line arguments.
29744 For example, for an unattended installation of
29745 @value{EDITION} 7.0.2 into the default directory
29746 @code{C:\GNATPRO\7.0.2} you would run:
29749 gnatpro-7.0.2-i686-pc-mingw32-bin.exe /S
29752 To install into a custom directory, say, @code{C:\TOOLS\GNATPRO\7.0.2}:
29755 gnatpro-7.0.2-i686-pc-mingw32-bin /S /D=C:\TOOLS\GNATPRO\7.0.2
29760 For example, for an unattended installation of
29761 @value{EDITION} 2012 into @code{C:\GNAT\2012}:
29764 gnat-gpl-2012-i686-pc-mingw32-bin /S /D=C:\GNAT\2012
29768 You can use the same syntax for all installers.
29770 Note that unattended installations don't modify system path, nor create file
29771 associations, so such activities need to be done by hand.
29774 @node Using GNAT on Windows
29775 @section Using GNAT on Windows
29778 One of the strengths of the GNAT technology is that its tool set
29779 (@command{gcc}, @command{gnatbind}, @command{gnatlink}, @command{gnatmake}, the
29780 @code{gdb} debugger, etc.) is used in the same way regardless of the
29783 On Windows this tool set is complemented by a number of Microsoft-specific
29784 tools that have been provided to facilitate interoperability with Windows
29785 when this is required. With these tools:
29790 You can build applications using the @code{CONSOLE} or @code{WINDOWS}
29794 You can use any Dynamically Linked Library (DLL) in your Ada code (both
29795 relocatable and non-relocatable DLLs are supported).
29798 You can build Ada DLLs for use in other applications. These applications
29799 can be written in a language other than Ada (e.g., C, C++, etc). Again both
29800 relocatable and non-relocatable Ada DLLs are supported.
29803 You can include Windows resources in your Ada application.
29806 You can use or create COM/DCOM objects.
29810 Immediately below are listed all known general GNAT-for-Windows restrictions.
29811 Other restrictions about specific features like Windows Resources and DLLs
29812 are listed in separate sections below.
29817 It is not possible to use @code{GetLastError} and @code{SetLastError}
29818 when tasking, protected records, or exceptions are used. In these
29819 cases, in order to implement Ada semantics, the GNAT run-time system
29820 calls certain Win32 routines that set the last error variable to 0 upon
29821 success. It should be possible to use @code{GetLastError} and
29822 @code{SetLastError} when tasking, protected record, and exception
29823 features are not used, but it is not guaranteed to work.
29826 It is not possible to link against Microsoft C++ libraries except for
29827 import libraries. Interfacing must be done by the mean of DLLs.
29830 It is possible to link against Microsoft C libraries. Yet the preferred
29831 solution is to use C/C++ compiler that comes with @value{EDITION}, since it
29832 doesn't require having two different development environments and makes the
29833 inter-language debugging experience smoother.
29836 When the compilation environment is located on FAT32 drives, users may
29837 experience recompilations of the source files that have not changed if
29838 Daylight Saving Time (DST) state has changed since the last time files
29839 were compiled. NTFS drives do not have this problem.
29842 No components of the GNAT toolset use any entries in the Windows
29843 registry. The only entries that can be created are file associations and
29844 PATH settings, provided the user has chosen to create them at installation
29845 time, as well as some minimal book-keeping information needed to correctly
29846 uninstall or integrate different GNAT products.
29849 @node Using a network installation of GNAT
29850 @section Using a network installation of GNAT
29853 Make sure the system on which GNAT is installed is accessible from the
29854 current machine, i.e., the install location is shared over the network.
29855 Shared resources are accessed on Windows by means of UNC paths, which
29856 have the format @code{\\server\sharename\path}
29858 In order to use such a network installation, simply add the UNC path of the
29859 @file{bin} directory of your GNAT installation in front of your PATH. For
29860 example, if GNAT is installed in @file{\GNAT} directory of a share location
29861 called @file{c-drive} on a machine @file{LOKI}, the following command will
29864 @code{@ @ @ path \\loki\c-drive\gnat\bin;%path%}
29866 Be aware that every compilation using the network installation results in the
29867 transfer of large amounts of data across the network and will likely cause
29868 serious performance penalty.
29870 @node CONSOLE and WINDOWS subsystems
29871 @section CONSOLE and WINDOWS subsystems
29872 @cindex CONSOLE Subsystem
29873 @cindex WINDOWS Subsystem
29877 There are two main subsystems under Windows. The @code{CONSOLE} subsystem
29878 (which is the default subsystem) will always create a console when
29879 launching the application. This is not something desirable when the
29880 application has a Windows GUI. To get rid of this console the
29881 application must be using the @code{WINDOWS} subsystem. To do so
29882 the @option{-mwindows} linker option must be specified.
29885 $ gnatmake winprog -largs -mwindows
29888 @node Temporary Files
29889 @section Temporary Files
29890 @cindex Temporary files
29893 It is possible to control where temporary files gets created by setting
29894 the @env{TMP} environment variable. The file will be created:
29897 @item Under the directory pointed to by the @env{TMP} environment variable if
29898 this directory exists.
29900 @item Under @file{c:\temp}, if the @env{TMP} environment variable is not
29901 set (or not pointing to a directory) and if this directory exists.
29903 @item Under the current working directory otherwise.
29907 This allows you to determine exactly where the temporary
29908 file will be created. This is particularly useful in networked
29909 environments where you may not have write access to some
29912 @node Mixed-Language Programming on Windows
29913 @section Mixed-Language Programming on Windows
29916 Developing pure Ada applications on Windows is no different than on
29917 other GNAT-supported platforms. However, when developing or porting an
29918 application that contains a mix of Ada and C/C++, the choice of your
29919 Windows C/C++ development environment conditions your overall
29920 interoperability strategy.
29922 If you use @command{gcc} or Microsoft C to compile the non-Ada part of
29923 your application, there are no Windows-specific restrictions that
29924 affect the overall interoperability with your Ada code. If you do want
29925 to use the Microsoft tools for your C++ code, you have two choices:
29929 Encapsulate your C++ code in a DLL to be linked with your Ada
29930 application. In this case, use the Microsoft or whatever environment to
29931 build the DLL and use GNAT to build your executable
29932 (@pxref{Using DLLs with GNAT}).
29935 Or you can encapsulate your Ada code in a DLL to be linked with the
29936 other part of your application. In this case, use GNAT to build the DLL
29937 (@pxref{Building DLLs with GNAT Project files}) and use the Microsoft
29938 or whatever environment to build your executable.
29941 In addition to the description about C main in
29942 @pxref{Mixed Language Programming} section, if the C main uses a
29943 stand-alone library it is required on x86-windows to
29944 setup the SEH context. For this the C main must looks like this:
29948 extern void adainit (void);
29949 extern void adafinal (void);
29950 extern void __gnat_initialize(void*);
29951 extern void call_to_ada (void);
29953 int main (int argc, char *argv[])
29957 /* Initialize the SEH context */
29958 __gnat_initialize (&SEH);
29962 /* Then call Ada services in the stand-alone library */
29970 Note that this is not needed on x86_64-windows where the Windows
29971 native SEH support is used.
29973 @node Windows Calling Conventions
29974 @section Windows Calling Conventions
29978 This section pertain only to Win32. On Win64 there is a single native
29979 calling convention. All convention specifiers are ignored on this
29983 * C Calling Convention::
29984 * Stdcall Calling Convention::
29985 * Win32 Calling Convention::
29986 * DLL Calling Convention::
29990 When a subprogram @code{F} (caller) calls a subprogram @code{G}
29991 (callee), there are several ways to push @code{G}'s parameters on the
29992 stack and there are several possible scenarios to clean up the stack
29993 upon @code{G}'s return. A calling convention is an agreed upon software
29994 protocol whereby the responsibilities between the caller (@code{F}) and
29995 the callee (@code{G}) are clearly defined. Several calling conventions
29996 are available for Windows:
30000 @code{C} (Microsoft defined)
30003 @code{Stdcall} (Microsoft defined)
30006 @code{Win32} (GNAT specific)
30009 @code{DLL} (GNAT specific)
30012 @node C Calling Convention
30013 @subsection @code{C} Calling Convention
30016 This is the default calling convention used when interfacing to C/C++
30017 routines compiled with either @command{gcc} or Microsoft Visual C++.
30019 In the @code{C} calling convention subprogram parameters are pushed on the
30020 stack by the caller from right to left. The caller itself is in charge of
30021 cleaning up the stack after the call. In addition, the name of a routine
30022 with @code{C} calling convention is mangled by adding a leading underscore.
30024 The name to use on the Ada side when importing (or exporting) a routine
30025 with @code{C} calling convention is the name of the routine. For
30026 instance the C function:
30029 int get_val (long);
30033 should be imported from Ada as follows:
30035 @smallexample @c ada
30037 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
30038 pragma Import (C, Get_Val, External_Name => "get_val");
30043 Note that in this particular case the @code{External_Name} parameter could
30044 have been omitted since, when missing, this parameter is taken to be the
30045 name of the Ada entity in lower case. When the @code{Link_Name} parameter
30046 is missing, as in the above example, this parameter is set to be the
30047 @code{External_Name} with a leading underscore.
30049 When importing a variable defined in C, you should always use the @code{C}
30050 calling convention unless the object containing the variable is part of a
30051 DLL (in which case you should use the @code{Stdcall} calling
30052 convention, @pxref{Stdcall Calling Convention}).
30054 @node Stdcall Calling Convention
30055 @subsection @code{Stdcall} Calling Convention
30058 This convention, which was the calling convention used for Pascal
30059 programs, is used by Microsoft for all the routines in the Win32 API for
30060 efficiency reasons. It must be used to import any routine for which this
30061 convention was specified.
30063 In the @code{Stdcall} calling convention subprogram parameters are pushed
30064 on the stack by the caller from right to left. The callee (and not the
30065 caller) is in charge of cleaning the stack on routine exit. In addition,
30066 the name of a routine with @code{Stdcall} calling convention is mangled by
30067 adding a leading underscore (as for the @code{C} calling convention) and a
30068 trailing @code{@@}@code{@var{nn}}, where @var{nn} is the overall size (in
30069 bytes) of the parameters passed to the routine.
30071 The name to use on the Ada side when importing a C routine with a
30072 @code{Stdcall} calling convention is the name of the C routine. The leading
30073 underscore and trailing @code{@@}@code{@var{nn}} are added automatically by
30074 the compiler. For instance the Win32 function:
30077 @b{APIENTRY} int get_val (long);
30081 should be imported from Ada as follows:
30083 @smallexample @c ada
30085 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
30086 pragma Import (Stdcall, Get_Val);
30087 -- On the x86 a long is 4 bytes, so the Link_Name is "_get_val@@4"
30092 As for the @code{C} calling convention, when the @code{External_Name}
30093 parameter is missing, it is taken to be the name of the Ada entity in lower
30094 case. If instead of writing the above import pragma you write:
30096 @smallexample @c ada
30098 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
30099 pragma Import (Stdcall, Get_Val, External_Name => "retrieve_val");
30104 then the imported routine is @code{_retrieve_val@@4}. However, if instead
30105 of specifying the @code{External_Name} parameter you specify the
30106 @code{Link_Name} as in the following example:
30108 @smallexample @c ada
30110 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
30111 pragma Import (Stdcall, Get_Val, Link_Name => "retrieve_val");
30116 then the imported routine is @code{retrieve_val}, that is, there is no
30117 decoration at all. No leading underscore and no Stdcall suffix
30118 @code{@@}@code{@var{nn}}.
30121 This is especially important as in some special cases a DLL's entry
30122 point name lacks a trailing @code{@@}@code{@var{nn}} while the exported
30123 name generated for a call has it.
30126 It is also possible to import variables defined in a DLL by using an
30127 import pragma for a variable. As an example, if a DLL contains a
30128 variable defined as:
30135 then, to access this variable from Ada you should write:
30137 @smallexample @c ada
30139 My_Var : Interfaces.C.int;
30140 pragma Import (Stdcall, My_Var);
30145 Note that to ease building cross-platform bindings this convention
30146 will be handled as a @code{C} calling convention on non-Windows platforms.
30148 @node Win32 Calling Convention
30149 @subsection @code{Win32} Calling Convention
30152 This convention, which is GNAT-specific is fully equivalent to the
30153 @code{Stdcall} calling convention described above.
30155 @node DLL Calling Convention
30156 @subsection @code{DLL} Calling Convention
30159 This convention, which is GNAT-specific is fully equivalent to the
30160 @code{Stdcall} calling convention described above.
30162 @node Introduction to Dynamic Link Libraries (DLLs)
30163 @section Introduction to Dynamic Link Libraries (DLLs)
30167 A Dynamically Linked Library (DLL) is a library that can be shared by
30168 several applications running under Windows. A DLL can contain any number of
30169 routines and variables.
30171 One advantage of DLLs is that you can change and enhance them without
30172 forcing all the applications that depend on them to be relinked or
30173 recompiled. However, you should be aware than all calls to DLL routines are
30174 slower since, as you will understand below, such calls are indirect.
30176 To illustrate the remainder of this section, suppose that an application
30177 wants to use the services of a DLL @file{API.dll}. To use the services
30178 provided by @file{API.dll} you must statically link against the DLL or
30179 an import library which contains a jump table with an entry for each
30180 routine and variable exported by the DLL. In the Microsoft world this
30181 import library is called @file{API.lib}. When using GNAT this import
30182 library is called either @file{libAPI.dll.a}, @file{libapi.dll.a},
30183 @file{libAPI.a} or @file{libapi.a} (names are case insensitive).
30185 After you have linked your application with the DLL or the import library
30186 and you run your application, here is what happens:
30190 Your application is loaded into memory.
30193 The DLL @file{API.dll} is mapped into the address space of your
30194 application. This means that:
30198 The DLL will use the stack of the calling thread.
30201 The DLL will use the virtual address space of the calling process.
30204 The DLL will allocate memory from the virtual address space of the calling
30208 Handles (pointers) can be safely exchanged between routines in the DLL
30209 routines and routines in the application using the DLL.
30213 The entries in the jump table (from the import library @file{libAPI.dll.a}
30214 or @file{API.lib} or automatically created when linking against a DLL)
30215 which is part of your application are initialized with the addresses
30216 of the routines and variables in @file{API.dll}.
30219 If present in @file{API.dll}, routines @code{DllMain} or
30220 @code{DllMainCRTStartup} are invoked. These routines typically contain
30221 the initialization code needed for the well-being of the routines and
30222 variables exported by the DLL.
30226 There is an additional point which is worth mentioning. In the Windows
30227 world there are two kind of DLLs: relocatable and non-relocatable
30228 DLLs. Non-relocatable DLLs can only be loaded at a very specific address
30229 in the target application address space. If the addresses of two
30230 non-relocatable DLLs overlap and these happen to be used by the same
30231 application, a conflict will occur and the application will run
30232 incorrectly. Hence, when possible, it is always preferable to use and
30233 build relocatable DLLs. Both relocatable and non-relocatable DLLs are
30234 supported by GNAT. Note that the @option{-s} linker option (see GNU Linker
30235 User's Guide) removes the debugging symbols from the DLL but the DLL can
30236 still be relocated.
30238 As a side note, an interesting difference between Microsoft DLLs and
30239 Unix shared libraries, is the fact that on most Unix systems all public
30240 routines are exported by default in a Unix shared library, while under
30241 Windows it is possible (but not required) to list exported routines in
30242 a definition file (@pxref{The Definition File}).
30244 @node Using DLLs with GNAT
30245 @section Using DLLs with GNAT
30248 * Creating an Ada Spec for the DLL Services::
30249 * Creating an Import Library::
30253 To use the services of a DLL, say @file{API.dll}, in your Ada application
30258 The Ada spec for the routines and/or variables you want to access in
30259 @file{API.dll}. If not available this Ada spec must be built from the C/C++
30260 header files provided with the DLL.
30263 The import library (@file{libAPI.dll.a} or @file{API.lib}). As previously
30264 mentioned an import library is a statically linked library containing the
30265 import table which will be filled at load time to point to the actual
30266 @file{API.dll} routines. Sometimes you don't have an import library for the
30267 DLL you want to use. The following sections will explain how to build
30268 one. Note that this is optional.
30271 The actual DLL, @file{API.dll}.
30275 Once you have all the above, to compile an Ada application that uses the
30276 services of @file{API.dll} and whose main subprogram is @code{My_Ada_App},
30277 you simply issue the command
30280 $ gnatmake my_ada_app -largs -lAPI
30284 The argument @option{-largs -lAPI} at the end of the @command{gnatmake} command
30285 tells the GNAT linker to look for an import library. The linker will
30286 look for a library name in this specific order:
30289 @item @file{libAPI.dll.a}
30290 @item @file{API.dll.a}
30291 @item @file{libAPI.a}
30292 @item @file{API.lib}
30293 @item @file{libAPI.dll}
30294 @item @file{API.dll}
30297 The first three are the GNU style import libraries. The third is the
30298 Microsoft style import libraries. The last two are the actual DLL names.
30300 Note that if the Ada package spec for @file{API.dll} contains the
30303 @smallexample @c ada
30304 pragma Linker_Options ("-lAPI");
30308 you do not have to add @option{-largs -lAPI} at the end of the
30309 @command{gnatmake} command.
30311 If any one of the items above is missing you will have to create it
30312 yourself. The following sections explain how to do so using as an
30313 example a fictitious DLL called @file{API.dll}.
30315 @node Creating an Ada Spec for the DLL Services
30316 @subsection Creating an Ada Spec for the DLL Services
30319 A DLL typically comes with a C/C++ header file which provides the
30320 definitions of the routines and variables exported by the DLL. The Ada
30321 equivalent of this header file is a package spec that contains definitions
30322 for the imported entities. If the DLL you intend to use does not come with
30323 an Ada spec you have to generate one such spec yourself. For example if
30324 the header file of @file{API.dll} is a file @file{api.h} containing the
30325 following two definitions:
30337 then the equivalent Ada spec could be:
30339 @smallexample @c ada
30342 with Interfaces.C.Strings;
30347 function Get (Str : C.Strings.Chars_Ptr) return C.int;
30350 pragma Import (C, Get);
30351 pragma Import (DLL, Some_Var);
30357 @node Creating an Import Library
30358 @subsection Creating an Import Library
30359 @cindex Import library
30362 * The Definition File::
30363 * GNAT-Style Import Library::
30364 * Microsoft-Style Import Library::
30368 If a Microsoft-style import library @file{API.lib} or a GNAT-style
30369 import library @file{libAPI.dll.a} or @file{libAPI.a} is available
30370 with @file{API.dll} you can skip this section. You can also skip this
30371 section if @file{API.dll} or @file{libAPI.dll} is built with GNU tools
30372 as in this case it is possible to link directly against the
30373 DLL. Otherwise read on.
30375 @node The Definition File
30376 @subsubsection The Definition File
30377 @cindex Definition file
30381 As previously mentioned, and unlike Unix systems, the list of symbols
30382 that are exported from a DLL must be provided explicitly in Windows.
30383 The main goal of a definition file is precisely that: list the symbols
30384 exported by a DLL. A definition file (usually a file with a @code{.def}
30385 suffix) has the following structure:
30390 @r{[}LIBRARY @var{name}@r{]}
30391 @r{[}DESCRIPTION @var{string}@r{]}
30401 @item LIBRARY @var{name}
30402 This section, which is optional, gives the name of the DLL.
30404 @item DESCRIPTION @var{string}
30405 This section, which is optional, gives a description string that will be
30406 embedded in the import library.
30409 This section gives the list of exported symbols (procedures, functions or
30410 variables). For instance in the case of @file{API.dll} the @code{EXPORTS}
30411 section of @file{API.def} looks like:
30425 Note that you must specify the correct suffix (@code{@@}@code{@var{nn}})
30426 (@pxref{Windows Calling Conventions}) for a Stdcall
30427 calling convention function in the exported symbols list.
30430 There can actually be other sections in a definition file, but these
30431 sections are not relevant to the discussion at hand.
30433 @node GNAT-Style Import Library
30434 @subsubsection GNAT-Style Import Library
30437 To create a static import library from @file{API.dll} with the GNAT tools
30438 you should proceed as follows:
30442 Create the definition file @file{API.def} (@pxref{The Definition File}).
30443 For that use the @code{dll2def} tool as follows:
30446 $ dll2def API.dll > API.def
30450 @code{dll2def} is a very simple tool: it takes as input a DLL and prints
30451 to standard output the list of entry points in the DLL. Note that if
30452 some routines in the DLL have the @code{Stdcall} convention
30453 (@pxref{Windows Calling Conventions}) with stripped @code{@@}@var{nn}
30454 suffix then you'll have to edit @file{api.def} to add it, and specify
30455 @option{-k} to @command{gnatdll} when creating the import library.
30458 Here are some hints to find the right @code{@@}@var{nn} suffix.
30462 If you have the Microsoft import library (.lib), it is possible to get
30463 the right symbols by using Microsoft @code{dumpbin} tool (see the
30464 corresponding Microsoft documentation for further details).
30467 $ dumpbin /exports api.lib
30471 If you have a message about a missing symbol at link time the compiler
30472 tells you what symbol is expected. You just have to go back to the
30473 definition file and add the right suffix.
30477 Build the import library @code{libAPI.dll.a}, using @code{gnatdll}
30478 (@pxref{Using gnatdll}) as follows:
30481 $ gnatdll -e API.def -d API.dll
30485 @code{gnatdll} takes as input a definition file @file{API.def} and the
30486 name of the DLL containing the services listed in the definition file
30487 @file{API.dll}. The name of the static import library generated is
30488 computed from the name of the definition file as follows: if the
30489 definition file name is @var{xyz}@code{.def}, the import library name will
30490 be @code{lib}@var{xyz}@code{.a}. Note that in the previous example option
30491 @option{-e} could have been removed because the name of the definition
30492 file (before the ``@code{.def}'' suffix) is the same as the name of the
30493 DLL (@pxref{Using gnatdll} for more information about @code{gnatdll}).
30496 @node Microsoft-Style Import Library
30497 @subsubsection Microsoft-Style Import Library
30500 With GNAT you can either use a GNAT-style or Microsoft-style import
30501 library. A Microsoft import library is needed only if you plan to make an
30502 Ada DLL available to applications developed with Microsoft
30503 tools (@pxref{Mixed-Language Programming on Windows}).
30505 To create a Microsoft-style import library for @file{API.dll} you
30506 should proceed as follows:
30510 Create the definition file @file{API.def} from the DLL. For this use either
30511 the @code{dll2def} tool as described above or the Microsoft @code{dumpbin}
30512 tool (see the corresponding Microsoft documentation for further details).
30515 Build the actual import library using Microsoft's @code{lib} utility:
30518 $ lib -machine:IX86 -def:API.def -out:API.lib
30522 If you use the above command the definition file @file{API.def} must
30523 contain a line giving the name of the DLL:
30530 See the Microsoft documentation for further details about the usage of
30534 @node Building DLLs with GNAT Project files
30535 @section Building DLLs with GNAT Project files
30536 @cindex DLLs, building
30539 There is nothing specific to Windows in the build process.
30540 @pxref{Library Projects}.
30543 Due to a system limitation, it is not possible under Windows to create threads
30544 when inside the @code{DllMain} routine which is used for auto-initialization
30545 of shared libraries, so it is not possible to have library level tasks in SALs.
30547 @node Building DLLs with GNAT
30548 @section Building DLLs with GNAT
30549 @cindex DLLs, building
30552 This section explain how to build DLLs using the GNAT built-in DLL
30553 support. With the following procedure it is straight forward to build
30554 and use DLLs with GNAT.
30558 @item building object files
30560 The first step is to build all objects files that are to be included
30561 into the DLL. This is done by using the standard @command{gnatmake} tool.
30563 @item building the DLL
30565 To build the DLL you must use @command{gcc}'s @option{-shared} and
30566 @option{-shared-libgcc} options. It is quite simple to use this method:
30569 $ gcc -shared -shared-libgcc -o api.dll obj1.o obj2.o @dots{}
30572 It is important to note that in this case all symbols found in the
30573 object files are automatically exported. It is possible to restrict
30574 the set of symbols to export by passing to @command{gcc} a definition
30575 file, @pxref{The Definition File}. For example:
30578 $ gcc -shared -shared-libgcc -o api.dll api.def obj1.o obj2.o @dots{}
30581 If you use a definition file you must export the elaboration procedures
30582 for every package that required one. Elaboration procedures are named
30583 using the package name followed by "_E".
30585 @item preparing DLL to be used
30587 For the DLL to be used by client programs the bodies must be hidden
30588 from it and the .ali set with read-only attribute. This is very important
30589 otherwise GNAT will recompile all packages and will not actually use
30590 the code in the DLL. For example:
30594 $ copy *.ads *.ali api.dll apilib
30595 $ attrib +R apilib\*.ali
30600 At this point it is possible to use the DLL by directly linking
30601 against it. Note that you must use the GNAT shared runtime when using
30602 GNAT shared libraries. This is achieved by using @option{-shared} binder's
30606 $ gnatmake main -Iapilib -bargs -shared -largs -Lapilib -lAPI
30609 @node Building DLLs with gnatdll
30610 @section Building DLLs with gnatdll
30611 @cindex DLLs, building
30614 * Limitations When Using Ada DLLs from Ada::
30615 * Exporting Ada Entities::
30616 * Ada DLLs and Elaboration::
30617 * Ada DLLs and Finalization::
30618 * Creating a Spec for Ada DLLs::
30619 * Creating the Definition File::
30624 Note that it is preferred to use GNAT Project files
30625 (@pxref{Building DLLs with GNAT Project files}) or the built-in GNAT
30626 DLL support (@pxref{Building DLLs with GNAT}) or to build DLLs.
30628 This section explains how to build DLLs containing Ada code using
30629 @code{gnatdll}. These DLLs will be referred to as Ada DLLs in the
30630 remainder of this section.
30632 The steps required to build an Ada DLL that is to be used by Ada as well as
30633 non-Ada applications are as follows:
30637 You need to mark each Ada @i{entity} exported by the DLL with a @code{C} or
30638 @code{Stdcall} calling convention to avoid any Ada name mangling for the
30639 entities exported by the DLL (@pxref{Exporting Ada Entities}). You can
30640 skip this step if you plan to use the Ada DLL only from Ada applications.
30643 Your Ada code must export an initialization routine which calls the routine
30644 @code{adainit} generated by @command{gnatbind} to perform the elaboration of
30645 the Ada code in the DLL (@pxref{Ada DLLs and Elaboration}). The initialization
30646 routine exported by the Ada DLL must be invoked by the clients of the DLL
30647 to initialize the DLL.
30650 When useful, the DLL should also export a finalization routine which calls
30651 routine @code{adafinal} generated by @command{gnatbind} to perform the
30652 finalization of the Ada code in the DLL (@pxref{Ada DLLs and Finalization}).
30653 The finalization routine exported by the Ada DLL must be invoked by the
30654 clients of the DLL when the DLL services are no further needed.
30657 You must provide a spec for the services exported by the Ada DLL in each
30658 of the programming languages to which you plan to make the DLL available.
30661 You must provide a definition file listing the exported entities
30662 (@pxref{The Definition File}).
30665 Finally you must use @code{gnatdll} to produce the DLL and the import
30666 library (@pxref{Using gnatdll}).
30670 Note that a relocatable DLL stripped using the @code{strip}
30671 binutils tool will not be relocatable anymore. To build a DLL without
30672 debug information pass @code{-largs -s} to @code{gnatdll}. This
30673 restriction does not apply to a DLL built using a Library Project.
30674 @pxref{Library Projects}.
30676 @node Limitations When Using Ada DLLs from Ada
30677 @subsection Limitations When Using Ada DLLs from Ada
30680 When using Ada DLLs from Ada applications there is a limitation users
30681 should be aware of. Because on Windows the GNAT run time is not in a DLL of
30682 its own, each Ada DLL includes a part of the GNAT run time. Specifically,
30683 each Ada DLL includes the services of the GNAT run time that are necessary
30684 to the Ada code inside the DLL. As a result, when an Ada program uses an
30685 Ada DLL there are two independent GNAT run times: one in the Ada DLL and
30686 one in the main program.
30688 It is therefore not possible to exchange GNAT run-time objects between the
30689 Ada DLL and the main Ada program. Example of GNAT run-time objects are file
30690 handles (e.g.@: @code{Text_IO.File_Type}), tasks types, protected objects
30693 It is completely safe to exchange plain elementary, array or record types,
30694 Windows object handles, etc.
30696 @node Exporting Ada Entities
30697 @subsection Exporting Ada Entities
30698 @cindex Export table
30701 Building a DLL is a way to encapsulate a set of services usable from any
30702 application. As a result, the Ada entities exported by a DLL should be
30703 exported with the @code{C} or @code{Stdcall} calling conventions to avoid
30704 any Ada name mangling. As an example here is an Ada package
30705 @code{API}, spec and body, exporting two procedures, a function, and a
30708 @smallexample @c ada
30711 with Interfaces.C; use Interfaces;
30713 Count : C.int := 0;
30714 function Factorial (Val : C.int) return C.int;
30716 procedure Initialize_API;
30717 procedure Finalize_API;
30718 -- Initialization & Finalization routines. More in the next section.
30720 pragma Export (C, Initialize_API);
30721 pragma Export (C, Finalize_API);
30722 pragma Export (C, Count);
30723 pragma Export (C, Factorial);
30729 @smallexample @c ada
30732 package body API is
30733 function Factorial (Val : C.int) return C.int is
30736 Count := Count + 1;
30737 for K in 1 .. Val loop
30743 procedure Initialize_API is
30745 pragma Import (C, Adainit);
30748 end Initialize_API;
30750 procedure Finalize_API is
30751 procedure Adafinal;
30752 pragma Import (C, Adafinal);
30762 If the Ada DLL you are building will only be used by Ada applications
30763 you do not have to export Ada entities with a @code{C} or @code{Stdcall}
30764 convention. As an example, the previous package could be written as
30767 @smallexample @c ada
30771 Count : Integer := 0;
30772 function Factorial (Val : Integer) return Integer;
30774 procedure Initialize_API;
30775 procedure Finalize_API;
30776 -- Initialization and Finalization routines.
30782 @smallexample @c ada
30785 package body API is
30786 function Factorial (Val : Integer) return Integer is
30787 Fact : Integer := 1;
30789 Count := Count + 1;
30790 for K in 1 .. Val loop
30797 -- The remainder of this package body is unchanged.
30804 Note that if you do not export the Ada entities with a @code{C} or
30805 @code{Stdcall} convention you will have to provide the mangled Ada names
30806 in the definition file of the Ada DLL
30807 (@pxref{Creating the Definition File}).
30809 @node Ada DLLs and Elaboration
30810 @subsection Ada DLLs and Elaboration
30811 @cindex DLLs and elaboration
30814 The DLL that you are building contains your Ada code as well as all the
30815 routines in the Ada library that are needed by it. The first thing a
30816 user of your DLL must do is elaborate the Ada code
30817 (@pxref{Elaboration Order Handling in GNAT}).
30819 To achieve this you must export an initialization routine
30820 (@code{Initialize_API} in the previous example), which must be invoked
30821 before using any of the DLL services. This elaboration routine must call
30822 the Ada elaboration routine @code{adainit} generated by the GNAT binder
30823 (@pxref{Binding with Non-Ada Main Programs}). See the body of
30824 @code{Initialize_Api} for an example. Note that the GNAT binder is
30825 automatically invoked during the DLL build process by the @code{gnatdll}
30826 tool (@pxref{Using gnatdll}).
30828 When a DLL is loaded, Windows systematically invokes a routine called
30829 @code{DllMain}. It would therefore be possible to call @code{adainit}
30830 directly from @code{DllMain} without having to provide an explicit
30831 initialization routine. Unfortunately, it is not possible to call
30832 @code{adainit} from the @code{DllMain} if your program has library level
30833 tasks because access to the @code{DllMain} entry point is serialized by
30834 the system (that is, only a single thread can execute ``through'' it at a
30835 time), which means that the GNAT run time will deadlock waiting for the
30836 newly created task to complete its initialization.
30838 @node Ada DLLs and Finalization
30839 @subsection Ada DLLs and Finalization
30840 @cindex DLLs and finalization
30843 When the services of an Ada DLL are no longer needed, the client code should
30844 invoke the DLL finalization routine, if available. The DLL finalization
30845 routine is in charge of releasing all resources acquired by the DLL. In the
30846 case of the Ada code contained in the DLL, this is achieved by calling
30847 routine @code{adafinal} generated by the GNAT binder
30848 (@pxref{Binding with Non-Ada Main Programs}).
30849 See the body of @code{Finalize_Api} for an
30850 example. As already pointed out the GNAT binder is automatically invoked
30851 during the DLL build process by the @code{gnatdll} tool
30852 (@pxref{Using gnatdll}).
30854 @node Creating a Spec for Ada DLLs
30855 @subsection Creating a Spec for Ada DLLs
30858 To use the services exported by the Ada DLL from another programming
30859 language (e.g.@: C), you have to translate the specs of the exported Ada
30860 entities in that language. For instance in the case of @code{API.dll},
30861 the corresponding C header file could look like:
30866 extern int *_imp__count;
30867 #define count (*_imp__count)
30868 int factorial (int);
30874 It is important to understand that when building an Ada DLL to be used by
30875 other Ada applications, you need two different specs for the packages
30876 contained in the DLL: one for building the DLL and the other for using
30877 the DLL. This is because the @code{DLL} calling convention is needed to
30878 use a variable defined in a DLL, but when building the DLL, the variable
30879 must have either the @code{Ada} or @code{C} calling convention. As an
30880 example consider a DLL comprising the following package @code{API}:
30882 @smallexample @c ada
30886 Count : Integer := 0;
30888 -- Remainder of the package omitted.
30895 After producing a DLL containing package @code{API}, the spec that
30896 must be used to import @code{API.Count} from Ada code outside of the
30899 @smallexample @c ada
30904 pragma Import (DLL, Count);
30910 @node Creating the Definition File
30911 @subsection Creating the Definition File
30914 The definition file is the last file needed to build the DLL. It lists
30915 the exported symbols. As an example, the definition file for a DLL
30916 containing only package @code{API} (where all the entities are exported
30917 with a @code{C} calling convention) is:
30932 If the @code{C} calling convention is missing from package @code{API},
30933 then the definition file contains the mangled Ada names of the above
30934 entities, which in this case are:
30943 api__initialize_api
30948 @node Using gnatdll
30949 @subsection Using @code{gnatdll}
30953 * gnatdll Example::
30954 * gnatdll behind the Scenes::
30959 @code{gnatdll} is a tool to automate the DLL build process once all the Ada
30960 and non-Ada sources that make up your DLL have been compiled.
30961 @code{gnatdll} is actually in charge of two distinct tasks: build the
30962 static import library for the DLL and the actual DLL. The form of the
30963 @code{gnatdll} command is
30967 @c $ gnatdll @ovar{switches} @var{list-of-files} @r{[}-largs @var{opts}@r{]}
30968 @c Expanding @ovar macro inline (explanation in macro def comments)
30969 $ gnatdll @r{[}@var{switches}@r{]} @var{list-of-files} @r{[}-largs @var{opts}@r{]}
30974 where @var{list-of-files} is a list of ALI and object files. The object
30975 file list must be the exact list of objects corresponding to the non-Ada
30976 sources whose services are to be included in the DLL. The ALI file list
30977 must be the exact list of ALI files for the corresponding Ada sources
30978 whose services are to be included in the DLL. If @var{list-of-files} is
30979 missing, only the static import library is generated.
30982 You may specify any of the following switches to @code{gnatdll}:
30985 @c @item -a@ovar{address}
30986 @c Expanding @ovar macro inline (explanation in macro def comments)
30987 @item -a@r{[}@var{address}@r{]}
30988 @cindex @option{-a} (@code{gnatdll})
30989 Build a non-relocatable DLL at @var{address}. If @var{address} is not
30990 specified the default address @var{0x11000000} will be used. By default,
30991 when this switch is missing, @code{gnatdll} builds relocatable DLL. We
30992 advise the reader to build relocatable DLL.
30994 @item -b @var{address}
30995 @cindex @option{-b} (@code{gnatdll})
30996 Set the relocatable DLL base address. By default the address is
30999 @item -bargs @var{opts}
31000 @cindex @option{-bargs} (@code{gnatdll})
31001 Binder options. Pass @var{opts} to the binder.
31003 @item -d @var{dllfile}
31004 @cindex @option{-d} (@code{gnatdll})
31005 @var{dllfile} is the name of the DLL. This switch must be present for
31006 @code{gnatdll} to do anything. The name of the generated import library is
31007 obtained algorithmically from @var{dllfile} as shown in the following
31008 example: if @var{dllfile} is @code{xyz.dll}, the import library name is
31009 @code{libxyz.dll.a}. The name of the definition file to use (if not specified
31010 by option @option{-e}) is obtained algorithmically from @var{dllfile}
31011 as shown in the following example:
31012 if @var{dllfile} is @code{xyz.dll}, the definition
31013 file used is @code{xyz.def}.
31015 @item -e @var{deffile}
31016 @cindex @option{-e} (@code{gnatdll})
31017 @var{deffile} is the name of the definition file.
31020 @cindex @option{-g} (@code{gnatdll})
31021 Generate debugging information. This information is stored in the object
31022 file and copied from there to the final DLL file by the linker,
31023 where it can be read by the debugger. You must use the
31024 @option{-g} switch if you plan on using the debugger or the symbolic
31028 @cindex @option{-h} (@code{gnatdll})
31029 Help mode. Displays @code{gnatdll} switch usage information.
31032 @cindex @option{-I} (@code{gnatdll})
31033 Direct @code{gnatdll} to search the @var{dir} directory for source and
31034 object files needed to build the DLL.
31035 (@pxref{Search Paths and the Run-Time Library (RTL)}).
31038 @cindex @option{-k} (@code{gnatdll})
31039 Removes the @code{@@}@var{nn} suffix from the import library's exported
31040 names, but keeps them for the link names. You must specify this
31041 option if you want to use a @code{Stdcall} function in a DLL for which
31042 the @code{@@}@var{nn} suffix has been removed. This is the case for most
31043 of the Windows NT DLL for example. This option has no effect when
31044 @option{-n} option is specified.
31046 @item -l @var{file}
31047 @cindex @option{-l} (@code{gnatdll})
31048 The list of ALI and object files used to build the DLL are listed in
31049 @var{file}, instead of being given in the command line. Each line in
31050 @var{file} contains the name of an ALI or object file.
31053 @cindex @option{-n} (@code{gnatdll})
31054 No Import. Do not create the import library.
31057 @cindex @option{-q} (@code{gnatdll})
31058 Quiet mode. Do not display unnecessary messages.
31061 @cindex @option{-v} (@code{gnatdll})
31062 Verbose mode. Display extra information.
31064 @item -largs @var{opts}
31065 @cindex @option{-largs} (@code{gnatdll})
31066 Linker options. Pass @var{opts} to the linker.
31069 @node gnatdll Example
31070 @subsubsection @code{gnatdll} Example
31073 As an example the command to build a relocatable DLL from @file{api.adb}
31074 once @file{api.adb} has been compiled and @file{api.def} created is
31077 $ gnatdll -d api.dll api.ali
31081 The above command creates two files: @file{libapi.dll.a} (the import
31082 library) and @file{api.dll} (the actual DLL). If you want to create
31083 only the DLL, just type:
31086 $ gnatdll -d api.dll -n api.ali
31090 Alternatively if you want to create just the import library, type:
31093 $ gnatdll -d api.dll
31096 @node gnatdll behind the Scenes
31097 @subsubsection @code{gnatdll} behind the Scenes
31100 This section details the steps involved in creating a DLL. @code{gnatdll}
31101 does these steps for you. Unless you are interested in understanding what
31102 goes on behind the scenes, you should skip this section.
31104 We use the previous example of a DLL containing the Ada package @code{API},
31105 to illustrate the steps necessary to build a DLL. The starting point is a
31106 set of objects that will make up the DLL and the corresponding ALI
31107 files. In the case of this example this means that @file{api.o} and
31108 @file{api.ali} are available. To build a relocatable DLL, @code{gnatdll} does
31113 @code{gnatdll} builds the base file (@file{api.base}). A base file gives
31114 the information necessary to generate relocation information for the
31120 $ gnatlink api -o api.jnk -mdll -Wl,--base-file,api.base
31125 In addition to the base file, the @command{gnatlink} command generates an
31126 output file @file{api.jnk} which can be discarded. The @option{-mdll} switch
31127 asks @command{gnatlink} to generate the routines @code{DllMain} and
31128 @code{DllMainCRTStartup} that are called by the Windows loader when the DLL
31129 is loaded into memory.
31132 @code{gnatdll} uses @code{dlltool} (@pxref{Using dlltool}) to build the
31133 export table (@file{api.exp}). The export table contains the relocation
31134 information in a form which can be used during the final link to ensure
31135 that the Windows loader is able to place the DLL anywhere in memory.
31139 $ dlltool --dllname api.dll --def api.def --base-file api.base \
31140 --output-exp api.exp
31145 @code{gnatdll} builds the base file using the new export table. Note that
31146 @command{gnatbind} must be called once again since the binder generated file
31147 has been deleted during the previous call to @command{gnatlink}.
31152 $ gnatlink api -o api.jnk api.exp -mdll
31153 -Wl,--base-file,api.base
31158 @code{gnatdll} builds the new export table using the new base file and
31159 generates the DLL import library @file{libAPI.dll.a}.
31163 $ dlltool --dllname api.dll --def api.def --base-file api.base \
31164 --output-exp api.exp --output-lib libAPI.a
31169 Finally @code{gnatdll} builds the relocatable DLL using the final export
31175 $ gnatlink api api.exp -o api.dll -mdll
31180 @node Using dlltool
31181 @subsubsection Using @code{dlltool}
31184 @code{dlltool} is the low-level tool used by @code{gnatdll} to build
31185 DLLs and static import libraries. This section summarizes the most
31186 common @code{dlltool} switches. The form of the @code{dlltool} command
31190 @c $ dlltool @ovar{switches}
31191 @c Expanding @ovar macro inline (explanation in macro def comments)
31192 $ dlltool @r{[}@var{switches}@r{]}
31196 @code{dlltool} switches include:
31199 @item --base-file @var{basefile}
31200 @cindex @option{--base-file} (@command{dlltool})
31201 Read the base file @var{basefile} generated by the linker. This switch
31202 is used to create a relocatable DLL.
31204 @item --def @var{deffile}
31205 @cindex @option{--def} (@command{dlltool})
31206 Read the definition file.
31208 @item --dllname @var{name}
31209 @cindex @option{--dllname} (@command{dlltool})
31210 Gives the name of the DLL. This switch is used to embed the name of the
31211 DLL in the static import library generated by @code{dlltool} with switch
31212 @option{--output-lib}.
31215 @cindex @option{-k} (@command{dlltool})
31216 Kill @code{@@}@var{nn} from exported names
31217 (@pxref{Windows Calling Conventions}
31218 for a discussion about @code{Stdcall}-style symbols.
31221 @cindex @option{--help} (@command{dlltool})
31222 Prints the @code{dlltool} switches with a concise description.
31224 @item --output-exp @var{exportfile}
31225 @cindex @option{--output-exp} (@command{dlltool})
31226 Generate an export file @var{exportfile}. The export file contains the
31227 export table (list of symbols in the DLL) and is used to create the DLL.
31229 @item --output-lib @var{libfile}
31230 @cindex @option{--output-lib} (@command{dlltool})
31231 Generate a static import library @var{libfile}.
31234 @cindex @option{-v} (@command{dlltool})
31237 @item --as @var{assembler-name}
31238 @cindex @option{--as} (@command{dlltool})
31239 Use @var{assembler-name} as the assembler. The default is @code{as}.
31242 @node GNAT and Windows Resources
31243 @section GNAT and Windows Resources
31244 @cindex Resources, windows
31247 * Building Resources::
31248 * Compiling Resources::
31249 * Using Resources::
31253 Resources are an easy way to add Windows specific objects to your
31254 application. The objects that can be added as resources include:
31263 @item string tables
31273 @item version information
31276 For example, a version information resource can be defined as follow and
31277 embedded into an executable or DLL:
31279 A version information resource can be used to embed information into an
31280 executable or a DLL. These information can be viewed using the file properties
31281 from the Windows Explorer. Here is an example of a version information
31287 FILEVERSION 1,0,0,0
31288 PRODUCTVERSION 1,0,0,0
31290 BLOCK "StringFileInfo"
31294 VALUE "CompanyName", "My Company Name"
31295 VALUE "FileDescription", "My application"
31296 VALUE "FileVersion", "1.0"
31297 VALUE "InternalName", "my_app"
31298 VALUE "LegalCopyright", "My Name"
31299 VALUE "OriginalFilename", "my_app.exe"
31300 VALUE "ProductName", "My App"
31301 VALUE "ProductVersion", "1.0"
31305 BLOCK "VarFileInfo"
31307 VALUE "Translation", 0x809, 1252
31313 The value @code{0809} (langID) is for the U.K English language and
31314 @code{04E4} (charsetID), which is equal to @code{1252} decimal, for
31318 This section explains how to build, compile and use resources. Note that this
31319 section does not cover all resource objects, for a complete description see
31320 the corresponding Microsoft documentation.
31322 @node Building Resources
31323 @subsection Building Resources
31324 @cindex Resources, building
31327 A resource file is an ASCII file. By convention resource files have an
31328 @file{.rc} extension.
31329 The easiest way to build a resource file is to use Microsoft tools
31330 such as @code{imagedit.exe} to build bitmaps, icons and cursors and
31331 @code{dlgedit.exe} to build dialogs.
31332 It is always possible to build an @file{.rc} file yourself by writing a
31335 It is not our objective to explain how to write a resource file. A
31336 complete description of the resource script language can be found in the
31337 Microsoft documentation.
31339 @node Compiling Resources
31340 @subsection Compiling Resources
31343 @cindex Resources, compiling
31346 This section describes how to build a GNAT-compatible (COFF) object file
31347 containing the resources. This is done using the Resource Compiler
31348 @code{windres} as follows:
31351 $ windres -i myres.rc -o myres.o
31355 By default @code{windres} will run @command{gcc} to preprocess the @file{.rc}
31356 file. You can specify an alternate preprocessor (usually named
31357 @file{cpp.exe}) using the @code{windres} @option{--preprocessor}
31358 parameter. A list of all possible options may be obtained by entering
31359 the command @code{windres} @option{--help}.
31361 It is also possible to use the Microsoft resource compiler @code{rc.exe}
31362 to produce a @file{.res} file (binary resource file). See the
31363 corresponding Microsoft documentation for further details. In this case
31364 you need to use @code{windres} to translate the @file{.res} file to a
31365 GNAT-compatible object file as follows:
31368 $ windres -i myres.res -o myres.o
31371 @node Using Resources
31372 @subsection Using Resources
31373 @cindex Resources, using
31376 To include the resource file in your program just add the
31377 GNAT-compatible object file for the resource(s) to the linker
31378 arguments. With @command{gnatmake} this is done by using the @option{-largs}
31382 $ gnatmake myprog -largs myres.o
31385 @node Debugging a DLL
31386 @section Debugging a DLL
31387 @cindex DLL debugging
31390 * Program and DLL Both Built with GCC/GNAT::
31391 * Program Built with Foreign Tools and DLL Built with GCC/GNAT::
31395 Debugging a DLL is similar to debugging a standard program. But
31396 we have to deal with two different executable parts: the DLL and the
31397 program that uses it. We have the following four possibilities:
31401 The program and the DLL are built with @code{GCC/GNAT}.
31403 The program is built with foreign tools and the DLL is built with
31406 The program is built with @code{GCC/GNAT} and the DLL is built with
31411 In this section we address only cases one and two above.
31412 There is no point in trying to debug
31413 a DLL with @code{GNU/GDB}, if there is no GDB-compatible debugging
31414 information in it. To do so you must use a debugger compatible with the
31415 tools suite used to build the DLL.
31417 @node Program and DLL Both Built with GCC/GNAT
31418 @subsection Program and DLL Both Built with GCC/GNAT
31421 This is the simplest case. Both the DLL and the program have @code{GDB}
31422 compatible debugging information. It is then possible to break anywhere in
31423 the process. Let's suppose here that the main procedure is named
31424 @code{ada_main} and that in the DLL there is an entry point named
31428 The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) and
31429 program must have been built with the debugging information (see GNAT -g
31430 switch). Here are the step-by-step instructions for debugging it:
31433 @item Launch @code{GDB} on the main program.
31439 @item Start the program and stop at the beginning of the main procedure
31446 This step is required to be able to set a breakpoint inside the DLL. As long
31447 as the program is not run, the DLL is not loaded. This has the
31448 consequence that the DLL debugging information is also not loaded, so it is not
31449 possible to set a breakpoint in the DLL.
31451 @item Set a breakpoint inside the DLL
31454 (gdb) break ada_dll
31461 At this stage a breakpoint is set inside the DLL. From there on
31462 you can use the standard approach to debug the whole program
31463 (@pxref{Running and Debugging Ada Programs}).
31466 @c This used to work, probably because the DLLs were non-relocatable
31467 @c keep this section around until the problem is sorted out.
31469 To break on the @code{DllMain} routine it is not possible to follow
31470 the procedure above. At the time the program stop on @code{ada_main}
31471 the @code{DllMain} routine as already been called. Either you can use
31472 the procedure below @pxref{Debugging the DLL Directly} or this procedure:
31475 @item Launch @code{GDB} on the main program.
31481 @item Load DLL symbols
31484 (gdb) add-sym api.dll
31487 @item Set a breakpoint inside the DLL
31490 (gdb) break ada_dll.adb:45
31493 Note that at this point it is not possible to break using the routine symbol
31494 directly as the program is not yet running. The solution is to break
31495 on the proper line (break in @file{ada_dll.adb} line 45).
31497 @item Start the program
31506 @node Program Built with Foreign Tools and DLL Built with GCC/GNAT
31507 @subsection Program Built with Foreign Tools and DLL Built with GCC/GNAT
31510 * Debugging the DLL Directly::
31511 * Attaching to a Running Process::
31515 In this case things are slightly more complex because it is not possible to
31516 start the main program and then break at the beginning to load the DLL and the
31517 associated DLL debugging information. It is not possible to break at the
31518 beginning of the program because there is no @code{GDB} debugging information,
31519 and therefore there is no direct way of getting initial control. This
31520 section addresses this issue by describing some methods that can be used
31521 to break somewhere in the DLL to debug it.
31524 First suppose that the main procedure is named @code{main} (this is for
31525 example some C code built with Microsoft Visual C) and that there is a
31526 DLL named @code{test.dll} containing an Ada entry point named
31530 The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) must have
31531 been built with debugging information (see GNAT -g option).
31533 @node Debugging the DLL Directly
31534 @subsubsection Debugging the DLL Directly
31538 Find out the executable starting address
31541 $ objdump --file-header main.exe
31544 The starting address is reported on the last line. For example:
31547 main.exe: file format pei-i386
31548 architecture: i386, flags 0x0000010a:
31549 EXEC_P, HAS_DEBUG, D_PAGED
31550 start address 0x00401010
31554 Launch the debugger on the executable.
31561 Set a breakpoint at the starting address, and launch the program.
31564 $ (gdb) break *0x00401010
31568 The program will stop at the given address.
31571 Set a breakpoint on a DLL subroutine.
31574 (gdb) break ada_dll.adb:45
31577 Or if you want to break using a symbol on the DLL, you need first to
31578 select the Ada language (language used by the DLL).
31581 (gdb) set language ada
31582 (gdb) break ada_dll
31586 Continue the program.
31593 This will run the program until it reaches the breakpoint that has been
31594 set. From that point you can use the standard way to debug a program
31595 as described in (@pxref{Running and Debugging Ada Programs}).
31600 It is also possible to debug the DLL by attaching to a running process.
31602 @node Attaching to a Running Process
31603 @subsubsection Attaching to a Running Process
31604 @cindex DLL debugging, attach to process
31607 With @code{GDB} it is always possible to debug a running process by
31608 attaching to it. It is possible to debug a DLL this way. The limitation
31609 of this approach is that the DLL must run long enough to perform the
31610 attach operation. It may be useful for instance to insert a time wasting
31611 loop in the code of the DLL to meet this criterion.
31615 @item Launch the main program @file{main.exe}.
31621 @item Use the Windows @i{Task Manager} to find the process ID. Let's say
31622 that the process PID for @file{main.exe} is 208.
31630 @item Attach to the running process to be debugged.
31636 @item Load the process debugging information.
31639 (gdb) symbol-file main.exe
31642 @item Break somewhere in the DLL.
31645 (gdb) break ada_dll
31648 @item Continue process execution.
31657 This last step will resume the process execution, and stop at
31658 the breakpoint we have set. From there you can use the standard
31659 approach to debug a program as described in
31660 (@pxref{Running and Debugging Ada Programs}).
31662 @node Setting Stack Size from gnatlink
31663 @section Setting Stack Size from @command{gnatlink}
31666 It is possible to specify the program stack size at link time. On modern
31667 versions of Windows, starting with XP, this is mostly useful to set the size of
31668 the main stack (environment task). The other task stacks are set with pragma
31669 Storage_Size or with the @command{gnatbind -d} command.
31671 Since older versions of Windows (2000, NT4, etc.) do not allow setting the
31672 reserve size of individual tasks, the link-time stack size applies to all
31673 tasks, and pragma Storage_Size has no effect.
31674 In particular, Stack Overflow checks are made against this
31675 link-time specified size.
31677 This setting can be done with
31678 @command{gnatlink} using either:
31682 @item using @option{-Xlinker} linker option
31685 $ gnatlink hello -Xlinker --stack=0x10000,0x1000
31688 This sets the stack reserve size to 0x10000 bytes and the stack commit
31689 size to 0x1000 bytes.
31691 @item using @option{-Wl} linker option
31694 $ gnatlink hello -Wl,--stack=0x1000000
31697 This sets the stack reserve size to 0x1000000 bytes. Note that with
31698 @option{-Wl} option it is not possible to set the stack commit size
31699 because the coma is a separator for this option.
31703 @node Setting Heap Size from gnatlink
31704 @section Setting Heap Size from @command{gnatlink}
31707 Under Windows systems, it is possible to specify the program heap size from
31708 @command{gnatlink} using either:
31712 @item using @option{-Xlinker} linker option
31715 $ gnatlink hello -Xlinker --heap=0x10000,0x1000
31718 This sets the heap reserve size to 0x10000 bytes and the heap commit
31719 size to 0x1000 bytes.
31721 @item using @option{-Wl} linker option
31724 $ gnatlink hello -Wl,--heap=0x1000000
31727 This sets the heap reserve size to 0x1000000 bytes. Note that with
31728 @option{-Wl} option it is not possible to set the heap commit size
31729 because the coma is a separator for this option.
31733 @node Mac OS Topics
31734 @appendix Mac OS Topics
31738 This chapter describes topics that are specific to Apple's OS X
31742 * Codesigning the Debugger::
31745 @node Codesigning the Debugger
31746 @section Codesigning the Debugger
31749 The Darwin Kernel requires the debugger to have special permissions
31750 before it is allowed to control other processes. These permissions
31751 are granted by codesigning the GDB executable. Without these
31752 permissions, the debugger will report error messages such as:
31755 Starting program: /x/y/foo
31756 Unable to find Mach task port for process-id 28885: (os/kern) failure (0x5).
31757 (please check gdb is codesigned - see taskgated(8))
31760 Codesigning requires a certificate. The following procedure explains
31764 @item Start the Keychain Access application (in
31765 /Applications/Utilities/Keychain Access.app)
31767 @item Select the Keychain Access -> Certificate Assistant ->
31768 Create a Certificate... menu
31773 @item Choose a name for the new certificate (this procedure will use
31774 "gdb-cert" as an example)
31776 @item Set "Identity Type" to "Self Signed Root"
31778 @item Set "Certificate Type" to "Code Signing"
31780 @item Activate the "Let me override defaults" option
31784 @item Click several times on "Continue" until the "Specify a Location
31785 For The Certificate" screen appears, then set "Keychain" to "System"
31787 @item Click on "Continue" until the certificate is created
31789 @item Finally, in the view, double-click on the new certificate,
31790 and set "When using this certificate" to "Always Trust"
31792 @item Exit the Keychain Access application and restart the computer
31793 (this is unfortunately required)
31797 Once a certificate has been created, the debugger can be codesigned
31798 as follow. In a Terminal, run the following command...
31801 codesign -f -s "gdb-cert" <gnat_install_prefix>/bin/gdb
31804 ... where "gdb-cert" should be replaced by the actual certificate
31805 name chosen above, and <gnat_install_prefix> should be replaced by
31806 the location where you installed GNAT.
31808 @c **********************************
31809 @c * GNU Free Documentation License *
31810 @c **********************************
31812 @c GNU Free Documentation License
31820 @c Put table of contents at end, otherwise it precedes the "title page" in
31821 @c the .txt version
31822 @c Edit the pdf file to move the contents to the beginning, after the title