Implement -mmemcpy-strategy= and -mmemset-strategy= options
[official-gcc.git] / gcc / ada / gnat_ugn.texi
blob0a5f07db04aa995d1734a24165a7601d7b73adce
1 \input texinfo   @c -*-texinfo-*-
2 @c %**start of header
4 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
5 @c                                                                            o
6 @c                            GNAT DOCUMENTATION                              o
7 @c                                                                            o
8 @c                             G N A T _ U G N                                o
9 @c                                                                            o
10 @c           Copyright (C) 1992-2013, Free Software Foundation, Inc.          o
11 @c                                                                            o
12 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
14 @setfilename gnat_ugn.info
16 @copying
17 Copyright @copyright{} 1995-2009 Free Software Foundation,
18 Inc.
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''.
26 @end copying
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:
35 @c          @chapter
36 @c          @section
37 @c          @subsection
38 @c          @subsubsection
39 @c          @subsubsubsection
41 @c          @end smallexample
42 @c          @end itemize
43 @c          @end enumerate
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"
68 @c     or "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
79 @c        Windows.
81 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
83 @set NOW January 2007
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}.
90 @set FSFEDITION
91 @set EDITION GNAT
93 @ifset unw
94 @set PLATFORM
95 @set TITLESUFFIX
96 @end ifset
98 @ifset vms
99 @set PLATFORM OpenVMS
100 @set TITLESUFFIX for OpenVMS
101 @end ifset
103 @c @ovar(ARG)
104 @c ----------
105 @c The ARG is an optional argument.  To be used for macro arguments in
106 @c their documentation (@defmac).
107 @macro ovar{varname}
108 @r{[}@var{\varname\}@r{]}@c
109 @end macro
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
120 @direntry
121 * @value{EDITION} User's Guide: (gnat_ugn). @value{PLATFORM}
122 @end direntry
124 @include gcc-common.texi
126 @setchapternewpage odd
127 @syncodeindex fn cp
128 @c %**end of header
130 @titlepage
131 @title @value{EDITION} User's Guide
132 @ifset vms
133 @sp 1
134 @flushright
135 @titlefont{@i{@value{PLATFORM}}}
136 @end flushright
137 @end ifset
139 @sp 2
141 @subtitle GNAT, The GNU Ada Compiler
142 @versionsubtitle
143 @author AdaCore
145 @page
146 @vskip 0pt plus 1filll
148 @insertcopying
150 @end titlepage
152 @ifnottex
153 @node Top, About This Guide, (dir), (dir)
154 @top @value{EDITION} User's Guide
156 @noindent
157 @value{EDITION} User's Guide @value{PLATFORM}
159 @noindent
160 GNAT, The GNU Ada Compiler@*
161 GCC version @value{version-GCC}@*
163 @noindent
164 AdaCore@*
166 @menu
167 * About This Guide::
168 * Getting Started with GNAT::
169 * The GNAT Compilation Model::
170 * Compiling with gcc::
171 * Binding with gnatbind::
172 * Linking with gnatlink::
173 * The GNAT Make Program gnatmake::
174 * Improving Performance::
175 * Renaming Files with gnatchop::
176 * Configuration Pragmas::
177 * Handling Arbitrary File Naming Conventions with gnatname::
178 * GNAT Project Manager::
179 * Tools Supporting Project Files::
180 * The Cross-Referencing Tools gnatxref and gnatfind::
181 * The GNAT Pretty-Printer gnatpp::
182 * The GNAT Metrics Tool gnatmetric::
183 * File Name Krunching with gnatkr::
184 * Preprocessing with gnatprep::
185 * The GNAT Library Browser gnatls::
186 * Cleaning Up with gnatclean::
187 @ifclear vms
188 * GNAT and Libraries::
189 * Using the GNU make Utility::
190 @end ifclear
191 * Memory Management Issues::
192 * Stack Related Facilities::
193 * Verifying Properties with gnatcheck::
194 * Creating Sample Bodies with gnatstub::
195 * Creating Unit Tests with gnattest::
196 * Performing Dimensionality Analysis in GNAT::
197 * Generating Ada Bindings for C and C++ headers::
198 * Other Utility Programs::
199 @ifclear vms
200 * Code Coverage and Profiling::
201 @end ifclear
202 * Running and Debugging Ada Programs::
203 @ifset vms
204 * Compatibility with HP Ada::
205 @end ifset
206 * Platform-Specific Information for the Run-Time Libraries::
207 * Example of Binder Output File::
208 * Elaboration Order Handling in GNAT::
209 * Overflow Check Handling in GNAT::
210 * Conditional Compilation::
211 * Inline Assembler::
212 * Compatibility and Porting Guide::
213 * Microsoft Windows Topics::
214 * Mac OS Topics::
215 * GNU Free Documentation License::
216 * Index::
217 @end menu
218 @end ifnottex
220 @node About This Guide
221 @unnumbered About This Guide
223 @noindent
224 @ifset vms
225 This guide describes the use of @value{EDITION},
226 a compiler and software development toolset for the full Ada
227 programming language, implemented on OpenVMS for HP's Alpha and
228 Integrity server (I64) platforms.
229 @end ifset
230 @ifclear vms
231 This guide describes the use of @value{EDITION},
232 a compiler and software development
233 toolset for the full Ada programming language.
234 @end ifclear
235 It documents the features of the compiler and tools, and explains
236 how to use them to build Ada applications.
238 @value{EDITION} implements Ada 95, Ada 2005 and Ada 2012, and it may also be
239 invoked in Ada 83 compatibility mode.
240 By default, @value{EDITION} assumes Ada 2012, but you can override with a
241 compiler switch (@pxref{Compiling Different Versions of Ada})
242 to explicitly specify the language version.
243 Throughout this manual, references to ``Ada'' without a year suffix
244 apply to both all Ada 95/2005/2012 versions of the language.
246 @ifclear FSFEDITION
247 For ease of exposition, ``@value{EDITION}'' will be referred to simply as
248 ``GNAT'' in the remainder of this document.
249 @end ifclear
252 @menu
253 * What This Guide Contains::
254 * What You Should Know before Reading This Guide::
255 * Related Information::
256 * Conventions::
257 @end menu
259 @node What This Guide Contains
260 @unnumberedsec What This Guide Contains
262 @noindent
263 This guide contains the following chapters:
264 @itemize @bullet
266 @item
267 @ref{Getting Started with GNAT}, describes how to get started compiling
268 and running Ada programs with the GNAT Ada programming environment.
269 @item
270 @ref{The GNAT Compilation Model}, describes the compilation model used
271 by GNAT.
273 @item
274 @ref{Compiling with gcc}, describes how to compile
275 Ada programs with @command{gcc}, the Ada compiler.
277 @item
278 @ref{Binding with gnatbind}, describes how to
279 perform binding of Ada programs with @code{gnatbind}, the GNAT binding
280 utility.
282 @item
283 @ref{Linking with gnatlink},
284 describes @command{gnatlink}, a
285 program that provides for linking using the GNAT run-time library to
286 construct a program. @command{gnatlink} can also incorporate foreign language
287 object units into the executable.
289 @item
290 @ref{The GNAT Make Program gnatmake}, describes @command{gnatmake}, a
291 utility that automatically determines the set of sources
292 needed by an Ada compilation unit, and executes the necessary compilations
293 binding and link.
295 @item
296 @ref{Improving Performance}, shows various techniques for making your
297 Ada program run faster or take less space.
298 It discusses the effect of the compiler's optimization switch and
299 also describes the @command{gnatelim} tool and unused subprogram/data
300 elimination.
302 @item
303 @ref{Renaming Files with gnatchop}, describes
304 @code{gnatchop}, a utility that allows you to preprocess a file that
305 contains Ada source code, and split it into one or more new files, one
306 for each compilation unit.
308 @item
309 @ref{Configuration Pragmas}, describes the configuration pragmas
310 handled by GNAT.
312 @item
313 @ref{Handling Arbitrary File Naming Conventions with gnatname},
314 shows how to override the default GNAT file naming conventions,
315 either for an individual unit or globally.
317 @item
318 @ref{GNAT Project Manager}, describes how to use project files
319 to organize large projects.
321 @item
322 @ref{The Cross-Referencing Tools gnatxref and gnatfind}, discusses
323 @code{gnatxref} and @code{gnatfind}, two tools that provide an easy
324 way to navigate through sources.
326 @item
327 @ref{The GNAT Pretty-Printer gnatpp}, shows how to produce a reformatted
328 version of an Ada source file with control over casing, indentation,
329 comment placement, and other elements of program presentation style.
331 @item
332 @ref{The GNAT Metrics Tool gnatmetric}, shows how to compute various
333 metrics for an Ada source file, such as the number of types and subprograms,
334 and assorted complexity measures.
336 @item
337 @ref{File Name Krunching with gnatkr}, describes the @code{gnatkr}
338 file name krunching utility, used to handle shortened
339 file names on operating systems with a limit on the length of names.
341 @item
342 @ref{Preprocessing with gnatprep}, describes @code{gnatprep}, a
343 preprocessor utility that allows a single source file to be used to
344 generate multiple or parameterized source files by means of macro
345 substitution.
347 @item
348 @ref{The GNAT Library Browser gnatls}, describes @code{gnatls}, a
349 utility that displays information about compiled units, including dependences
350 on the corresponding sources files, and consistency of compilations.
352 @item
353 @ref{Cleaning Up with gnatclean}, describes @code{gnatclean}, a utility
354 to delete files that are produced by the compiler, binder and linker.
356 @ifclear vms
357 @item
358 @ref{GNAT and Libraries}, describes the process of creating and using
359 Libraries with GNAT. It also describes how to recompile the GNAT run-time
360 library.
362 @item
363 @ref{Using the GNU make Utility}, describes some techniques for using
364 the GNAT toolset in Makefiles.
365 @end ifclear
367 @item
368 @ref{Memory Management Issues}, describes some useful predefined storage pools
369 and in particular the GNAT Debug Pool facility, which helps detect incorrect
370 memory references.
371 @ifclear vms
372 It also describes @command{gnatmem}, a utility that monitors dynamic
373 allocation and deallocation and helps detect ``memory leaks''.
374 @end ifclear
376 @item
377 @ref{Stack Related Facilities}, describes some useful tools associated with
378 stack checking and analysis.
380 @item
381 @ref{Verifying Properties with gnatcheck}, discusses @code{gnatcheck},
382 a utility that checks Ada code against a set of rules.
384 @item
385 @ref{Creating Sample Bodies with gnatstub}, discusses @code{gnatstub},
386 a utility that generates empty but compilable bodies for library units.
388 @item
389 @ref{Creating Unit Tests with gnattest}, discusses @code{gnattest},
390 a utility that generates unit testing templates for library units.
392 @item
393 @ref{Performing Dimensionality Analysis in GNAT}, describes the Ada 2012
394 facilities used in GNAT to declare dimensioned objects, and to verify that
395 uses of these objects are consistent with their given physical dimensions
396 (so that meters cannot be assigned to kilograms, and so on).
398 @item
399 @ref{Generating Ada Bindings for C and C++ headers}, describes how to
400 generate automatically Ada bindings from C and C++ headers.
402 @item
403 @ref{Other Utility Programs}, discusses several other GNAT utilities,
404 including @code{gnathtml}.
406 @ifclear vms
407 @item
408 @ref{Code Coverage and Profiling}, describes how to perform a structural
409 coverage and profile the execution of Ada programs.
410 @end ifclear
412 @item
413 @ref{Running and Debugging Ada Programs}, describes how to run and debug
414 Ada programs.
416 @ifset vms
417 @item
418 @ref{Compatibility with HP Ada}, details the compatibility of GNAT with
419 HP Ada 83 @footnote{``HP Ada'' refers to the legacy product originally
420 developed by Digital Equipment Corporation and currently supported by HP.}
421 for OpenVMS Alpha. This product was formerly known as DEC Ada,
422 @cindex DEC Ada
423 and for
424 historical compatibility reasons, the relevant libraries still use the
425 DEC prefix.
426 @end ifset
428 @item
429 @ref{Platform-Specific Information for the Run-Time Libraries},
430 describes the various run-time
431 libraries supported by GNAT on various platforms and explains how to
432 choose a particular library.
434 @item
435 @ref{Example of Binder Output File}, shows the source code for the binder
436 output file for a sample program.
438 @item
439 @ref{Elaboration Order Handling in GNAT}, describes how GNAT helps
440 you deal with elaboration order issues.
442 @item
443 @ref{Overflow Check Handling in GNAT}, describes how GNAT helps
444 you deal with arithmetic overflow issues.
446 @item
447 @ref{Conditional Compilation}, describes how to model conditional compilation,
448 both with Ada in general and with GNAT facilities in particular.
450 @item
451 @ref{Inline Assembler}, shows how to use the inline assembly facility
452 in an Ada program.
454 @item
455 @ref{Compatibility and Porting Guide}, contains sections on compatibility
456 of GNAT with other Ada development environments (including Ada 83 systems),
457 to assist in porting code from those environments.
459 @ifset unw
460 @item
461 @ref{Microsoft Windows Topics}, presents information relevant to the
462 Microsoft Windows platform.
464 @item
465 @ref{Mac OS Topics}, presents information relevant to Apple's OS X
466 platform.
467 @end ifset
468 @end itemize
470 @c *************************************************
471 @node What You Should Know before Reading This Guide
472 @c *************************************************
473 @unnumberedsec What You Should Know before Reading This Guide
475 @cindex Ada 95 Language Reference Manual
476 @cindex Ada 2005 Language Reference Manual
477 @noindent
478 This guide assumes a basic familiarity with the Ada 95 language, as
479 described in the International Standard ANSI/ISO/IEC-8652:1995, January
480 1995.
481 It does not require knowledge of the new features introduced by Ada 2005,
482 (officially known as ISO/IEC 8652:1995 with Technical Corrigendum 1
483 and Amendment 1).
484 Both reference manuals are included in the GNAT documentation
485 package.
487 @node Related Information
488 @unnumberedsec Related Information
490 @noindent
491 For further information about related tools, refer to the following
492 documents:
494 @itemize @bullet
495 @item
496 @xref{Top, GNAT Reference Manual, About This Guide, gnat_rm, GNAT
497 Reference Manual}, which contains all reference material for the GNAT
498 implementation of Ada.
500 @ifset unw
501 @item
502 @cite{Using the GNAT Programming Studio}, which describes the GPS
503 Integrated Development Environment.
505 @item
506 @cite{GNAT Programming Studio Tutorial}, which introduces the
507 main GPS features through examples.
508 @end ifset
510 @item
511 @cite{Ada 95 Reference Manual}, which contains reference
512 material for the Ada 95 programming language.
514 @item
515 @cite{Ada 2005 Reference Manual}, which contains reference
516 material for the Ada 2005 programming language.
518 @item
519 @xref{Top,, Debugging with GDB, gdb, Debugging with GDB},
520 @ifset vms
521 in the GNU:[DOCS] directory,
522 @end ifset
523 for all details on the use of the GNU source-level debugger.
525 @item
526 @xref{Top,, The extensible self-documenting text editor, emacs,
527 GNU Emacs Manual},
528 @ifset vms
529 located in the GNU:[DOCS] directory if the EMACS kit is installed,
530 @end ifset
531 for full information on the extensible editor and programming
532 environment Emacs.
534 @end itemize
536 @c **************
537 @node Conventions
538 @unnumberedsec Conventions
539 @cindex Conventions
540 @cindex Typographical conventions
542 @noindent
543 Following are examples of the typographical and graphic conventions used
544 in this guide:
546 @itemize @bullet
547 @item
548 @code{Functions}, @command{utility program names}, @code{standard names},
549 and @code{classes}.
551 @item
552 @option{Option flags}
554 @item
555 @file{File names}, @samp{button names}, and @samp{field names}.
557 @item
558 @code{Variables}, @env{environment variables}, and @var{metasyntactic
559 variables}.
561 @item
562 @emph{Emphasis}.
564 @item
565 @r{[}optional information or parameters@r{]}
567 @item
568 Examples are described by text
569 @smallexample
570 and then shown this way.
571 @end smallexample
572 @end itemize
574 @noindent
575 Commands that are entered by the user are preceded in this manual by the
576 characters @w{``@code{$ }''} (dollar sign followed by space). If your system
577 uses this sequence as a prompt, then the commands will appear exactly as
578 you see them in the manual. If your system uses some other prompt, then
579 the command will appear with the @code{$} replaced by whatever prompt
580 character you are using.
582 @ifset unw
583 Full file names are shown with the ``@code{/}'' character
584 as the directory separator; e.g., @file{parent-dir/subdir/myfile.adb}.
585 If you are using GNAT on a Windows platform, please note that
586 the ``@code{\}'' character should be used instead.
587 @end ifset
589 @c ****************************
590 @node Getting Started with GNAT
591 @chapter Getting Started with GNAT
593 @noindent
594 This chapter describes some simple ways of using GNAT to build
595 executable Ada programs.
596 @ifset unw
597 @ref{Running GNAT}, through @ref{Using the gnatmake Utility},
598 show how to use the command line environment.
599 @ref{Introduction to GPS}, provides a brief
600 introduction to the GNAT Programming Studio, a visually-oriented
601 Integrated Development Environment for GNAT.
602 GPS offers a graphical ``look and feel'', support for development in
603 other programming languages, comprehensive browsing features, and
604 many other capabilities.
605 For information on GPS please refer to
606 @cite{Using the GNAT Programming Studio}.
607 @end ifset
609 @menu
610 * Running GNAT::
611 * Running a Simple Ada Program::
612 * Running a Program with Multiple Units::
613 * Using the gnatmake Utility::
614 @ifset vms
615 * Editing with Emacs::
616 @end ifset
617 @ifclear vms
618 * Introduction to GPS::
619 @end ifclear
620 @end menu
622 @node Running GNAT
623 @section Running GNAT
625 @noindent
626 Three steps are needed to create an executable file from an Ada source
627 file:
629 @enumerate
630 @item
631 The source file(s) must be compiled.
632 @item
633 The file(s) must be bound using the GNAT binder.
634 @item
635 All appropriate object files must be linked to produce an executable.
636 @end enumerate
638 @noindent
639 All three steps are most commonly handled by using the @command{gnatmake}
640 utility program that, given the name of the main program, automatically
641 performs the necessary compilation, binding and linking steps.
643 @node Running a Simple Ada Program
644 @section Running a Simple Ada Program
646 @noindent
647 Any text editor may be used to prepare an Ada program.
648 (If @code{Emacs} is
649 used, the optional Ada mode may be helpful in laying out the program.)
651 program text is a normal text file. We will assume in our initial
652 example that you have used your editor to prepare the following
653 standard format text file:
655 @smallexample @c ada
656 @cartouche
657 with Ada.Text_IO; use Ada.Text_IO;
658 procedure Hello is
659 begin
660    Put_Line ("Hello WORLD!");
661 end Hello;
662 @end cartouche
663 @end smallexample
665 @noindent
666 This file should be named @file{hello.adb}.
667 With the normal default file naming conventions, GNAT requires
668 that each file
669 contain a single compilation unit whose file name is the
670 unit name,
671 with periods replaced by hyphens; the
672 extension is @file{ads} for a
673 spec and @file{adb} for a body.
674 You can override this default file naming convention by use of the
675 special pragma @code{Source_File_Name} (@pxref{Using Other File Names}).
676 Alternatively, if you want to rename your files according to this default
677 convention, which is probably more convenient if you will be using GNAT
678 for all your compilations, then the @code{gnatchop} utility
679 can be used to generate correctly-named source files
680 (@pxref{Renaming Files with gnatchop}).
682 You can compile the program using the following command (@code{$} is used
683 as the command prompt in the examples in this document):
685 @smallexample
686 $ gcc -c hello.adb
687 @end smallexample
689 @noindent
690 @command{gcc} is the command used to run the compiler. This compiler is
691 capable of compiling programs in several languages, including Ada and
692 C. It assumes that you have given it an Ada program if the file extension is
693 either @file{.ads} or @file{.adb}, and it will then call
694 the GNAT compiler to compile the specified file.
696 @ifclear vms
697 The @option{-c} switch is required. It tells @command{gcc} to only do a
698 compilation. (For C programs, @command{gcc} can also do linking, but this
699 capability is not used directly for Ada programs, so the @option{-c}
700 switch must always be present.)
701 @end ifclear
703 This compile command generates a file
704 @file{hello.o}, which is the object
705 file corresponding to your Ada program. It also generates
706 an ``Ada Library Information'' file @file{hello.ali},
707 which contains additional information used to check
708 that an Ada program is consistent.
709 To build an executable file,
710 use @code{gnatbind} to bind the program
711 and @command{gnatlink} to link it. The
712 argument to both @code{gnatbind} and @command{gnatlink} is the name of the
713 @file{ALI} file, but the default extension of @file{.ali} can
714 be omitted. This means that in the most common case, the argument
715 is simply the name of the main program:
717 @smallexample
718 $ gnatbind hello
719 $ gnatlink hello
720 @end smallexample
722 @noindent
723 A simpler method of carrying out these steps is to use
724 @command{gnatmake},
725 a master program that invokes all the required
726 compilation, binding and linking tools in the correct order. In particular,
727 @command{gnatmake} automatically recompiles any sources that have been
728 modified since they were last compiled, or sources that depend
729 on such modified sources, so that ``version skew'' is avoided.
730 @cindex Version skew (avoided by @command{gnatmake})
732 @smallexample
733 $ gnatmake hello.adb
734 @end smallexample
736 @noindent
737 The result is an executable program called @file{hello}, which can be
738 run by entering:
740 @smallexample
741 $ ^hello^RUN HELLO^
742 @end smallexample
744 @noindent
745 assuming that the current directory is on the search path
746 for executable programs.
748 @noindent
749 and, if all has gone well, you will see
751 @smallexample
752 Hello WORLD!
753 @end smallexample
755 @noindent
756 appear in response to this command.
758 @c ****************************************
759 @node Running a Program with Multiple Units
760 @section Running a Program with Multiple Units
762 @noindent
763 Consider a slightly more complicated example that has three files: a
764 main program, and the spec and body of a package:
766 @smallexample @c ada
767 @cartouche
768 @group
769 package Greetings is
770    procedure Hello;
771    procedure Goodbye;
772 end Greetings;
774 with Ada.Text_IO; use Ada.Text_IO;
775 package body Greetings is
776    procedure Hello is
777    begin
778       Put_Line ("Hello WORLD!");
779    end Hello;
781    procedure Goodbye is
782    begin
783       Put_Line ("Goodbye WORLD!");
784    end Goodbye;
785 end Greetings;
786 @end group
788 @group
789 with Greetings;
790 procedure Gmain is
791 begin
792    Greetings.Hello;
793    Greetings.Goodbye;
794 end Gmain;
795 @end group
796 @end cartouche
797 @end smallexample
799 @noindent
800 Following the one-unit-per-file rule, place this program in the
801 following three separate files:
803 @table @file
804 @item greetings.ads
805 spec of package @code{Greetings}
807 @item greetings.adb
808 body of package @code{Greetings}
810 @item gmain.adb
811 body of main program
812 @end table
814 @noindent
815 To build an executable version of
816 this program, we could use four separate steps to compile, bind, and link
817 the program, as follows:
819 @smallexample
820 $ gcc -c gmain.adb
821 $ gcc -c greetings.adb
822 $ gnatbind gmain
823 $ gnatlink gmain
824 @end smallexample
826 @noindent
827 Note that there is no required order of compilation when using GNAT.
828 In particular it is perfectly fine to compile the main program first.
829 Also, it is not necessary to compile package specs in the case where
830 there is an accompanying body; you only need to compile the body. If you want
831 to submit these files to the compiler for semantic checking and not code
832 generation, then use the
833 @option{-gnatc} switch:
835 @smallexample
836 $ gcc -c greetings.ads -gnatc
837 @end smallexample
839 @noindent
840 Although the compilation can be done in separate steps as in the
841 above example, in practice it is almost always more convenient
842 to use the @command{gnatmake} tool. All you need to know in this case
843 is the name of the main program's source file. The effect of the above four
844 commands can be achieved with a single one:
846 @smallexample
847 $ gnatmake gmain.adb
848 @end smallexample
850 @noindent
851 In the next section we discuss the advantages of using @command{gnatmake} in
852 more detail.
854 @c *****************************
855 @node Using the gnatmake Utility
856 @section Using the @command{gnatmake} Utility
858 @noindent
859 If you work on a program by compiling single components at a time using
860 @command{gcc}, you typically keep track of the units you modify. In order to
861 build a consistent system, you compile not only these units, but also any
862 units that depend on the units you have modified.
863 For example, in the preceding case,
864 if you edit @file{gmain.adb}, you only need to recompile that file. But if
865 you edit @file{greetings.ads}, you must recompile both
866 @file{greetings.adb} and @file{gmain.adb}, because both files contain
867 units that depend on @file{greetings.ads}.
869 @code{gnatbind} will warn you if you forget one of these compilation
870 steps, so that it is impossible to generate an inconsistent program as a
871 result of forgetting to do a compilation. Nevertheless it is tedious and
872 error-prone to keep track of dependencies among units.
873 One approach to handle the dependency-bookkeeping is to use a
874 makefile. However, makefiles present maintenance problems of their own:
875 if the dependencies change as you change the program, you must make
876 sure that the makefile is kept up-to-date manually, which is also an
877 error-prone process.
879 The @command{gnatmake} utility takes care of these details automatically.
880 Invoke it using either one of the following forms:
882 @smallexample
883 $ gnatmake gmain.adb
884 $ gnatmake ^gmain^GMAIN^
885 @end smallexample
887 @noindent
888 The argument is the name of the file containing the main program;
889 you may omit the extension. @command{gnatmake}
890 examines the environment, automatically recompiles any files that need
891 recompiling, and binds and links the resulting set of object files,
892 generating the executable file, @file{^gmain^GMAIN.EXE^}.
893 In a large program, it
894 can be extremely helpful to use @command{gnatmake}, because working out by hand
895 what needs to be recompiled can be difficult.
897 Note that @command{gnatmake}
898 takes into account all the Ada rules that
899 establish dependencies among units. These include dependencies that result
900 from inlining subprogram bodies, and from
901 generic instantiation. Unlike some other
902 Ada make tools, @command{gnatmake} does not rely on the dependencies that were
903 found by the compiler on a previous compilation, which may possibly
904 be wrong when sources change. @command{gnatmake} determines the exact set of
905 dependencies from scratch each time it is run.
907 @ifset vms
908 @node Editing with Emacs
909 @section Editing with Emacs
910 @cindex Emacs
912 @noindent
913 Emacs is an extensible self-documenting text editor that is available in a
914 separate VMSINSTAL kit.
916 Invoke Emacs by typing @kbd{Emacs} at the command prompt. To get started,
917 click on the Emacs Help menu and run the Emacs Tutorial.
918 In a character cell terminal, Emacs help is invoked with @kbd{Ctrl-h} (also
919 written as @kbd{C-h}), and the tutorial by @kbd{C-h t}.
921 Documentation on Emacs and other tools is available in Emacs under the
922 pull-down menu button: @code{Help - Info}. After selecting @code{Info},
923 use the middle mouse button to select a topic (e.g.@: Emacs).
925 In a character cell terminal, do @kbd{C-h i} to invoke info, and then @kbd{m}
926 (stands for menu) followed by the menu item desired, as in @kbd{m Emacs}, to
927 get to the Emacs manual.
928 Help on Emacs is also available by typing @kbd{HELP EMACS} at the DCL command
929 prompt.
931 The tutorial is highly recommended in order to learn the intricacies of Emacs,
932 which is sufficiently extensible to provide for a complete programming
933 environment and shell for the sophisticated user.
934 @end ifset
936 @ifclear vms
937 @node Introduction to GPS
938 @section Introduction to GPS
939 @cindex GPS (GNAT Programming Studio)
940 @cindex GNAT Programming Studio (GPS)
941 @noindent
942 Although the command line interface (@command{gnatmake}, etc.) alone
943 is sufficient, a graphical Interactive Development
944 Environment can make it easier for you to compose, navigate, and debug
945 programs.  This section describes the main features of GPS
946 (``GNAT Programming Studio''), the GNAT graphical IDE.
947 You will see how to use GPS to build and debug an executable, and
948 you will also learn some of the basics of the GNAT ``project'' facility.
950 GPS enables you to do much more than is presented here;
951 e.g., you can produce a call graph, interface to a third-party
952 Version Control System, and inspect the generated assembly language
953 for a program.
954 Indeed, GPS also supports languages other than Ada.
955 Such additional information, and an explanation of all of the GPS menu
956 items. may be found in the on-line help, which includes
957 a user's guide and a tutorial (these are also accessible from the GNAT
958 startup menu).
960 @menu
961 * Building a New Program with GPS::
962 * Simple Debugging with GPS::
963 @end menu
965 @node Building a New Program with GPS
966 @subsection Building a New Program with GPS
967 @noindent
968 GPS invokes the GNAT compilation tools using information
969 contained in a @emph{project} (also known as a @emph{project file}):
970 a collection of properties such
971 as source directories, identities of main subprograms, tool switches, etc.,
972 and their associated values.
973 See @ref{GNAT Project Manager} for details.
974 In order to run GPS, you will need to either create a new project
975 or else open an existing one.
977 This section will explain how you can use GPS to create a project,
978 to associate Ada source files with a project, and to build and run
979 programs.
981 @enumerate
982 @item @emph{Creating a project}
984 Invoke GPS, either from the command line or the platform's IDE.
985 After it starts, GPS will display a ``Welcome'' screen with three
986 radio buttons:
988 @itemize @bullet
989 @item
990 @code{Start with default project in directory}
992 @item
993 @code{Create new project with wizard}
995 @item
996 @code{Open existing project}
997 @end itemize
999 @noindent
1000 Select @code{Create new project with wizard} and press @code{OK}.
1001 A new window will appear.  In the text box labeled with
1002 @code{Enter the name of the project to create}, type @file{sample}
1003 as the project name.
1004 In the next box, browse to choose the directory in which you
1005 would like to create the project file.
1006 After selecting an appropriate directory, press @code{Forward}.
1008 A window will appear with the title
1009 @code{Version Control System Configuration}.
1010 Simply press @code{Forward}.
1012 A window will appear with the title
1013 @code{Please select the source directories for this project}.
1014 The directory that you specified for the project file will be selected
1015 by default as the one to use for sources; simply press @code{Forward}.
1017 A window will appear with the title
1018 @code{Please select the build directory for this project}.
1019 The directory that you specified for the project file will be selected
1020 by default for object files and executables;
1021 simply press @code{Forward}.
1023 A window will appear with the title
1024 @code{Please select the main units for this project}.
1025 You will supply this information later, after creating the source file.
1026 Simply press @code{Forward} for now.
1028 A window will appear with the title
1029 @code{Please select the switches to build the project}.
1030 Press @code{Apply}.  This will create a project file named
1031 @file{sample.prj} in the directory that you had specified.
1033 @item @emph{Creating and saving the source file}
1035 After you create the new project, a GPS window will appear, which is
1036 partitioned into two main sections:
1038 @itemize @bullet
1039 @item
1040 A @emph{Workspace area}, initially greyed out, which you will use for
1041 creating and editing source files
1043 @item
1044 Directly below, a @emph{Messages area}, which initially displays a
1045 ``Welcome'' message.
1046 (If the Messages area is not visible, drag its border upward to expand it.)
1047 @end itemize
1049 @noindent
1050 Select @code{File} on the menu bar, and then the @code{New} command.
1051 The Workspace area will become white, and you can now
1052 enter the source program explicitly.
1053 Type the following text
1055 @smallexample @c ada
1056 @group
1057 with Ada.Text_IO; use Ada.Text_IO;
1058 procedure Hello is
1059 begin
1060   Put_Line("Hello from GPS!");
1061 end Hello;
1062 @end group
1063 @end smallexample
1065 @noindent
1066 Select @code{File}, then @code{Save As}, and enter the source file name
1067 @file{hello.adb}.
1068 The file will be saved in the same directory you specified as the
1069 location of the default project file.
1071 @item @emph{Updating the project file}
1073 You need to add the new source file to the project.
1074 To do this, select
1075 the @code{Project} menu and then @code{Edit project properties}.
1076 Click the @code{Main files} tab on the left, and then the
1077 @code{Add} button.
1078 Choose @file{hello.adb} from the list, and press @code{Open}.
1079 The project settings window will reflect this action.
1080 Click @code{OK}.
1082 @item @emph{Building and running the program}
1084 In the main GPS window, now choose the @code{Build} menu, then @code{Make},
1085 and select @file{hello.adb}.
1086 The Messages window will display the resulting invocations of @command{gcc},
1087 @command{gnatbind}, and @command{gnatlink}
1088 (reflecting the default switch settings from the
1089 project file that you created) and then a ``successful compilation/build''
1090 message.
1092 To run the program, choose the @code{Build} menu, then @code{Run}, and
1093 select @command{hello}.
1094 An @emph{Arguments Selection} window will appear.
1095 There are no command line arguments, so just click @code{OK}.
1097 The Messages window will now display the program's output (the string
1098 @code{Hello from GPS}), and at the bottom of the GPS window a status
1099 update is displayed (@code{Run: hello}).
1100 Close the GPS window (or select @code{File}, then @code{Exit}) to
1101 terminate this GPS session.
1102 @end enumerate
1104 @node Simple Debugging with GPS
1105 @subsection Simple Debugging with GPS
1106 @noindent
1107 This section illustrates basic debugging techniques (setting breakpoints,
1108 examining/modifying variables, single stepping).
1110 @enumerate
1111 @item @emph{Opening a project}
1113 Start GPS and select @code{Open existing project}; browse to
1114 specify the project file @file{sample.prj} that you had created in the
1115 earlier example.
1117 @item @emph{Creating a source file}
1119 Select @code{File}, then @code{New}, and type in the following program:
1121 @smallexample @c ada
1122 @group
1123 with Ada.Text_IO; use Ada.Text_IO;
1124 procedure Example is
1125    Line : String (1..80);
1126    N    : Natural;
1127 begin
1128    Put_Line("Type a line of text at each prompt; an empty line to exit");
1129    loop
1130       Put(": ");
1131       Get_Line (Line, N);
1132       Put_Line (Line (1..N) );
1133       exit when N=0;
1134    end loop;
1135 end Example;
1136 @end group
1137 @end smallexample
1139 @noindent
1140 Select @code{File}, then @code{Save as}, and enter the file name
1141 @file{example.adb}.
1143 @item @emph{Updating the project file}
1145 Add @code{Example} as a new main unit for the project:
1146 @enumerate a
1147 @item
1148 Select @code{Project}, then @code{Edit Project Properties}.
1150 @item
1151 Select the @code{Main files} tab, click @code{Add}, then
1152 select the file @file{example.adb} from the list, and
1153 click @code{Open}.
1154 You will see the file name appear in the list of main units
1156 @item
1157 Click @code{OK}
1158 @end enumerate
1160 @item @emph{Building/running the executable}
1162 To build the executable
1163 select @code{Build}, then @code{Make}, and then choose @file{example.adb}.
1165 Run the program to see its effect (in the Messages area).
1166 Each line that you enter is displayed; an empty line will
1167 cause the loop to exit and the program to terminate.
1169 @item @emph{Debugging the program}
1171 Note that the @option{-g} switches to @command{gcc} and @command{gnatlink},
1172 which are required for debugging, are on by default when you create
1173 a new project.
1174 Thus unless you intentionally remove these settings, you will be able
1175 to debug any program that you develop using GPS.
1177 @enumerate a
1178 @item @emph{Initializing}
1180 Select @code{Debug}, then @code{Initialize}, then @file{example}
1182 @item @emph{Setting a breakpoint}
1184 After performing the initialization step, you will observe a small
1185 icon to the right of each line number.
1186 This serves as a toggle for breakpoints; clicking the icon will
1187 set a breakpoint at the corresponding line (the icon will change to
1188 a red circle with an ``x''), and clicking it again
1189 will remove the breakpoint / reset the icon.
1191 For purposes of this example, set a breakpoint at line 10 (the
1192 statement @code{Put_Line@ (Line@ (1..N));}
1194 @item @emph{Starting program execution}
1196 Select @code{Debug}, then @code{Run}.  When the
1197 @code{Program Arguments} window appears, click @code{OK}.
1198 A console window will appear; enter some line of text,
1199 e.g.@: @code{abcde}, at the prompt.
1200 The program will pause execution when it gets to the
1201 breakpoint, and the corresponding line is highlighted.
1203 @item @emph{Examining a variable}
1205 Move the mouse over one of the occurrences of the variable @code{N}.
1206 You will see the value (5) displayed, in ``tool tip'' fashion.
1207 Right click on @code{N}, select @code{Debug}, then select @code{Display N}.
1208 You will see information about @code{N} appear in the @code{Debugger Data}
1209 pane, showing the value as 5.
1211 @item @emph{Assigning a new value to a variable}
1213 Right click on the @code{N} in the @code{Debugger Data} pane, and
1214 select @code{Set value of N}.
1215 When the input window appears, enter the value @code{4} and click
1216 @code{OK}.
1217 This value does not automatically appear in the @code{Debugger Data}
1218 pane; to see it, right click again on the @code{N} in the
1219 @code{Debugger Data} pane and select @code{Update value}.
1220 The new value, 4, will appear in red.
1222 @item @emph{Single stepping}
1224 Select @code{Debug}, then @code{Next}.
1225 This will cause the next statement to be executed, in this case the
1226 call of @code{Put_Line} with the string slice.
1227 Notice in the console window that the displayed string is simply
1228 @code{abcd} and not @code{abcde} which you had entered.
1229 This is because the upper bound of the slice is now 4 rather than 5.
1231 @item @emph{Removing a breakpoint}
1233 Toggle the breakpoint icon at line 10.
1235 @item @emph{Resuming execution from a breakpoint}
1237 Select @code{Debug}, then @code{Continue}.
1238 The program will reach the next iteration of the loop, and
1239 wait for input after displaying the prompt.
1240 This time, just hit the @kbd{Enter} key.
1241 The value of @code{N} will be 0, and the program will terminate.
1242 The console window will disappear.
1243 @end enumerate
1244 @end enumerate
1245 @end ifclear
1247 @node The GNAT Compilation Model
1248 @chapter The GNAT Compilation Model
1249 @cindex GNAT compilation model
1250 @cindex Compilation model
1252 @menu
1253 * Source Representation::
1254 * Foreign Language Representation::
1255 * File Naming Rules::
1256 * Using Other File Names::
1257 * Alternative File Naming Schemes::
1258 * Generating Object Files::
1259 * Source Dependencies::
1260 * The Ada Library Information Files::
1261 * Binding an Ada Program::
1262 * Mixed Language Programming::
1263 @ifclear vms
1264 * Building Mixed Ada & C++ Programs::
1265 * Comparison between GNAT and C/C++ Compilation Models::
1266 @end ifclear
1267 * Comparison between GNAT and Conventional Ada Library Models::
1268 @ifset vms
1269 * Placement of temporary files::
1270 @end ifset
1271 @end menu
1273 @noindent
1274 This chapter describes the compilation model used by GNAT. Although
1275 similar to that used by other languages, such as C and C++, this model
1276 is substantially different from the traditional Ada compilation models,
1277 which are based on a library. The model is initially described without
1278 reference to the library-based model. If you have not previously used an
1279 Ada compiler, you need only read the first part of this chapter. The
1280 last section describes and discusses the differences between the GNAT
1281 model and the traditional Ada compiler models. If you have used other
1282 Ada compilers, this section will help you to understand those
1283 differences, and the advantages of the GNAT model.
1285 @node Source Representation
1286 @section Source Representation
1287 @cindex Latin-1
1289 @noindent
1290 Ada source programs are represented in standard text files, using
1291 Latin-1 coding. Latin-1 is an 8-bit code that includes the familiar
1292 7-bit ASCII set, plus additional characters used for
1293 representing foreign languages (@pxref{Foreign Language Representation}
1294 for support of non-USA character sets). The format effector characters
1295 are represented using their standard ASCII encodings, as follows:
1297 @table @code
1298 @item VT
1299 @findex VT
1300 Vertical tab, @code{16#0B#}
1302 @item HT
1303 @findex HT
1304 Horizontal tab, @code{16#09#}
1306 @item CR
1307 @findex CR
1308 Carriage return, @code{16#0D#}
1310 @item LF
1311 @findex LF
1312 Line feed, @code{16#0A#}
1314 @item FF
1315 @findex FF
1316 Form feed, @code{16#0C#}
1317 @end table
1319 @noindent
1320 Source files are in standard text file format. In addition, GNAT will
1321 recognize a wide variety of stream formats, in which the end of
1322 physical lines is marked by any of the following sequences:
1323 @code{LF}, @code{CR}, @code{CR-LF}, or @code{LF-CR}. This is useful
1324 in accommodating files that are imported from other operating systems.
1326 @cindex End of source file
1327 @cindex Source file, end
1328 @findex SUB
1329 The end of a source file is normally represented by the physical end of
1330 file. However, the control character @code{16#1A#} (@code{SUB}) is also
1331 recognized as signalling the end of the source file. Again, this is
1332 provided for compatibility with other operating systems where this
1333 code is used to represent the end of file.
1335 Each file contains a single Ada compilation unit, including any pragmas
1336 associated with the unit. For example, this means you must place a
1337 package declaration (a package @dfn{spec}) and the corresponding body in
1338 separate files. An Ada @dfn{compilation} (which is a sequence of
1339 compilation units) is represented using a sequence of files. Similarly,
1340 you will place each subunit or child unit in a separate file.
1342 @node Foreign Language Representation
1343 @section Foreign Language Representation
1345 @noindent
1346 GNAT supports the standard character sets defined in Ada as well as
1347 several other non-standard character sets for use in localized versions
1348 of the compiler (@pxref{Character Set Control}).
1349 @menu
1350 * Latin-1::
1351 * Other 8-Bit Codes::
1352 * Wide Character Encodings::
1353 @end menu
1355 @node Latin-1
1356 @subsection Latin-1
1357 @cindex Latin-1
1359 @noindent
1360 The basic character set is Latin-1. This character set is defined by ISO
1361 standard 8859, part 1. The lower half (character codes @code{16#00#}
1362 @dots{} @code{16#7F#)} is identical to standard ASCII coding, but the upper
1363 half is used to represent additional characters. These include extended letters
1364 used by European languages, such as French accents, the vowels with umlauts
1365 used in German, and the extra letter A-ring used in Swedish.
1367 @findex Ada.Characters.Latin_1
1368 For a complete list of Latin-1 codes and their encodings, see the source
1369 file of library unit @code{Ada.Characters.Latin_1} in file
1370 @file{a-chlat1.ads}.
1371 You may use any of these extended characters freely in character or
1372 string literals. In addition, the extended characters that represent
1373 letters can be used in identifiers.
1375 @node Other 8-Bit Codes
1376 @subsection Other 8-Bit Codes
1378 @noindent
1379 GNAT also supports several other 8-bit coding schemes:
1381 @table @asis
1382 @item ISO 8859-2 (Latin-2)
1383 @cindex Latin-2
1384 @cindex ISO 8859-2
1385 Latin-2 letters allowed in identifiers, with uppercase and lowercase
1386 equivalence.
1388 @item ISO 8859-3 (Latin-3)
1389 @cindex Latin-3
1390 @cindex ISO 8859-3
1391 Latin-3 letters allowed in identifiers, with uppercase and lowercase
1392 equivalence.
1394 @item ISO 8859-4 (Latin-4)
1395 @cindex Latin-4
1396 @cindex ISO 8859-4
1397 Latin-4 letters allowed in identifiers, with uppercase and lowercase
1398 equivalence.
1400 @item ISO 8859-5 (Cyrillic)
1401 @cindex ISO 8859-5
1402 @cindex Cyrillic
1403 ISO 8859-5 letters (Cyrillic) allowed in identifiers, with uppercase and
1404 lowercase equivalence.
1406 @item ISO 8859-15 (Latin-9)
1407 @cindex ISO 8859-15
1408 @cindex Latin-9
1409 ISO 8859-15 (Latin-9) letters allowed in identifiers, with uppercase and
1410 lowercase equivalence
1412 @item IBM PC (code page 437)
1413 @cindex code page 437
1414 This code page is the normal default for PCs in the U.S. It corresponds
1415 to the original IBM PC character set. This set has some, but not all, of
1416 the extended Latin-1 letters, but these letters do not have the same
1417 encoding as Latin-1. In this mode, these letters are allowed in
1418 identifiers with uppercase and lowercase equivalence.
1420 @item IBM PC (code page 850)
1421 @cindex code page 850
1422 This code page is a modification of 437 extended to include all the
1423 Latin-1 letters, but still not with the usual Latin-1 encoding. In this
1424 mode, all these letters are allowed in identifiers with uppercase and
1425 lowercase equivalence.
1427 @item Full Upper 8-bit
1428 Any character in the range 80-FF allowed in identifiers, and all are
1429 considered distinct. In other words, there are no uppercase and lowercase
1430 equivalences in this range. This is useful in conjunction with
1431 certain encoding schemes used for some foreign character sets (e.g.,
1432 the typical method of representing Chinese characters on the PC).
1434 @item No Upper-Half
1435 No upper-half characters in the range 80-FF are allowed in identifiers.
1436 This gives Ada 83 compatibility for identifier names.
1437 @end table
1439 @noindent
1440 For precise data on the encodings permitted, and the uppercase and lowercase
1441 equivalences that are recognized, see the file @file{csets.adb} in
1442 the GNAT compiler sources. You will need to obtain a full source release
1443 of GNAT to obtain this file.
1445 @node Wide Character Encodings
1446 @subsection Wide Character Encodings
1448 @noindent
1449 GNAT allows wide character codes to appear in character and string
1450 literals, and also optionally in identifiers, by means of the following
1451 possible encoding schemes:
1453 @table @asis
1455 @item Hex Coding
1456 In this encoding, a wide character is represented by the following five
1457 character sequence:
1459 @smallexample
1460 ESC a b c d
1461 @end smallexample
1463 @noindent
1464 Where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal
1465 characters (using uppercase letters) of the wide character code. For
1466 example, ESC A345 is used to represent the wide character with code
1467 @code{16#A345#}.
1468 This scheme is compatible with use of the full Wide_Character set.
1470 @item Upper-Half Coding
1471 @cindex Upper-Half Coding
1472 The wide character with encoding @code{16#abcd#} where the upper bit is on
1473 (in other words, ``a'' is in the range 8-F) is represented as two bytes,
1474 @code{16#ab#} and @code{16#cd#}. The second byte cannot be a format control
1475 character, but is not required to be in the upper half. This method can
1476 be also used for shift-JIS or EUC, where the internal coding matches the
1477 external coding.
1479 @item Shift JIS Coding
1480 @cindex Shift JIS Coding
1481 A wide character is represented by a two-character sequence,
1482 @code{16#ab#} and
1483 @code{16#cd#}, with the restrictions described for upper-half encoding as
1484 described above. The internal character code is the corresponding JIS
1485 character according to the standard algorithm for Shift-JIS
1486 conversion. Only characters defined in the JIS code set table can be
1487 used with this encoding method.
1489 @item EUC Coding
1490 @cindex EUC Coding
1491 A wide character is represented by a two-character sequence
1492 @code{16#ab#} and
1493 @code{16#cd#}, with both characters being in the upper half. The internal
1494 character code is the corresponding JIS character according to the EUC
1495 encoding algorithm. Only characters defined in the JIS code set table
1496 can be used with this encoding method.
1498 @item UTF-8 Coding
1499 A wide character is represented using
1500 UCS Transformation Format 8 (UTF-8) as defined in Annex R of ISO
1501 10646-1/Am.2. Depending on the character value, the representation
1502 is a one, two, or three byte sequence:
1503 @smallexample
1504 @iftex
1505 @leftskip=.7cm
1506 @end iftex
1507 16#0000#-16#007f#: 2#0@var{xxxxxxx}#
1508 16#0080#-16#07ff#: 2#110@var{xxxxx}# 2#10@var{xxxxxx}#
1509 16#0800#-16#ffff#: 2#1110@var{xxxx}# 2#10@var{xxxxxx}# 2#10@var{xxxxxx}#
1511 @end smallexample
1513 @noindent
1514 where the @var{xxx} bits correspond to the left-padded bits of the
1515 16-bit character value. Note that all lower half ASCII characters
1516 are represented as ASCII bytes and all upper half characters and
1517 other wide characters are represented as sequences of upper-half
1518 (The full UTF-8 scheme allows for encoding 31-bit characters as
1519 6-byte sequences, but in this implementation, all UTF-8 sequences
1520 of four or more bytes length will be treated as illegal).
1521 @item Brackets Coding
1522 In this encoding, a wide character is represented by the following eight
1523 character sequence:
1525 @smallexample
1526 [ " a b c d " ]
1527 @end smallexample
1529 @noindent
1530 Where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal
1531 characters (using uppercase letters) of the wide character code. For
1532 example, [``A345''] is used to represent the wide character with code
1533 @code{16#A345#}. It is also possible (though not required) to use the
1534 Brackets coding for upper half characters. For example, the code
1535 @code{16#A3#} can be represented as @code{[``A3'']}.
1537 This scheme is compatible with use of the full Wide_Character set,
1538 and is also the method used for wide character encoding in the standard
1539 ACVC (Ada Compiler Validation Capability) test suite distributions.
1541 @end table
1543 @noindent
1544 Note: Some of these coding schemes do not permit the full use of the
1545 Ada character set. For example, neither Shift JIS, nor EUC allow the
1546 use of the upper half of the Latin-1 set.
1548 @node File Naming Rules
1549 @section File Naming Rules
1551 @noindent
1552 The default file name is determined by the name of the unit that the
1553 file contains. The name is formed by taking the full expanded name of
1554 the unit and replacing the separating dots with hyphens and using
1555 ^lowercase^uppercase^ for all letters.
1557 An exception arises if the file name generated by the above rules starts
1558 with one of the characters
1559 @ifset vms
1560 @samp{A}, @samp{G}, @samp{I}, or @samp{S},
1561 @end ifset
1562 @ifclear vms
1563 @samp{a}, @samp{g}, @samp{i}, or @samp{s},
1564 @end ifclear
1565 and the second character is a
1566 minus. In this case, the character ^tilde^dollar sign^ is used in place
1567 of the minus. The reason for this special rule is to avoid clashes with
1568 the standard names for child units of the packages System, Ada,
1569 Interfaces, and GNAT, which use the prefixes
1570 @ifset vms
1571 @samp{S-}, @samp{A-}, @samp{I-}, and @samp{G-},
1572 @end ifset
1573 @ifclear vms
1574 @samp{s-}, @samp{a-}, @samp{i-}, and @samp{g-},
1575 @end ifclear
1576 respectively.
1578 The file extension is @file{.ads} for a spec and
1579 @file{.adb} for a body. The following list shows some
1580 examples of these rules.
1582 @table @file
1583 @item main.ads
1584 Main (spec)
1585 @item main.adb
1586 Main (body)
1587 @item arith_functions.ads
1588 Arith_Functions (package spec)
1589 @item arith_functions.adb
1590 Arith_Functions (package body)
1591 @item func-spec.ads
1592 Func.Spec (child package spec)
1593 @item func-spec.adb
1594 Func.Spec (child package body)
1595 @item main-sub.adb
1596 Sub (subunit of Main)
1597 @item ^a~bad.adb^A$BAD.ADB^
1598 A.Bad (child package body)
1599 @end table
1601 @noindent
1602 Following these rules can result in excessively long
1603 file names if corresponding
1604 unit names are long (for example, if child units or subunits are
1605 heavily nested). An option is available to shorten such long file names
1606 (called file name ``krunching''). This may be particularly useful when
1607 programs being developed with GNAT are to be used on operating systems
1608 with limited file name lengths. @xref{Using gnatkr}.
1610 Of course, no file shortening algorithm can guarantee uniqueness over
1611 all possible unit names; if file name krunching is used, it is your
1612 responsibility to ensure no name clashes occur. Alternatively you
1613 can specify the exact file names that you want used, as described
1614 in the next section. Finally, if your Ada programs are migrating from a
1615 compiler with a different naming convention, you can use the gnatchop
1616 utility to produce source files that follow the GNAT naming conventions.
1617 (For details @pxref{Renaming Files with gnatchop}.)
1619 Note: in the case of @code{Windows NT/XP} or @code{OpenVMS} operating
1620 systems, case is not significant. So for example on @code{Windows XP}
1621 if the canonical name is @code{main-sub.adb}, you can use the file name
1622 @code{Main-Sub.adb} instead. However, case is significant for other
1623 operating systems, so for example, if you want to use other than
1624 canonically cased file names on a Unix system, you need to follow
1625 the procedures described in the next section.
1627 @node Using Other File Names
1628 @section Using Other File Names
1629 @cindex File names
1631 @noindent
1632 In the previous section, we have described the default rules used by
1633 GNAT to determine the file name in which a given unit resides. It is
1634 often convenient to follow these default rules, and if you follow them,
1635 the compiler knows without being explicitly told where to find all
1636 the files it needs.
1638 However, in some cases, particularly when a program is imported from
1639 another Ada compiler environment, it may be more convenient for the
1640 programmer to specify which file names contain which units. GNAT allows
1641 arbitrary file names to be used by means of the Source_File_Name pragma.
1642 The form of this pragma is as shown in the following examples:
1643 @cindex Source_File_Name pragma
1645 @smallexample @c ada
1646 @cartouche
1647 pragma Source_File_Name (My_Utilities.Stacks,
1648   Spec_File_Name => "myutilst_a.ada");
1649 pragma Source_File_name (My_Utilities.Stacks,
1650   Body_File_Name => "myutilst.ada");
1651 @end cartouche
1652 @end smallexample
1654 @noindent
1655 As shown in this example, the first argument for the pragma is the unit
1656 name (in this example a child unit). The second argument has the form
1657 of a named association. The identifier
1658 indicates whether the file name is for a spec or a body;
1659 the file name itself is given by a string literal.
1661 The source file name pragma is a configuration pragma, which means that
1662 normally it will be placed in the @file{gnat.adc}
1663 file used to hold configuration
1664 pragmas that apply to a complete compilation environment.
1665 For more details on how the @file{gnat.adc} file is created and used
1666 see @ref{Handling of Configuration Pragmas}.
1667 @cindex @file{gnat.adc}
1669 @ifclear vms
1670 GNAT allows completely arbitrary file names to be specified using the
1671 source file name pragma. However, if the file name specified has an
1672 extension other than @file{.ads} or @file{.adb} it is necessary to use
1673 a special syntax when compiling the file. The name in this case must be
1674 preceded by the special sequence @option{-x} followed by a space and the name
1675 of the language, here @code{ada}, as in:
1677 @smallexample
1678 $ gcc -c -x ada peculiar_file_name.sim
1679 @end smallexample
1680 @end ifclear
1682 @noindent
1683 @command{gnatmake} handles non-standard file names in the usual manner (the
1684 non-standard file name for the main program is simply used as the
1685 argument to gnatmake). Note that if the extension is also non-standard,
1686 then it must be included in the @command{gnatmake} command, it may not
1687 be omitted.
1689 @node Alternative File Naming Schemes
1690 @section Alternative File Naming Schemes
1691 @cindex File naming schemes, alternative
1692 @cindex File names
1694 In the previous section, we described the use of the @code{Source_File_Name}
1695 pragma to allow arbitrary names to be assigned to individual source files.
1696 However, this approach requires one pragma for each file, and especially in
1697 large systems can result in very long @file{gnat.adc} files, and also create
1698 a maintenance problem.
1700 GNAT also provides a facility for specifying systematic file naming schemes
1701 other than the standard default naming scheme previously described. An
1702 alternative scheme for naming is specified by the use of
1703 @code{Source_File_Name} pragmas having the following format:
1704 @cindex Source_File_Name pragma
1706 @smallexample @c ada
1707 pragma Source_File_Name (
1708    Spec_File_Name  => FILE_NAME_PATTERN
1709  @r{[},Casing          => CASING_SPEC@r{]}
1710  @r{[},Dot_Replacement => STRING_LITERAL@r{]});
1712 pragma Source_File_Name (
1713    Body_File_Name  => FILE_NAME_PATTERN
1714  @r{[},Casing          => CASING_SPEC@r{]}
1715  @r{[},Dot_Replacement => STRING_LITERAL@r{]});
1717 pragma Source_File_Name (
1718    Subunit_File_Name  => FILE_NAME_PATTERN
1719  @r{[},Casing             => CASING_SPEC@r{]}
1720  @r{[},Dot_Replacement    => STRING_LITERAL@r{]});
1722 FILE_NAME_PATTERN ::= STRING_LITERAL
1723 CASING_SPEC ::= Lowercase | Uppercase | Mixedcase
1724 @end smallexample
1726 @noindent
1727 The @code{FILE_NAME_PATTERN} string shows how the file name is constructed.
1728 It contains a single asterisk character, and the unit name is substituted
1729 systematically for this asterisk. The optional parameter
1730 @code{Casing} indicates
1731 whether the unit name is to be all upper-case letters, all lower-case letters,
1732 or mixed-case. If no
1733 @code{Casing} parameter is used, then the default is all
1734 ^lower-case^upper-case^.
1736 The optional @code{Dot_Replacement} string is used to replace any periods
1737 that occur in subunit or child unit names. If no @code{Dot_Replacement}
1738 argument is used then separating dots appear unchanged in the resulting
1739 file name.
1740 Although the above syntax indicates that the
1741 @code{Casing} argument must appear
1742 before the @code{Dot_Replacement} argument, but it
1743 is also permissible to write these arguments in the opposite order.
1745 As indicated, it is possible to specify different naming schemes for
1746 bodies, specs, and subunits. Quite often the rule for subunits is the
1747 same as the rule for bodies, in which case, there is no need to give
1748 a separate @code{Subunit_File_Name} rule, and in this case the
1749 @code{Body_File_name} rule is used for subunits as well.
1751 The separate rule for subunits can also be used to implement the rather
1752 unusual case of a compilation environment (e.g.@: a single directory) which
1753 contains a subunit and a child unit with the same unit name. Although
1754 both units cannot appear in the same partition, the Ada Reference Manual
1755 allows (but does not require) the possibility of the two units coexisting
1756 in the same environment.
1758 The file name translation works in the following steps:
1760 @itemize @bullet
1762 @item
1763 If there is a specific @code{Source_File_Name} pragma for the given unit,
1764 then this is always used, and any general pattern rules are ignored.
1766 @item
1767 If there is a pattern type @code{Source_File_Name} pragma that applies to
1768 the unit, then the resulting file name will be used if the file exists. If
1769 more than one pattern matches, the latest one will be tried first, and the
1770 first attempt resulting in a reference to a file that exists will be used.
1772 @item
1773 If no pattern type @code{Source_File_Name} pragma that applies to the unit
1774 for which the corresponding file exists, then the standard GNAT default
1775 naming rules are used.
1777 @end itemize
1779 @noindent
1780 As an example of the use of this mechanism, consider a commonly used scheme
1781 in which file names are all lower case, with separating periods copied
1782 unchanged to the resulting file name, and specs end with @file{.1.ada}, and
1783 bodies end with @file{.2.ada}. GNAT will follow this scheme if the following
1784 two pragmas appear:
1786 @smallexample @c ada
1787 pragma Source_File_Name
1788   (Spec_File_Name => "*.1.ada");
1789 pragma Source_File_Name
1790   (Body_File_Name => "*.2.ada");
1791 @end smallexample
1793 @noindent
1794 The default GNAT scheme is actually implemented by providing the following
1795 default pragmas internally:
1797 @smallexample @c ada
1798 pragma Source_File_Name
1799   (Spec_File_Name => "*.ads", Dot_Replacement => "-");
1800 pragma Source_File_Name
1801   (Body_File_Name => "*.adb", Dot_Replacement => "-");
1802 @end smallexample
1804 @noindent
1805 Our final example implements a scheme typically used with one of the
1806 Ada 83 compilers, where the separator character for subunits was ``__''
1807 (two underscores), specs were identified by adding @file{_.ADA}, bodies
1808 by adding @file{.ADA}, and subunits by
1809 adding @file{.SEP}. All file names were
1810 upper case. Child units were not present of course since this was an
1811 Ada 83 compiler, but it seems reasonable to extend this scheme to use
1812 the same double underscore separator for child units.
1814 @smallexample @c ada
1815 pragma Source_File_Name
1816   (Spec_File_Name => "*_.ADA",
1817    Dot_Replacement => "__",
1818    Casing = Uppercase);
1819 pragma Source_File_Name
1820   (Body_File_Name => "*.ADA",
1821    Dot_Replacement => "__",
1822    Casing = Uppercase);
1823 pragma Source_File_Name
1824   (Subunit_File_Name => "*.SEP",
1825    Dot_Replacement => "__",
1826    Casing = Uppercase);
1827 @end smallexample
1829 @node Generating Object Files
1830 @section Generating Object Files
1832 @noindent
1833 An Ada program consists of a set of source files, and the first step in
1834 compiling the program is to generate the corresponding object files.
1835 These are generated by compiling a subset of these source files.
1836 The files you need to compile are the following:
1838 @itemize @bullet
1839 @item
1840 If a package spec has no body, compile the package spec to produce the
1841 object file for the package.
1843 @item
1844 If a package has both a spec and a body, compile the body to produce the
1845 object file for the package. The source file for the package spec need
1846 not be compiled in this case because there is only one object file, which
1847 contains the code for both the spec and body of the package.
1849 @item
1850 For a subprogram, compile the subprogram body to produce the object file
1851 for the subprogram. The spec, if one is present, is as usual in a
1852 separate file, and need not be compiled.
1854 @item
1855 @cindex Subunits
1856 In the case of subunits, only compile the parent unit. A single object
1857 file is generated for the entire subunit tree, which includes all the
1858 subunits.
1860 @item
1861 Compile child units independently of their parent units
1862 (though, of course, the spec of all the ancestor unit must be present in order
1863 to compile a child unit).
1865 @item
1866 @cindex Generics
1867 Compile generic units in the same manner as any other units. The object
1868 files in this case are small dummy files that contain at most the
1869 flag used for elaboration checking. This is because GNAT always handles generic
1870 instantiation by means of macro expansion. However, it is still necessary to
1871 compile generic units, for dependency checking and elaboration purposes.
1872 @end itemize
1874 @noindent
1875 The preceding rules describe the set of files that must be compiled to
1876 generate the object files for a program. Each object file has the same
1877 name as the corresponding source file, except that the extension is
1878 @file{.o} as usual.
1880 You may wish to compile other files for the purpose of checking their
1881 syntactic and semantic correctness. For example, in the case where a
1882 package has a separate spec and body, you would not normally compile the
1883 spec. However, it is convenient in practice to compile the spec to make
1884 sure it is error-free before compiling clients of this spec, because such
1885 compilations will fail if there is an error in the spec.
1887 GNAT provides an option for compiling such files purely for the
1888 purposes of checking correctness; such compilations are not required as
1889 part of the process of building a program. To compile a file in this
1890 checking mode, use the @option{-gnatc} switch.
1892 @node Source Dependencies
1893 @section Source Dependencies
1895 @noindent
1896 A given object file clearly depends on the source file which is compiled
1897 to produce it. Here we are using @dfn{depends} in the sense of a typical
1898 @code{make} utility; in other words, an object file depends on a source
1899 file if changes to the source file require the object file to be
1900 recompiled.
1901 In addition to this basic dependency, a given object may depend on
1902 additional source files as follows:
1904 @itemize @bullet
1905 @item
1906 If a file being compiled @code{with}'s a unit @var{X}, the object file
1907 depends on the file containing the spec of unit @var{X}. This includes
1908 files that are @code{with}'ed implicitly either because they are parents
1909 of @code{with}'ed child units or they are run-time units required by the
1910 language constructs used in a particular unit.
1912 @item
1913 If a file being compiled instantiates a library level generic unit, the
1914 object file depends on both the spec and body files for this generic
1915 unit.
1917 @item
1918 If a file being compiled instantiates a generic unit defined within a
1919 package, the object file depends on the body file for the package as
1920 well as the spec file.
1922 @item
1923 @findex Inline
1924 @cindex @option{-gnatn} switch
1925 If a file being compiled contains a call to a subprogram for which
1926 pragma @code{Inline} applies and inlining is activated with the
1927 @option{-gnatn} switch, the object file depends on the file containing the
1928 body of this subprogram as well as on the file containing the spec. Note
1929 that for inlining to actually occur as a result of the use of this switch,
1930 it is necessary to compile in optimizing mode.
1932 @cindex @option{-gnatN} switch
1933 The use of @option{-gnatN} activates  inlining optimization
1934 that is performed by the front end of the compiler. This inlining does
1935 not require that the code generation be optimized. Like @option{-gnatn},
1936 the use of this switch generates additional dependencies.
1938 When using a gcc-based back end (in practice this means using any version
1939 of GNAT other than the JGNAT, .NET or GNAAMP versions), then the use of
1940 @option{-gnatN} is deprecated, and the use of @option{-gnatn} is preferred.
1941 Historically front end inlining was more extensive than the gcc back end
1942 inlining, but that is no longer the case.
1944 @item
1945 If an object file @file{O} depends on the proper body of a subunit through
1946 inlining or instantiation, it depends on the parent unit of the subunit.
1947 This means that any modification of the parent unit or one of its subunits
1948 affects the compilation of @file{O}.
1950 @item
1951 The object file for a parent unit depends on all its subunit body files.
1953 @item
1954 The previous two rules meant that for purposes of computing dependencies and
1955 recompilation, a body and all its subunits are treated as an indivisible whole.
1957 @noindent
1958 These rules are applied transitively: if unit @code{A} @code{with}'s
1959 unit @code{B}, whose elaboration calls an inlined procedure in package
1960 @code{C}, the object file for unit @code{A} will depend on the body of
1961 @code{C}, in file @file{c.adb}.
1963 The set of dependent files described by these rules includes all the
1964 files on which the unit is semantically dependent, as dictated by the
1965 Ada language standard. However, it is a superset of what the
1966 standard describes, because it includes generic, inline, and subunit
1967 dependencies.
1969 An object file must be recreated by recompiling the corresponding source
1970 file if any of the source files on which it depends are modified. For
1971 example, if the @code{make} utility is used to control compilation,
1972 the rule for an Ada object file must mention all the source files on
1973 which the object file depends, according to the above definition.
1974 The determination of the necessary
1975 recompilations is done automatically when one uses @command{gnatmake}.
1976 @end itemize
1978 @node The Ada Library Information Files
1979 @section The Ada Library Information Files
1980 @cindex Ada Library Information files
1981 @cindex @file{ALI} files
1983 @noindent
1984 Each compilation actually generates two output files. The first of these
1985 is the normal object file that has a @file{.o} extension. The second is a
1986 text file containing full dependency information. It has the same
1987 name as the source file, but an @file{.ali} extension.
1988 This file is known as the Ada Library Information (@file{ALI}) file.
1989 The following information is contained in the @file{ALI} file.
1991 @itemize @bullet
1992 @item
1993 Version information (indicates which version of GNAT was used to compile
1994 the unit(s) in question)
1996 @item
1997 Main program information (including priority and time slice settings,
1998 as well as the wide character encoding used during compilation).
2000 @item
2001 List of arguments used in the @command{gcc} command for the compilation
2003 @item
2004 Attributes of the unit, including configuration pragmas used, an indication
2005 of whether the compilation was successful, exception model used etc.
2007 @item
2008 A list of relevant restrictions applying to the unit (used for consistency)
2009 checking.
2011 @item
2012 Categorization information (e.g.@: use of pragma @code{Pure}).
2014 @item
2015 Information on all @code{with}'ed units, including presence of
2016 @code{Elaborate} or @code{Elaborate_All} pragmas.
2018 @item
2019 Information from any @code{Linker_Options} pragmas used in the unit
2021 @item
2022 Information on the use of @code{Body_Version} or @code{Version}
2023 attributes in the unit.
2025 @item
2026 Dependency information. This is a list of files, together with
2027 time stamp and checksum information. These are files on which
2028 the unit depends in the sense that recompilation is required
2029 if any of these units are modified.
2031 @item
2032 Cross-reference data. Contains information on all entities referenced
2033 in the unit. Used by tools like @code{gnatxref} and @code{gnatfind} to
2034 provide cross-reference information.
2036 @end itemize
2038 @noindent
2039 For a full detailed description of the format of the @file{ALI} file,
2040 see the source of the body of unit @code{Lib.Writ}, contained in file
2041 @file{lib-writ.adb} in the GNAT compiler sources.
2043 @node Binding an Ada Program
2044 @section Binding an Ada Program
2046 @noindent
2047 When using languages such as C and C++, once the source files have been
2048 compiled the only remaining step in building an executable program
2049 is linking the object modules together. This means that it is possible to
2050 link an inconsistent version of a program, in which two units have
2051 included different versions of the same header.
2053 The rules of Ada do not permit such an inconsistent program to be built.
2054 For example, if two clients have different versions of the same package,
2055 it is illegal to build a program containing these two clients.
2056 These rules are enforced by the GNAT binder, which also determines an
2057 elaboration order consistent with the Ada rules.
2059 The GNAT binder is run after all the object files for a program have
2060 been created. It is given the name of the main program unit, and from
2061 this it determines the set of units required by the program, by reading the
2062 corresponding ALI files. It generates error messages if the program is
2063 inconsistent or if no valid order of elaboration exists.
2065 If no errors are detected, the binder produces a main program, in Ada by
2066 default, that contains calls to the elaboration procedures of those
2067 compilation unit that require them, followed by
2068 a call to the main program. This Ada program is compiled to generate the
2069 object file for the main program. The name of
2070 the Ada file is @file{b~@var{xxx}.adb} (with the corresponding spec
2071 @file{b~@var{xxx}.ads}) where @var{xxx} is the name of the
2072 main program unit.
2074 Finally, the linker is used to build the resulting executable program,
2075 using the object from the main program from the bind step as well as the
2076 object files for the Ada units of the program.
2078 @node Mixed Language Programming
2079 @section Mixed Language Programming
2080 @cindex Mixed Language Programming
2082 @noindent
2083 This section describes how to develop a mixed-language program,
2084 specifically one that comprises units in both Ada and C.
2086 @menu
2087 * Interfacing to C::
2088 * Calling Conventions::
2089 @end menu
2091 @node Interfacing to C
2092 @subsection Interfacing to C
2093 @noindent
2094 Interfacing Ada with a foreign language such as C involves using
2095 compiler directives to import and/or export entity definitions in each
2096 language---using @code{extern} statements in C, for instance, and the
2097 @code{Import}, @code{Export}, and @code{Convention} pragmas in Ada.
2098 A full treatment of these topics is provided in Appendix B, section 1
2099 of the Ada Reference Manual.
2101 There are two ways to build a program using GNAT that contains some Ada
2102 sources and some foreign language sources, depending on whether or not
2103 the main subprogram is written in Ada.  Here is a source example with
2104 the main subprogram in Ada:
2106 @smallexample
2107 /* file1.c */
2108 #include <stdio.h>
2110 void print_num (int num)
2112   printf ("num is %d.\n", num);
2113   return;
2116 /* file2.c */
2118 /* num_from_Ada is declared in my_main.adb */
2119 extern int num_from_Ada;
2121 int get_num (void)
2123   return num_from_Ada;
2125 @end smallexample
2127 @smallexample @c ada
2128 --  my_main.adb
2129 procedure My_Main is
2131    --  Declare then export an Integer entity called num_from_Ada
2132    My_Num : Integer := 10;
2133    pragma Export (C, My_Num, "num_from_Ada");
2135    --  Declare an Ada function spec for Get_Num, then use
2136    --  C function get_num for the implementation.
2137    function Get_Num return Integer;
2138    pragma Import (C, Get_Num, "get_num");
2140    --  Declare an Ada procedure spec for Print_Num, then use
2141    --  C function print_num for the implementation.
2142    procedure Print_Num (Num : Integer);
2143    pragma Import (C, Print_Num, "print_num");
2145 begin
2146    Print_Num (Get_Num);
2147 end My_Main;
2148 @end smallexample
2150 @enumerate
2151 @item
2152 To build this example, first compile the foreign language files to
2153 generate object files:
2154 @smallexample
2155 ^gcc -c file1.c^gcc -c FILE1.C^
2156 ^gcc -c file2.c^gcc -c FILE2.C^
2157 @end smallexample
2159 @item
2160 Then, compile the Ada units to produce a set of object files and ALI
2161 files:
2162 @smallexample
2163 gnatmake ^-c^/ACTIONS=COMPILE^ my_main.adb
2164 @end smallexample
2166 @item
2167 Run the Ada binder on the Ada main program:
2168 @smallexample
2169 gnatbind my_main.ali
2170 @end smallexample
2172 @item
2173 Link the Ada main program, the Ada objects and the other language
2174 objects:
2175 @smallexample
2176 gnatlink my_main.ali file1.o file2.o
2177 @end smallexample
2178 @end enumerate
2180 The last three steps can be grouped in a single command:
2181 @smallexample
2182 gnatmake my_main.adb -largs file1.o file2.o
2183 @end smallexample
2185 @cindex Binder output file
2186 @noindent
2187 If the main program is in a language other than Ada, then you may have
2188 more than one entry point into the Ada subsystem. You must use a special
2189 binder option to generate callable routines that initialize and
2190 finalize the Ada units (@pxref{Binding with Non-Ada Main Programs}).
2191 Calls to the initialization and finalization routines must be inserted
2192 in the main program, or some other appropriate point in the code. The
2193 call to initialize the Ada units must occur before the first Ada
2194 subprogram is called, and the call to finalize the Ada units must occur
2195 after the last Ada subprogram returns. The binder will place the
2196 initialization and finalization subprograms into the
2197 @file{b~@var{xxx}.adb} file where they can be accessed by your C
2198 sources.  To illustrate, we have the following example:
2200 @smallexample
2201 /* main.c */
2202 extern void adainit (void);
2203 extern void adafinal (void);
2204 extern int add (int, int);
2205 extern int sub (int, int);
2207 int main (int argc, char *argv[])
2209   int a = 21, b = 7;
2211   adainit();
2213   /* Should print "21 + 7 = 28" */
2214   printf ("%d + %d = %d\n", a, b, add (a, b));
2215   /* Should print "21 - 7 = 14" */
2216   printf ("%d - %d = %d\n", a, b, sub (a, b));
2218   adafinal();
2220 @end smallexample
2222 @smallexample @c ada
2223 --  unit1.ads
2224 package Unit1 is
2225    function Add (A, B : Integer) return Integer;
2226    pragma Export (C, Add, "add");
2227 end Unit1;
2229 --  unit1.adb
2230 package body Unit1 is
2231    function Add (A, B : Integer) return Integer is
2232    begin
2233       return A + B;
2234    end Add;
2235 end Unit1;
2237 --  unit2.ads
2238 package Unit2 is
2239    function Sub (A, B : Integer) return Integer;
2240    pragma Export (C, Sub, "sub");
2241 end Unit2;
2243 --  unit2.adb
2244 package body Unit2 is
2245    function Sub (A, B : Integer) return Integer is
2246    begin
2247       return A - B;
2248    end Sub;
2249 end Unit2;
2250 @end smallexample
2252 @enumerate
2253 @item
2254 The build procedure for this application is similar to the last
2255 example's.  First, compile the foreign language files to generate object
2256 files:
2257 @smallexample
2258 ^gcc -c main.c^gcc -c main.c^
2259 @end smallexample
2261 @item
2262 Next, compile the Ada units to produce a set of object files and ALI
2263 files:
2264 @smallexample
2265 gnatmake ^-c^/ACTIONS=COMPILE^ unit1.adb
2266 gnatmake ^-c^/ACTIONS=COMPILE^ unit2.adb
2267 @end smallexample
2269 @item
2270 Run the Ada binder on every generated ALI file.  Make sure to use the
2271 @option{-n} option to specify a foreign main program:
2272 @smallexample
2273 gnatbind ^-n^/NOMAIN^ unit1.ali unit2.ali
2274 @end smallexample
2276 @item
2277 Link the Ada main program, the Ada objects and the foreign language
2278 objects. You need only list the last ALI file here:
2279 @smallexample
2280 gnatlink unit2.ali main.o -o exec_file
2281 @end smallexample
2283 This procedure yields a binary executable called @file{exec_file}.
2284 @end enumerate
2286 @noindent
2287 Depending on the circumstances (for example when your non-Ada main object
2288 does not provide symbol @code{main}), you may also need to instruct the
2289 GNAT linker not to include the standard startup objects by passing the
2290 @option{^-nostartfiles^/NOSTART_FILES^} switch to @command{gnatlink}.
2292 @node Calling Conventions
2293 @subsection Calling Conventions
2294 @cindex Foreign Languages
2295 @cindex Calling Conventions
2296 GNAT follows standard calling sequence conventions and will thus interface
2297 to any other language that also follows these conventions. The following
2298 Convention identifiers are recognized by GNAT:
2300 @table @code
2301 @cindex Interfacing to Ada
2302 @cindex Other Ada compilers
2303 @cindex Convention Ada
2304 @item Ada
2305 This indicates that the standard Ada calling sequence will be
2306 used and all Ada data items may be passed without any limitations in the
2307 case where GNAT is used to generate both the caller and callee. It is also
2308 possible to mix GNAT generated code and code generated by another Ada
2309 compiler. In this case, the data types should be restricted to simple
2310 cases, including primitive types. Whether complex data types can be passed
2311 depends on the situation. Probably it is safe to pass simple arrays, such
2312 as arrays of integers or floats. Records may or may not work, depending
2313 on whether both compilers lay them out identically. Complex structures
2314 involving variant records, access parameters, tasks, or protected types,
2315 are unlikely to be able to be passed.
2317 Note that in the case of GNAT running
2318 on a platform that supports HP Ada 83, a higher degree of compatibility
2319 can be guaranteed, and in particular records are laid out in an identical
2320 manner in the two compilers. Note also that if output from two different
2321 compilers is mixed, the program is responsible for dealing with elaboration
2322 issues. Probably the safest approach is to write the main program in the
2323 version of Ada other than GNAT, so that it takes care of its own elaboration
2324 requirements, and then call the GNAT-generated adainit procedure to ensure
2325 elaboration of the GNAT components. Consult the documentation of the other
2326 Ada compiler for further details on elaboration.
2328 However, it is not possible to mix the tasking run time of GNAT and
2329 HP Ada 83, All the tasking operations must either be entirely within
2330 GNAT compiled sections of the program, or entirely within HP Ada 83
2331 compiled sections of the program.
2333 @cindex Interfacing to Assembly
2334 @cindex Convention Assembler
2335 @item Assembler
2336 Specifies assembler as the convention. In practice this has the
2337 same effect as convention Ada (but is not equivalent in the sense of being
2338 considered the same convention).
2340 @cindex Convention Asm
2341 @findex Asm
2342 @item Asm
2343 Equivalent to Assembler.
2345 @cindex Interfacing to COBOL
2346 @cindex Convention COBOL
2347 @findex COBOL
2348 @item COBOL
2349 Data will be passed according to the conventions described
2350 in section B.4 of the Ada Reference Manual.
2352 @findex C
2353 @cindex Interfacing to C
2354 @cindex Convention C
2355 @item C
2356 Data will be passed according to the conventions described
2357 in section B.3 of the Ada Reference Manual.
2359 A note on interfacing to a C ``varargs'' function:
2360 @findex C varargs function
2361 @cindex Interfacing to C varargs function
2362 @cindex varargs function interfaces
2364 @itemize @bullet
2365 @item
2366 In C, @code{varargs} allows a function to take a variable number of
2367 arguments. There is no direct equivalent in this to Ada. One
2368 approach that can be used is to create a C wrapper for each
2369 different profile and then interface to this C wrapper. For
2370 example, to print an @code{int} value using @code{printf},
2371 create a C function @code{printfi} that takes two arguments, a
2372 pointer to a string and an int, and calls @code{printf}.
2373 Then in the Ada program, use pragma @code{Import} to
2374 interface to @code{printfi}.
2376 @item
2377 It may work on some platforms to directly interface to
2378 a @code{varargs} function by providing a specific Ada profile
2379 for a particular call. However, this does not work on
2380 all platforms, since there is no guarantee that the
2381 calling sequence for a two argument normal C function
2382 is the same as for calling a @code{varargs} C function with
2383 the same two arguments.
2384 @end itemize
2386 @cindex Convention Default
2387 @findex Default
2388 @item Default
2389 Equivalent to C.
2391 @cindex Convention External
2392 @findex External
2393 @item External
2394 Equivalent to C.
2396 @ifclear vms
2397 @findex C++
2398 @cindex Interfacing to C++
2399 @cindex Convention C++
2400 @item C_Plus_Plus (or CPP)
2401 This stands for C++. For most purposes this is identical to C.
2402 See the separate description of the specialized GNAT pragmas relating to
2403 C++ interfacing for further details.
2404 @end ifclear
2406 @findex Fortran
2407 @cindex Interfacing to Fortran
2408 @cindex Convention Fortran
2409 @item Fortran
2410 Data will be passed according to the conventions described
2411 in section B.5 of the Ada Reference Manual.
2413 @item Intrinsic
2414 This applies to an intrinsic operation, as defined in the Ada
2415 Reference Manual. If a pragma Import (Intrinsic) applies to a subprogram,
2416 this means that the body of the subprogram is provided by the compiler itself,
2417 usually by means of an efficient code sequence, and that the user does not
2418 supply an explicit body for it. In an application program, the pragma may
2419 be applied to the following sets of names:
2421 @itemize @bullet
2422 @item
2423 Rotate_Left, Rotate_Right, Shift_Left, Shift_Right,
2424 Shift_Right_Arithmetic.  The corresponding subprogram declaration must have
2425 two formal parameters. The
2426 first one must be a signed integer type or a modular type with a binary
2427 modulus, and the second parameter must be of type Natural.
2428 The return type must be the same as the type of the first argument. The size
2429 of this type can only be 8, 16, 32, or 64.
2431 @item
2432 Binary arithmetic operators: ``+'', ``-'', ``*'', ``/''
2433 The corresponding operator declaration must have parameters and result type
2434 that have the same root numeric type (for example, all three are long_float
2435 types). This simplifies the definition of operations that use type checking
2436 to perform dimensional checks:
2438 @smallexample @c ada
2439 type Distance is new Long_Float;
2440 type Time     is new Long_Float;
2441 type Velocity is new Long_Float;
2442 function "/" (D : Distance; T : Time)
2443   return Velocity;
2444 pragma Import (Intrinsic, "/");
2445 @end smallexample
2447 @noindent
2448 This common idiom is often programmed with a generic definition and an
2449 explicit body. The pragma makes it simpler to introduce such declarations.
2450 It incurs no overhead in compilation time or code size, because it is
2451 implemented as a single machine instruction.
2453 @item
2454 General subprogram entities, to bind an Ada subprogram declaration to
2455 a compiler builtin by name with back-ends where such interfaces are
2456 available. A typical example is the set of ``__builtin'' functions
2457 exposed by the GCC back-end, as in the following example:
2459 @smallexample @c ada
2460    function builtin_sqrt (F : Float) return Float;
2461    pragma Import (Intrinsic, builtin_sqrt, "__builtin_sqrtf");
2462 @end smallexample
2464 Most of the GCC builtins are accessible this way, and as for other
2465 import conventions (e.g. C), it is the user's responsibility to ensure
2466 that the Ada subprogram profile matches the underlying builtin
2467 expectations.
2468 @end itemize
2470 @noindent
2472 @ifset unw
2473 @findex Stdcall
2474 @cindex Convention Stdcall
2475 @item Stdcall
2476 This is relevant only to Windows XP/2000/NT implementations of GNAT,
2477 and specifies that the @code{Stdcall} calling sequence will be used,
2478 as defined by the NT API. Nevertheless, to ease building
2479 cross-platform bindings this convention will be handled as a @code{C} calling
2480 convention on non-Windows platforms.
2482 @findex DLL
2483 @cindex Convention DLL
2484 @item DLL
2485 This is equivalent to @code{Stdcall}.
2487 @findex Win32
2488 @cindex Convention Win32
2489 @item Win32
2490 This is equivalent to @code{Stdcall}.
2491 @end ifset
2493 @findex Stubbed
2494 @cindex Convention Stubbed
2495 @item Stubbed
2496 This is a special convention that indicates that the compiler
2497 should provide a stub body that raises @code{Program_Error}.
2498 @end table
2500 @noindent
2501 GNAT additionally provides a useful pragma @code{Convention_Identifier}
2502 that can be used to parameterize conventions and allow additional synonyms
2503 to be specified. For example if you have legacy code in which the convention
2504 identifier Fortran77 was used for Fortran, you can use the configuration
2505 pragma:
2507 @smallexample @c ada
2508 pragma Convention_Identifier (Fortran77, Fortran);
2509 @end smallexample
2511 @noindent
2512 And from now on the identifier Fortran77 may be used as a convention
2513 identifier (for example in an @code{Import} pragma) with the same
2514 meaning as Fortran.
2516 @ifclear vms
2517 @node Building Mixed Ada & C++ Programs
2518 @section Building Mixed Ada and C++ Programs
2520 @noindent
2521 A programmer inexperienced with mixed-language development may find that
2522 building an application containing both Ada and C++ code can be a
2523 challenge.  This section gives a few
2524 hints that should make this task easier. The first section addresses
2525 the differences between interfacing with C and interfacing with C++.
2526 The second section
2527 looks into the delicate problem of linking the complete application from
2528 its Ada and C++ parts. The last section gives some hints on how the GNAT
2529 run-time library can be adapted in order to allow inter-language dispatching
2530 with a new C++ compiler.
2532 @menu
2533 * Interfacing to C++::
2534 * Linking a Mixed C++ & Ada Program::
2535 * A Simple Example::
2536 * Interfacing with C++ constructors::
2537 * Interfacing with C++ at the Class Level::
2538 @end menu
2540 @node Interfacing to C++
2541 @subsection Interfacing to C++
2543 @noindent
2544 GNAT supports interfacing with the G++ compiler (or any C++ compiler
2545 generating code that is compatible with the G++ Application Binary
2546 Interface ---see http://www.codesourcery.com/archives/cxx-abi).
2548 @noindent
2549 Interfacing can be done at 3 levels: simple data, subprograms, and
2550 classes. In the first two cases, GNAT offers a specific @code{Convention
2551 C_Plus_Plus} (or @code{CPP}) that behaves exactly like @code{Convention C}.
2552 Usually, C++ mangles the names of subprograms. To generate proper mangled
2553 names automatically, see @ref{Generating Ada Bindings for C and C++ headers}).
2554 This problem can also be addressed manually in two ways:
2556 @itemize @bullet
2557 @item
2558 by modifying the C++ code in order to force a C convention using
2559 the @code{extern "C"} syntax.
2561 @item
2562 by figuring out the mangled name (using e.g. @command{nm}) and using it as the
2563 Link_Name argument of the pragma import.
2564 @end itemize
2566 @noindent
2567 Interfacing at the class level can be achieved by using the GNAT specific
2568 pragmas such as @code{CPP_Constructor}.  @xref{Interfacing to C++,,,
2569 gnat_rm, GNAT Reference Manual}, for additional information.
2571 @node Linking a Mixed C++ & Ada Program
2572 @subsection Linking a Mixed C++ & Ada Program
2574 @noindent
2575 Usually the linker of the C++ development system must be used to link
2576 mixed applications because most C++ systems will resolve elaboration
2577 issues (such as calling constructors on global class instances)
2578 transparently during the link phase. GNAT has been adapted to ease the
2579 use of a foreign linker for the last phase. Three cases can be
2580 considered:
2581 @enumerate
2583 @item
2584 Using GNAT and G++ (GNU C++ compiler) from the same GCC installation:
2585 The C++ linker can simply be called by using the C++ specific driver
2586 called @code{g++}.
2588 Note that if the C++ code uses inline functions, you will need to
2589 compile your C++ code with the @code{-fkeep-inline-functions} switch in
2590 order to provide an existing function implementation that the Ada code can
2591 link with.
2593 @smallexample
2594 $ g++ -c -fkeep-inline-functions file1.C
2595 $ g++ -c -fkeep-inline-functions file2.C
2596 $ gnatmake ada_unit -largs file1.o file2.o --LINK=g++
2597 @end smallexample
2599 @item
2600 Using GNAT and G++ from two different GCC installations: If both
2601 compilers are on the @env{PATH}, the previous method may be used. It is
2602 important to note that environment variables such as
2603 @env{C_INCLUDE_PATH}, @env{GCC_EXEC_PREFIX}, @env{BINUTILS_ROOT}, and
2604 @env{GCC_ROOT} will affect both compilers
2605 at the same time and may make one of the two compilers operate
2606 improperly if set during invocation of the wrong compiler.  It is also
2607 very important that the linker uses the proper @file{libgcc.a} GCC
2608 library -- that is, the one from the C++ compiler installation. The
2609 implicit link command as suggested in the @command{gnatmake} command
2610 from the former example can be replaced by an explicit link command with
2611 the full-verbosity option in order to verify which library is used:
2612 @smallexample
2613 $ gnatbind ada_unit
2614 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=c++
2615 @end smallexample
2616 If there is a problem due to interfering environment variables, it can
2617 be worked around by using an intermediate script. The following example
2618 shows the proper script to use when GNAT has not been installed at its
2619 default location and g++ has been installed at its default location:
2621 @smallexample
2622 $ cat ./my_script
2623 #!/bin/sh
2624 unset BINUTILS_ROOT
2625 unset GCC_ROOT
2626 c++ $*
2627 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=./my_script
2628 @end smallexample
2630 @item
2631 Using a non-GNU C++ compiler: The commands previously described can be
2632 used to insure that the C++ linker is used. Nonetheless, you need to add
2633 a few more parameters to the link command line, depending on the exception
2634 mechanism used.
2636 If the @code{setjmp/longjmp} exception mechanism is used, only the paths
2637 to the libgcc libraries are required:
2639 @smallexample
2640 $ cat ./my_script
2641 #!/bin/sh
2642 CC $* `gcc -print-file-name=libgcc.a` `gcc -print-file-name=libgcc_eh.a`
2643 $ gnatlink ada_unit file1.o file2.o --LINK=./my_script
2644 @end smallexample
2646 Where CC is the name of the non-GNU C++ compiler.
2648 If the @code{zero cost} exception mechanism is used, and the platform
2649 supports automatic registration of exception tables (e.g.@: Solaris),
2650 paths to more objects are required:
2652 @smallexample
2653 $ cat ./my_script
2654 #!/bin/sh
2655 CC `gcc -print-file-name=crtbegin.o` $* \
2656 `gcc -print-file-name=libgcc.a` `gcc -print-file-name=libgcc_eh.a` \
2657 `gcc -print-file-name=crtend.o`
2658 $ gnatlink ada_unit file1.o file2.o --LINK=./my_script
2659 @end smallexample
2661 If the @code{zero cost} exception mechanism is used, and the platform
2662 doesn't support automatic registration of exception tables (e.g.@: HP-UX
2663 or AIX), the simple approach described above will not work and
2664 a pre-linking phase using GNAT will be necessary.
2666 @end enumerate
2668 Another alternative is to use the @command{gprbuild} multi-language builder
2669 which has a large knowledge base and knows how to link Ada and C++ code
2670 together automatically in most cases.
2672 @node A Simple Example
2673 @subsection  A Simple Example
2674 @noindent
2675 The following example, provided as part of the GNAT examples, shows how
2676 to achieve procedural interfacing between Ada and C++ in both
2677 directions. The C++ class A has two methods. The first method is exported
2678 to Ada by the means of an extern C wrapper function. The second method
2679 calls an Ada subprogram. On the Ada side, The C++ calls are modelled by
2680 a limited record with a layout comparable to the C++ class. The Ada
2681 subprogram, in turn, calls the C++ method. So, starting from the C++
2682 main program, the process passes back and forth between the two
2683 languages.
2685 @noindent
2686 Here are the compilation commands:
2687 @smallexample
2688 $ gnatmake -c simple_cpp_interface
2689 $ g++ -c cpp_main.C
2690 $ g++ -c ex7.C
2691 $ gnatbind -n simple_cpp_interface
2692 $ gnatlink simple_cpp_interface -o cpp_main --LINK=g++
2693       -lstdc++ ex7.o cpp_main.o
2694 @end smallexample
2696 @noindent
2697 Here are the corresponding sources:
2698 @smallexample
2700 //cpp_main.C
2702 #include "ex7.h"
2704 extern "C" @{
2705   void adainit (void);
2706   void adafinal (void);
2707   void method1 (A *t);
2710 void method1 (A *t)
2712   t->method1 ();
2715 int main ()
2717   A obj;
2718   adainit ();
2719   obj.method2 (3030);
2720   adafinal ();
2723 //ex7.h
2725 class Origin @{
2726  public:
2727   int o_value;
2729 class A : public Origin @{
2730  public:
2731   void method1 (void);
2732   void method2 (int v);
2733   A();
2734   int   a_value;
2737 //ex7.C
2739 #include "ex7.h"
2740 #include <stdio.h>
2742 extern "C" @{ void ada_method2 (A *t, int v);@}
2744 void A::method1 (void)
2746   a_value = 2020;
2747   printf ("in A::method1, a_value = %d \n",a_value);
2751 void A::method2 (int v)
2753    ada_method2 (this, v);
2754    printf ("in A::method2, a_value = %d \n",a_value);
2758 A::A(void)
2760    a_value = 1010;
2761   printf ("in A::A, a_value = %d \n",a_value);
2763 @end smallexample
2765 @smallexample @c ada
2766 -- Ada sources
2767 package body Simple_Cpp_Interface is
2769    procedure Ada_Method2 (This : in out A; V : Integer) is
2770    begin
2771       Method1 (This);
2772       This.A_Value := V;
2773    end Ada_Method2;
2775 end Simple_Cpp_Interface;
2777 with System;
2778 package Simple_Cpp_Interface is
2779    type A is limited
2780       record
2781          Vptr    : System.Address;
2782          O_Value : Integer;
2783          A_Value : Integer;
2784       end record;
2785    pragma Convention (C, A);
2787    procedure Method1 (This : in out A);
2788    pragma Import (C, Method1);
2790    procedure Ada_Method2 (This : in out A; V : Integer);
2791    pragma Export (C, Ada_Method2);
2793 end Simple_Cpp_Interface;
2794 @end smallexample
2796 @node Interfacing with C++ constructors
2797 @subsection Interfacing with C++ constructors
2798 @noindent
2800 In order to interface with C++ constructors GNAT provides the
2801 @code{pragma CPP_Constructor} (@xref{Interfacing to C++,,,
2802 gnat_rm, GNAT Reference Manual}, for additional information).
2803 In this section we present some common uses of C++ constructors
2804 in mixed-languages programs in GNAT.
2806 Let us assume that we need to interface with the following
2807 C++ class:
2809 @smallexample
2810 @b{class} Root @{
2811 @b{public}:
2812   int  a_value;
2813   int  b_value;
2814   @b{virtual} int Get_Value ();
2815   Root();              // Default constructor
2816   Root(int v);         // 1st non-default constructor
2817   Root(int v, int w);  // 2nd non-default constructor
2819 @end smallexample
2821 For this purpose we can write the following package spec (further
2822 information on how to build this spec is available in
2823 @ref{Interfacing with C++ at the Class Level} and
2824 @ref{Generating Ada Bindings for C and C++ headers}).
2826 @smallexample @c ada
2827 with Interfaces.C; use Interfaces.C;
2828 package Pkg_Root is
2829   type Root is tagged limited record
2830      A_Value : int;
2831      B_Value : int;
2832   end record;
2833   pragma Import (CPP, Root);
2835   function Get_Value (Obj : Root) return int;
2836   pragma Import (CPP, Get_Value);
2838   function Constructor return Root;
2839   pragma Cpp_Constructor (Constructor, "_ZN4RootC1Ev");
2841   function Constructor (v : Integer) return Root;
2842   pragma Cpp_Constructor (Constructor, "_ZN4RootC1Ei");
2844   function Constructor (v, w : Integer) return Root;
2845   pragma Cpp_Constructor (Constructor, "_ZN4RootC1Eii");
2846 end Pkg_Root;
2847 @end smallexample
2849 On the Ada side the constructor is represented by a function (whose
2850 name is arbitrary) that returns the classwide type corresponding to
2851 the imported C++ class. Although the constructor is described as a
2852 function, it is typically a procedure with an extra implicit argument
2853 (the object being initialized) at the implementation level. GNAT
2854 issues the appropriate call, whatever it is, to get the object
2855 properly initialized.
2857 Constructors can only appear in the following contexts:
2859 @itemize @bullet
2860 @item
2861 On the right side of an initialization of an object of type @var{T}.
2862 @item
2863 On the right side of an initialization of a record component of type @var{T}.
2864 @item
2865 In an Ada 2005 limited aggregate.
2866 @item
2867 In an Ada 2005 nested limited aggregate.
2868 @item
2869 In an Ada 2005 limited aggregate that initializes an object built in
2870 place by an extended return statement.
2871 @end itemize
2873 @noindent
2874 In a declaration of an object whose type is a class imported from C++,
2875 either the default C++ constructor is implicitly called by GNAT, or
2876 else the required C++ constructor must be explicitly called in the
2877 expression that initializes the object. For example:
2879 @smallexample @c ada
2880   Obj1 : Root;
2881   Obj2 : Root := Constructor;
2882   Obj3 : Root := Constructor (v => 10);
2883   Obj4 : Root := Constructor (30, 40);
2884 @end smallexample
2886 The first two declarations are equivalent: in both cases the default C++
2887 constructor is invoked (in the former case the call to the constructor is
2888 implicit, and in the latter case the call is explicit in the object
2889 declaration). @code{Obj3} is initialized by the C++ non-default constructor
2890 that takes an integer argument, and @code{Obj4} is initialized by the
2891 non-default C++ constructor that takes two integers.
2893 Let us derive the imported C++ class in the Ada side. For example:
2895 @smallexample @c ada
2896   type DT is new Root with record
2897      C_Value : Natural := 2009;
2898   end record;
2899 @end smallexample
2901 In this case the components DT inherited from the C++ side must be
2902 initialized by a C++ constructor, and the additional Ada components
2903 of type DT are initialized by GNAT. The initialization of such an
2904 object is done either by default, or by means of a function returning
2905 an aggregate of type DT, or by means of an extension aggregate.
2907 @smallexample @c ada
2908   Obj5 : DT;
2909   Obj6 : DT := Function_Returning_DT (50);
2910   Obj7 : DT := (Constructor (30,40) with C_Value => 50);
2911 @end smallexample
2913 The declaration of @code{Obj5} invokes the default constructors: the
2914 C++ default constructor of the parent type takes care of the initialization
2915 of the components inherited from Root, and GNAT takes care of the default
2916 initialization of the additional Ada components of type DT (that is,
2917 @code{C_Value} is initialized to value 2009). The order of invocation of
2918 the constructors is consistent with the order of elaboration required by
2919 Ada and C++. That is, the constructor of the parent type is always called
2920 before the constructor of the derived type.
2922 Let us now consider a record that has components whose type is imported
2923 from C++. For example:
2925 @smallexample @c ada
2926   type Rec1 is limited record
2927      Data1 : Root := Constructor (10);
2928      Value : Natural := 1000;
2929   end record;
2931   type Rec2 (D : Integer := 20) is limited record
2932      Rec   : Rec1;
2933      Data2 : Root := Constructor (D, 30);
2934   end record;
2935 @end smallexample
2937 The initialization of an object of type @code{Rec2} will call the
2938 non-default C++ constructors specified for the imported components.
2939 For example:
2941 @smallexample @c ada
2942   Obj8 : Rec2 (40);
2943 @end smallexample
2945 Using Ada 2005 we can use limited aggregates to initialize an object
2946 invoking C++ constructors that differ from those specified in the type
2947 declarations. For example:
2949 @smallexample @c ada
2950   Obj9 : Rec2 := (Rec => (Data1 => Constructor (15, 16),
2951                           others => <>),
2952                   others => <>);
2953 @end smallexample
2955 The above declaration uses an Ada 2005 limited aggregate to
2956 initialize @code{Obj9}, and the C++ constructor that has two integer
2957 arguments is invoked to initialize the @code{Data1} component instead
2958 of the constructor specified in the declaration of type @code{Rec1}. In
2959 Ada 2005 the box in the aggregate indicates that unspecified components
2960 are initialized using the expression (if any) available in the component
2961 declaration. That is, in this case discriminant @code{D} is initialized
2962 to value @code{20}, @code{Value} is initialized to value 1000, and the
2963 non-default C++ constructor that handles two integers takes care of
2964 initializing component @code{Data2} with values @code{20,30}.
2966 In Ada 2005 we can use the extended return statement to build the Ada
2967 equivalent to C++ non-default constructors. For example:
2969 @smallexample @c ada
2970   function Constructor (V : Integer) return Rec2 is
2971   begin
2972      return Obj : Rec2 := (Rec => (Data1  => Constructor (V, 20),
2973                                    others => <>),
2974                            others => <>) do
2975         --  Further actions required for construction of
2976         --  objects of type Rec2
2977         ...
2978      end record;
2979   end Constructor;
2980 @end smallexample
2982 In this example the extended return statement construct is used to
2983 build in place the returned object whose components are initialized
2984 by means of a limited aggregate. Any further action associated with
2985 the constructor can be placed inside the construct.
2987 @node Interfacing with C++ at the Class Level
2988 @subsection Interfacing with C++ at the Class Level
2989 @noindent
2990 In this section we demonstrate the GNAT features for interfacing with
2991 C++ by means of an example making use of Ada 2005 abstract interface
2992 types. This example consists of a classification of animals; classes
2993 have been used to model our main classification of animals, and
2994 interfaces provide support for the management of secondary
2995 classifications. We first demonstrate a case in which the types and
2996 constructors are defined on the C++ side and imported from the Ada
2997 side, and latter the reverse case.
2999 The root of our derivation will be the @code{Animal} class, with a
3000 single private attribute (the @code{Age} of the animal) and two public
3001 primitives to set and get the value of this attribute.
3003 @smallexample
3004 @b{class} Animal @{
3005  @b{public}:
3006    @b{virtual} void Set_Age (int New_Age);
3007    @b{virtual} int Age ();
3008  @b{private}:
3009    int Age_Count;
3011 @end smallexample
3013 Abstract interface types are defined in C++ by means of classes with pure
3014 virtual functions and no data members. In our example we will use two
3015 interfaces that provide support for the common management of @code{Carnivore}
3016 and @code{Domestic} animals:
3018 @smallexample
3019 @b{class} Carnivore @{
3020 @b{public}:
3021    @b{virtual} int Number_Of_Teeth () = 0;
3024 @b{class} Domestic @{
3025 @b{public}:
3026    @b{virtual void} Set_Owner (char* Name) = 0;
3028 @end smallexample
3030 Using these declarations, we can now say that a @code{Dog} is an animal that is
3031 both Carnivore and Domestic, that is:
3033 @smallexample
3034 @b{class} Dog : Animal, Carnivore, Domestic @{
3035  @b{public}:
3036    @b{virtual} int  Number_Of_Teeth ();
3037    @b{virtual} void Set_Owner (char* Name);
3039    Dog(); // Constructor
3040  @b{private}:
3041    int  Tooth_Count;
3042    char *Owner;
3044 @end smallexample
3046 In the following examples we will assume that the previous declarations are
3047 located in a file named @code{animals.h}. The following package demonstrates
3048 how to import these C++ declarations from the Ada side:
3050 @smallexample @c ada
3051 with Interfaces.C.Strings; use Interfaces.C.Strings;
3052 package Animals is
3053   type Carnivore is interface;
3054   pragma Convention (C_Plus_Plus, Carnivore);
3055   function Number_Of_Teeth (X : Carnivore)
3056      return Natural is abstract;
3058   type Domestic is interface;
3059   pragma Convention (C_Plus_Plus, Set_Owner);
3060   procedure Set_Owner
3061     (X    : in out Domestic;
3062      Name : Chars_Ptr) is abstract;
3064   type Animal is tagged record
3065     Age : Natural := 0;
3066   end record;
3067   pragma Import (C_Plus_Plus, Animal);
3069   procedure Set_Age (X : in out Animal; Age : Integer);
3070   pragma Import (C_Plus_Plus, Set_Age);
3072   function Age (X : Animal) return Integer;
3073   pragma Import (C_Plus_Plus, Age);
3075   type Dog is new Animal and Carnivore and Domestic with record
3076     Tooth_Count : Natural;
3077     Owner       : String (1 .. 30);
3078   end record;
3079   pragma Import (C_Plus_Plus, Dog);
3081   function Number_Of_Teeth (A : Dog) return Integer;
3082   pragma Import (C_Plus_Plus, Number_Of_Teeth);
3084   procedure Set_Owner (A : in out Dog; Name : Chars_Ptr);
3085   pragma Import (C_Plus_Plus, Set_Owner);
3087   function New_Dog return Dog;
3088   pragma CPP_Constructor (New_Dog);
3089   pragma Import (CPP, New_Dog, "_ZN3DogC2Ev");
3090 end Animals;
3091 @end smallexample
3093 Thanks to the compatibility between GNAT run-time structures and the C++ ABI,
3094 interfacing with these C++ classes is easy. The only requirement is that all
3095 the primitives and components must be declared exactly in the same order in
3096 the two languages.
3098 Regarding the abstract interfaces, we must indicate to the GNAT compiler by
3099 means of a @code{pragma Convention (C_Plus_Plus)}, the convention used to pass
3100 the arguments to the called primitives will be the same as for C++. For the
3101 imported classes we use @code{pragma Import} with convention @code{C_Plus_Plus}
3102 to indicate that they have been defined on the C++ side; this is required
3103 because the dispatch table associated with these tagged types will be built
3104 in the C++ side and therefore will not contain the predefined Ada primitives
3105 which Ada would otherwise expect.
3107 As the reader can see there is no need to indicate the C++ mangled names
3108 associated with each subprogram because it is assumed that all the calls to
3109 these primitives will be dispatching calls. The only exception is the
3110 constructor, which must be registered with the compiler by means of
3111 @code{pragma CPP_Constructor} and needs to provide its associated C++
3112 mangled name because the Ada compiler generates direct calls to it.
3114 With the above packages we can now declare objects of type Dog on the Ada side
3115 and dispatch calls to the corresponding subprograms on the C++ side. We can
3116 also extend the tagged type Dog with further fields and primitives, and
3117 override some of its C++ primitives on the Ada side. For example, here we have
3118 a type derivation defined on the Ada side that inherits all the dispatching
3119 primitives of the ancestor from the C++ side.
3121 @smallexample
3122 @b{with} Animals; @b{use} Animals;
3123 @b{package} Vaccinated_Animals @b{is}
3124   @b{type} Vaccinated_Dog @b{is new} Dog @b{with null record};
3125   @b{function} Vaccination_Expired (A : Vaccinated_Dog) @b{return} Boolean;
3126 @b{end} Vaccinated_Animals;
3127 @end smallexample
3129 It is important to note that, because of the ABI compatibility, the programmer
3130 does not need to add any further information to indicate either the object
3131 layout or the dispatch table entry associated with each dispatching operation.
3133 Now let us define all the types and constructors on the Ada side and export
3134 them to C++, using the same hierarchy of our previous example:
3136 @smallexample @c ada
3137 with Interfaces.C.Strings;
3138 use Interfaces.C.Strings;
3139 package Animals is
3140   type Carnivore is interface;
3141   pragma Convention (C_Plus_Plus, Carnivore);
3142   function Number_Of_Teeth (X : Carnivore)
3143      return Natural is abstract;
3145   type Domestic is interface;
3146   pragma Convention (C_Plus_Plus, Set_Owner);
3147   procedure Set_Owner
3148     (X    : in out Domestic;
3149      Name : Chars_Ptr) is abstract;
3151   type Animal is tagged record
3152     Age : Natural := 0;
3153   end record;
3154   pragma Convention (C_Plus_Plus, Animal);
3156   procedure Set_Age (X : in out Animal; Age : Integer);
3157   pragma Export (C_Plus_Plus, Set_Age);
3159   function Age (X : Animal) return Integer;
3160   pragma Export (C_Plus_Plus, Age);
3162   type Dog is new Animal and Carnivore and Domestic with record
3163     Tooth_Count : Natural;
3164     Owner       : String (1 .. 30);
3165   end record;
3166   pragma Convention (C_Plus_Plus, Dog);
3168   function Number_Of_Teeth (A : Dog) return Integer;
3169   pragma Export (C_Plus_Plus, Number_Of_Teeth);
3171   procedure Set_Owner (A : in out Dog; Name : Chars_Ptr);
3172   pragma Export (C_Plus_Plus, Set_Owner);
3174   function New_Dog return Dog'Class;
3175   pragma Export (C_Plus_Plus, New_Dog);
3176 end Animals;
3177 @end smallexample
3179 Compared with our previous example the only difference is the use of
3180 @code{pragma Export} to indicate to the GNAT compiler that the primitives will
3181 be available to C++. Thanks to the ABI compatibility, on the C++ side there is
3182 nothing else to be done; as explained above, the only requirement is that all
3183 the primitives and components are declared in exactly the same order.
3185 For completeness, let us see a brief C++ main program that uses the
3186 declarations available in @code{animals.h} (presented in our first example) to
3187 import and use the declarations from the Ada side, properly initializing and
3188 finalizing the Ada run-time system along the way:
3190 @smallexample
3191 @b{#include} "animals.h"
3192 @b{#include} <iostream>
3193 @b{using namespace} std;
3195 void Check_Carnivore (Carnivore *obj) @{@dots{}@}
3196 void Check_Domestic (Domestic *obj)   @{@dots{}@}
3197 void Check_Animal (Animal *obj)       @{@dots{}@}
3198 void Check_Dog (Dog *obj)             @{@dots{}@}
3200 @b{extern} "C" @{
3201   void adainit (void);
3202   void adafinal (void);
3203   Dog* new_dog ();
3206 void test ()
3208   Dog *obj = new_dog();  // Ada constructor
3209   Check_Carnivore (obj); // Check secondary DT
3210   Check_Domestic (obj);  // Check secondary DT
3211   Check_Animal (obj);    // Check primary DT
3212   Check_Dog (obj);       // Check primary DT
3215 int main ()
3217   adainit ();  test();  adafinal ();
3218   return 0;
3220 @end smallexample
3222 @node Comparison between GNAT and C/C++ Compilation Models
3223 @section Comparison between GNAT and C/C++ Compilation Models
3225 @noindent
3226 The GNAT model of compilation is close to the C and C++ models. You can
3227 think of Ada specs as corresponding to header files in C. As in C, you
3228 don't need to compile specs; they are compiled when they are used. The
3229 Ada @code{with} is similar in effect to the @code{#include} of a C
3230 header.
3232 One notable difference is that, in Ada, you may compile specs separately
3233 to check them for semantic and syntactic accuracy. This is not always
3234 possible with C headers because they are fragments of programs that have
3235 less specific syntactic or semantic rules.
3237 The other major difference is the requirement for running the binder,
3238 which performs two important functions. First, it checks for
3239 consistency. In C or C++, the only defense against assembling
3240 inconsistent programs lies outside the compiler, in a makefile, for
3241 example. The binder satisfies the Ada requirement that it be impossible
3242 to construct an inconsistent program when the compiler is used in normal
3243 mode.
3245 @cindex Elaboration order control
3246 The other important function of the binder is to deal with elaboration
3247 issues. There are also elaboration issues in C++ that are handled
3248 automatically. This automatic handling has the advantage of being
3249 simpler to use, but the C++ programmer has no control over elaboration.
3250 Where @code{gnatbind} might complain there was no valid order of
3251 elaboration, a C++ compiler would simply construct a program that
3252 malfunctioned at run time.
3253 @end ifclear
3255 @node Comparison between GNAT and Conventional Ada Library Models
3256 @section Comparison between GNAT and Conventional Ada Library Models
3258 @noindent
3259 This section is intended for Ada programmers who have
3260 used an Ada compiler implementing the traditional Ada library
3261 model, as described in the Ada Reference Manual.
3263 @cindex GNAT library
3264 In GNAT, there is no ``library'' in the normal sense. Instead, the set of
3265 source files themselves acts as the library. Compiling Ada programs does
3266 not generate any centralized information, but rather an object file and
3267 a ALI file, which are of interest only to the binder and linker.
3268 In a traditional system, the compiler reads information not only from
3269 the source file being compiled, but also from the centralized library.
3270 This means that the effect of a compilation depends on what has been
3271 previously compiled. In particular:
3273 @itemize @bullet
3274 @item
3275 When a unit is @code{with}'ed, the unit seen by the compiler corresponds
3276 to the version of the unit most recently compiled into the library.
3278 @item
3279 Inlining is effective only if the necessary body has already been
3280 compiled into the library.
3282 @item
3283 Compiling a unit may obsolete other units in the library.
3284 @end itemize
3286 @noindent
3287 In GNAT, compiling one unit never affects the compilation of any other
3288 units because the compiler reads only source files. Only changes to source
3289 files can affect the results of a compilation. In particular:
3291 @itemize @bullet
3292 @item
3293 When a unit is @code{with}'ed, the unit seen by the compiler corresponds
3294 to the source version of the unit that is currently accessible to the
3295 compiler.
3297 @item
3298 @cindex Inlining
3299 Inlining requires the appropriate source files for the package or
3300 subprogram bodies to be available to the compiler. Inlining is always
3301 effective, independent of the order in which units are complied.
3303 @item
3304 Compiling a unit never affects any other compilations. The editing of
3305 sources may cause previous compilations to be out of date if they
3306 depended on the source file being modified.
3307 @end itemize
3309 @noindent
3310 The most important result of these differences is that order of compilation
3311 is never significant in GNAT. There is no situation in which one is
3312 required to do one compilation before another. What shows up as order of
3313 compilation requirements in the traditional Ada library becomes, in
3314 GNAT, simple source dependencies; in other words, there is only a set
3315 of rules saying what source files must be present when a file is
3316 compiled.
3318 @ifset vms
3319 @node Placement of temporary files
3320 @section Placement of temporary files
3321 @cindex Temporary files (user control over placement)
3323 @noindent
3324 GNAT creates temporary files in the directory designated by the environment
3325 variable @env{TMPDIR}.
3326 (See the HP @emph{C RTL Reference Manual} on the function @code{getenv()}
3327 for detailed information on how environment variables are resolved.
3328 For most users the easiest way to make use of this feature is to simply
3329 define @env{TMPDIR} as a job level logical name).
3330 For example, if you wish to use a Ramdisk (assuming DECRAM is installed)
3331 for compiler temporary files, then you can include something like the
3332 following command in your @file{LOGIN.COM} file:
3334 @smallexample
3335 $ define/job TMPDIR "/disk$scratchram/000000/temp/"
3336 @end smallexample
3338 @noindent
3339 If @env{TMPDIR} is not defined, then GNAT uses the directory designated by
3340 @env{TMP}; if @env{TMP} is not defined, then GNAT uses the directory
3341 designated by @env{TEMP}.
3342 If none of these environment variables are defined then GNAT uses the
3343 directory designated by the logical name @code{SYS$SCRATCH:}
3344 (by default the user's home directory). If all else fails
3345 GNAT uses the current directory for temporary files.
3346 @end ifset
3348 @c *************************
3349 @node Compiling with gcc
3350 @chapter Compiling with @command{gcc}
3352 @noindent
3353 This chapter discusses how to compile Ada programs using the @command{gcc}
3354 command. It also describes the set of switches
3355 that can be used to control the behavior of the compiler.
3356 @menu
3357 * Compiling Programs::
3358 * Switches for gcc::
3359 * Search Paths and the Run-Time Library (RTL)::
3360 * Order of Compilation Issues::
3361 * Examples::
3362 @end menu
3364 @node Compiling Programs
3365 @section Compiling Programs
3367 @noindent
3368 The first step in creating an executable program is to compile the units
3369 of the program using the @command{gcc} command. You must compile the
3370 following files:
3372 @itemize @bullet
3373 @item
3374 the body file (@file{.adb}) for a library level subprogram or generic
3375 subprogram
3377 @item
3378 the spec file (@file{.ads}) for a library level package or generic
3379 package that has no body
3381 @item
3382 the body file (@file{.adb}) for a library level package
3383 or generic package that has a body
3385 @end itemize
3387 @noindent
3388 You need @emph{not} compile the following files
3390 @itemize @bullet
3392 @item
3393 the spec of a library unit which has a body
3395 @item
3396 subunits
3397 @end itemize
3399 @noindent
3400 because they are compiled as part of compiling related units. GNAT
3401 package specs
3402 when the corresponding body is compiled, and subunits when the parent is
3403 compiled.
3405 @cindex cannot generate code
3406 If you attempt to compile any of these files, you will get one of the
3407 following error messages (where @var{fff} is the name of the file you
3408 compiled):
3410 @smallexample
3411 cannot generate code for file @var{fff} (package spec)
3412 to check package spec, use -gnatc
3414 cannot generate code for file @var{fff} (missing subunits)
3415 to check parent unit, use -gnatc
3417 cannot generate code for file @var{fff} (subprogram spec)
3418 to check subprogram spec, use -gnatc
3420 cannot generate code for file @var{fff} (subunit)
3421 to check subunit, use -gnatc
3422 @end smallexample
3424 @noindent
3425 As indicated by the above error messages, if you want to submit
3426 one of these files to the compiler to check for correct semantics
3427 without generating code, then use the @option{-gnatc} switch.
3429 The basic command for compiling a file containing an Ada unit is
3431 @smallexample
3432 @c $ gcc -c @ovar{switches} @file{file name}
3433 @c Expanding @ovar macro inline (explanation in macro def comments)
3434 $ gcc -c @r{[}@var{switches}@r{]} @file{file name}
3435 @end smallexample
3437 @noindent
3438 where @var{file name} is the name of the Ada file (usually
3439 having an extension
3440 @file{.ads} for a spec or @file{.adb} for a body).
3441 @ifclear vms
3442 You specify the
3443 @option{-c} switch to tell @command{gcc} to compile, but not link, the file.
3444 @end ifclear
3445 The result of a successful compilation is an object file, which has the
3446 same name as the source file but an extension of @file{.o} and an Ada
3447 Library Information (ALI) file, which also has the same name as the
3448 source file, but with @file{.ali} as the extension. GNAT creates these
3449 two output files in the current directory, but you may specify a source
3450 file in any directory using an absolute or relative path specification
3451 containing the directory information.
3453 @findex gnat1
3454 @command{gcc} is actually a driver program that looks at the extensions of
3455 the file arguments and loads the appropriate compiler. For example, the
3456 GNU C compiler is @file{cc1}, and the Ada compiler is @file{gnat1}.
3457 These programs are in directories known to the driver program (in some
3458 configurations via environment variables you set), but need not be in
3459 your path. The @command{gcc} driver also calls the assembler and any other
3460 utilities needed to complete the generation of the required object
3461 files.
3463 It is possible to supply several file names on the same @command{gcc}
3464 command. This causes @command{gcc} to call the appropriate compiler for
3465 each file. For example, the following command lists two separate
3466 files to be compiled:
3468 @smallexample
3469 $ gcc -c x.adb y.adb
3470 @end smallexample
3472 @noindent
3473 calls @code{gnat1} (the Ada compiler) twice to compile @file{x.adb} and
3474 @file{y.adb}.
3475 The compiler generates two object files @file{x.o} and @file{y.o}
3476 and the two ALI files @file{x.ali} and @file{y.ali}.
3477 Any switches apply to all the files ^listed,^listed.^
3479 @node Switches for gcc
3480 @section Switches for @command{gcc}
3482 @noindent
3483 The @command{gcc} command accepts switches that control the
3484 compilation process. These switches are fully described in this section.
3485 First we briefly list all the switches, in alphabetical order, then we
3486 describe the switches in more detail in functionally grouped sections.
3488 More switches exist for GCC than those documented here, especially
3489 for specific targets. However, their use is not recommended as
3490 they may change code generation in ways that are incompatible with
3491 the Ada run-time library, or can cause inconsistencies between
3492 compilation units.
3494 @menu
3495 * Output and Error Message Control::
3496 * Warning Message Control::
3497 * Debugging and Assertion Control::
3498 * Validity Checking::
3499 * Style Checking::
3500 * Run-Time Checks::
3501 * Using gcc for Syntax Checking::
3502 * Using gcc for Semantic Checking::
3503 * Compiling Different Versions of Ada::
3504 * Character Set Control::
3505 * File Naming Control::
3506 * Subprogram Inlining Control::
3507 * Auxiliary Output Control::
3508 * Debugging Control::
3509 * Exception Handling Control::
3510 * Units to Sources Mapping Files::
3511 * Integrated Preprocessing::
3512 * Code Generation Control::
3513 @ifset vms
3514 * Return Codes::
3515 @end ifset
3516 @end menu
3518 @table @option
3519 @c !sort!
3520 @ifclear vms
3521 @cindex @option{-b} (@command{gcc})
3522 @item -b @var{target}
3523 Compile your program to run on @var{target}, which is the name of a
3524 system configuration. You must have a GNAT cross-compiler built if
3525 @var{target} is not the same as your host system.
3527 @item -B@var{dir}
3528 @cindex @option{-B} (@command{gcc})
3529 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
3530 from @var{dir} instead of the default location. Only use this switch
3531 when multiple versions of the GNAT compiler are available.
3532 @xref{Directory Options,, Options for Directory Search, gcc, Using the
3533 GNU Compiler Collection (GCC)}, for further details. You would normally
3534 use the @option{-b} or @option{-V} switch instead.
3536 @item -c
3537 @cindex @option{-c} (@command{gcc})
3538 Compile. Always use this switch when compiling Ada programs.
3540 Note: for some other languages when using @command{gcc}, notably in
3541 the case of C and C++, it is possible to use
3542 use @command{gcc} without a @option{-c} switch to
3543 compile and link in one step. In the case of GNAT, you
3544 cannot use this approach, because the binder must be run
3545 and @command{gcc} cannot be used to run the GNAT binder.
3546 @end ifclear
3548 @item -fcallgraph-info@r{[}=su,da@r{]}
3549 @cindex @option{-fcallgraph-info} (@command{gcc})
3550 Makes the compiler output callgraph information for the program, on a
3551 per-file basis. The information is generated in the VCG format.  It can
3552 be decorated with additional, per-node and/or per-edge information, if a
3553 list of comma-separated markers is additionally specified. When the
3554 @var{su} marker is specified, the callgraph is decorated with stack usage information; it is equivalent to @option{-fstack-usage}. When the @var{da}
3555 marker is specified, the callgraph is decorated with information about
3556 dynamically allocated objects.
3558 @item -fdump-scos
3559 @cindex @option{-fdump-scos} (@command{gcc})
3560 Generates SCO (Source Coverage Obligation) information in the ALI file.
3561 This information is used by advanced coverage tools. See unit @file{SCOs}
3562 in the compiler sources for details in files @file{scos.ads} and
3563 @file{scos.adb}.
3565 @item -flto@r{[}=n@r{]}
3566 @cindex @option{-flto} (@command{gcc})
3567 Enables Link Time Optimization. This switch must be used in conjunction
3568 with the traditional @option{-Ox} switches and instructs the compiler to
3569 defer most optimizations until the link stage. The advantage of this
3570 approach is that the compiler can do a whole-program analysis and choose
3571 the best interprocedural optimization strategy based on a complete view
3572 of the program, instead of a fragmentary view with the usual approach.
3573 This can also speed up the compilation of huge programs and reduce the
3574 size of the final executable, compared with a per-unit compilation with
3575 full inlining across modules enabled with the @option{-gnatn2} switch.
3576 The drawback of this approach is that it may require much more memory.
3577 The switch, as well as the accompanying @option{-Ox} switches, must be
3578 specified both for the compilation and the link phases.
3579 If the @var{n} parameter is specified, the optimization and final code
3580 generation at link time are executed using @var{n} parallel jobs by
3581 means of an installed @command{make} program.
3583 @item -fno-inline
3584 @cindex @option{-fno-inline} (@command{gcc})
3585 Suppresses all inlining, even if other optimization or inlining
3586 switches are set.  This includes suppression of inlining that
3587 results from the use of the pragma @code{Inline_Always}.
3588 Any occurrences of pragma @code{Inline} or @code{Inline_Always}
3589 are ignored, and @option{-gnatn} and @option{-gnatN} have no
3590 effects if this switch is present.  Note that inlining can also
3591 be suppressed on a finer-grained basis with pragma @code{No_Inline}.
3593 @item -fno-inline-functions
3594 @cindex @option{-fno-inline-functions} (@command{gcc})
3595 Suppresses automatic inlining of subprograms, which is enabled
3596 if @option{-O3} is used.
3598 @item -fno-inline-small-functions
3599 @cindex @option{-fno-inline-small-functions} (@command{gcc})
3600 Suppresses automatic inlining of small subprograms, which is enabled
3601 if @option{-O2} is used.
3603 @item -fno-inline-functions-called-once
3604 @cindex @option{-fno-inline-functions-called-once} (@command{gcc})
3605 Suppresses inlining of subprograms local to the unit and called once
3606 from within it, which is enabled if @option{-O1} is used.
3608 @item -fno-ivopts
3609 @cindex @option{-fno-ivopts} (@command{gcc})
3610 Suppresses high-level loop induction variable optimizations, which are
3611 enabled if @option{-O1} is used. These optimizations are generally
3612 profitable but, for some specific cases of loops with numerous uses
3613 of the iteration variable that follow a common pattern, they may end
3614 up destroying the regularity that could be exploited at a lower level
3615 and thus producing inferior code.
3617 @item -fno-strict-aliasing
3618 @cindex @option{-fno-strict-aliasing} (@command{gcc})
3619 Causes the compiler to avoid assumptions regarding non-aliasing
3620 of objects of different types. See
3621 @ref{Optimization and Strict Aliasing} for details.
3623 @item -fstack-check
3624 @cindex @option{-fstack-check} (@command{gcc})
3625 Activates stack checking.
3626 See @ref{Stack Overflow Checking} for details.
3628 @item -fstack-usage
3629 @cindex @option{-fstack-usage} (@command{gcc})
3630 Makes the compiler output stack usage information for the program, on a
3631 per-subprogram basis. See @ref{Static Stack Usage Analysis} for details.
3633 @item ^-g^/DEBUG^
3634 @cindex @option{^-g^/DEBUG^} (@command{gcc})
3635 Generate debugging information. This information is stored in the object
3636 file and copied from there to the final executable file by the linker,
3637 where it can be read by the debugger. You must use the
3638 @option{^-g^/DEBUG^} switch if you plan on using the debugger.
3640 @item -gnat83
3641 @cindex @option{-gnat83} (@command{gcc})
3642 Enforce Ada 83 restrictions.
3644 @item -gnat95
3645 @cindex @option{-gnat95} (@command{gcc})
3646 Enforce Ada 95 restrictions.
3648 @item -gnat05
3649 @cindex @option{-gnat05} (@command{gcc})
3650 Allow full Ada 2005 features.
3652 @item -gnat2005
3653 @cindex @option{-gnat2005} (@command{gcc})
3654 Allow full Ada 2005 features (same as @option{-gnat05})
3656 @item -gnat12
3657 @cindex @option{-gnat12} (@command{gcc})
3659 @item -gnat2012
3660 @cindex @option{-gnat2012} (@command{gcc})
3661 Allow full Ada 2012 features (same as @option{-gnat12})
3663 @item -gnata
3664 @cindex @option{-gnata} (@command{gcc})
3665 Assertions enabled. @code{Pragma Assert} and @code{pragma Debug} to be
3666 activated. Note that these pragmas can also be controlled using the
3667 configuration pragmas @code{Assertion_Policy} and @code{Debug_Policy}.
3668 It also activates pragmas @code{Check}, @code{Precondition}, and
3669 @code{Postcondition}. Note that these pragmas can also be controlled
3670 using the configuration pragma @code{Check_Policy}. In Ada 2012, it
3671 also activates all assertions defined in the RM as aspects: preconditions,
3672 postconditions, type invariants and (sub)type predicates. In all Ada modes,
3673 corresponding pragmas for type invariants and (sub)type predicates are
3674 also activated.
3676 @item -gnatA
3677 @cindex @option{-gnatA} (@command{gcc})
3678 Avoid processing @file{gnat.adc}. If a @file{gnat.adc} file is present,
3679 it will be ignored.
3681 @item -gnatb
3682 @cindex @option{-gnatb} (@command{gcc})
3683 Generate brief messages to @file{stderr} even if verbose mode set.
3685 @item -gnatB
3686 @cindex @option{-gnatB} (@command{gcc})
3687 Assume no invalid (bad) values except for 'Valid attribute use
3688 (@pxref{Validity Checking}).
3690 @item -gnatc
3691 @cindex @option{-gnatc} (@command{gcc})
3692 Check syntax and semantics only (no code generation attempted). When the
3693 compiler is invoked by @command{gnatmake}, if the switch @option{-gnatc} is
3694 only given to the compiler (after @option{-cargs} or in package Compiler of
3695 the project file, @command{gnatmake} will fail because it will not find the
3696 object file after compilation. If @command{gnatmake} is called with
3697 @option{-gnatc} as a builder switch (before @option{-cargs} or in package
3698 Builder of the project file) then @command{gnatmake} will not fail because
3699 it will not look for the object files after compilation, and it will not try
3700 to build and link.
3702 @item -gnatC
3703 @cindex @option{-gnatC} (@command{gcc})
3704 Generate CodePeer information (no code generation attempted).
3705 This switch will generate an intermediate representation suitable for
3706 use by CodePeer (@file{.scil} files). This switch is not compatible with
3707 code generation (it will, among other things, disable some switches such
3708 as -gnatn, and enable others such as -gnata).
3710 @item -gnatd
3711 @cindex @option{-gnatd} (@command{gcc})
3712 Specify debug options for the compiler. The string of characters after
3713 the @option{-gnatd} specify the specific debug options. The possible
3714 characters are 0-9, a-z, A-Z, optionally preceded by a dot. See
3715 compiler source file @file{debug.adb} for details of the implemented
3716 debug options. Certain debug options are relevant to applications
3717 programmers, and these are documented at appropriate points in this
3718 users guide.
3720 @ifclear vms
3721 @item -gnatD
3722 @cindex @option{-gnatD[nn]} (@command{gcc})
3723 @end ifclear
3724 @ifset vms
3725 @item /XDEBUG /LXDEBUG=nnn
3726 @end ifset
3727 Create expanded source files for source level debugging. This switch
3728 also suppress generation of cross-reference information
3729 (see @option{-gnatx}). Note that this switch is not allowed if a previous
3730 -gnatR switch has been given, since these two switches are not compatible.
3732 @item ^-gnateA^/ALIASING_CHECK^
3733 @cindex @option{-gnateA} (@command{gcc})
3734 Check that there is no aliasing between two parameters of the same subprogram.
3736 @item -gnatec=@var{path}
3737 @cindex @option{-gnatec} (@command{gcc})
3738 Specify a configuration pragma file
3739 @ifclear vms
3740 (the equal sign is optional)
3741 @end ifclear
3742 (@pxref{The Configuration Pragmas Files}).
3744 @item ^-gnated^/DISABLE_ATOMIC_SYNCHRONIZATION^
3745 @cindex @option{-gnated} (@command{gcc})
3746 Disable atomic synchronization
3748 @item ^-gnateD^/DATA_PREPROCESSING=^symbol@r{[}=@var{value}@r{]}
3749 @cindex @option{-gnateD} (@command{gcc})
3750 Defines a symbol, associated with @var{value}, for preprocessing.
3751 (@pxref{Integrated Preprocessing}).
3753 @item -gnateE
3754 @cindex @option{-gnateE} (@command{gcc})
3755 Generate extra information in exception messages. In particular, display
3756 extra column information and the value and range associated with index and
3757 range check failures, and extra column information for access checks.
3758 In cases where the compiler is able to determine at compile time that
3759 a check will fail, it gives a warning, and the extra information is not
3760 produced at run time.
3762 @item -gnatef
3763 @cindex @option{-gnatef} (@command{gcc})
3764 Display full source path name in brief error messages.
3766 @item -gnateF
3767 @cindex @option{-gnateF} (@command{gcc})
3768 Check for overflow on all floating-point operations, including those
3769 for unconstrained predefined types. See description of pragma
3770 @code{Check_Float_Overflow} in GNAT RM.
3772 @item -gnateG
3773 @cindex @option{-gnateG} (@command{gcc})
3774 Save result of preprocessing in a text file.
3776 @item -gnatei@var{nnn}
3777 @cindex @option{-gnatei} (@command{gcc})
3778 Set maximum number of instantiations during compilation of a single unit to
3779 @var{nnn}. This may be useful in increasing the default maximum of 8000 for
3780 the rare case when a single unit legitimately exceeds this limit.
3782 @item -gnateI@var{nnn}
3783 @cindex @option{-gnateI} (@command{gcc})
3784 Indicates that the source is a multi-unit source and that the index of the
3785 unit to compile is @var{nnn}. @var{nnn} needs to be a positive number and need
3786 to be a valid index in the multi-unit source.
3788 @item -gnatem=@var{path}
3789 @cindex @option{-gnatem} (@command{gcc})
3790 Specify a mapping file
3791 @ifclear vms
3792 (the equal sign is optional)
3793 @end ifclear
3794 (@pxref{Units to Sources Mapping Files}).
3796 @item -gnatep=@var{file}
3797 @cindex @option{-gnatep} (@command{gcc})
3798 Specify a preprocessing data file
3799 @ifclear vms
3800 (the equal sign is optional)
3801 @end ifclear
3802 (@pxref{Integrated Preprocessing}).
3804 @item -gnateP
3805 @cindex @option{-gnateP} (@command{gcc})
3806 Turn categorization dependency errors into warnings.
3807 Ada requires that units that WITH one another have compatible categories, for
3808 example a Pure unit cannot WITH a Preelaborate unit. If this switch is used,
3809 these errors become warnings (which can be ignored, or suppressed in the usual
3810 manner). This can be useful in some specialized circumstances such as the
3811 temporary use of special test software.
3813 @item -gnateS
3814 @cindex @option{-gnateS} (@command{gcc})
3815 Synonym of @option{-fdump-scos}, kept for backards compatibility.
3817 @item ^-gnatet^/TARGET_DEPENDENT_INFO^
3818 @cindex @option{-gnatet} (@command{gcc})
3819 Generate target dependent information.
3821 @item ^-gnateV^/PARAMETER_VALIDITY_CHECK^
3822 @cindex @option{-gnateV} (@command{gcc})
3823 Check validity of subprogram parameters.
3825 @item ^-gnateY^/IGNORE_SUPPRESS_SYLE_CHECK_PRAGMAS^
3826 @cindex @option{-gnateY} (@command{gcc})
3827 Ignore all STYLE_CHECKS pragmas. Full legality checks
3828 are still carried out, but the pragmas have no effect
3829 on what style checks are active. This allows all style
3830 checking options to be controlled from the command line.
3832 @item -gnatE
3833 @cindex @option{-gnatE} (@command{gcc})
3834 Full dynamic elaboration checks.
3836 @item -gnatf
3837 @cindex @option{-gnatf} (@command{gcc})
3838 Full errors. Multiple errors per line, all undefined references, do not
3839 attempt to suppress cascaded errors.
3841 @item -gnatF
3842 @cindex @option{-gnatF} (@command{gcc})
3843 Externals names are folded to all uppercase.
3845 @item ^-gnatg^/GNAT_INTERNAL^
3846 @cindex @option{^-gnatg^/GNAT_INTERNAL^} (@command{gcc})
3847 Internal GNAT implementation mode. This should not be used for
3848 applications programs, it is intended only for use by the compiler
3849 and its run-time library. For documentation, see the GNAT sources.
3850 Note that @option{^-gnatg^/GNAT_INTERNAL^} implies
3851 @option{^-gnatwae^/WARNINGS=ALL,ERRORS^} and
3852 @option{^-gnatyg^/STYLE_CHECKS=GNAT^}
3853 so that all standard warnings and all standard style options are turned on.
3854 All warnings and style messages are treated as errors.
3856 @ifclear vms
3857 @item -gnatG=nn
3858 @cindex @option{-gnatG[nn]} (@command{gcc})
3859 @end ifclear
3860 @ifset vms
3861 @item /EXPAND_SOURCE, /LEXPAND_SOURCE=nnn
3862 @end ifset
3863 List generated expanded code in source form.
3865 @item ^-gnath^/HELP^
3866 @cindex @option{^-gnath^/HELP^} (@command{gcc})
3867 Output usage information. The output is written to @file{stdout}.
3869 @item ^-gnati^/IDENTIFIER_CHARACTER_SET=^@var{c}
3870 @cindex @option{^-gnati^/IDENTIFIER_CHARACTER_SET^} (@command{gcc})
3871 Identifier character set
3872 @ifclear vms
3873 (@var{c}=1/2/3/4/8/9/p/f/n/w).
3874 @end ifclear
3875 For details of the possible selections for @var{c},
3876 see @ref{Character Set Control}.
3878 @item ^-gnatI^/IGNORE_REP_CLAUSES^
3879 @cindex @option{^-gnatI^IGNORE_REP_CLAUSES^} (@command{gcc})
3880 Ignore representation clauses. When this switch is used,
3881 representation clauses are treated as comments. This is useful
3882 when initially porting code where you want to ignore rep clause
3883 problems, and also for compiling foreign code (particularly
3884 for use with ASIS). The representation clauses that are ignored
3885 are: enumeration_representation_clause, record_representation_clause,
3886 and attribute_definition_clause for the following attributes:
3887 Address, Alignment, Bit_Order, Component_Size, Machine_Radix,
3888 Object_Size, Size, Small, Stream_Size, and Value_Size.
3889 Note that this option should be used only for compiling -- the
3890 code is likely to malfunction at run time.
3892 @item -gnatjnn
3893 @cindex @option{-gnatjnn} (@command{gcc})
3894 Reformat error messages to fit on nn character lines
3896 @item -gnatk=@var{n}
3897 @cindex @option{-gnatk} (@command{gcc})
3898 Limit file names to @var{n} (1-999) characters ^(@code{k} = krunch)^^.
3900 @item -gnatl
3901 @cindex @option{-gnatl} (@command{gcc})
3902 Output full source listing with embedded error messages.
3904 @item -gnatL
3905 @cindex @option{-gnatL} (@command{gcc})
3906 Used in conjunction with -gnatG or -gnatD to intersperse original
3907 source lines (as comment lines with line numbers) in the expanded
3908 source output.
3910 @item -gnatm=@var{n}
3911 @cindex @option{-gnatm} (@command{gcc})
3912 Limit number of detected error or warning messages to @var{n}
3913 where @var{n} is in the range 1..999999. The default setting if
3914 no switch is given is 9999. If the number of warnings reaches this
3915 limit, then a message is output and further warnings are suppressed,
3916 but the compilation is continued. If the number of error messages
3917 reaches this limit, then a message is output and the compilation
3918 is abandoned. The equal sign here is optional. A value of zero
3919 means that no limit applies.
3921 @item -gnatn[12]
3922 @cindex @option{-gnatn} (@command{gcc})
3923 Activate inlining for subprograms for which pragma @code{Inline} is
3924 specified. This inlining is performed by the GCC back-end. An optional
3925 digit sets the inlining level: 1 for moderate inlining across modules
3926 or 2 for full inlining across modules. If no inlining level is specified,
3927 the compiler will pick it based on the optimization level.
3929 @item -gnatN
3930 @cindex @option{-gnatN} (@command{gcc})
3931 Activate front end inlining for subprograms for which
3932 pragma @code{Inline} is specified. This inlining is performed
3933 by the front end and will be visible in the
3934 @option{-gnatG} output.
3936 When using a gcc-based back end (in practice this means using any version
3937 of GNAT other than the JGNAT, .NET or GNAAMP versions), then the use of
3938 @option{-gnatN} is deprecated, and the use of @option{-gnatn} is preferred.
3939 Historically front end inlining was more extensive than the gcc back end
3940 inlining, but that is no longer the case.
3942 @item -gnato??
3943 @cindex @option{-gnato??} (@command{gcc})
3944 Set default mode for handling generation of code to avoid intermediate
3945 arithmetic overflow. Here `@code{??}' is two digits, a
3946 single digit, or nothing. Each digit is one of the digits `@code{1}'
3947 through `@code{3}':
3949 @itemize @bullet
3950 @item   @code{1}:
3951 all intermediate overflows checked against base type (@code{STRICT})
3952 @item   @code{2}:
3953 minimize intermediate overflows (@code{MINIMIZED})
3954 @item   @code{3}:
3955 eliminate intermediate overflows (@code{ELIMINATED})
3956 @end itemize
3958 If only one digit appears then it applies to all
3959 cases; if two digits are given, then the first applies outside
3960 assertions, and the second within assertions.
3962 If no digits follow the @option{-gnato}, then it is equivalent to
3963 @option{^-gnato11^/OVERFLOW_CHECKS=11^},
3964 causing all intermediate overflows to be handled in strict mode.
3966 This switch also causes arithmetic overflow checking to be performed
3967 (as though pragma @code{Unsuppress (Overflow_Mode)} has been specified.
3969 The default if no option @option{-gnato} is given is that overflow handling
3970 is in @code{STRICT} mode (computations done using the base type), and that
3971 overflow checking is suppressed.
3973 Note that division by zero is a separate check that is not
3974 controlled by this switch (division by zero checking is on by default).
3976 See also @ref{Specifying the Desired Mode}.
3978 @item -gnatp
3979 @cindex @option{-gnatp} (@command{gcc})
3980 Suppress all checks. See @ref{Run-Time Checks} for details. This switch
3981 has no effect if cancelled by a subsequent @option{-gnat-p} switch.
3983 @item -gnat-p
3984 @cindex @option{-gnat-p} (@command{gcc})
3985 Cancel effect of previous @option{-gnatp} switch.
3987 @item -gnatP
3988 @cindex @option{-gnatP} (@command{gcc})
3989 Enable polling. This is required on some systems (notably Windows NT) to
3990 obtain asynchronous abort and asynchronous transfer of control capability.
3991 @xref{Pragma Polling,,, gnat_rm, GNAT Reference Manual}, for full
3992 details.
3994 @item -gnatq
3995 @cindex @option{-gnatq} (@command{gcc})
3996 Don't quit. Try semantics, even if parse errors.
3998 @item -gnatQ
3999 @cindex @option{-gnatQ} (@command{gcc})
4000 Don't quit. Generate @file{ALI} and tree files even if illegalities.
4002 @item -gnatr
4003 @cindex @option{-gnatr} (@command{gcc})
4004 Treat pragma Restrictions as Restriction_Warnings.
4006 @item ^-gnatR@r{[}0@r{/}1@r{/}2@r{/}3@r{[}s@r{]]}^/REPRESENTATION_INFO^
4007 @cindex @option{-gnatR} (@command{gcc})
4008 Output representation information for declared types and objects.
4009 Note that this switch is not allowed if a previous
4010 -gnatD switch has been given, since these two switches are not compatible.
4012 @item -gnats
4013 @cindex @option{-gnats} (@command{gcc})
4014 Syntax check only.
4016 @item -gnatS
4017 @cindex @option{-gnatS} (@command{gcc})
4018 Print package Standard.
4020 @item -gnatt
4021 @cindex @option{-gnatt} (@command{gcc})
4022 Generate tree output file.
4024 @item ^-gnatT^/TABLE_MULTIPLIER=^@var{nnn}
4025 @cindex @option{^-gnatT^/TABLE_MULTIPLIER^} (@command{gcc})
4026 All compiler tables start at @var{nnn} times usual starting size.
4028 @item -gnatu
4029 @cindex @option{-gnatu} (@command{gcc})
4030 List units for this compilation.
4032 @item -gnatU
4033 @cindex @option{-gnatU} (@command{gcc})
4034 Tag all error messages with the unique string ``error:''
4036 @item -gnatv
4037 @cindex @option{-gnatv} (@command{gcc})
4038 Verbose mode. Full error output with source lines to @file{stdout}.
4040 @item -gnatV
4041 @cindex @option{-gnatV} (@command{gcc})
4042 Control level of validity checking (@pxref{Validity Checking}).
4044 @item ^-gnatw@var{xxx}^/WARNINGS=(@var{option}@r{[},@dots{}@r{]})^
4045 @cindex @option{^-gnatw^/WARNINGS^} (@command{gcc})
4046 Warning mode where
4047 ^@var{xxx} is a string of option letters that^the list of options^ denotes
4048 the exact warnings that
4049 are enabled or disabled (@pxref{Warning Message Control}).
4051 @item ^-gnatW^/WIDE_CHARACTER_ENCODING=^@var{e}
4052 @cindex @option{^-gnatW^/WIDE_CHARACTER_ENCODING^} (@command{gcc})
4053 Wide character encoding method
4054 @ifclear vms
4055 (@var{e}=n/h/u/s/e/8).
4056 @end ifclear
4057 @ifset vms
4058 (@var{e}=@code{BRACKETS, NONE, HEX, UPPER, SHIFT_JIS, EUC, UTF8})
4059 @end ifset
4061 @item -gnatx
4062 @cindex @option{-gnatx} (@command{gcc})
4063 Suppress generation of cross-reference information.
4065 @item -gnatX
4066 @cindex @option{-gnatX} (@command{gcc})
4067 Enable GNAT implementation extensions and latest Ada version.
4069 @item ^-gnaty^/STYLE_CHECKS=(option,option@dots{})^
4070 @cindex @option{^-gnaty^/STYLE_CHECKS^} (@command{gcc})
4071 Enable built-in style checks (@pxref{Style Checking}).
4073 @item ^-gnatz^/DISTRIBUTION_STUBS=^@var{m}
4074 @cindex @option{^-gnatz^/DISTRIBUTION_STUBS^} (@command{gcc})
4075 Distribution stub generation and compilation
4076 @ifclear vms
4077 (@var{m}=r/c for receiver/caller stubs).
4078 @end ifclear
4079 @ifset vms
4080 (@var{m}=@code{RECEIVER} or @code{CALLER} to specify the type of stubs
4081 to be generated and compiled).
4082 @end ifset
4084 @item ^-I^/SEARCH=^@var{dir}
4085 @cindex @option{^-I^/SEARCH^} (@command{gcc})
4086 @cindex RTL
4087 Direct GNAT to search the @var{dir} directory for source files needed by
4088 the current compilation
4089 (@pxref{Search Paths and the Run-Time Library (RTL)}).
4091 @item ^-I-^/NOCURRENT_DIRECTORY^
4092 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gcc})
4093 @cindex RTL
4094 Except for the source file named in the command line, do not look for source
4095 files in the directory containing the source file named in the command line
4096 (@pxref{Search Paths and the Run-Time Library (RTL)}).
4098 @ifclear vms
4099 @item -mbig-switch
4100 @cindex @option{-mbig-switch} (@command{gcc})
4101 @cindex @code{case} statement (effect of @option{-mbig-switch} option)
4102 This standard gcc switch causes the compiler to use larger offsets in its
4103 jump table representation for @code{case} statements.
4104 This may result in less efficient code, but is sometimes necessary
4105 (for example on HP-UX targets)
4106 @cindex HP-UX and @option{-mbig-switch} option
4107 in order to compile large and/or nested @code{case} statements.
4109 @item -o @var{file}
4110 @cindex @option{-o} (@command{gcc})
4111 This switch is used in @command{gcc} to redirect the generated object file
4112 and its associated ALI file. Beware of this switch with GNAT, because it may
4113 cause the object file and ALI file to have different names which in turn
4114 may confuse the binder and the linker.
4115 @end ifclear
4117 @item -nostdinc
4118 @cindex @option{-nostdinc} (@command{gcc})
4119 Inhibit the search of the default location for the GNAT Run Time
4120 Library (RTL) source files.
4122 @item -nostdlib
4123 @cindex @option{-nostdlib} (@command{gcc})
4124 Inhibit the search of the default location for the GNAT Run Time
4125 Library (RTL) ALI files.
4127 @ifclear vms
4128 @c @item -O@ovar{n}
4129 @c Expanding @ovar macro inline (explanation in macro def comments)
4130 @item -O@r{[}@var{n}@r{]}
4131 @cindex @option{-O} (@command{gcc})
4132 @var{n} controls the optimization level.
4134 @table @asis
4135 @item n = 0
4136 No optimization, the default setting if no @option{-O} appears
4138 @item n = 1
4139 Normal optimization, the default if you specify @option{-O} without
4140 an operand. A good compromise between code quality and compilation
4141 time.
4143 @item n = 2
4144 Extensive optimization, may improve execution time, possibly at the cost of
4145 substantially increased compilation time.
4147 @item n = 3
4148 Same as @option{-O2}, and also includes inline expansion for small subprograms
4149 in the same unit.
4151 @item n = s
4152 Optimize space usage
4153 @end table
4155 @noindent
4156 See also @ref{Optimization Levels}.
4157 @end ifclear
4159 @ifset vms
4160 @item  /NOOPTIMIZE
4161 @cindex @option{/NOOPTIMIZE} (@code{GNAT COMPILE})
4162 Equivalent to @option{/OPTIMIZE=NONE}.
4163 This is the default behavior in the absence of an @option{/OPTIMIZE}
4164 qualifier.
4166 @item /OPTIMIZE@r{[}=(keyword@r{[},@dots{}@r{]})@r{]}
4167 @cindex @option{/OPTIMIZE} (@code{GNAT COMPILE})
4168 Selects the level of optimization for your program. The supported
4169 keywords are as follows:
4170 @table @code
4171 @item   ALL
4172 Perform most optimizations, including those that
4173 are expensive.
4174 This is the default if the @option{/OPTIMIZE} qualifier is supplied
4175 without keyword options.
4177 @item   NONE
4178 Do not do any optimizations. Same as @code{/NOOPTIMIZE}.
4180 @item SOME
4181 Perform some optimizations, but omit ones that are costly.
4183 @item   DEVELOPMENT
4184 Same as @code{SOME}.
4186 @item INLINING
4187 Full optimization as in @option{/OPTIMIZE=ALL}, and also attempts
4188 automatic inlining of small subprograms within a unit
4190 @item   UNROLL_LOOPS
4191 Try to unroll loops. This keyword may be specified together with
4192 any keyword above other than @code{NONE}. Loop unrolling
4193 usually, but not always, improves the performance of programs.
4195 @item SPACE
4196 Optimize space usage
4197 @end table
4199 @noindent
4200 See also @ref{Optimization Levels}.
4201 @end ifset
4203 @ifclear vms
4204 @item -pass-exit-codes
4205 @cindex @option{-pass-exit-codes} (@command{gcc})
4206 Catch exit codes from the compiler and use the most meaningful as
4207 exit status.
4208 @end ifclear
4210 @item --RTS=@var{rts-path}
4211 @cindex @option{--RTS} (@command{gcc})
4212 Specifies the default location of the runtime library. Same meaning as the
4213 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
4215 @item ^-S^/ASM^
4216 @cindex @option{^-S^/ASM^} (@command{gcc})
4217 ^Used in place of @option{-c} to^Used to^
4218 cause the assembler source file to be
4219 generated, using @file{^.s^.S^} as the extension,
4220 instead of the object file.
4221 This may be useful if you need to examine the generated assembly code.
4223 @item ^-fverbose-asm^/VERBOSE_ASM^
4224 @cindex @option{^-fverbose-asm^/VERBOSE_ASM^} (@command{gcc})
4225 ^Used in conjunction with @option{-S}^Used in place of @option{/ASM}^
4226 to cause the generated assembly code file to be annotated with variable
4227 names, making it significantly easier to follow.
4229 @item ^-v^/VERBOSE^
4230 @cindex @option{^-v^/VERBOSE^} (@command{gcc})
4231 Show commands generated by the @command{gcc} driver. Normally used only for
4232 debugging purposes or if you need to be sure what version of the
4233 compiler you are executing.
4235 @ifclear vms
4236 @item -V @var{ver}
4237 @cindex @option{-V} (@command{gcc})
4238 Execute @var{ver} version of the compiler. This is the @command{gcc}
4239 version, not the GNAT version.
4240 @end ifclear
4242 @item ^-w^/NO_BACK_END_WARNINGS^
4243 @cindex @option{-w} (@command{gcc})
4244 Turn off warnings generated by the back end of the compiler. Use of
4245 this switch also causes the default for front end warnings to be set
4246 to suppress (as though @option{-gnatws} had appeared at the start of
4247 the options).
4249 @end table
4251 @ifclear vms
4252 @c Combining qualifiers does not work on VMS
4253 You may combine a sequence of GNAT switches into a single switch. For
4254 example, the combined switch
4256 @cindex Combining GNAT switches
4257 @smallexample
4258 -gnatofi3
4259 @end smallexample
4261 @noindent
4262 is equivalent to specifying the following sequence of switches:
4264 @smallexample
4265 -gnato -gnatf -gnati3
4266 @end smallexample
4267 @end ifclear
4269 @noindent
4270 The following restrictions apply to the combination of switches
4271 in this manner:
4273 @itemize @bullet
4274 @item
4275 The switch @option{-gnatc} if combined with other switches must come
4276 first in the string.
4278 @item
4279 The switch @option{-gnats} if combined with other switches must come
4280 first in the string.
4282 @item
4283 The switches
4284 ^^@option{/DISTRIBUTION_STUBS=},^
4285 @option{-gnatzc} and @option{-gnatzr} may not be combined with any other
4286 switches, and only one of them may appear in the command line.
4288 @item
4289 The switch @option{-gnat-p} may not be combined with any other switch.
4291 @ifclear vms
4292 @item
4293 Once a ``y'' appears in the string (that is a use of the @option{-gnaty}
4294 switch), then all further characters in the switch are interpreted
4295 as style modifiers (see description of @option{-gnaty}).
4297 @item
4298 Once a ``d'' appears in the string (that is a use of the @option{-gnatd}
4299 switch), then all further characters in the switch are interpreted
4300 as debug flags (see description of @option{-gnatd}).
4302 @item
4303 Once a ``w'' appears in the string (that is a use of the @option{-gnatw}
4304 switch), then all further characters in the switch are interpreted
4305 as warning mode modifiers (see description of @option{-gnatw}).
4307 @item
4308 Once a ``V'' appears in the string (that is a use of the @option{-gnatV}
4309 switch), then all further characters in the switch are interpreted
4310 as validity checking options (@pxref{Validity Checking}).
4312 @item
4313 Option ``em'', ``ec'', ``ep'', ``l='' and ``R'' must be the last options in
4314 a combined list of options.
4315 @end ifclear
4316 @end itemize
4318 @node Output and Error Message Control
4319 @subsection Output and Error Message Control
4320 @findex stderr
4322 @noindent
4323 The standard default format for error messages is called ``brief format''.
4324 Brief format messages are written to @file{stderr} (the standard error
4325 file) and have the following form:
4327 @smallexample
4328 e.adb:3:04: Incorrect spelling of keyword "function"
4329 e.adb:4:20: ";" should be "is"
4330 @end smallexample
4332 @noindent
4333 The first integer after the file name is the line number in the file,
4334 and the second integer is the column number within the line.
4335 @ifclear vms
4336 @code{GPS} can parse the error messages
4337 and point to the referenced character.
4338 @end ifclear
4339 The following switches provide control over the error message
4340 format:
4342 @table @option
4343 @c !sort!
4344 @item -gnatv
4345 @cindex @option{-gnatv} (@command{gcc})
4346 @findex stdout
4347 @ifclear vms
4348 The v stands for verbose.
4349 @end ifclear
4350 The effect of this setting is to write long-format error
4351 messages to @file{stdout} (the standard output file.
4352 The same program compiled with the
4353 @option{-gnatv} switch would generate:
4355 @smallexample
4356 @cartouche
4357 3. funcion X (Q : Integer)
4358    |
4359 >>> Incorrect spelling of keyword "function"
4360 4. return Integer;
4361                  |
4362 >>> ";" should be "is"
4363 @end cartouche
4364 @end smallexample
4366 @noindent
4367 The vertical bar indicates the location of the error, and the @samp{>>>}
4368 prefix can be used to search for error messages. When this switch is
4369 used the only source lines output are those with errors.
4371 @item -gnatl
4372 @cindex @option{-gnatl} (@command{gcc})
4373 @ifclear vms
4374 The @code{l} stands for list.
4375 @end ifclear
4376 This switch causes a full listing of
4377 the file to be generated. In the case where a body is
4378 compiled, the corresponding spec is also listed, along
4379 with any subunits. Typical output from compiling a package
4380 body @file{p.adb} might look like:
4382 @smallexample @c ada
4383 @cartouche
4384  Compiling: p.adb
4386      1. package body p is
4387      2.    procedure a;
4388      3.    procedure a is separate;
4389      4. begin
4390      5.    null
4391                |
4392         >>> missing ";"
4394      6. end;
4396 Compiling: p.ads
4398      1. package p is
4399      2.    pragma Elaborate_Body
4400                                 |
4401         >>> missing ";"
4403      3. end p;
4405 Compiling: p-a.adb
4407      1. separate p
4408                 |
4409         >>> missing "("
4411      2. procedure a is
4412      3. begin
4413      4.    null
4414                |
4415         >>> missing ";"
4417      5. end;
4418 @end cartouche
4419 @end smallexample
4421 @noindent
4422 @findex stderr
4423 When you specify the @option{-gnatv} or @option{-gnatl} switches and
4424 standard output is redirected, a brief summary is written to
4425 @file{stderr} (standard error) giving the number of error messages and
4426 warning messages generated.
4428 @item ^-gnatl^/OUTPUT_FILE^=file
4429 @cindex @option{^-gnatl^/OUTPUT_FILE^=fname} (@command{gcc})
4430 This has the same effect as @option{-gnatl} except that the output is
4431 written to a file instead of to standard output. If the given name
4432 @file{fname} does not start with a period, then it is the full name
4433 of the file to be written. If @file{fname} is an extension, it is
4434 appended to the name of the file being compiled. For example, if
4435 file @file{xyz.adb} is compiled with @option{^-gnatl^/OUTPUT_FILE^=.lst},
4436 then the output is written to file ^xyz.adb.lst^xyz.adb_lst^.
4438 @item -gnatU
4439 @cindex @option{-gnatU} (@command{gcc})
4440 This switch forces all error messages to be preceded by the unique
4441 string ``error:''. This means that error messages take a few more
4442 characters in space, but allows easy searching for and identification
4443 of error messages.
4445 @item -gnatb
4446 @cindex @option{-gnatb} (@command{gcc})
4447 @ifclear vms
4448 The @code{b} stands for brief.
4449 @end ifclear
4450 This switch causes GNAT to generate the
4451 brief format error messages to @file{stderr} (the standard error
4452 file) as well as the verbose
4453 format message or full listing (which as usual is written to
4454 @file{stdout} (the standard output file).
4456 @item -gnatm=@var{n}
4457 @cindex @option{-gnatm} (@command{gcc})
4458 @ifclear vms
4459 The @code{m} stands for maximum.
4460 @end ifclear
4461 @var{n} is a decimal integer in the
4462 range of 1 to 999999 and limits the number of error or warning
4463 messages to be generated. For example, using
4464 @option{-gnatm2} might yield
4466 @smallexample
4467 e.adb:3:04: Incorrect spelling of keyword "function"
4468 e.adb:5:35: missing ".."
4469 fatal error: maximum number of errors detected
4470 compilation abandoned
4471 @end smallexample
4473 @noindent
4474 The default setting if
4475 no switch is given is 9999. If the number of warnings reaches this
4476 limit, then a message is output and further warnings are suppressed,
4477 but the compilation is continued. If the number of error messages
4478 reaches this limit, then a message is output and the compilation
4479 is abandoned. A value of zero means that no limit applies.
4481 @noindent
4482 Note that the equal sign is optional, so the switches
4483 @option{-gnatm2} and @option{-gnatm=2} are equivalent.
4485 @item -gnatf
4486 @cindex @option{-gnatf} (@command{gcc})
4487 @cindex Error messages, suppressing
4488 @ifclear vms
4489 The @code{f} stands for full.
4490 @end ifclear
4491 Normally, the compiler suppresses error messages that are likely to be
4492 redundant. This switch causes all error
4493 messages to be generated. In particular, in the case of
4494 references to undefined variables. If a given variable is referenced
4495 several times, the normal format of messages is
4496 @smallexample
4497 e.adb:7:07: "V" is undefined (more references follow)
4498 @end smallexample
4500 @noindent
4501 where the parenthetical comment warns that there are additional
4502 references to the variable @code{V}. Compiling the same program with the
4503 @option{-gnatf} switch yields
4505 @smallexample
4506 e.adb:7:07: "V" is undefined
4507 e.adb:8:07: "V" is undefined
4508 e.adb:8:12: "V" is undefined
4509 e.adb:8:16: "V" is undefined
4510 e.adb:9:07: "V" is undefined
4511 e.adb:9:12: "V" is undefined
4512 @end smallexample
4514 @noindent
4515 The @option{-gnatf} switch also generates additional information for
4516 some error messages.  Some examples are:
4518 @itemize @bullet
4519 @item
4520 Details on possibly non-portable unchecked conversion
4521 @item
4522 List possible interpretations for ambiguous calls
4523 @item
4524 Additional details on incorrect parameters
4525 @end itemize
4527 @item -gnatjnn
4528 @cindex @option{-gnatjnn} (@command{gcc})
4529 In normal operation mode (or if @option{-gnatj0} is used), then error messages
4530 with continuation lines are treated as though the continuation lines were
4531 separate messages (and so a warning with two continuation lines counts as
4532 three warnings, and is listed as three separate messages).
4534 If the @option{-gnatjnn} switch is used with a positive value for nn, then
4535 messages are output in a different manner. A message and all its continuation
4536 lines are treated as a unit, and count as only one warning or message in the
4537 statistics totals. Furthermore, the message is reformatted so that no line
4538 is longer than nn characters.
4540 @item -gnatq
4541 @cindex @option{-gnatq} (@command{gcc})
4542 @ifclear vms
4543 The @code{q} stands for quit (really ``don't quit'').
4544 @end ifclear
4545 In normal operation mode, the compiler first parses the program and
4546 determines if there are any syntax errors. If there are, appropriate
4547 error messages are generated and compilation is immediately terminated.
4548 This switch tells
4549 GNAT to continue with semantic analysis even if syntax errors have been
4550 found. This may enable the detection of more errors in a single run. On
4551 the other hand, the semantic analyzer is more likely to encounter some
4552 internal fatal error when given a syntactically invalid tree.
4554 @item -gnatQ
4555 @cindex @option{-gnatQ} (@command{gcc})
4556 In normal operation mode, the @file{ALI} file is not generated if any
4557 illegalities are detected in the program. The use of @option{-gnatQ} forces
4558 generation of the @file{ALI} file. This file is marked as being in
4559 error, so it cannot be used for binding purposes, but it does contain
4560 reasonably complete cross-reference information, and thus may be useful
4561 for use by tools (e.g., semantic browsing tools or integrated development
4562 environments) that are driven from the @file{ALI} file. This switch
4563 implies @option{-gnatq}, since the semantic phase must be run to get a
4564 meaningful ALI file.
4566 In addition, if @option{-gnatt} is also specified, then the tree file is
4567 generated even if there are illegalities. It may be useful in this case
4568 to also specify @option{-gnatq} to ensure that full semantic processing
4569 occurs. The resulting tree file can be processed by ASIS, for the purpose
4570 of providing partial information about illegal units, but if the error
4571 causes the tree to be badly malformed, then ASIS may crash during the
4572 analysis.
4574 When @option{-gnatQ} is used and the generated @file{ALI} file is marked as
4575 being in error, @command{gnatmake} will attempt to recompile the source when it
4576 finds such an @file{ALI} file, including with switch @option{-gnatc}.
4578 Note that @option{-gnatQ} has no effect if @option{-gnats} is specified,
4579 since ALI files are never generated if @option{-gnats} is set.
4581 @end table
4583 @node Warning Message Control
4584 @subsection Warning Message Control
4585 @cindex Warning messages
4586 @noindent
4587 In addition to error messages, which correspond to illegalities as defined
4588 in the Ada Reference Manual, the compiler detects two kinds of warning
4589 situations.
4591 First, the compiler considers some constructs suspicious and generates a
4592 warning message to alert you to a possible error. Second, if the
4593 compiler detects a situation that is sure to raise an exception at
4594 run time, it generates a warning message. The following shows an example
4595 of warning messages:
4596 @smallexample
4597 e.adb:4:24: warning: creation of object may raise Storage_Error
4598 e.adb:10:17: warning: static value out of range
4599 e.adb:10:17: warning: "Constraint_Error" will be raised at run time
4600 @end smallexample
4602 @noindent
4603 GNAT considers a large number of situations as appropriate
4604 for the generation of warning messages. As always, warnings are not
4605 definite indications of errors. For example, if you do an out-of-range
4606 assignment with the deliberate intention of raising a
4607 @code{Constraint_Error} exception, then the warning that may be
4608 issued does not indicate an error. Some of the situations for which GNAT
4609 issues warnings (at least some of the time) are given in the following
4610 list. This list is not complete, and new warnings are often added to
4611 subsequent versions of GNAT. The list is intended to give a general idea
4612 of the kinds of warnings that are generated.
4614 @itemize @bullet
4615 @item
4616 Possible infinitely recursive calls
4618 @item
4619 Out-of-range values being assigned
4621 @item
4622 Possible order of elaboration problems
4624 @item
4625 Assertions (pragma Assert) that are sure to fail
4627 @item
4628 Unreachable code
4630 @item
4631 Address clauses with possibly unaligned values, or where an attempt is
4632 made to overlay a smaller variable with a larger one.
4634 @item
4635 Fixed-point type declarations with a null range
4637 @item
4638 Direct_IO or Sequential_IO instantiated with a type that has access values
4640 @item
4641 Variables that are never assigned a value
4643 @item
4644 Variables that are referenced before being initialized
4646 @item
4647 Task entries with no corresponding @code{accept} statement
4649 @item
4650 Duplicate accepts for the same task entry in a @code{select}
4652 @item
4653 Objects that take too much storage
4655 @item
4656 Unchecked conversion between types of differing sizes
4658 @item
4659 Missing @code{return} statement along some execution path in a function
4661 @item
4662 Incorrect (unrecognized) pragmas
4664 @item
4665 Incorrect external names
4667 @item
4668 Allocation from empty storage pool
4670 @item
4671 Potentially blocking operation in protected type
4673 @item
4674 Suspicious parenthesization of expressions
4676 @item
4677 Mismatching bounds in an aggregate
4679 @item
4680 Attempt to return local value by reference
4682 @item
4683 Premature instantiation of a generic body
4685 @item
4686 Attempt to pack aliased components
4688 @item
4689 Out of bounds array subscripts
4691 @item
4692 Wrong length on string assignment
4694 @item
4695 Violations of style rules if style checking is enabled
4697 @item
4698 Unused @code{with} clauses
4700 @item
4701 @code{Bit_Order} usage that does not have any effect
4703 @item
4704 @code{Standard.Duration} used to resolve universal fixed expression
4706 @item
4707 Dereference of possibly null value
4709 @item
4710 Declaration that is likely to cause storage error
4712 @item
4713 Internal GNAT unit @code{with}'ed by application unit
4715 @item
4716 Values known to be out of range at compile time
4718 @item
4719 Unreferenced labels and variables
4721 @item
4722 Address overlays that could clobber memory
4724 @item
4725 Unexpected initialization when address clause present
4727 @item
4728 Bad alignment for address clause
4730 @item
4731 Useless type conversions
4733 @item
4734 Redundant assignment statements and other redundant constructs
4736 @item
4737 Useless exception handlers
4739 @item
4740 Accidental hiding of name by child unit
4742 @item
4743 Access before elaboration detected at compile time
4745 @item
4746 A range in a @code{for} loop that is known to be null or might be null
4748 @end itemize
4750 @noindent
4751 The following section lists compiler switches that are available
4752 to control the handling of warning messages. It is also possible
4753 to exercise much finer control over what warnings are issued and
4754 suppressed using the GNAT pragma Warnings, @xref{Pragma Warnings,,,
4755 gnat_rm, GNAT Reference manual}.
4757 @table @option
4758 @c !sort!
4759 @item -gnatwa
4760 @emph{Activate most optional warnings.}
4761 @cindex @option{-gnatwa} (@command{gcc})
4762 This switch activates most optional warning messages.  See the remaining list
4763 in this section for details on optional warning messages that can be
4764 individually controlled.  The warnings that are not turned on by this
4765 switch are
4766 @option{-gnatwd} (implicit dereferencing),
4767 @option{-gnatwh} (hiding),
4768 @ifclear vms
4769 @option{-gnatw.d} (tag warnings with -gnatw switch)
4770 @end ifclear
4771 @option{-gnatw.h} (holes (gaps) in record layouts)
4772 @option{-gnatw.i} (overlapping actuals),
4773 @option{-gnatw.k} (redefinition of names in standard),
4774 @option{-gnatwl} (elaboration warnings),
4775 @option{-gnatw.l} (inherited aspects),
4776 @option{-gnatw.o} (warn on values set by out parameters ignored),
4777 @option{-gnatwt} (tracking of deleted conditional code)
4778 and @option{-gnatw.u} (unordered enumeration),
4779 All other optional warnings are turned on.
4781 @item -gnatwA
4782 @emph{Suppress all optional errors.}
4783 @cindex @option{-gnatwA} (@command{gcc})
4784 This switch suppresses all optional warning messages, see remaining list
4785 in this section for details on optional warning messages that can be
4786 individually controlled. Note that unlike switch @option{-gnatws}, the
4787 use of switch @option{-gnatwA} does not suppress warnings that are
4788 normally given unconditionally and cannot be individually controlled
4789 (for example, the warning about a missing exit path in a function).
4790 Also, again unlike switch @option{-gnatws}, warnings suppressed by
4791 the use of switch @option{-gnatwA} can be individually turned back
4792 on. For example the use of switch @option{-gnatwA} followed by
4793 switch @option{-gnatwd} will suppress all optional warnings except
4794 the warnings for implicit dereferencing.
4796 @item -gnatw.a
4797 @emph{Activate warnings on failing assertions.}
4798 @cindex @option{-gnatw.a} (@command{gcc})
4799 @cindex Assert failures
4800 This switch activates warnings for assertions where the compiler can tell at
4801 compile time that the assertion will fail. Note that this warning is given
4802 even if assertions are disabled. The default is that such warnings are
4803 generated.
4805 @item -gnatw.A
4806 @emph{Suppress warnings on failing assertions.}
4807 @cindex @option{-gnatw.A} (@command{gcc})
4808 @cindex Assert failures
4809 This switch suppresses warnings for assertions where the compiler can tell at
4810 compile time that the assertion will fail.
4812 @item -gnatwb
4813 @emph{Activate warnings on bad fixed values.}
4814 @cindex @option{-gnatwb} (@command{gcc})
4815 @cindex Bad fixed values
4816 @cindex Fixed-point Small value
4817 @cindex Small value
4818 This switch activates warnings for static fixed-point expressions whose
4819 value is not an exact multiple of Small. Such values are implementation
4820 dependent, since an implementation is free to choose either of the multiples
4821 that surround the value. GNAT always chooses the closer one, but this is not
4822 required behavior, and it is better to specify a value that is an exact
4823 multiple, ensuring predictable execution. The default is that such warnings
4824 are not generated.
4826 @item -gnatwB
4827 @emph{Suppress warnings on bad fixed values.}
4828 @cindex @option{-gnatwB} (@command{gcc})
4829 This switch suppresses warnings for static fixed-point expressions whose
4830 value is not an exact multiple of Small.
4832 @item -gnatw.b
4833 @emph{Activate warnings on biased representation.}
4834 @cindex @option{-gnatw.b} (@command{gcc})
4835 @cindex Biased representation
4836 This switch activates warnings when a size clause, value size clause, component
4837 clause, or component size clause forces the use of biased representation for an
4838 integer type (e.g. representing a range of 10..11 in a single bit by using 0/1
4839 to represent 10/11). The default is that such warnings are generated.
4841 @item -gnatw.B
4842 @emph{Suppress warnings on biased representation.}
4843 @cindex @option{-gnatwB} (@command{gcc})
4844 This switch suppresses warnings for representation clauses that force the use
4845 of biased representation.
4847 @item -gnatwc
4848 @emph{Activate warnings on conditionals.}
4849 @cindex @option{-gnatwc} (@command{gcc})
4850 @cindex Conditionals, constant
4851 This switch activates warnings for conditional expressions used in
4852 tests that are known to be True or False at compile time. The default
4853 is that such warnings are not generated.
4854 Note that this warning does
4855 not get issued for the use of boolean variables or constants whose
4856 values are known at compile time, since this is a standard technique
4857 for conditional compilation in Ada, and this would generate too many
4858 false positive warnings.
4860 This warning option also activates a special test for comparisons using
4861 the operators ``>='' and`` <=''.
4862 If the compiler can tell that only the equality condition is possible,
4863 then it will warn that the ``>'' or ``<'' part of the test
4864 is useless and that the operator could be replaced by ``=''.
4865 An example would be comparing a @code{Natural} variable <= 0.
4867 This warning option also generates warnings if
4868 one or both tests is optimized away in a membership test for integer
4869 values if the result can be determined at compile time. Range tests on
4870 enumeration types are not included, since it is common for such tests
4871 to include an end point.
4873 This warning can also be turned on using @option{-gnatwa}.
4875 @item -gnatwC
4876 @emph{Suppress warnings on conditionals.}
4877 @cindex @option{-gnatwC} (@command{gcc})
4878 This switch suppresses warnings for conditional expressions used in
4879 tests that are known to be True or False at compile time.
4881 @item -gnatw.c
4882 @emph{Activate warnings on missing component clauses.}
4883 @cindex @option{-gnatw.c} (@command{gcc})
4884 @cindex Component clause, missing
4885 This switch activates warnings for record components where a record
4886 representation clause is present and has component clauses for the
4887 majority, but not all, of the components. A warning is given for each
4888 component for which no component clause is present.
4890 This warning can also be turned on using @option{-gnatwa}.
4892 @item -gnatw.C
4893 @emph{Suppress warnings on missing component clauses.}
4894 @cindex @option{-gnatwC} (@command{gcc})
4895 This switch suppresses warnings for record components that are
4896 missing a component clause in the situation described above.
4898 @item -gnatwd
4899 @emph{Activate warnings on implicit dereferencing.}
4900 @cindex @option{-gnatwd} (@command{gcc})
4901 If this switch is set, then the use of a prefix of an access type
4902 in an indexed component, slice, or selected component without an
4903 explicit @code{.all} will generate a warning. With this warning
4904 enabled, access checks occur only at points where an explicit
4905 @code{.all} appears in the source code (assuming no warnings are
4906 generated as a result of this switch). The default is that such
4907 warnings are not generated.
4908 Note that @option{-gnatwa} does not affect the setting of
4909 this warning option.
4911 @item -gnatwD
4912 @emph{Suppress warnings on implicit dereferencing.}
4913 @cindex @option{-gnatwD} (@command{gcc})
4914 @cindex Implicit dereferencing
4915 @cindex Dereferencing, implicit
4916 This switch suppresses warnings for implicit dereferences in
4917 indexed components, slices, and selected components.
4919 @ifclear vms
4920 @item -gnatw.d
4921 @emph{Activate tagging of warning messages.}
4922 @cindex @option{-gnatw.d} (@command{gcc})
4923 If this switch is set, then warning messages are tagged, either with
4924 the string ``@option{-gnatw?}'' showing which switch controls the warning,
4925 or with ``[enabled by default]'' if the warning is not under control of a
4926 specific @option{-gnatw?} switch. This mode is off by default, and is not
4927 affected by the use of @code{-gnatwa}.
4929 @item -gnatw.D
4930 @emph{Deactivate tagging of warning messages.}
4931 @cindex @option{-gnatw.d} (@command{gcc})
4932 If this switch is set, then warning messages return to the default
4933 mode in which warnings are not tagged as described above for
4934 @code{-gnatw.d}.
4935 @end ifclear
4937 @item -gnatwe
4938 @emph{Treat warnings and style checks as errors.}
4939 @cindex @option{-gnatwe} (@command{gcc})
4940 @cindex Warnings, treat as error
4941 This switch causes warning messages and style check messages to be
4942 treated as errors.
4943 The warning string still appears, but the warning messages are counted
4944 as errors, and prevent the generation of an object file. Note that this
4945 is the only -gnatw switch that affects the handling of style check messages.
4947 @item -gnatw.e
4948 @emph{Activate every optional warning}
4949 @cindex @option{-gnatw.e} (@command{gcc})
4950 @cindex Warnings, activate every optional warning
4951 This switch activates all optional warnings, including those which
4952 are not activated by @code{-gnatwa}. The use of this switch is not
4953 recommended for normal use. If you turn this switch on, it is almost
4954 certain that you will get large numbers of useless warnings. The
4955 warnings that are excluded from @code{-gnatwa} are typically highly
4956 specialized warnings that are suitable for use only in code that has
4957 been specifically designed according to specialized coding rules.
4959 @item -gnatwf
4960 @emph{Activate warnings on unreferenced formals.}
4961 @cindex @option{-gnatwf} (@command{gcc})
4962 @cindex Formals, unreferenced
4963 This switch causes a warning to be generated if a formal parameter
4964 is not referenced in the body of the subprogram. This warning can
4965 also be turned on using @option{-gnatwa} or @option{-gnatwu}. The
4966 default is that these warnings are not generated.
4968 @item -gnatwF
4969 @emph{Suppress warnings on unreferenced formals.}
4970 @cindex @option{-gnatwF} (@command{gcc})
4971 This switch suppresses warnings for unreferenced formal
4972 parameters. Note that the
4973 combination @option{-gnatwu} followed by @option{-gnatwF} has the
4974 effect of warning on unreferenced entities other than subprogram
4975 formals.
4977 @item -gnatwg
4978 @emph{Activate warnings on unrecognized pragmas.}
4979 @cindex @option{-gnatwg} (@command{gcc})
4980 @cindex Pragmas, unrecognized
4981 This switch causes a warning to be generated if an unrecognized
4982 pragma is encountered. Apart from issuing this warning, the
4983 pragma is ignored and has no effect. This warning can
4984 also be turned on using @option{-gnatwa}. The default
4985 is that such warnings are issued (satisfying the Ada Reference
4986 Manual requirement that such warnings appear).
4988 @item -gnatwG
4989 @emph{Suppress warnings on unrecognized pragmas.}
4990 @cindex @option{-gnatwG} (@command{gcc})
4991 This switch suppresses warnings for unrecognized pragmas.
4993 @item -gnatwh
4994 @emph{Activate warnings on hiding.}
4995 @cindex @option{-gnatwh} (@command{gcc})
4996 @cindex Hiding of Declarations
4997 This switch activates warnings on hiding declarations.
4998 A declaration is considered hiding
4999 if it is for a non-overloadable entity, and it declares an entity with the
5000 same name as some other entity that is directly or use-visible. The default
5001 is that such warnings are not generated.
5002 Note that @option{-gnatwa} does not affect the setting of this warning option.
5004 @item -gnatwH
5005 @emph{Suppress warnings on hiding.}
5006 @cindex @option{-gnatwH} (@command{gcc})
5007 This switch suppresses warnings on hiding declarations.
5009 @item -gnatw.h
5010 @emph{Activate warnings on holes/gaps in records.}
5011 @cindex @option{-gnatw.h} (@command{gcc})
5012 @cindex Record Representation (gaps)
5013 This switch activates warnings on component clauses in record
5014 representation clauses that leave holes (gaps) in the record layout.
5015 If this warning option is active, then record representation clauses
5016 should specify a contiguous layout, adding unused fill fields if needed.
5017 Note that @option{-gnatwa} does not affect the setting of this warning option.
5019 @item -gnatw.H
5020 @emph{Suppress warnings on holes/gaps in records.}
5021 @cindex @option{-gnatw.H} (@command{gcc})
5022 This switch suppresses warnings on component clauses in record
5023 representation clauses that leave holes (haps) in the record layout.
5025 @item -gnatwi
5026 @emph{Activate warnings on implementation units.}
5027 @cindex @option{-gnatwi} (@command{gcc})
5028 This switch activates warnings for a @code{with} of an internal GNAT
5029 implementation unit, defined as any unit from the @code{Ada},
5030 @code{Interfaces}, @code{GNAT},
5031 ^^@code{DEC},^ or @code{System}
5032 hierarchies that is not
5033 documented in either the Ada Reference Manual or the GNAT
5034 Programmer's Reference Manual. Such units are intended only
5035 for internal implementation purposes and should not be @code{with}'ed
5036 by user programs. The default is that such warnings are generated
5037 This warning can also be turned on using @option{-gnatwa}.
5039 @item -gnatwI
5040 @emph{Disable warnings on implementation units.}
5041 @cindex @option{-gnatwI} (@command{gcc})
5042 This switch disables warnings for a @code{with} of an internal GNAT
5043 implementation unit.
5045 @item -gnatw.i
5046 @emph{Activate warnings on overlapping actuals.}
5047 @cindex @option{-gnatw.i} (@command{gcc})
5048 This switch enables a warning on statically detectable overlapping actuals in
5049 a subprogram call, when one of the actuals is an in-out parameter, and the
5050 types of the actuals are not by-copy types. The warning is off by default,
5051 and is not included under -gnatwa.
5053 @item -gnatw.I
5054 @emph{Disable warnings on overlapping actuals.}
5055 @cindex @option{-gnatw.I} (@command{gcc})
5056 This switch disables warnings on overlapping actuals in a call..
5058 @item -gnatwj
5059 @emph{Activate warnings on obsolescent features (Annex J).}
5060 @cindex @option{-gnatwj} (@command{gcc})
5061 @cindex Features, obsolescent
5062 @cindex Obsolescent features
5063 If this warning option is activated, then warnings are generated for
5064 calls to subprograms marked with @code{pragma Obsolescent} and
5065 for use of features in Annex J of the Ada Reference Manual. In the
5066 case of Annex J, not all features are flagged. In particular use
5067 of the renamed packages (like @code{Text_IO}) and use of package
5068 @code{ASCII} are not flagged, since these are very common and
5069 would generate many annoying positive warnings. The default is that
5070 such warnings are not generated. This warning is also turned on by
5071 the use of @option{-gnatwa}.
5073 In addition to the above cases, warnings are also generated for
5074 GNAT features that have been provided in past versions but which
5075 have been superseded (typically by features in the new Ada standard).
5076 For example, @code{pragma Ravenscar} will be flagged since its
5077 function is replaced by @code{pragma Profile(Ravenscar)}, and
5078 @code{pragma Interface_Name} will be flagged since its function
5079 is replaced by @code{pragma Import}.
5081 Note that this warning option functions differently from the
5082 restriction @code{No_Obsolescent_Features} in two respects.
5083 First, the restriction applies only to annex J features.
5084 Second, the restriction does flag uses of package @code{ASCII}.
5086 @item -gnatwJ
5087 @emph{Suppress warnings on obsolescent features (Annex J).}
5088 @cindex @option{-gnatwJ} (@command{gcc})
5089 This switch disables warnings on use of obsolescent features.
5091 @item -gnatwk
5092 @emph{Activate warnings on variables that could be constants.}
5093 @cindex @option{-gnatwk} (@command{gcc})
5094 This switch activates warnings for variables that are initialized but
5095 never modified, and then could be declared constants. The default is that
5096 such warnings are not given.
5097 This warning can also be turned on using @option{-gnatwa}.
5099 @item -gnatwK
5100 @emph{Suppress warnings on variables that could be constants.}
5101 @cindex @option{-gnatwK} (@command{gcc})
5102 This switch disables warnings on variables that could be declared constants.
5104 @item -gnatw.k
5105 @emph{Activate warnings on redefinition of names in standard.}
5106 @cindex @option{-gnatw.k} (@command{gcc})
5107 This switch activates warnings for declarations that declare a name that
5108 is defined in package Standard. Such declarations can be confusing,
5109 especially since the names in package Standard continue to be directly
5110 visible, meaning that use visibiliy on such redeclared names does not
5111 work as expected. Names of discriminants and components in records are
5112 not included in this check.
5113 This warning is not part of the warnings activated by @option{-gnatwa}.
5114 It must be explicitly activated.
5116 @item -gnatw.K
5117 @emph{Suppress warnings on variables that could be constants.}
5118 @cindex @option{-gnatwK} (@command{gcc})
5119 This switch activates warnings for declarations that declare a name that
5120 is defined in package Standard.
5122 @item -gnatwl
5123 @emph{Activate warnings for elaboration pragmas.}
5124 @cindex @option{-gnatwl} (@command{gcc})
5125 @cindex Elaboration, warnings
5126 This switch activates warnings on missing
5127 @code{Elaborate_All} and @code{Elaborate} pragmas.
5128 See the section in this guide on elaboration checking for details on
5129 when such pragmas should be used. In dynamic elaboration mode, this switch
5130 generations warnings about the need to add elaboration pragmas. Note however,
5131 that if you blindly follow these warnings, and add @code{Elaborate_All}
5132 warnings wherever they are recommended, you basically end up with the
5133 equivalent of the static elaboration model, which may not be what you want for
5134 legacy code for which the static model does not work.
5136 For the static model, the messages generated are labeled "info:" (for
5137 information messages). They are not warnings to add elaboration pragmas,
5138 merely informational messages showing what implicit elaboration pragmas
5139 have been added, for use in analyzing elaboration circularity problems.
5141 Warnings are also generated if you
5142 are using the static mode of elaboration, and a @code{pragma Elaborate}
5143 is encountered. The default is that such warnings
5144 are not generated.
5145 This warning is not automatically turned on by the use of @option{-gnatwa}.
5147 @item -gnatwL
5148 @emph{Suppress warnings for elaboration pragmas.}
5149 @cindex @option{-gnatwL} (@command{gcc})
5150 This switch suppresses warnings on missing Elaborate and Elaborate_All pragmas.
5151 See the section in this guide on elaboration checking for details on
5152 when such pragmas should be used.
5154 @item -gnatw.l
5155 @emph{List inherited aspects.}
5156 @cindex @option{-gnatw.l} (@command{gcc})
5157 This switch causes the compiler to list inherited invariants,
5158 preconditions, and postconditions from Type_Invariant'Class, Invariant'Class,
5159 Pre'Class, and Post'Class aspects. Also list inherited subtype predicates.
5160 These messages are not automatically turned on by the use of @option{-gnatwa}.
5162 @item -gnatw.L
5163 @emph{Suppress listing of inherited aspects.}
5164 @cindex @option{-gnatw.L} (@command{gcc})
5165 This switch suppresses listing of inherited aspects.
5167 @item -gnatwm
5168 @emph{Activate warnings on modified but unreferenced variables.}
5169 @cindex @option{-gnatwm} (@command{gcc})
5170 This switch activates warnings for variables that are assigned (using
5171 an initialization value or with one or more assignment statements) but
5172 whose value is never read. The warning is suppressed for volatile
5173 variables and also for variables that are renamings of other variables
5174 or for which an address clause is given.
5175 This warning can also be turned on using @option{-gnatwa}.
5176 The default is that these warnings are not given.
5178 @item -gnatwM
5179 @emph{Disable warnings on modified but unreferenced variables.}
5180 @cindex @option{-gnatwM} (@command{gcc})
5181 This switch disables warnings for variables that are assigned or
5182 initialized, but never read.
5184 @item -gnatw.m
5185 @emph{Activate warnings on suspicious modulus values.}
5186 @cindex @option{-gnatw.m} (@command{gcc})
5187 This switch activates warnings for modulus values that seem suspicious.
5188 The cases caught are where the size is the same as the modulus (e.g.
5189 a modulus of 7 with a size of 7 bits), and modulus values of 32 or 64
5190 with no size clause. The guess in both cases is that 2**x was intended
5191 rather than x. In addition expressions of the form 2*x for small x
5192 generate a warning (the almost certainly accurate guess being that
5193 2**x was intended). The default is that these warnings are given.
5195 @item -gnatw.M
5196 @emph{Disable warnings on suspicious modulus values.}
5197 @cindex @option{-gnatw.M} (@command{gcc})
5198 This switch disables warnings for suspicious modulus values.
5200 @item -gnatwn
5201 @emph{Set normal warnings mode.}
5202 @cindex @option{-gnatwn} (@command{gcc})
5203 This switch sets normal warning mode, in which enabled warnings are
5204 issued and treated as warnings rather than errors. This is the default
5205 mode. the switch @option{-gnatwn} can be used to cancel the effect of
5206 an explicit @option{-gnatws} or
5207 @option{-gnatwe}. It also cancels the effect of the
5208 implicit @option{-gnatwe} that is activated by the
5209 use of @option{-gnatg}.
5211 @item -gnatwo
5212 @emph{Activate warnings on address clause overlays.}
5213 @cindex @option{-gnatwo} (@command{gcc})
5214 @cindex Address Clauses, warnings
5215 This switch activates warnings for possibly unintended initialization
5216 effects of defining address clauses that cause one variable to overlap
5217 another. The default is that such warnings are generated.
5218 This warning can also be turned on using @option{-gnatwa}.
5220 @item -gnatwO
5221 @emph{Suppress warnings on address clause overlays.}
5222 @cindex @option{-gnatwO} (@command{gcc})
5223 This switch suppresses warnings on possibly unintended initialization
5224 effects of defining address clauses that cause one variable to overlap
5225 another.
5227 @item -gnatw.o
5228 @emph{Activate warnings on modified but unreferenced out parameters.}
5229 @cindex @option{-gnatw.o} (@command{gcc})
5230 This switch activates warnings for variables that are modified by using
5231 them as actuals for a call to a procedure with an out mode formal, where
5232 the resulting assigned value is never read. It is applicable in the case
5233 where there is more than one out mode formal. If there is only one out
5234 mode formal, the warning is issued by default (controlled by -gnatwu).
5235 The warning is suppressed for volatile
5236 variables and also for variables that are renamings of other variables
5237 or for which an address clause is given.
5238 The default is that these warnings are not given. Note that this warning
5239 is not included in -gnatwa, it must be activated explicitly.
5241 @item -gnatw.O
5242 @emph{Disable warnings on modified but unreferenced out parameters.}
5243 @cindex @option{-gnatw.O} (@command{gcc})
5244 This switch suppresses warnings for variables that are modified by using
5245 them as actuals for a call to a procedure with an out mode formal, where
5246 the resulting assigned value is never read.
5248 @item -gnatwp
5249 @emph{Activate warnings on ineffective pragma Inlines.}
5250 @cindex @option{-gnatwp} (@command{gcc})
5251 @cindex Inlining, warnings
5252 This switch activates warnings for failure of front end inlining
5253 (activated by @option{-gnatN}) to inline a particular call. There are
5254 many reasons for not being able to inline a call, including most
5255 commonly that the call is too complex to inline. The default is
5256 that such warnings are not given.
5257 This warning can also be turned on using @option{-gnatwa}.
5258 Warnings on ineffective inlining by the gcc back-end can be activated
5259 separately, using the gcc switch -Winline.
5261 @item -gnatwP
5262 @emph{Suppress warnings on ineffective pragma Inlines.}
5263 @cindex @option{-gnatwP} (@command{gcc})
5264 This switch suppresses warnings on ineffective pragma Inlines. If the
5265 inlining mechanism cannot inline a call, it will simply ignore the
5266 request silently.
5268 @item -gnatw.p
5269 @emph{Activate warnings on parameter ordering.}
5270 @cindex @option{-gnatw.p} (@command{gcc})
5271 @cindex Parameter order, warnings
5272 This switch activates warnings for cases of suspicious parameter
5273 ordering when the list of arguments are all simple identifiers that
5274 match the names of the formals, but are in a different order. The
5275 warning is suppressed if any use of named parameter notation is used,
5276 so this is the appropriate way to suppress a false positive (and
5277 serves to emphasize that the "misordering" is deliberate). The
5278 default is
5279 that such warnings are not given.
5280 This warning can also be turned on using @option{-gnatwa}.
5282 @item -gnatw.P
5283 @emph{Suppress warnings on parameter ordering.}
5284 @cindex @option{-gnatw.P} (@command{gcc})
5285 This switch suppresses warnings on cases of suspicious parameter
5286 ordering.
5288 @item -gnatwq
5289 @emph{Activate warnings on questionable missing parentheses.}
5290 @cindex @option{-gnatwq} (@command{gcc})
5291 @cindex Parentheses, warnings
5292 This switch activates warnings for cases where parentheses are not used and
5293 the result is potential ambiguity from a readers point of view. For example
5294 (not a > b) when a and b are modular means ((not a) > b) and very likely the
5295 programmer intended (not (a > b)). Similarly (-x mod 5) means (-(x mod 5)) and
5296 quite likely ((-x) mod 5) was intended. In such situations it seems best to
5297 follow the rule of always parenthesizing to make the association clear, and
5298 this warning switch warns if such parentheses are not present. The default
5299 is that these warnings are given.
5300 This warning can also be turned on using @option{-gnatwa}.
5302 @item -gnatwQ
5303 @emph{Suppress warnings on questionable missing parentheses.}
5304 @cindex @option{-gnatwQ} (@command{gcc})
5305 This switch suppresses warnings for cases where the association is not
5306 clear and the use of parentheses is preferred.
5308 @item -gnatwr
5309 @emph{Activate warnings on redundant constructs.}
5310 @cindex @option{-gnatwr} (@command{gcc})
5311 This switch activates warnings for redundant constructs. The following
5312 is the current list of constructs regarded as redundant:
5314 @itemize @bullet
5315 @item
5316 Assignment of an item to itself.
5317 @item
5318 Type conversion that converts an expression to its own type.
5319 @item
5320 Use of the attribute @code{Base} where @code{typ'Base} is the same
5321 as @code{typ}.
5322 @item
5323 Use of pragma @code{Pack} when all components are placed by a record
5324 representation clause.
5325 @item
5326 Exception handler containing only a reraise statement (raise with no
5327 operand) which has no effect.
5328 @item
5329 Use of the operator abs on an operand that is known at compile time
5330 to be non-negative
5331 @item
5332 Comparison of boolean expressions to an explicit True value.
5333 @end itemize
5335 This warning can also be turned on using @option{-gnatwa}.
5336 The default is that warnings for redundant constructs are not given.
5338 @item -gnatwR
5339 @emph{Suppress warnings on redundant constructs.}
5340 @cindex @option{-gnatwR} (@command{gcc})
5341 This switch suppresses warnings for redundant constructs.
5343 @item -gnatw.r
5344 @emph{Activate warnings for object renaming function.}
5345 @cindex @option{-gnatw.r} (@command{gcc})
5346 This switch activates warnings for an object renaming that renames a
5347 function call, which is equivalent to a constant declaration (as
5348 opposed to renaming the function itself).  The default is that these
5349 warnings are given.  This warning can also be turned on using
5350 @option{-gnatwa}.
5352 @item -gnatw.R
5353 @emph{Suppress warnings for object renaming function.}
5354 @cindex @option{-gnatwT} (@command{gcc})
5355 This switch suppresses warnings for object renaming function.
5357 @item -gnatws
5358 @emph{Suppress all warnings.}
5359 @cindex @option{-gnatws} (@command{gcc})
5360 This switch completely suppresses the
5361 output of all warning messages from the GNAT front end, including
5362 both warnings that can be controlled by switches described in this
5363 section, and those that are normally given unconditionally. The
5364 effect of this suppress action can only be cancelled by a subsequent
5365 use of the switch @option{-gnatwn}.
5367 Note that switch @option{-gnatws} does not suppress
5368 warnings from the @command{gcc} back end.
5369 To suppress these back end warnings as well, use the switch @option{-w}
5370 in addition to @option{-gnatws}. Also this switch has no effect on the
5371 handling of style check messages.
5373 @item -gnatw.s
5374 @emph{Activate warnings on overridden size clauses.}
5375 @cindex @option{-gnatw.s} (@command{gcc})
5376 @cindex Record Representation (component sizes)
5377 This switch activates warnings on component clauses in record
5378 representation clauses where the length given overrides that
5379 specified by an explicit size clause for the component type. A
5380 warning is similarly given in the array case if a specified
5381 component size overrides an explicit size clause for the array
5382 component type.
5383 Note that @option{-gnatwa} does not affect the setting of this warning option.
5385 @item -gnatw.S
5386 @emph{Suppress warnings on overridden size clauses.}
5387 @cindex @option{-gnatw.S} (@command{gcc})
5388 This switch suppresses warnings on component clauses in record
5389 representation clauses that override size clauses, and similar
5390 warnings when an array component size overrides a size clause.
5392 @item -gnatwt
5393 @emph{Activate warnings for tracking of deleted conditional code.}
5394 @cindex @option{-gnatwt} (@command{gcc})
5395 @cindex Deactivated code, warnings
5396 @cindex Deleted code, warnings
5397 This switch activates warnings for tracking of code in conditionals (IF and
5398 CASE statements) that is detected to be dead code which cannot be executed, and
5399 which is removed by the front end. This warning is off by default, and is not
5400 turned on by @option{-gnatwa}, it has to be turned on explicitly. This may be
5401 useful for detecting deactivated code in certified applications.
5403 @item -gnatwT
5404 @emph{Suppress warnings for tracking of deleted conditional code.}
5405 @cindex @option{-gnatwT} (@command{gcc})
5406 This switch suppresses warnings for tracking of deleted conditional code.
5408 @item -gnatw.t
5409 @emph{Activate warnings on suspicious contracts.}
5410 @cindex @option{-gnatw.t} (@command{gcc})
5411 This switch activates warnings on suspicious postconditions (whether a
5412 pragma @code{Postcondition} or a @code{Post} aspect in Ada 2012)
5413 and suspicious contract cases (pragma @code{Contract_Cases}). A
5414 function postcondition or contract case is suspicious when no postcondition
5415 or contract case for this function mentions the result of the function.
5416 A procedure postcondition or contract case is suspicious when it only
5417 refers to the pre-state of the procedure, because in that case it should
5418 rather be expressed as a precondition. The default is that such warnings
5419 are not generated. This warning can also be turned on using @option{-gnatwa}.
5421 @item -gnatw.T
5422 @emph{Suppress warnings on suspicious contracts.}
5423 @cindex @option{-gnatw.T} (@command{gcc})
5424 This switch suppresses warnings on suspicious postconditions.
5426 @item -gnatwu
5427 @emph{Activate warnings on unused entities.}
5428 @cindex @option{-gnatwu} (@command{gcc})
5429 This switch activates warnings to be generated for entities that
5430 are declared but not referenced, and for units that are @code{with}'ed
5431 and not
5432 referenced. In the case of packages, a warning is also generated if
5433 no entities in the package are referenced. This means that if a with'ed
5434 package is referenced but the only references are in @code{use}
5435 clauses or @code{renames}
5436 declarations, a warning is still generated. A warning is also generated
5437 for a generic package that is @code{with}'ed but never instantiated.
5438 In the case where a package or subprogram body is compiled, and there
5439 is a @code{with} on the corresponding spec
5440 that is only referenced in the body,
5441 a warning is also generated, noting that the
5442 @code{with} can be moved to the body. The default is that
5443 such warnings are not generated.
5444 This switch also activates warnings on unreferenced formals
5445 (it includes the effect of @option{-gnatwf}).
5446 This warning can also be turned on using @option{-gnatwa}.
5448 @item -gnatwU
5449 @emph{Suppress warnings on unused entities.}
5450 @cindex @option{-gnatwU} (@command{gcc})
5451 This switch suppresses warnings for unused entities and packages.
5452 It also turns off warnings on unreferenced formals (and thus includes
5453 the effect of @option{-gnatwF}).
5455 @item -gnatw.u
5456 @emph{Activate warnings on unordered enumeration types.}
5457 @cindex @option{-gnatw.u} (@command{gcc})
5458 This switch causes enumeration types to be considered as conceptually
5459 unordered, unless an explicit pragma @code{Ordered} is given for the type.
5460 The effect is to generate warnings in clients that use explicit comparisons
5461 or subranges, since these constructs both treat objects of the type as
5462 ordered. (A @emph{client} is defined as a unit that is other than the unit in
5463 which the type is declared, or its body or subunits.) Please refer to
5464 the description of pragma @code{Ordered} in the
5465 @cite{@value{EDITION} Reference Manual} for further details.
5466 The default is that such warnings are not generated.
5467 This warning is not automatically turned on by the use of @option{-gnatwa}.
5469 @item -gnatw.U
5470 @emph{Deactivate warnings on unordered enumeration types.}
5471 @cindex @option{-gnatw.U} (@command{gcc})
5472 This switch causes all enumeration types to be considered as ordered, so
5473 that no warnings are given for comparisons or subranges for any type.
5475 @item -gnatwv
5476 @emph{Activate warnings on unassigned variables.}
5477 @cindex @option{-gnatwv} (@command{gcc})
5478 @cindex Unassigned variable warnings
5479 This switch activates warnings for access to variables which
5480 may not be properly initialized. The default is that
5481 such warnings are generated.
5482 This warning can also be turned on using @option{-gnatwa}.
5484 @item -gnatwV
5485 @emph{Suppress warnings on unassigned variables.}
5486 @cindex @option{-gnatwV} (@command{gcc})
5487 This switch suppresses warnings for access to variables which
5488 may not be properly initialized.
5489 For variables of a composite type, the warning can also be suppressed in
5490 Ada 2005 by using a default initialization with a box. For example, if
5491 Table is an array of records whose components are only partially uninitialized,
5492 then the following code:
5494 @smallexample @c ada
5495    Tab : Table := (others => <>);
5496 @end smallexample
5498 will suppress warnings on subsequent statements that access components
5499 of variable Tab.
5501 @item -gnatw.v
5502 @emph{Activate info messages for non-default bit order.}
5503 @cindex @option{-gnatw.v} (@command{gcc})
5504 @cindex bit order warnings
5505 This switch activates messages (labeled "info", they are not warnings,
5506 just informational messages) about the effects of non-default bit-order
5507 on records to which a component clause is applied. The effect of specifying
5508 non-default bit ordering is a bit subtle (and changed with Ada 2005), so
5509 these messages, which are given by default, are useful in understanding the
5510 exact consequences of using this feature. These messages
5511 can also be turned on using @option{-gnatwa}
5513 @item -gnatw.V
5514 @emph{Suppress info messages for non-default bit order.}
5515 @cindex @option{-gnatw.V} (@command{gcc})
5516 This switch suppresses information messages for the effects of specifying
5517 non-default bit order on record components with component clauses.
5519 @item -gnatww
5520 @emph{Activate warnings on wrong low bound assumption.}
5521 @cindex @option{-gnatww} (@command{gcc})
5522 @cindex String indexing warnings
5523 This switch activates warnings for indexing an unconstrained string parameter
5524 with a literal or S'Length. This is a case where the code is assuming that the
5525 low bound is one, which is in general not true (for example when a slice is
5526 passed). The default is that such warnings are generated.
5527 This warning can also be turned on using @option{-gnatwa}.
5529 @item -gnatwW
5530 @emph{Suppress warnings on wrong low bound assumption.}
5531 @cindex @option{-gnatwW} (@command{gcc})
5532 This switch suppresses warnings for indexing an unconstrained string parameter
5533 with a literal or S'Length. Note that this warning can also be suppressed
5534 in a particular case by adding an
5535 assertion that the lower bound is 1,
5536 as shown in the following example.
5538 @smallexample @c ada
5539    procedure K (S : String) is
5540       pragma Assert (S'First = 1);
5541       @dots{}
5542 @end smallexample
5544 @item -gnatw.w
5545 @emph{Activate warnings on unnecessary Warnings Off pragmas}
5546 @cindex @option{-gnatw.w} (@command{gcc})
5547 @cindex Warnings Off control
5548 This switch activates warnings for use of @code{pragma Warnings (Off, entity)}
5549 where either the pragma is entirely useless (because it suppresses no
5550 warnings), or it could be replaced by @code{pragma Unreferenced} or
5551 @code{pragma Unmodified}. The default is that these warnings are not given.
5552 Note that this warning is not included in -gnatwa, it must be
5553 activated explicitly.
5555 @item -gnatw.W
5556 @emph{Suppress warnings on unnecessary Warnings Off pragmas}
5557 @cindex @option{-gnatw.W} (@command{gcc})
5558 This switch suppresses warnings for use of @code{pragma Warnings (Off, entity)}.
5560 @item -gnatwx
5561 @emph{Activate warnings on Export/Import pragmas.}
5562 @cindex @option{-gnatwx} (@command{gcc})
5563 @cindex Export/Import pragma warnings
5564 This switch activates warnings on Export/Import pragmas when
5565 the compiler detects a possible conflict between the Ada and
5566 foreign language calling sequences. For example, the use of
5567 default parameters in a convention C procedure is dubious
5568 because the C compiler cannot supply the proper default, so
5569 a warning is issued. The default is that such warnings are
5570 generated.
5571 This warning can also be turned on using @option{-gnatwa}.
5573 @item -gnatwX
5574 @emph{Suppress warnings on Export/Import pragmas.}
5575 @cindex @option{-gnatwX} (@command{gcc})
5576 This switch suppresses warnings on Export/Import pragmas.
5577 The sense of this is that you are telling the compiler that
5578 you know what you are doing in writing the pragma, and it
5579 should not complain at you.
5581 @item -gnatw.x
5582 @emph{Activate warnings for No_Exception_Propagation mode.}
5583 @cindex @option{-gnatwm} (@command{gcc})
5584 This switch activates warnings for exception usage when pragma Restrictions
5585 (No_Exception_Propagation) is in effect. Warnings are given for implicit or
5586 explicit exception raises which are not covered by a local handler, and for
5587 exception handlers which do not cover a local raise. The default is that these
5588 warnings are not given.
5590 @item -gnatw.X
5591 @emph{Disable warnings for No_Exception_Propagation mode.}
5592 This switch disables warnings for exception usage when pragma Restrictions
5593 (No_Exception_Propagation) is in effect.
5595 @item -gnatwy
5596 @emph{Activate warnings for Ada compatibility issues.}
5597 @cindex @option{-gnatwy} (@command{gcc})
5598 @cindex Ada compatibility issues warnings
5599 For the most part, newer versions of Ada are upwards compatible
5600 with older versions. For example, Ada 2005 programs will almost
5601 always work when compiled as Ada 2012.
5602 However there are some exceptions (for example the fact that
5603 @code{some} is now a reserved word in Ada 2012). This
5604 switch activates several warnings to help in identifying
5605 and correcting such incompatibilities. The default is that
5606 these warnings are generated. Note that at one point Ada 2005
5607 was called Ada 0Y, hence the choice of character.
5608 This warning can also be turned on using @option{-gnatwa}.
5610 @item -gnatwY
5611 @emph{Disable warnings for Ada compatibility issues.}
5612 @cindex @option{-gnatwY} (@command{gcc})
5613 @cindex Ada compatibility issues warnings
5614 This switch suppresses the warnings intended to help in identifying
5615 incompatibilities between Ada language versions.
5617 @item -gnatwz
5618 @emph{Activate warnings on unchecked conversions.}
5619 @cindex @option{-gnatwz} (@command{gcc})
5620 @cindex Unchecked_Conversion warnings
5621 This switch activates warnings for unchecked conversions
5622 where the types are known at compile time to have different
5623 sizes. The default
5624 is that such warnings are generated. Warnings are also
5625 generated for subprogram pointers with different conventions,
5626 and, on VMS only, for data pointers with different conventions.
5627 This warning can also be turned on using @option{-gnatwa}.
5629 @item -gnatwZ
5630 @emph{Suppress warnings on unchecked conversions.}
5631 @cindex @option{-gnatwZ} (@command{gcc})
5632 This switch suppresses warnings for unchecked conversions
5633 where the types are known at compile time to have different
5634 sizes or conventions.
5636 @item ^-Wunused^WARNINGS=UNUSED^
5637 @cindex @option{-Wunused}
5638 The warnings controlled by the @option{-gnatw} switch are generated by
5639 the front end of the compiler. The @option{GCC} back end can provide
5640 additional warnings and they are controlled by the @option{-W} switch.
5641 For example, @option{^-Wunused^WARNINGS=UNUSED^} activates back end
5642 warnings for entities that are declared but not referenced.
5644 @item ^-Wuninitialized^WARNINGS=UNINITIALIZED^
5645 @cindex @option{-Wuninitialized}
5646 Similarly, @option{^-Wuninitialized^WARNINGS=UNINITIALIZED^} activates
5647 the back end warning for uninitialized variables. This switch must be
5648 used in conjunction with an optimization level greater than zero.
5650 @item -Wstack-usage=@var{len}
5651 @cindex @option{-Wstack-usage}
5652 Warn if the stack usage of a subprogram might be larger than @var{len} bytes.
5653 See @ref{Static Stack Usage Analysis} for details.
5655 @item ^-Wall^/ALL_BACK_END_WARNINGS^
5656 @cindex @option{-Wall}
5657 This switch enables most warnings from the @option{GCC} back end.
5658 The code generator detects a number of warning situations that are missed
5659 by the @option{GNAT} front end, and this switch can be used to activate them.
5660 The use of this switch also sets the default front end warning mode to
5661 @option{-gnatwa}, that is, most front end warnings activated as well.
5663 @item ^-w^/NO_BACK_END_WARNINGS^
5664 @cindex @option{-w}
5665 Conversely, this switch suppresses warnings from the @option{GCC} back end.
5666 The use of this switch also sets the default front end warning mode to
5667 @option{-gnatws}, that is, front end warnings suppressed as well.
5669 @end table
5671 @noindent
5672 @ifclear vms
5673 A string of warning parameters can be used in the same parameter. For example:
5675 @smallexample
5676 -gnatwaGe
5677 @end smallexample
5679 @noindent
5680 will turn on all optional warnings except for unrecognized pragma warnings,
5681 and also specify that warnings should be treated as errors.
5682 @end ifclear
5684 When no switch @option{^-gnatw^/WARNINGS^} is used, this is equivalent to:
5686 @table @option
5687 @c !sort!
5688 @item -gnatw.a
5689 @item -gnatwB
5690 @item -gnatw.b
5691 @item -gnatwC
5692 @item -gnatw.C
5693 @item -gnatwD
5694 @item -gnatwF
5695 @item -gnatwg
5696 @item -gnatwH
5697 @item -gnatwi
5698 @item -gnatw.I
5699 @item -gnatwJ
5700 @item -gnatwK
5701 @item -gnatwL
5702 @item -gnatw.L
5703 @item -gnatwM
5704 @item -gnatw.m
5705 @item -gnatwn
5706 @item -gnatwo
5707 @item -gnatw.O
5708 @item -gnatwP
5709 @item -gnatw.P
5710 @item -gnatwq
5711 @item -gnatwR
5712 @item -gnatw.R
5713 @item -gnatw.S
5714 @item -gnatwT
5715 @item -gnatw.T
5716 @item -gnatwU
5717 @item -gnatwv
5718 @item -gnatww
5719 @item -gnatw.W
5720 @item -gnatwx
5721 @item -gnatw.X
5722 @item -gnatwy
5723 @item -gnatwz
5725 @end table
5727 @node Debugging and Assertion Control
5728 @subsection Debugging and Assertion Control
5730 @table @option
5731 @item -gnata
5732 @cindex @option{-gnata} (@command{gcc})
5733 @findex Assert
5734 @findex Debug
5735 @cindex Assertions
5737 @noindent
5738 The pragmas @code{Assert} and @code{Debug} normally have no effect and
5739 are ignored. This switch, where @samp{a} stands for assert, causes
5740 @code{Assert} and @code{Debug} pragmas to be activated.
5742 The pragmas have the form:
5744 @smallexample
5745 @cartouche
5746    @b{pragma} Assert (@var{Boolean-expression} @r{[},
5747                       @var{static-string-expression}@r{]})
5748    @b{pragma} Debug (@var{procedure call})
5749 @end cartouche
5750 @end smallexample
5752 @noindent
5753 The @code{Assert} pragma causes @var{Boolean-expression} to be tested.
5754 If the result is @code{True}, the pragma has no effect (other than
5755 possible side effects from evaluating the expression). If the result is
5756 @code{False}, the exception @code{Assert_Failure} declared in the package
5757 @code{System.Assertions} is
5758 raised (passing @var{static-string-expression}, if present, as the
5759 message associated with the exception). If no string expression is
5760 given the default is a string giving the file name and line number
5761 of the pragma.
5763 The @code{Debug} pragma causes @var{procedure} to be called. Note that
5764 @code{pragma Debug} may appear within a declaration sequence, allowing
5765 debugging procedures to be called between declarations.
5767 @ifset vms
5768 @item /DEBUG@r{[}=debug-level@r{]}
5769 @itemx  /NODEBUG
5770 Specifies how much debugging information is to be included in
5771 the resulting object file where 'debug-level' is one of the following:
5772 @table @code
5773 @item   TRACEBACK
5774 Include both debugger symbol records and traceback
5775 the object file.
5776 This is the default setting.
5777 @item   ALL
5778 Include both debugger symbol records and traceback in
5779 object file.
5780 @item   NONE
5781 Excludes both debugger symbol records and traceback
5782 the object file. Same as /NODEBUG.
5783 @item   SYMBOLS
5784 Includes only debugger symbol records in the object
5785 file. Note that this doesn't include traceback information.
5786 @end table
5787 @end ifset
5788 @end table
5790 @node Validity Checking
5791 @subsection Validity Checking
5792 @findex Validity Checking
5794 @noindent
5795 The Ada Reference Manual defines the concept of invalid values (see
5796 RM 13.9.1). The primary source of invalid values is uninitialized
5797 variables. A scalar variable that is left uninitialized may contain
5798 an invalid value; the concept of invalid does not apply to access or
5799 composite types.
5801 It is an error to read an invalid value, but the RM does not require
5802 run-time checks to detect such errors, except for some minimal
5803 checking to prevent erroneous execution (i.e. unpredictable
5804 behavior). This corresponds to the @option{-gnatVd} switch below,
5805 which is the default. For example, by default, if the expression of a
5806 case statement is invalid, it will raise Constraint_Error rather than
5807 causing a wild jump, and if an array index on the left-hand side of an
5808 assignment is invalid, it will raise Constraint_Error rather than
5809 overwriting an arbitrary memory location.
5811 The @option{-gnatVa} may be used to enable additional validity checks,
5812 which are not required by the RM. These checks are often very
5813 expensive (which is why the RM does not require them). These checks
5814 are useful in tracking down uninitialized variables, but they are
5815 not usually recommended for production builds.
5817 The other @option{-gnatV^@var{x}^^} switches below allow finer-grained
5818 control; you can enable whichever validity checks you desire. However,
5819 for most debugging purposes, @option{-gnatVa} is sufficient, and the
5820 default @option{-gnatVd} (i.e. standard Ada behavior) is usually
5821 sufficient for non-debugging use.
5823 The @option{-gnatB} switch tells the compiler to assume that all
5824 values are valid (that is, within their declared subtype range)
5825 except in the context of a use of the Valid attribute. This means
5826 the compiler can generate more efficient code, since the range
5827 of values is better known at compile time. However, an uninitialized
5828 variable can cause wild jumps and memory corruption in this mode.
5830 The @option{-gnatV^@var{x}^^} switch allows control over the validity
5831 checking mode as described below.
5832 @ifclear vms
5833 The @code{x} argument is a string of letters that
5834 indicate validity checks that are performed or not performed in addition
5835 to the default checks required by Ada as described above.
5836 @end ifclear
5837 @ifset vms
5838 The options allowed for this qualifier
5839 indicate validity checks that are performed or not performed in addition
5840 to the default checks required by Ada as described above.
5841 @end ifset
5843 @table @option
5844 @c !sort!
5845 @item -gnatVa
5846 @emph{All validity checks.}
5847 @cindex @option{-gnatVa} (@command{gcc})
5848 All validity checks are turned on.
5849 @ifclear vms
5850 That is, @option{-gnatVa} is
5851 equivalent to @option{gnatVcdfimorst}.
5852 @end ifclear
5854 @item -gnatVc
5855 @emph{Validity checks for copies.}
5856 @cindex @option{-gnatVc} (@command{gcc})
5857 The right hand side of assignments, and the initializing values of
5858 object declarations are validity checked.
5860 @item -gnatVd
5861 @emph{Default (RM) validity checks.}
5862 @cindex @option{-gnatVd} (@command{gcc})
5863 Some validity checks are done by default following normal Ada semantics
5864 (RM 13.9.1 (9-11)).
5865 A check is done in case statements that the expression is within the range
5866 of the subtype. If it is not, Constraint_Error is raised.
5867 For assignments to array components, a check is done that the expression used
5868 as index is within the range. If it is not, Constraint_Error is raised.
5869 Both these validity checks may be turned off using switch @option{-gnatVD}.
5870 They are turned on by default. If @option{-gnatVD} is specified, a subsequent
5871 switch @option{-gnatVd} will leave the checks turned on.
5872 Switch @option{-gnatVD} should be used only if you are sure that all such
5873 expressions have valid values. If you use this switch and invalid values
5874 are present, then the program is erroneous, and wild jumps or memory
5875 overwriting may occur.
5877 @item -gnatVe
5878 @emph{Validity checks for elementary components.}
5879 @cindex @option{-gnatVe} (@command{gcc})
5880 In the absence of this switch, assignments to record or array components are
5881 not validity checked, even if validity checks for assignments generally
5882 (@option{-gnatVc}) are turned on. In Ada, assignment of composite values do not
5883 require valid data, but assignment of individual components does. So for
5884 example, there is a difference between copying the elements of an array with a
5885 slice assignment, compared to assigning element by element in a loop. This
5886 switch allows you to turn off validity checking for components, even when they
5887 are assigned component by component.
5889 @item -gnatVf
5890 @emph{Validity checks for floating-point values.}
5891 @cindex @option{-gnatVf} (@command{gcc})
5892 In the absence of this switch, validity checking occurs only for discrete
5893 values. If @option{-gnatVf} is specified, then validity checking also applies
5894 for floating-point values, and NaNs and infinities are considered invalid,
5895 as well as out of range values for constrained types. Note that this means
5896 that standard IEEE infinity mode is not allowed. The exact contexts
5897 in which floating-point values are checked depends on the setting of other
5898 options. For example,
5899 @option{^-gnatVif^VALIDITY_CHECKING=(IN_PARAMS,FLOATS)^} or
5900 @option{^-gnatVfi^VALIDITY_CHECKING=(FLOATS,IN_PARAMS)^}
5901 (the order does not matter) specifies that floating-point parameters of mode
5902 @code{in} should be validity checked.
5904 @item -gnatVi
5905 @emph{Validity checks for @code{in} mode parameters}
5906 @cindex @option{-gnatVi} (@command{gcc})
5907 Arguments for parameters of mode @code{in} are validity checked in function
5908 and procedure calls at the point of call.
5910 @item -gnatVm
5911 @emph{Validity checks for @code{in out} mode parameters.}
5912 @cindex @option{-gnatVm} (@command{gcc})
5913 Arguments for parameters of mode @code{in out} are validity checked in
5914 procedure calls at the point of call. The @code{'m'} here stands for
5915 modify, since this concerns parameters that can be modified by the call.
5916 Note that there is no specific option to test @code{out} parameters,
5917 but any reference within the subprogram will be tested in the usual
5918 manner, and if an invalid value is copied back, any reference to it
5919 will be subject to validity checking.
5921 @item -gnatVn
5922 @emph{No validity checks.}
5923 @cindex @option{-gnatVn} (@command{gcc})
5924 This switch turns off all validity checking, including the default checking
5925 for case statements and left hand side subscripts. Note that the use of
5926 the switch @option{-gnatp} suppresses all run-time checks, including
5927 validity checks, and thus implies @option{-gnatVn}. When this switch
5928 is used, it cancels any other @option{-gnatV} previously issued.
5930 @item -gnatVo
5931 @emph{Validity checks for operator and attribute operands.}
5932 @cindex @option{-gnatVo} (@command{gcc})
5933 Arguments for predefined operators and attributes are validity checked.
5934 This includes all operators in package @code{Standard},
5935 the shift operators defined as intrinsic in package @code{Interfaces}
5936 and operands for attributes such as @code{Pos}. Checks are also made
5937 on individual component values for composite comparisons, and on the
5938 expressions in type conversions and qualified expressions. Checks are
5939 also made on explicit ranges using @samp{..} (e.g.@: slices, loops etc).
5941 @item -gnatVp
5942 @emph{Validity checks for parameters.}
5943 @cindex @option{-gnatVp} (@command{gcc})
5944 This controls the treatment of parameters within a subprogram (as opposed
5945 to @option{-gnatVi} and @option{-gnatVm} which control validity testing
5946 of parameters on a call. If either of these call options is used, then
5947 normally an assumption is made within a subprogram that the input arguments
5948 have been validity checking at the point of call, and do not need checking
5949 again within a subprogram). If @option{-gnatVp} is set, then this assumption
5950 is not made, and parameters are not assumed to be valid, so their validity
5951 will be checked (or rechecked) within the subprogram.
5953 @item -gnatVr
5954 @emph{Validity checks for function returns.}
5955 @cindex @option{-gnatVr} (@command{gcc})
5956 The expression in @code{return} statements in functions is validity
5957 checked.
5959 @item -gnatVs
5960 @emph{Validity checks for subscripts.}
5961 @cindex @option{-gnatVs} (@command{gcc})
5962 All subscripts expressions are checked for validity, whether they appear
5963 on the right side or left side (in default mode only left side subscripts
5964 are validity checked).
5966 @item -gnatVt
5967 @emph{Validity checks for tests.}
5968 @cindex @option{-gnatVt} (@command{gcc})
5969 Expressions used as conditions in @code{if}, @code{while} or @code{exit}
5970 statements are checked, as well as guard expressions in entry calls.
5972 @end table
5974 @noindent
5975 The @option{-gnatV} switch may be followed by
5976 ^a string of letters^a list of options^
5977 to turn on a series of validity checking options.
5978 For example,
5979 @option{^-gnatVcr^/VALIDITY_CHECKING=(COPIES, RETURNS)^}
5980 specifies that in addition to the default validity checking, copies and
5981 function return expressions are to be validity checked.
5982 In order to make it easier
5983 to specify the desired combination of effects,
5984 @ifclear vms
5985 the upper case letters @code{CDFIMORST} may
5986 be used to turn off the corresponding lower case option.
5987 @end ifclear
5988 @ifset vms
5989 the prefix @code{NO} on an option turns off the corresponding validity
5990 checking:
5991 @itemize @bullet
5992 @item @code{NOCOPIES}
5993 @item @code{NODEFAULT}
5994 @item @code{NOFLOATS}
5995 @item @code{NOIN_PARAMS}
5996 @item @code{NOMOD_PARAMS}
5997 @item @code{NOOPERANDS}
5998 @item @code{NORETURNS}
5999 @item @code{NOSUBSCRIPTS}
6000 @item @code{NOTESTS}
6001 @end itemize
6002 @end ifset
6003 Thus
6004 @option{^-gnatVaM^/VALIDITY_CHECKING=(ALL, NOMOD_PARAMS)^}
6005 turns on all validity checking options except for
6006 checking of @code{@b{in out}} procedure arguments.
6008 The specification of additional validity checking generates extra code (and
6009 in the case of @option{-gnatVa} the code expansion can be substantial).
6010 However, these additional checks can be very useful in detecting
6011 uninitialized variables, incorrect use of unchecked conversion, and other
6012 errors leading to invalid values. The use of pragma @code{Initialize_Scalars}
6013 is useful in conjunction with the extra validity checking, since this
6014 ensures that wherever possible uninitialized variables have invalid values.
6016 See also the pragma @code{Validity_Checks} which allows modification of
6017 the validity checking mode at the program source level, and also allows for
6018 temporary disabling of validity checks.
6020 @node Style Checking
6021 @subsection Style Checking
6022 @findex Style checking
6024 @noindent
6025 The @option{-gnaty^x^(option,option,@dots{})^} switch
6026 @cindex @option{-gnaty} (@command{gcc})
6027 causes the compiler to
6028 enforce specified style rules. A limited set of style rules has been used
6029 in writing the GNAT sources themselves. This switch allows user programs
6030 to activate all or some of these checks. If the source program fails a
6031 specified style check, an appropriate message is given, preceded by
6032 the character sequence ``(style)''. This message does not prevent
6033 successful compilation (unless the @option{-gnatwe} switch is used).
6035 Note that this is by no means intended to be a general facility for
6036 checking arbitrary coding standards. It is simply an embedding of the
6037 style rules we have chosen for the GNAT sources. If you are starting
6038 a project which does not have established style standards, you may
6039 find it useful to adopt the entire set of GNAT coding standards, or
6040 some subset of them. If you already have an established set of coding
6041 standards, then it may be that selected style checking options do
6042 indeed correspond to choices you have made, but for general checking
6043 of an existing set of coding rules, you should look to the gnatcheck
6044 tool, which is designed for that purpose.
6046 @ifset vms
6047 @code{(option,option,@dots{})} is a sequence of keywords
6048 @end ifset
6049 @ifclear vms
6050 The string @var{x} is a sequence of letters or digits
6051 @end ifclear
6052 indicating the particular style
6053 checks to be performed. The following checks are defined:
6055 @table @option
6056 @c !sort!
6057 @item 0-9
6058 @emph{Specify indentation level.}
6059 If a digit from 1-9 appears
6060 ^in the string after @option{-gnaty}^as an option for /STYLE_CHECKS^
6061 then proper indentation is checked, with the digit indicating the
6062 indentation level required. A value of zero turns off this style check.
6063 The general style of required indentation is as specified by
6064 the examples in the Ada Reference Manual. Full line comments must be
6065 aligned with the @code{--} starting on a column that is a multiple of
6066 the alignment level, or they may be aligned the same way as the following
6067 non-blank line (this is useful when full line comments appear in the middle
6068 of a statement, or they may be aligned with the source line on the previous
6069 non-blank line.
6071 @item ^a^ATTRIBUTE^
6072 @emph{Check attribute casing.}
6073 Attribute names, including the case of keywords such as @code{digits}
6074 used as attributes names, must be written in mixed case, that is, the
6075 initial letter and any letter following an underscore must be uppercase.
6076 All other letters must be lowercase.
6078 @item ^A^ARRAY_INDEXES^
6079 @emph{Use of array index numbers in array attributes.}
6080 When using the array attributes First, Last, Range,
6081 or Length, the index number must be omitted for one-dimensional arrays
6082 and is required for multi-dimensional arrays.
6084 @item ^b^BLANKS^
6085 @emph{Blanks not allowed at statement end.}
6086 Trailing blanks are not allowed at the end of statements. The purpose of this
6087 rule, together with h (no horizontal tabs), is to enforce a canonical format
6088 for the use of blanks to separate source tokens.
6090 @item ^B^BOOLEAN_OPERATORS^
6091 @emph{Check Boolean operators.}
6092 The use of AND/OR operators is not permitted except in the cases of modular
6093 operands, array operands, and simple stand-alone boolean variables or
6094 boolean constants. In all other cases @code{and then}/@code{or else} are
6095 required.
6097 @item ^c^COMMENTS^
6098 @emph{Check comments, double space.}
6099 Comments must meet the following set of rules:
6101 @itemize @bullet
6103 @item
6104 The ``@code{--}'' that starts the column must either start in column one,
6105 or else at least one blank must precede this sequence.
6107 @item
6108 Comments that follow other tokens on a line must have at least one blank
6109 following the ``@code{--}'' at the start of the comment.
6111 @item
6112 Full line comments must have at least two blanks following the
6113 ``@code{--}'' that starts the comment, with the following exceptions.
6115 @item
6116 A line consisting only of the ``@code{--}'' characters, possibly preceded
6117 by blanks is permitted.
6119 @item
6120 A comment starting with ``@code{--x}'' where @code{x} is a special character
6121 is permitted.
6122 This allows proper processing of the output generated by specialized tools
6123 including @command{gnatprep} (where ``@code{--!}'' is used) and the SPARK
6124 annotation
6125 language (where ``@code{--#}'' is used). For the purposes of this rule, a
6126 special character is defined as being in one of the ASCII ranges
6127 @code{16#21#@dots{}16#2F#} or @code{16#3A#@dots{}16#3F#}.
6128 Note that this usage is not permitted
6129 in GNAT implementation units (i.e., when @option{-gnatg} is used).
6131 @item
6132 A line consisting entirely of minus signs, possibly preceded by blanks, is
6133 permitted. This allows the construction of box comments where lines of minus
6134 signs are used to form the top and bottom of the box.
6136 @item
6137 A comment that starts and ends with ``@code{--}'' is permitted as long as at
6138 least one blank follows the initial ``@code{--}''. Together with the preceding
6139 rule, this allows the construction of box comments, as shown in the following
6140 example:
6141 @smallexample
6142 ---------------------------
6143 -- This is a box comment --
6144 -- with two text lines.  --
6145 ---------------------------
6146 @end smallexample
6147 @end itemize
6149 @item ^C^COMMENTS1^
6150 @emph{Check comments, single space.}
6151 This is identical to @code{^c^COMMENTS^} except that only one space
6152 is required following the @code{--} of a comment instead of two.
6154 @item ^d^DOS_LINE_ENDINGS^
6155 @emph{Check no DOS line terminators present.}
6156 All lines must be terminated by a single ASCII.LF
6157 character (in particular the DOS line terminator sequence CR/LF is not
6158 allowed).
6160 @item ^e^END^
6161 @emph{Check end/exit labels.}
6162 Optional labels on @code{end} statements ending subprograms and on
6163 @code{exit} statements exiting named loops, are required to be present.
6165 @item ^f^VTABS^
6166 @emph{No form feeds or vertical tabs.}
6167 Neither form feeds nor vertical tab characters are permitted
6168 in the source text.
6170 @item ^g^GNAT^
6171 @emph{GNAT style mode.}
6172 The set of style check switches is set to match that used by the GNAT sources.
6173 This may be useful when developing code that is eventually intended to be
6174 incorporated into GNAT. For further details, see GNAT sources.
6176 @item ^h^HTABS^
6177 @emph{No horizontal tabs.}
6178 Horizontal tab characters are not permitted in the source text.
6179 Together with the b (no blanks at end of line) check, this
6180 enforces a canonical form for the use of blanks to separate
6181 source tokens.
6183 @item ^i^IF_THEN^
6184 @emph{Check if-then layout.}
6185 The keyword @code{then} must appear either on the same
6186 line as corresponding @code{if}, or on a line on its own, lined
6187 up under the @code{if} with at least one non-blank line in between
6188 containing all or part of the condition to be tested.
6190 @item ^I^IN_MODE^
6191 @emph{check mode IN keywords.}
6192 Mode @code{in} (the default mode) is not
6193 allowed to be given explicitly. @code{in out} is fine,
6194 but not @code{in} on its own.
6196 @item ^k^KEYWORD^
6197 @emph{Check keyword casing.}
6198 All keywords must be in lower case (with the exception of keywords
6199 such as @code{digits} used as attribute names to which this check
6200 does not apply).
6202 @item ^l^LAYOUT^
6203 @emph{Check layout.}
6204 Layout of statement and declaration constructs must follow the
6205 recommendations in the Ada Reference Manual, as indicated by the
6206 form of the syntax rules. For example an @code{else} keyword must
6207 be lined up with the corresponding @code{if} keyword.
6209 There are two respects in which the style rule enforced by this check
6210 option are more liberal than those in the Ada Reference Manual. First
6211 in the case of record declarations, it is permissible to put the
6212 @code{record} keyword on the same line as the @code{type} keyword, and
6213 then the @code{end} in @code{end record} must line up under @code{type}.
6214 This is also permitted when the type declaration is split on two lines.
6215 For example, any of the following three layouts is acceptable:
6217 @smallexample @c ada
6218 @cartouche
6219 type q is record
6220    a : integer;
6221    b : integer;
6222 end record;
6224 type q is
6225    record
6226       a : integer;
6227       b : integer;
6228    end record;
6230 type q is
6231    record
6232       a : integer;
6233       b : integer;
6234 end record;
6236 @end cartouche
6237 @end smallexample
6239 @noindent
6240 Second, in the case of a block statement, a permitted alternative
6241 is to put the block label on the same line as the @code{declare} or
6242 @code{begin} keyword, and then line the @code{end} keyword up under
6243 the block label. For example both the following are permitted:
6245 @smallexample @c ada
6246 @cartouche
6247 Block : declare
6248    A : Integer := 3;
6249 begin
6250    Proc (A, A);
6251 end Block;
6253 Block :
6254    declare
6255       A : Integer := 3;
6256    begin
6257       Proc (A, A);
6258    end Block;
6259 @end cartouche
6260 @end smallexample
6262 @noindent
6263 The same alternative format is allowed for loops. For example, both of
6264 the following are permitted:
6266 @smallexample @c ada
6267 @cartouche
6268 Clear : while J < 10 loop
6269    A (J) := 0;
6270 end loop Clear;
6272 Clear :
6273    while J < 10 loop
6274       A (J) := 0;
6275    end loop Clear;
6276 @end cartouche
6277 @end smallexample
6279 @item ^Lnnn^MAX_NESTING=nnn^
6280 @emph{Set maximum nesting level.}
6281 The maximum level of nesting of constructs (including subprograms, loops,
6282 blocks, packages, and conditionals) may not exceed the given value
6283 @option{nnn}. A value of zero disconnects this style check.
6285 @item ^m^LINE_LENGTH^
6286 @emph{Check maximum line length.}
6287 The length of source lines must not exceed 79 characters, including
6288 any trailing blanks. The value of 79 allows convenient display on an
6289 80 character wide device or window, allowing for possible special
6290 treatment of 80 character lines. Note that this count is of
6291 characters in the source text. This means that a tab character counts
6292 as one character in this count and a wide character sequence counts as
6293 a single character (however many bytes are needed in the encoding).
6295 @item ^Mnnn^MAX_LENGTH=nnn^
6296 @emph{Set maximum line length.}
6297 The length of lines must not exceed the
6298 given value @option{nnn}. The maximum value that can be specified is 32767.
6299 If neither style option for setting the line length is used, then the
6300 default is 255. This also controls the maximum length of lexical elements,
6301 where the only restriction is that they must fit on a single line.
6303 @item ^n^STANDARD_CASING^
6304 @emph{Check casing of entities in Standard.}
6305 Any identifier from Standard must be cased
6306 to match the presentation in the Ada Reference Manual (for example,
6307 @code{Integer} and @code{ASCII.NUL}).
6309 @item ^N^NONE^
6310 @emph{Turn off all style checks.}
6311 All style check options are turned off.
6313 @item ^o^ORDERED_SUBPROGRAMS^
6314 @emph{Check order of subprogram bodies.}
6315 All subprogram bodies in a given scope
6316 (e.g.@: a package body) must be in alphabetical order. The ordering
6317 rule uses normal Ada rules for comparing strings, ignoring casing
6318 of letters, except that if there is a trailing numeric suffix, then
6319 the value of this suffix is used in the ordering (e.g.@: Junk2 comes
6320 before Junk10).
6322 @item ^O^OVERRIDING_INDICATORS^
6323 @emph{Check that overriding subprograms are explicitly marked as such.}
6324 The declaration of a primitive operation of a type extension that overrides
6325 an inherited operation must carry an overriding indicator.
6327 @item ^p^PRAGMA^
6328 @emph{Check pragma casing.}
6329 Pragma names must be written in mixed case, that is, the
6330 initial letter and any letter following an underscore must be uppercase.
6331 All other letters must be lowercase.
6333 @item ^r^REFERENCES^
6334 @emph{Check references.}
6335 All identifier references must be cased in the same way as the
6336 corresponding declaration. No specific casing style is imposed on
6337 identifiers. The only requirement is for consistency of references
6338 with declarations.
6340 @item ^s^SPECS^
6341 @emph{Check separate specs.}
6342 Separate declarations (``specs'') are required for subprograms (a
6343 body is not allowed to serve as its own declaration). The only
6344 exception is that parameterless library level procedures are
6345 not required to have a separate declaration. This exception covers
6346 the most frequent form of main program procedures.
6348 @item ^S^STATEMENTS_AFTER_THEN_ELSE^
6349 @emph{Check no statements after @code{then}/@code{else}.}
6350 No statements are allowed
6351 on the same line as a @code{then} or @code{else} keyword following the
6352 keyword in an @code{if} statement. @code{or else} and @code{and then} are not
6353 affected, and a special exception allows a pragma to appear after @code{else}.
6355 @item ^t^TOKEN^
6356 @emph{Check token spacing.}
6357 The following token spacing rules are enforced:
6359 @itemize @bullet
6361 @item
6362 The keywords @code{abs} and @code{not} must be followed by a space.
6364 @item
6365 The token @code{=>} must be surrounded by spaces.
6367 @item
6368 The token @code{<>} must be preceded by a space or a left parenthesis.
6370 @item
6371 Binary operators other than @code{**} must be surrounded by spaces.
6372 There is no restriction on the layout of the @code{**} binary operator.
6374 @item
6375 Colon must be surrounded by spaces.
6377 @item
6378 Colon-equal (assignment, initialization) must be surrounded by spaces.
6380 @item
6381 Comma must be the first non-blank character on the line, or be
6382 immediately preceded by a non-blank character, and must be followed
6383 by a space.
6385 @item
6386 If the token preceding a left parenthesis ends with a letter or digit, then
6387 a space must separate the two tokens.
6389 @item
6390 if the token following a right parenthesis starts with a letter or digit, then
6391 a space must separate the two tokens.
6393 @item
6394 A right parenthesis must either be the first non-blank character on
6395 a line, or it must be preceded by a non-blank character.
6397 @item
6398 A semicolon must not be preceded by a space, and must not be followed by
6399 a non-blank character.
6401 @item
6402 A unary plus or minus may not be followed by a space.
6404 @item
6405 A vertical bar must be surrounded by spaces.
6406 @end itemize
6408 @item
6409 Exactly one blank (and no other white space) must appear between
6410 a @code{not} token and a following @code{in} token.
6412 @item ^u^UNNECESSARY_BLANK_LINES^
6413 @emph{Check unnecessary blank lines.}
6414 Unnecessary blank lines are not allowed. A blank line is considered
6415 unnecessary if it appears at the end of the file, or if more than
6416 one blank line occurs in sequence.
6418 @item ^x^XTRA_PARENS^
6419 @emph{Check extra parentheses.}
6420 Unnecessary extra level of parentheses (C-style) are not allowed
6421 around conditions in @code{if} statements, @code{while} statements and
6422 @code{exit} statements.
6424 @item ^y^ALL_BUILTIN^
6425 @emph{Set all standard style check options}
6426 This is equivalent to @code{gnaty3aAbcefhiklmnprst}, that is all checking
6427 options enabled with the exception of @option{-gnatyB}, @option{-gnatyd},
6428 @option{-gnatyI}, @option{-gnatyLnnn}, @option{-gnatyo}, @option{-gnatyO},
6429 @option{-gnatyS}, @option{-gnatyu}, and @option{-gnatyx}.
6431 @ifclear vms
6432 @item -
6433 @emph{Remove style check options}
6434 This causes any subsequent options in the string to act as canceling the
6435 corresponding style check option. To cancel maximum nesting level control,
6436 use @option{L} parameter witout any integer value after that, because any
6437 digit following @option{-} in the parameter string of the @option{-gnaty}
6438 option will be threated as canceling indentation check. The same is true
6439 for @option{M} parameter. @option{y} and @option{N} parameters are not
6440 allowed after @option{-}.
6442 @item +
6443 This causes any subsequent options in the string to enable the corresponding
6444 style check option. That is, it cancels the effect of a previous ^-^REMOVE^,
6445 if any.
6446 @end ifclear
6448 @ifset vms
6449 @item NOxxx
6450 @emph{Removing style check options}
6451 If the name of a style check is preceded by @option{NO} then the corresponding
6452 style check is turned off. For example @option{NOCOMMENTS} turns off style
6453 checking for comments.
6454 @end ifset
6455 @end table
6457 @noindent
6458 In the above rules, appearing in column one is always permitted, that is,
6459 counts as meeting either a requirement for a required preceding space,
6460 or as meeting a requirement for no preceding space.
6462 Appearing at the end of a line is also always permitted, that is, counts
6463 as meeting either a requirement for a following space, or as meeting
6464 a requirement for no following space.
6466 @noindent
6467 If any of these style rules is violated, a message is generated giving
6468 details on the violation. The initial characters of such messages are
6469 always ``@code{(style)}''. Note that these messages are treated as warning
6470 messages, so they normally do not prevent the generation of an object
6471 file. The @option{-gnatwe} switch can be used to treat warning messages,
6472 including style messages, as fatal errors.
6474 The switch
6475 @ifclear vms
6476 @option{-gnaty} on its own (that is not
6477 followed by any letters or digits) is equivalent
6478 to the use of @option{-gnatyy} as described above, that is all
6479 built-in standard style check options are enabled.
6481 @end ifclear
6482 @ifset vms
6483 /STYLE_CHECKS=ALL_BUILTIN enables all checking options with
6484 the exception of ORDERED_SUBPROGRAMS, UNNECESSARY_BLANK_LINES,
6485 XTRA_PARENS, and DOS_LINE_ENDINGS. In addition
6486 @end ifset
6488 The switch
6489 @ifclear vms
6490 @option{-gnatyN}
6491 @end ifclear
6492 @ifset vms
6493 /STYLE_CHECKS=NONE
6494 @end ifset
6495 clears any previously set style checks.
6497 @node Run-Time Checks
6498 @subsection Run-Time Checks
6499 @cindex Division by zero
6500 @cindex Access before elaboration
6501 @cindex Checks, division by zero
6502 @cindex Checks, access before elaboration
6503 @cindex Checks, stack overflow checking
6505 @noindent
6506 By default, the following checks are suppressed: integer overflow
6507 checks, stack overflow checks, and checks for access before
6508 elaboration on subprogram calls. All other checks, including range
6509 checks and array bounds checks, are turned on by default. The
6510 following @command{gcc} switches refine this default behavior.
6512 @table @option
6513 @c !sort!
6514 @item -gnatp
6515 @cindex @option{-gnatp} (@command{gcc})
6516 @cindex Suppressing checks
6517 @cindex Checks, suppressing
6518 @findex Suppress
6519 This switch causes the unit to be compiled
6520 as though @code{pragma Suppress (All_checks)}
6521 had been present in the source. Validity checks are also eliminated (in
6522 other words @option{-gnatp} also implies @option{-gnatVn}.
6523 Use this switch to improve the performance
6524 of the code at the expense of safety in the presence of invalid data or
6525 program bugs.
6527 Note that when checks are suppressed, the compiler is allowed, but not
6528 required, to omit the checking code. If the run-time cost of the
6529 checking code is zero or near-zero, the compiler will generate it even
6530 if checks are suppressed. In particular, if the compiler can prove
6531 that a certain check will necessarily fail, it will generate code to
6532 do an unconditional ``raise'', even if checks are suppressed. The
6533 compiler warns in this case. Another case in which checks may not be
6534 eliminated is when they are embedded in certain run time routines such
6535 as math library routines.
6537 Of course, run-time checks are omitted whenever the compiler can prove
6538 that they will not fail, whether or not checks are suppressed.
6540 Note that if you suppress a check that would have failed, program
6541 execution is erroneous, which means the behavior is totally
6542 unpredictable. The program might crash, or print wrong answers, or
6543 do anything else. It might even do exactly what you wanted it to do
6544 (and then it might start failing mysteriously next week or next
6545 year). The compiler will generate code based on the assumption that
6546 the condition being checked is true, which can result in disaster if
6547 that assumption is wrong.
6549 The checks subject to suppression include all the checks defined by
6550 the Ada standard, the additional implementation defined checks
6551 @code{Alignment_Check}, @code{Atomic_Synchronization}, and
6552 @code{Validity_Check}, as well as any checks introduced using
6553 @code{pragma Check_Name}.
6555 The @option{-gnatp} switch has no effect if a subsequent
6556 @option{-gnat-p} switch appears.
6558 @item -gnat-p
6559 @cindex @option{-gnat-p} (@command{gcc})
6560 @cindex Suppressing checks
6561 @cindex Checks, suppressing
6562 @findex Suppress
6563 This switch cancels the effect of a previous @option{gnatp} switch.
6565 @item -gnato??
6566 @cindex @option{-gnato??} (@command{gcc})
6567 @cindex Overflow checks
6568 @cindex Overflow mode
6569 @cindex Check, overflow
6570 This switch controls the mode used for computing intermediate
6571 arithmetic integer operations, and also enables overflow checking.
6572 For a full description of overflow mode and checking control, see
6573 the ``Overflow Check Handling in GNAT'' appendix in this
6574 User's Guide.
6576 Overflow checks are always enabled by this switch. The argument
6577 controls the mode, using the codes
6579 @itemize
6580 @item 1 = STRICT
6581 In STRICT mode, intermediate operations are always done using the
6582 base type, and overflow checking ensures that the result is within
6583 the base type range.
6585 @item 2 = MINIMIZED
6586 In MINIMIZED mode, overflows in intermediate operations are avoided
6587 where possible by using a larger integer type for the computation
6588 (typically @code{Long_Long_Integer}). Overflow checking ensures that
6589 the result fits in this larger integer type.
6591 @item 3 = ELIMINATED
6592 In ELIMINATED mode, overflows in intermediate operations are avoided
6593 by using multi-precision arithmetic. In this case, overflow checking
6594 has no effect on intermediate operations (since overflow is impossible).
6595 @end itemize
6597 If two digits are present after @option{-gnato} then the first digit
6598 sets the mode for expressions outside assertions, and the second digit
6599 sets the mode for expressions within assertions. Here assertions is used
6600 in the technical sense (which includes for example precondition and
6601 postcondition expressions).
6603 If one digit is present, the corresponding mode is applicable to both
6604 expressions within and outside assertion expressions.
6606 If no digits are present, the default is to enable overflow checks
6607 and set STRICT mode for both kinds of expressions. This is compatible
6608 with the use of @option{-gnato} in previous versions of GNAT.
6610 @findex Machine_Overflows
6611 Note that the @option{-gnato??} switch does not affect the code generated
6612 for any floating-point operations; it applies only to integer semantics.
6613 For floating-point, @value{EDITION} has the @code{Machine_Overflows}
6614 attribute set to @code{False} and the normal mode of operation is to
6615 generate IEEE NaN and infinite values on overflow or invalid operations
6616 (such as dividing 0.0 by 0.0).
6618 The reason that we distinguish overflow checking from other kinds of
6619 range constraint checking is that a failure of an overflow check, unlike
6620 for example the failure of a range check, can result in an incorrect
6621 value, but cannot cause random memory destruction (like an out of range
6622 subscript), or a wild jump (from an out of range case value). Overflow
6623 checking is also quite expensive in time and space, since in general it
6624 requires the use of double length arithmetic.
6626 Note again that the default is @option{^-gnato00^/OVERFLOW_CHECKS=00^},
6627 so overflow checking is not performed in default mode. This means that out of
6628 the box, with the default settings, @value{EDITION} does not do all the checks
6629 expected from the language description in the Ada Reference Manual.
6630 If you want all constraint checks to be performed, as described in this Manual,
6631 then you must explicitly use the @option{-gnato??}
6632 switch either on the @command{gnatmake} or @command{gcc} command.
6634 @item -gnatE
6635 @cindex @option{-gnatE} (@command{gcc})
6636 @cindex Elaboration checks
6637 @cindex Check, elaboration
6638 Enables dynamic checks for access-before-elaboration
6639 on subprogram calls and generic instantiations.
6640 Note that @option{-gnatE} is not necessary for safety, because in the
6641 default mode, GNAT ensures statically that the checks would not fail.
6642 For full details of the effect and use of this switch,
6643 @xref{Compiling with gcc}.
6645 @item -fstack-check
6646 @cindex @option{-fstack-check} (@command{gcc})
6647 @cindex Stack Overflow Checking
6648 @cindex Checks, stack overflow checking
6649 Activates stack overflow checking. For full details of the effect and use of
6650 this switch see @ref{Stack Overflow Checking}.
6651 @end table
6653 @findex Unsuppress
6654 @noindent
6655 The setting of these switches only controls the default setting of the
6656 checks. You may modify them using either @code{Suppress} (to remove
6657 checks) or @code{Unsuppress} (to add back suppressed checks) pragmas in
6658 the program source.
6660 @node Using gcc for Syntax Checking
6661 @subsection Using @command{gcc} for Syntax Checking
6662 @table @option
6663 @item -gnats
6664 @cindex @option{-gnats} (@command{gcc})
6665 @ifclear vms
6667 @noindent
6668 The @code{s} stands for ``syntax''.
6669 @end ifclear
6671 Run GNAT in syntax checking only mode. For
6672 example, the command
6674 @smallexample
6675 $ gcc -c -gnats x.adb
6676 @end smallexample
6678 @noindent
6679 compiles file @file{x.adb} in syntax-check-only mode. You can check a
6680 series of files in a single command
6681 @ifclear vms
6682 , and can use wild cards to specify such a group of files.
6683 Note that you must specify the @option{-c} (compile
6684 only) flag in addition to the @option{-gnats} flag.
6685 @end ifclear
6687 You may use other switches in conjunction with @option{-gnats}. In
6688 particular, @option{-gnatl} and @option{-gnatv} are useful to control the
6689 format of any generated error messages.
6691 When the source file is empty or contains only empty lines and/or comments,
6692 the output is a warning:
6694 @smallexample
6695 $ gcc -c -gnats -x ada toto.txt
6696 toto.txt:1:01: warning: empty file, contains no compilation units
6698 @end smallexample
6700 Otherwise, the output is simply the error messages, if any. No object file or
6701 ALI file is generated by a syntax-only compilation. Also, no units other
6702 than the one specified are accessed. For example, if a unit @code{X}
6703 @code{with}'s a unit @code{Y}, compiling unit @code{X} in syntax
6704 check only mode does not access the source file containing unit
6705 @code{Y}.
6707 @cindex Multiple units, syntax checking
6708 Normally, GNAT allows only a single unit in a source file. However, this
6709 restriction does not apply in syntax-check-only mode, and it is possible
6710 to check a file containing multiple compilation units concatenated
6711 together. This is primarily used by the @code{gnatchop} utility
6712 (@pxref{Renaming Files with gnatchop}).
6713 @end table
6715 @node Using gcc for Semantic Checking
6716 @subsection Using @command{gcc} for Semantic Checking
6717 @table @option
6718 @item -gnatc
6719 @cindex @option{-gnatc} (@command{gcc})
6721 @ifclear vms
6722 @noindent
6723 The @code{c} stands for ``check''.
6724 @end ifclear
6725 Causes the compiler to operate in semantic check mode,
6726 with full checking for all illegalities specified in the
6727 Ada Reference Manual, but without generation of any object code
6728 (no object file is generated).
6730 Because dependent files must be accessed, you must follow the GNAT
6731 semantic restrictions on file structuring to operate in this mode:
6733 @itemize @bullet
6734 @item
6735 The needed source files must be accessible
6736 (@pxref{Search Paths and the Run-Time Library (RTL)}).
6738 @item
6739 Each file must contain only one compilation unit.
6741 @item
6742 The file name and unit name must match (@pxref{File Naming Rules}).
6743 @end itemize
6745 The output consists of error messages as appropriate. No object file is
6746 generated. An @file{ALI} file is generated for use in the context of
6747 cross-reference tools, but this file is marked as not being suitable
6748 for binding (since no object file is generated).
6749 The checking corresponds exactly to the notion of
6750 legality in the Ada Reference Manual.
6752 Any unit can be compiled in semantics-checking-only mode, including
6753 units that would not normally be compiled (subunits,
6754 and specifications where a separate body is present).
6755 @end table
6757 @node Compiling Different Versions of Ada
6758 @subsection Compiling Different Versions of Ada
6760 @noindent
6761 The switches described in this section allow you to explicitly specify
6762 the version of the Ada language that your programs are written in.
6763 The default mode is Ada 2012,
6764 but you can also specify Ada 95, Ada 2005 mode, or
6765 indicate Ada 83 compatibility mode.
6767 @table @option
6768 @cindex Compatibility with Ada 83
6770 @item -gnat83 (Ada 83 Compatibility Mode)
6771 @cindex @option{-gnat83} (@command{gcc})
6772 @cindex ACVC, Ada 83 tests
6773 @cindex Ada 83 mode
6775 @noindent
6776 Although GNAT is primarily an Ada 95 / Ada 2005 compiler, this switch
6777 specifies that the program is to be compiled in Ada 83 mode. With
6778 @option{-gnat83}, GNAT rejects most post-Ada 83 extensions and applies Ada 83
6779 semantics where this can be done easily.
6780 It is not possible to guarantee this switch does a perfect
6781 job; some subtle tests, such as are
6782 found in earlier ACVC tests (and that have been removed from the ACATS suite
6783 for Ada 95), might not compile correctly.
6784 Nevertheless, this switch may be useful in some circumstances, for example
6785 where, due to contractual reasons, existing code needs to be maintained
6786 using only Ada 83 features.
6788 With few exceptions (most notably the need to use @code{<>} on
6789 @cindex Generic formal parameters
6790 unconstrained generic formal parameters, the use of the new Ada 95 / Ada 2005
6791 reserved words, and the use of packages
6792 with optional bodies), it is not necessary to specify the
6793 @option{-gnat83} switch when compiling Ada 83 programs, because, with rare
6794 exceptions, Ada 95 and Ada 2005 are upwardly compatible with Ada 83. Thus
6795 a correct Ada 83 program is usually also a correct program
6796 in these later versions of the language standard.
6797 For further information, please refer to @ref{Compatibility and Porting Guide}.
6799 @item -gnat95 (Ada 95 mode)
6800 @cindex @option{-gnat95} (@command{gcc})
6801 @cindex Ada 95 mode
6803 @noindent
6804 This switch directs the compiler to implement the Ada 95 version of the
6805 language.
6806 Since Ada 95 is almost completely upwards
6807 compatible with Ada 83, Ada 83 programs may generally be compiled using
6808 this switch (see the description of the @option{-gnat83} switch for further
6809 information about Ada 83 mode).
6810 If an Ada 2005 program is compiled in Ada 95 mode,
6811 uses of the new Ada 2005 features will cause error
6812 messages or warnings.
6814 This switch also can be used to cancel the effect of a previous
6815 @option{-gnat83}, @option{-gnat05/2005}, or @option{-gnat12/2012}
6816 switch earlier in the command line.
6818 @item -gnat05 or -gnat2005 (Ada 2005 mode)
6819 @cindex @option{-gnat05} (@command{gcc})
6820 @cindex @option{-gnat2005} (@command{gcc})
6821 @cindex Ada 2005 mode
6823 @noindent
6824 This switch directs the compiler to implement the Ada 2005 version of the
6825 language, as documented in the official Ada standards document.
6826 Since Ada 2005 is almost completely upwards
6827 compatible with Ada 95 (and thus also with Ada 83), Ada 83 and Ada 95 programs
6828 may generally be compiled using this switch (see the description of the
6829 @option{-gnat83} and @option{-gnat95} switches for further
6830 information).
6832 @item -gnat12 or -gnat2012 (Ada 2012 mode)
6833 @cindex @option{-gnat12} (@command{gcc})
6834 @cindex @option{-gnat2012} (@command{gcc})
6835 @cindex Ada 2012 mode
6837 @noindent
6838 This switch directs the compiler to implement the Ada 2012 version of the
6839 language (also the default).
6840 Since Ada 2012 is almost completely upwards
6841 compatible with Ada 2005 (and thus also with Ada 83, and Ada 95),
6842 Ada 83 and Ada 95 programs
6843 may generally be compiled using this switch (see the description of the
6844 @option{-gnat83}, @option{-gnat95}, and @option{-gnat05/2005} switches
6845 for further information).
6847 @item -gnatX (Enable GNAT Extensions)
6848 @cindex @option{-gnatX} (@command{gcc})
6849 @cindex Ada language extensions
6850 @cindex GNAT extensions
6852 @noindent
6853 This switch directs the compiler to implement the latest version of the
6854 language (currently Ada 2012) and also to enable certain GNAT implementation
6855 extensions that are not part of any Ada standard. For a full list of these
6856 extensions, see the GNAT reference manual.
6858 @end table
6860 @node Character Set Control
6861 @subsection Character Set Control
6862 @table @option
6863 @item ^-gnati^/IDENTIFIER_CHARACTER_SET=^@var{c}
6864 @cindex @option{^-gnati^/IDENTIFIER_CHARACTER_SET^} (@command{gcc})
6866 @noindent
6867 Normally GNAT recognizes the Latin-1 character set in source program
6868 identifiers, as described in the Ada Reference Manual.
6869 This switch causes
6870 GNAT to recognize alternate character sets in identifiers. @var{c} is a
6871 single character ^^or word^ indicating the character set, as follows:
6873 @table @code
6874 @item 1
6875 ISO 8859-1 (Latin-1) identifiers
6877 @item 2
6878 ISO 8859-2 (Latin-2) letters allowed in identifiers
6880 @item 3
6881 ISO 8859-3 (Latin-3) letters allowed in identifiers
6883 @item 4
6884 ISO 8859-4 (Latin-4) letters allowed in identifiers
6886 @item 5
6887 ISO 8859-5 (Cyrillic) letters allowed in identifiers
6889 @item 9
6890 ISO 8859-15 (Latin-9) letters allowed in identifiers
6892 @item ^p^PC^
6893 IBM PC letters (code page 437) allowed in identifiers
6895 @item ^8^PC850^
6896 IBM PC letters (code page 850) allowed in identifiers
6898 @item ^f^FULL_UPPER^
6899 Full upper-half codes allowed in identifiers
6901 @item ^n^NO_UPPER^
6902 No upper-half codes allowed in identifiers
6904 @item ^w^WIDE^
6905 Wide-character codes (that is, codes greater than 255)
6906 allowed in identifiers
6907 @end table
6909 @xref{Foreign Language Representation}, for full details on the
6910 implementation of these character sets.
6912 @item ^-gnatW^/WIDE_CHARACTER_ENCODING=^@var{e}
6913 @cindex @option{^-gnatW^/WIDE_CHARACTER_ENCODING^} (@command{gcc})
6914 Specify the method of encoding for wide characters.
6915 @var{e} is one of the following:
6917 @table @code
6919 @item ^h^HEX^
6920 Hex encoding (brackets coding also recognized)
6922 @item ^u^UPPER^
6923 Upper half encoding (brackets encoding also recognized)
6925 @item ^s^SHIFT_JIS^
6926 Shift/JIS encoding (brackets encoding also recognized)
6928 @item ^e^EUC^
6929 EUC encoding (brackets encoding also recognized)
6931 @item ^8^UTF8^
6932 UTF-8 encoding (brackets encoding also recognized)
6934 @item ^b^BRACKETS^
6935 Brackets encoding only (default value)
6936 @end table
6937 For full details on these encoding
6938 methods see @ref{Wide Character Encodings}.
6939 Note that brackets coding is always accepted, even if one of the other
6940 options is specified, so for example @option{-gnatW8} specifies that both
6941 brackets and UTF-8 encodings will be recognized. The units that are
6942 with'ed directly or indirectly will be scanned using the specified
6943 representation scheme, and so if one of the non-brackets scheme is
6944 used, it must be used consistently throughout the program. However,
6945 since brackets encoding is always recognized, it may be conveniently
6946 used in standard libraries, allowing these libraries to be used with
6947 any of the available coding schemes.
6949 Note that brackets encoding only applies to program text. Within comments,
6950 brackets are considered to be normal graphic characters, and bracket sequences
6951 are never recognized as wide characters.
6953 If no @option{-gnatW?} parameter is present, then the default
6954 representation is normally Brackets encoding only. However, if the
6955 first three characters of the file are 16#EF# 16#BB# 16#BF# (the standard
6956 byte order mark or BOM for UTF-8), then these three characters are
6957 skipped and the default representation for the file is set to UTF-8.
6959 Note that the wide character representation that is specified (explicitly
6960 or by default) for the main program also acts as the default encoding used
6961 for Wide_Text_IO files if not specifically overridden by a WCEM form
6962 parameter.
6964 @end table
6966 When no @option{-gnatW?} is specified, then characters (other than wide
6967 characters represented using brackets notation) are treated as 8-bit
6968 Latin-1 codes. The codes recognized are the Latin-1 graphic characters,
6969 and ASCII format effectors (CR, LF, HT, VT). Other lower half control
6970 characters in the range 16#00#..16#1F# are not accepted in program text
6971 or in comments. Upper half control characters (16#80#..16#9F#) are rejected
6972 in program text, but allowed and ignored in comments. Note in particular
6973 that the Next Line (NEL) character whose encoding is 16#85# is not recognized
6974 as an end of line in this default mode. If your source program contains
6975 instances of the NEL character used as a line terminator,
6976 you must use UTF-8 encoding for the whole
6977 source program. In default mode, all lines must be ended by a standard
6978 end of line sequence (CR, CR/LF, or LF).
6980 Note that the convention of simply accepting all upper half characters in
6981 comments means that programs that use standard ASCII for program text, but
6982 UTF-8 encoding for comments are accepted in default mode, providing that the
6983 comments are ended by an appropriate (CR, or CR/LF, or LF) line terminator.
6984 This is a common mode for many programs with foreign language comments.
6986 @node File Naming Control
6987 @subsection File Naming Control
6989 @table @option
6990 @item ^-gnatk^/FILE_NAME_MAX_LENGTH=^@var{n}
6991 @cindex @option{-gnatk} (@command{gcc})
6992 Activates file name ``krunching''. @var{n}, a decimal integer in the range
6993 1-999, indicates the maximum allowable length of a file name (not
6994 including the @file{.ads} or @file{.adb} extension). The default is not
6995 to enable file name krunching.
6997 For the source file naming rules, @xref{File Naming Rules}.
6998 @end table
7000 @node Subprogram Inlining Control
7001 @subsection Subprogram Inlining Control
7003 @table @option
7004 @c !sort!
7005 @item -gnatn[12]
7006 @cindex @option{-gnatn} (@command{gcc})
7007 @ifclear vms
7008 The @code{n} here is intended to suggest the first syllable of the
7009 word ``inline''.
7010 @end ifclear
7011 GNAT recognizes and processes @code{Inline} pragmas. However, for the
7012 inlining to actually occur, optimization must be enabled and, in order
7013 to enable inlining of subprograms specified by pragma @code{Inline},
7014 you must also specify this switch.
7015 In the absence of this switch, GNAT does not attempt
7016 inlining and does not need to access the bodies of
7017 subprograms for which @code{pragma Inline} is specified if they are not
7018 in the current unit.
7020 You can optionally specify the inlining level: 1 for moderate inlining across
7021 modules, which is a good compromise between compilation times and performances
7022 at run time, or 2 for full inlining across modules, which may bring about
7023 longer compilation times. If no inlining level is specified, the compiler will
7024 pick it based on the optimization level: 1 for @option{-O1}, @option{-O2} or
7025 @option{-Os} and 2 for @option{-O3}.
7027 If you specify this switch the compiler will access these bodies,
7028 creating an extra source dependency for the resulting object file, and
7029 where possible, the call will be inlined.
7030 For further details on when inlining is possible
7031 see @ref{Inlining of Subprograms}.
7033 @item -gnatN
7034 @cindex @option{-gnatN} (@command{gcc})
7035 This switch activates front-end inlining which also
7036 generates additional dependencies.
7038 When using a gcc-based back end (in practice this means using any version
7039 of GNAT other than the JGNAT, .NET or GNAAMP versions), then the use of
7040 @option{-gnatN} is deprecated, and the use of @option{-gnatn} is preferred.
7041 Historically front end inlining was more extensive than the gcc back end
7042 inlining, but that is no longer the case.
7043 @end table
7045 @node Auxiliary Output Control
7046 @subsection Auxiliary Output Control
7048 @table @option
7049 @item -gnatt
7050 @cindex @option{-gnatt} (@command{gcc})
7051 @cindex Writing internal trees
7052 @cindex Internal trees, writing to file
7053 Causes GNAT to write the internal tree for a unit to a file (with the
7054 extension @file{.adt}.
7055 This not normally required, but is used by separate analysis tools.
7056 Typically
7057 these tools do the necessary compilations automatically, so you should
7058 not have to specify this switch in normal operation.
7059 Note that the combination of switches @option{-gnatct}
7060 generates a tree in the form required by ASIS applications.
7062 @item -gnatu
7063 @cindex @option{-gnatu} (@command{gcc})
7064 Print a list of units required by this compilation on @file{stdout}.
7065 The listing includes all units on which the unit being compiled depends
7066 either directly or indirectly.
7068 @ifclear vms
7069 @item -pass-exit-codes
7070 @cindex @option{-pass-exit-codes} (@command{gcc})
7071 If this switch is not used, the exit code returned by @command{gcc} when
7072 compiling multiple files indicates whether all source files have
7073 been successfully used to generate object files or not.
7075 When @option{-pass-exit-codes} is used, @command{gcc} exits with an extended
7076 exit status and allows an integrated development environment to better
7077 react to a compilation failure. Those exit status are:
7079 @table @asis
7080 @item 5
7081 There was an error in at least one source file.
7082 @item 3
7083 At least one source file did not generate an object file.
7084 @item 2
7085 The compiler died unexpectedly (internal error for example).
7086 @item 0
7087 An object file has been generated for every source file.
7088 @end table
7089 @end ifclear
7090 @end table
7092 @node Debugging Control
7093 @subsection Debugging Control
7095 @table @option
7096 @c !sort!
7097 @cindex Debugging options
7098 @ifclear vms
7099 @item -gnatd@var{x}
7100 @cindex @option{-gnatd} (@command{gcc})
7101 Activate internal debugging switches. @var{x} is a letter or digit, or
7102 string of letters or digits, which specifies the type of debugging
7103 outputs desired. Normally these are used only for internal development
7104 or system debugging purposes. You can find full documentation for these
7105 switches in the body of the @code{Debug} unit in the compiler source
7106 file @file{debug.adb}.
7107 @end ifclear
7109 @item -gnatG[=nn]
7110 @cindex @option{-gnatG} (@command{gcc})
7111 This switch causes the compiler to generate auxiliary output containing
7112 a pseudo-source listing of the generated expanded code. Like most Ada
7113 compilers, GNAT works by first transforming the high level Ada code into
7114 lower level constructs. For example, tasking operations are transformed
7115 into calls to the tasking run-time routines. A unique capability of GNAT
7116 is to list this expanded code in a form very close to normal Ada source.
7117 This is very useful in understanding the implications of various Ada
7118 usage on the efficiency of the generated code. There are many cases in
7119 Ada (e.g.@: the use of controlled types), where simple Ada statements can
7120 generate a lot of run-time code. By using @option{-gnatG} you can identify
7121 these cases, and consider whether it may be desirable to modify the coding
7122 approach to improve efficiency.
7124 The optional parameter @code{nn} if present after -gnatG specifies an
7125 alternative maximum line length that overrides the normal default of 72.
7126 This value is in the range 40-999999, values less than 40 being silently
7127 reset to 40. The equal sign is optional.
7129 The format of the output is very similar to standard Ada source, and is
7130 easily understood by an Ada programmer. The following special syntactic
7131 additions correspond to low level features used in the generated code that
7132 do not have any exact analogies in pure Ada source form. The following
7133 is a partial list of these special constructions. See the spec
7134 of package @code{Sprint} in file @file{sprint.ads} for a full list.
7136 If the switch @option{-gnatL} is used in conjunction with
7137 @cindex @option{-gnatL} (@command{gcc})
7138 @option{-gnatG}, then the original source lines are interspersed
7139 in the expanded source (as comment lines with the original line number).
7141 @table @code
7142 @item new @var{xxx} @r{[}storage_pool = @var{yyy}@r{]}
7143 Shows the storage pool being used for an allocator.
7145 @item at end @var{procedure-name};
7146 Shows the finalization (cleanup) procedure for a scope.
7148 @item (if @var{expr} then @var{expr} else @var{expr})
7149 Conditional expression equivalent to the @code{x?y:z} construction in C.
7151 @item @var{target}^^^(@var{source})
7152 A conversion with floating-point truncation instead of rounding.
7154 @item @var{target}?(@var{source})
7155 A conversion that bypasses normal Ada semantic checking. In particular
7156 enumeration types and fixed-point types are treated simply as integers.
7158 @item @var{target}?^^^(@var{source})
7159 Combines the above two cases.
7161 @item @var{x} #/ @var{y}
7162 @itemx @var{x} #mod @var{y}
7163 @itemx @var{x} #* @var{y}
7164 @itemx @var{x} #rem @var{y}
7165 A division or multiplication of fixed-point values which are treated as
7166 integers without any kind of scaling.
7168 @item free @var{expr} @r{[}storage_pool = @var{xxx}@r{]}
7169 Shows the storage pool associated with a @code{free} statement.
7171 @item [subtype or type declaration]
7172 Used to list an equivalent declaration for an internally generated
7173 type that is referenced elsewhere in the listing.
7175 @c @item freeze @var{type-name} @ovar{actions}
7176 @c Expanding @ovar macro inline (explanation in macro def comments)
7177 @item freeze @var{type-name} @r{[}@var{actions}@r{]}
7178 Shows the point at which @var{type-name} is frozen, with possible
7179 associated actions to be performed at the freeze point.
7181 @item reference @var{itype}
7182 Reference (and hence definition) to internal type @var{itype}.
7184 @item @var{function-name}! (@var{arg}, @var{arg}, @var{arg})
7185 Intrinsic function call.
7187 @item @var{label-name} : label
7188 Declaration of label @var{labelname}.
7190 @item #$ @var{subprogram-name}
7191 An implicit call to a run-time support routine
7192 (to meet the requirement of H.3.1(9) in a
7193 convenient manner).
7195 @item @var{expr} && @var{expr} && @var{expr} @dots{} && @var{expr}
7196 A multiple concatenation (same effect as @var{expr} & @var{expr} &
7197 @var{expr}, but handled more efficiently).
7199 @item [constraint_error]
7200 Raise the @code{Constraint_Error} exception.
7202 @item @var{expression}'reference
7203 A pointer to the result of evaluating @var{expression}.
7205 @item @var{target-type}!(@var{source-expression})
7206 An unchecked conversion of @var{source-expression} to @var{target-type}.
7208 @item [@var{numerator}/@var{denominator}]
7209 Used to represent internal real literals (that) have no exact
7210 representation in base 2-16 (for example, the result of compile time
7211 evaluation of the expression 1.0/27.0).
7212 @end table
7214 @item -gnatD[=nn]
7215 @cindex @option{-gnatD} (@command{gcc})
7216 When used in conjunction with @option{-gnatG}, this switch causes
7217 the expanded source, as described above for
7218 @option{-gnatG} to be written to files with names
7219 @file{^xxx.dg^XXX_DG^}, where @file{xxx} is the normal file name,
7220 instead of to the standard output file. For
7221 example, if the source file name is @file{hello.adb}, then a file
7222 @file{^hello.adb.dg^HELLO.ADB_DG^} will be written.  The debugging
7223 information generated by the @command{gcc} @option{^-g^/DEBUG^} switch
7224 will refer to the generated @file{^xxx.dg^XXX_DG^} file. This allows
7225 you to do source level debugging using the generated code which is
7226 sometimes useful for complex code, for example to find out exactly
7227 which part of a complex construction raised an exception. This switch
7228 also suppress generation of cross-reference information (see
7229 @option{-gnatx}) since otherwise the cross-reference information
7230 would refer to the @file{^.dg^.DG^} file, which would cause
7231 confusion since this is not the original source file.
7233 Note that @option{-gnatD} actually implies @option{-gnatG}
7234 automatically, so it is not necessary to give both options.
7235 In other words @option{-gnatD} is equivalent to @option{-gnatDG}).
7237 If the switch @option{-gnatL} is used in conjunction with
7238 @cindex @option{-gnatL} (@command{gcc})
7239 @option{-gnatDG}, then the original source lines are interspersed
7240 in the expanded source (as comment lines with the original line number).
7242 The optional parameter @code{nn} if present after -gnatD specifies an
7243 alternative maximum line length that overrides the normal default of 72.
7244 This value is in the range 40-999999, values less than 40 being silently
7245 reset to 40. The equal sign is optional.
7247 @item -gnatr
7248 @cindex @option{-gnatr} (@command{gcc})
7249 @cindex pragma Restrictions
7250 This switch causes pragma Restrictions to be treated as Restriction_Warnings
7251 so that violation of restrictions causes warnings rather than illegalities.
7252 This is useful during the development process when new restrictions are added
7253 or investigated. The switch also causes pragma Profile to be treated as
7254 Profile_Warnings, and pragma Restricted_Run_Time and pragma Ravenscar set
7255 restriction warnings rather than restrictions.
7257 @ifclear vms
7258 @item -gnatR@r{[}0@r{|}1@r{|}2@r{|}3@r{[}s@r{]]}
7259 @cindex @option{-gnatR} (@command{gcc})
7260 This switch controls output from the compiler of a listing showing
7261 representation information for declared types and objects. For
7262 @option{-gnatR0}, no information is output (equivalent to omitting
7263 the @option{-gnatR} switch). For @option{-gnatR1} (which is the default,
7264 so @option{-gnatR} with no parameter has the same effect), size and alignment
7265 information is listed for declared array and record types. For
7266 @option{-gnatR2}, size and alignment information is listed for all
7267 declared types and objects. Finally @option{-gnatR3} includes symbolic
7268 expressions for values that are computed at run time for
7269 variant records. These symbolic expressions have a mostly obvious
7270 format with #n being used to represent the value of the n'th
7271 discriminant. See source files @file{repinfo.ads/adb} in the
7272 @code{GNAT} sources for full details on the format of @option{-gnatR3}
7273 output. If the switch is followed by an s (e.g.@: @option{-gnatR2s}), then
7274 the output is to a file with the name @file{^file.rep^file_REP^} where
7275 file is the name of the corresponding source file.
7276 @end ifclear
7277 @ifset vms
7278 @item /REPRESENTATION_INFO
7279 @cindex @option{/REPRESENTATION_INFO} (@command{gcc})
7280 This qualifier controls output from the compiler of a listing showing
7281 representation information for declared types and objects. For
7282 @option{/REPRESENTATION_INFO=NONE}, no information is output
7283 (equivalent to omitting the @option{/REPRESENTATION_INFO} qualifier).
7284 @option{/REPRESENTATION_INFO} without option is equivalent to
7285 @option{/REPRESENTATION_INFO=ARRAYS}.
7286 For @option{/REPRESENTATION_INFO=ARRAYS}, size and alignment
7287 information is listed for declared array and record types. For
7288 @option{/REPRESENTATION_INFO=OBJECTS}, size and alignment information
7289 is listed for all expression information for values that are computed
7290 at run time for variant records. These symbolic expressions have a mostly
7291 obvious format with #n being used to represent the value of the n'th
7292 discriminant. See source files @file{REPINFO.ADS/ADB} in the
7293 @code{GNAT} sources for full details on the format of
7294 @option{/REPRESENTATION_INFO=SYMBOLIC} output.
7295 If _FILE is added at the end of an option
7296 (e.g.@: @option{/REPRESENTATION_INFO=ARRAYS_FILE}),
7297 then the output is to a file with the name @file{file_REP} where
7298 file is the name of the corresponding source file.
7299 @end ifset
7300 Note that it is possible for record components to have zero size. In
7301 this case, the component clause uses an obvious extension of permitted
7302 Ada syntax, for example @code{at 0 range 0 .. -1}.
7304 Representation information requires that code be generated (since it is the
7305 code generator that lays out complex data structures). If an attempt is made
7306 to output representation information when no code is generated, for example
7307 when a subunit is compiled on its own, then no information can be generated
7308 and the compiler outputs a message to this effect.
7310 @item -gnatS
7311 @cindex @option{-gnatS} (@command{gcc})
7312 The use of the switch @option{-gnatS} for an
7313 Ada compilation will cause the compiler to output a
7314 representation of package Standard in a form very
7315 close to standard Ada. It is not quite possible to
7316 do this entirely in standard Ada (since new
7317 numeric base types cannot be created in standard
7318 Ada), but the output is easily
7319 readable to any Ada programmer, and is useful to
7320 determine the characteristics of target dependent
7321 types in package Standard.
7323 @item -gnatx
7324 @cindex @option{-gnatx} (@command{gcc})
7325 Normally the compiler generates full cross-referencing information in
7326 the @file{ALI} file. This information is used by a number of tools,
7327 including @code{gnatfind} and @code{gnatxref}. The @option{-gnatx} switch
7328 suppresses this information. This saves some space and may slightly
7329 speed up compilation, but means that these tools cannot be used.
7330 @end table
7332 @node Exception Handling Control
7333 @subsection Exception Handling Control
7335 @noindent
7336 GNAT uses two methods for handling exceptions at run-time. The
7337 @code{setjmp/longjmp} method saves the context when entering
7338 a frame with an exception handler. Then when an exception is
7339 raised, the context can be restored immediately, without the
7340 need for tracing stack frames. This method provides very fast
7341 exception propagation, but introduces significant overhead for
7342 the use of exception handlers, even if no exception is raised.
7344 The other approach is called ``zero cost'' exception handling.
7345 With this method, the compiler builds static tables to describe
7346 the exception ranges. No dynamic code is required when entering
7347 a frame containing an exception handler. When an exception is
7348 raised, the tables are used to control a back trace of the
7349 subprogram invocation stack to locate the required exception
7350 handler. This method has considerably poorer performance for
7351 the propagation of exceptions, but there is no overhead for
7352 exception handlers if no exception is raised. Note that in this
7353 mode and in the context of mixed Ada and C/C++ programming,
7354 to propagate an exception through a C/C++ code, the C/C++ code
7355 must be compiled with the @option{-funwind-tables} GCC's
7356 option.
7358 The following switches may be used to control which of the
7359 two exception handling methods is used.
7361 @table @option
7362 @c !sort!
7364 @item --RTS=sjlj
7365 @cindex @option{--RTS=sjlj} (@command{gnatmake})
7366 This switch causes the setjmp/longjmp run-time (when available) to be used
7367 for exception handling. If the default
7368 mechanism for the target is zero cost exceptions, then
7369 this switch can be used to modify this default, and must be
7370 used for all units in the partition.
7371 This option is rarely used. One case in which it may be
7372 advantageous is if you have an application where exception
7373 raising is common and the overall performance of the
7374 application is improved by favoring exception propagation.
7376 @item --RTS=zcx
7377 @cindex @option{--RTS=zcx} (@command{gnatmake})
7378 @cindex Zero Cost Exceptions
7379 This switch causes the zero cost approach to be used
7380 for exception handling. If this is the default mechanism for the
7381 target (see below), then this switch is unneeded. If the default
7382 mechanism for the target is setjmp/longjmp exceptions, then
7383 this switch can be used to modify this default, and must be
7384 used for all units in the partition.
7385 This option can only be used if the zero cost approach
7386 is available for the target in use, otherwise it will generate an error.
7387 @end table
7389 @noindent
7390 The same option @option{--RTS} must be used both for @command{gcc}
7391 and @command{gnatbind}. Passing this option to @command{gnatmake}
7392 (@pxref{Switches for gnatmake}) will ensure the required consistency
7393 through the compilation and binding steps.
7395 @node Units to Sources Mapping Files
7396 @subsection Units to Sources Mapping Files
7398 @table @option
7400 @item -gnatem=@var{path}
7401 @cindex @option{-gnatem} (@command{gcc})
7402 A mapping file is a way to communicate to the compiler two mappings:
7403 from unit names to file names (without any directory information) and from
7404 file names to path names (with full directory information). These mappings
7405 are used by the compiler to short-circuit the path search.
7407 The use of mapping files is not required for correct operation of the
7408 compiler, but mapping files can improve efficiency, particularly when
7409 sources are read over a slow network connection. In normal operation,
7410 you need not be concerned with the format or use of mapping files,
7411 and the @option{-gnatem} switch is not a switch that you would use
7412 explicitly. It is intended primarily for use by automatic tools such as
7413 @command{gnatmake} running under the project file facility. The
7414 description here of the format of mapping files is provided
7415 for completeness and for possible use by other tools.
7417 A mapping file is a sequence of sets of three lines. In each set, the
7418 first line is the unit name, in lower case, with @code{%s} appended
7419 for specs and @code{%b} appended for bodies; the second line is the
7420 file name; and the third line is the path name.
7422 Example:
7423 @smallexample
7424    main%b
7425    main.2.ada
7426    /gnat/project1/sources/main.2.ada
7427 @end smallexample
7429 When the switch @option{-gnatem} is specified, the compiler will
7430 create in memory the two mappings from the specified file. If there is
7431 any problem (nonexistent file, truncated file or duplicate entries),
7432 no mapping will be created.
7434 Several @option{-gnatem} switches may be specified; however, only the
7435 last one on the command line will be taken into account.
7437 When using a project file, @command{gnatmake} creates a temporary
7438 mapping file and communicates it to the compiler using this switch.
7440 @end table
7442 @node Integrated Preprocessing
7443 @subsection Integrated Preprocessing
7445 @noindent
7446 GNAT sources may be preprocessed immediately before compilation.
7447 In this case, the actual
7448 text of the source is not the text of the source file, but is derived from it
7449 through a process called preprocessing. Integrated preprocessing is specified
7450 through switches @option{-gnatep} and/or @option{-gnateD}. @option{-gnatep}
7451 indicates, through a text file, the preprocessing data to be used.
7452 @option{-gnateD} specifies or modifies the values of preprocessing symbol.
7454 @noindent
7455 Note that when integrated preprocessing is used, the output from the
7456 preprocessor is not written to any external file. Instead it is passed
7457 internally to the compiler. If you need to preserve the result of
7458 preprocessing in a file, then you should use @command{gnatprep}
7459 to perform the desired preprocessing in stand-alone mode.
7461 @noindent
7462 It is recommended that @command{gnatmake} switch ^-s^/SWITCH_CHECK^ should be
7463 used when Integrated Preprocessing is used. The reason is that preprocessing
7464 with another Preprocessing Data file without changing the sources will
7465 not trigger recompilation without this switch.
7467 @noindent
7468 Note that @command{gnatmake} switch ^-m^/MINIMAL_RECOMPILATION^ will almost
7469 always trigger recompilation for sources that are preprocessed,
7470 because @command{gnatmake} cannot compute the checksum of the source after
7471 preprocessing.
7473 @noindent
7474 The actual preprocessing function is described in details in section
7475 @ref{Preprocessing with gnatprep}. This section only describes how integrated
7476 preprocessing is triggered and parameterized.
7478 @table @code
7480 @item -gnatep=@var{file}
7481 @cindex @option{-gnatep} (@command{gcc})
7482 This switch indicates to the compiler the file name (without directory
7483 information) of the preprocessor data file to use. The preprocessor data file
7484 should be found in the source directories. Note that when the compiler is
7485 called by a builder such as (@command{gnatmake} with a project
7486 file, if the object directory is not also a source directory, the builder needs
7487 to be called with @option{-x}.
7489 @noindent
7490 A preprocessing data file is a text file with significant lines indicating
7491 how should be preprocessed either a specific source or all sources not
7492 mentioned in other lines. A significant line is a nonempty, non-comment line.
7493 Comments are similar to Ada comments.
7495 @noindent
7496 Each significant line starts with either a literal string or the character '*'.
7497 A literal string is the file name (without directory information) of the source
7498 to preprocess. A character '*' indicates the preprocessing for all the sources
7499 that are not specified explicitly on other lines (order of the lines is not
7500 significant). It is an error to have two lines with the same file name or two
7501 lines starting with the character '*'.
7503 @noindent
7504 After the file name or the character '*', another optional literal string
7505 indicating the file name of the definition file to be used for preprocessing
7506 (@pxref{Form of Definitions File}). The definition files are found by the
7507 compiler in one of the source directories. In some cases, when compiling
7508 a source in a directory other than the current directory, if the definition
7509 file is in the current directory, it may be necessary to add the current
7510 directory as a source directory through switch ^-I.^/SEARCH=[]^, otherwise
7511 the compiler would not find the definition file.
7513 @noindent
7514 Then, optionally, ^switches^switches^ similar to those of @code{gnatprep} may
7515 be found. Those ^switches^switches^ are:
7517 @table @code
7519 @item -b
7520 Causes both preprocessor lines and the lines deleted by
7521 preprocessing to be replaced by blank lines, preserving the line number.
7522 This ^switch^switch^ is always implied; however, if specified after @option{-c}
7523 it cancels the effect of @option{-c}.
7525 @item -c
7526 Causes both preprocessor lines and the lines deleted
7527 by preprocessing to be retained as comments marked
7528 with the special string ``@code{--! }''.
7530 @item -Dsymbol=value
7531 Define or redefine a symbol, associated with value. A symbol is an Ada
7532 identifier, or an Ada reserved word, with the exception of @code{if},
7533 @code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}.
7534 @code{value} is either a literal string, an Ada identifier or any Ada reserved
7535 word. A symbol declared with this ^switch^switch^ replaces a symbol with the
7536 same name defined in a definition file.
7538 @item -s
7539 Causes a sorted list of symbol names and values to be
7540 listed on the standard output file.
7542 @item -u
7543 Causes undefined symbols to be treated as having the value @code{FALSE}
7544 in the context
7545 of a preprocessor test. In the absence of this option, an undefined symbol in
7546 a @code{#if} or @code{#elsif} test will be treated as an error.
7548 @end table
7550 @noindent
7551 Examples of valid lines in a preprocessor data file:
7553 @smallexample
7554   "toto.adb"  "prep.def" -u
7555   --  preprocess "toto.adb", using definition file "prep.def",
7556   --  undefined symbol are False.
7558   * -c -DVERSION=V101
7559   --  preprocess all other sources without a definition file;
7560   --  suppressed lined are commented; symbol VERSION has the value V101.
7562   "titi.adb" "prep2.def" -s
7563   --  preprocess "titi.adb", using definition file "prep2.def";
7564   --  list all symbols with their values.
7565 @end smallexample
7567 @item ^-gnateD^/DATA_PREPROCESSING=^symbol@r{[}=value@r{]}
7568 @cindex @option{-gnateD} (@command{gcc})
7569 Define or redefine a preprocessing symbol, associated with value. If no value
7570 is given on the command line, then the value of the symbol is @code{True}.
7571 A symbol is an identifier, following normal Ada (case-insensitive)
7572 rules for its syntax, and value is any sequence (including an empty sequence)
7573 of characters from the set (letters, digits, period, underline).
7574 Ada reserved words may be used as symbols, with the exceptions of @code{if},
7575 @code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}.
7577 @noindent
7578 A symbol declared with this ^switch^switch^ on the command line replaces a
7579 symbol with the same name either in a definition file or specified with a
7580 ^switch^switch^ -D in the preprocessor data file.
7582 @noindent
7583 This switch is similar to switch @option{^-D^/ASSOCIATE^} of @code{gnatprep}.
7585 @item -gnateG
7586 When integrated preprocessing is performed and the preprocessor modifies
7587 the source text, write the result of this preprocessing into a file
7588 <source>^.prep^_prep^.
7590 @end table
7592 @node Code Generation Control
7593 @subsection Code Generation Control
7595 @noindent
7597 The GCC technology provides a wide range of target dependent
7598 @option{-m} switches for controlling
7599 details of code generation with respect to different versions of
7600 architectures. This includes variations in instruction sets (e.g.@:
7601 different members of the power pc family), and different requirements
7602 for optimal arrangement of instructions (e.g.@: different members of
7603 the x86 family). The list of available @option{-m} switches may be
7604 found in the GCC documentation.
7606 Use of these @option{-m} switches may in some cases result in improved
7607 code performance.
7609 The @value{EDITION} technology is tested and qualified without any
7610 @option{-m} switches,
7611 so generally the most reliable approach is to avoid the use of these
7612 switches. However, we generally expect most of these switches to work
7613 successfully with @value{EDITION}, and many customers have reported successful
7614 use of these options.
7616 Our general advice is to avoid the use of @option{-m} switches unless
7617 special needs lead to requirements in this area. In particular,
7618 there is no point in using @option{-m} switches to improve performance
7619 unless you actually see a performance improvement.
7621 @ifset vms
7622 @node Return Codes
7623 @subsection Return Codes
7624 @cindex Return Codes
7625 @cindex @option{/RETURN_CODES=VMS}
7627 @noindent
7628 On VMS, GNAT compiled programs return POSIX-style codes by default,
7629 e.g.@: @option{/RETURN_CODES=POSIX}.
7631 To enable VMS style return codes, use GNAT BIND and LINK with the option
7632 @option{/RETURN_CODES=VMS}. For example:
7634 @smallexample
7635 GNAT BIND MYMAIN.ALI /RETURN_CODES=VMS
7636 GNAT LINK MYMAIN.ALI /RETURN_CODES=VMS
7637 @end smallexample
7639 @noindent
7640 Programs built with /RETURN_CODES=VMS are suitable to be called in
7641 VMS DCL scripts. Programs compiled with the default /RETURN_CODES=POSIX
7642 are suitable for spawning with appropriate GNAT RTL routines.
7644 @end ifset
7646 @node Search Paths and the Run-Time Library (RTL)
7647 @section Search Paths and the Run-Time Library (RTL)
7649 @noindent
7650 With the GNAT source-based library system, the compiler must be able to
7651 find source files for units that are needed by the unit being compiled.
7652 Search paths are used to guide this process.
7654 The compiler compiles one source file whose name must be given
7655 explicitly on the command line. In other words, no searching is done
7656 for this file. To find all other source files that are needed (the most
7657 common being the specs of units), the compiler examines the following
7658 directories, in the following order:
7660 @enumerate
7661 @item
7662 The directory containing the source file of the main unit being compiled
7663 (the file name on the command line).
7665 @item
7666 Each directory named by an @option{^-I^/SOURCE_SEARCH^} switch given on the
7667 @command{gcc} command line, in the order given.
7669 @item
7670 @findex ADA_PRJ_INCLUDE_FILE
7671 Each of the directories listed in the text file whose name is given
7672 by the @env{ADA_PRJ_INCLUDE_FILE} ^environment variable^logical name^.
7674 @noindent
7675 @env{ADA_PRJ_INCLUDE_FILE} is normally set by gnatmake or by the ^gnat^GNAT^
7676 driver when project files are used. It should not normally be set
7677 by other means.
7679 @item
7680 @findex ADA_INCLUDE_PATH
7681 Each of the directories listed in the value of the
7682 @env{ADA_INCLUDE_PATH} ^environment variable^logical name^.
7683 @ifclear vms
7684 Construct this value
7685 exactly as the @env{PATH} environment variable: a list of directory
7686 names separated by colons (semicolons when working with the NT version).
7687 @end ifclear
7688 @ifset vms
7689 Normally, define this value as a logical name containing a comma separated
7690 list of directory names.
7692 This variable can also be defined by means of an environment string
7693 (an argument to the HP C exec* set of functions).
7695 Logical Name:
7696 @smallexample
7697 DEFINE ANOTHER_PATH FOO:[BAG]
7698 DEFINE ADA_INCLUDE_PATH ANOTHER_PATH,FOO:[BAM],FOO:[BAR]
7699 @end smallexample
7701 By default, the path includes GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB]
7702 first, followed by the standard Ada
7703 libraries in GNU:[LIB.OPENVMS7_x.2_8_x.ADAINCLUDE].
7704 If this is not redefined, the user will obtain the HP Ada 83 IO packages
7705 (Text_IO, Sequential_IO, etc)
7706 instead of the standard Ada packages. Thus, in order to get the standard Ada
7707 packages by default, ADA_INCLUDE_PATH must be redefined.
7708 @end ifset
7710 @item
7711 The content of the @file{ada_source_path} file which is part of the GNAT
7712 installation tree and is used to store standard libraries such as the
7713 GNAT Run Time Library (RTL) source files.
7714 @ifclear vms
7715 @ref{Installing a library}
7716 @end ifclear
7717 @end enumerate
7719 @noindent
7720 Specifying the switch @option{^-I-^/NOCURRENT_DIRECTORY^}
7721 inhibits the use of the directory
7722 containing the source file named in the command line. You can still
7723 have this directory on your search path, but in this case it must be
7724 explicitly requested with a @option{^-I^/SOURCE_SEARCH^} switch.
7726 Specifying the switch @option{-nostdinc}
7727 inhibits the search of the default location for the GNAT Run Time
7728 Library (RTL) source files.
7730 The compiler outputs its object files and ALI files in the current
7731 working directory.
7732 @ifclear vms
7733 Caution: The object file can be redirected with the @option{-o} switch;
7734 however, @command{gcc} and @code{gnat1} have not been coordinated on this
7735 so the @file{ALI} file will not go to the right place. Therefore, you should
7736 avoid using the @option{-o} switch.
7737 @end ifclear
7739 @findex System.IO
7740 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
7741 children make up the GNAT RTL, together with the simple @code{System.IO}
7742 package used in the @code{"Hello World"} example. The sources for these units
7743 are needed by the compiler and are kept together in one directory. Not
7744 all of the bodies are needed, but all of the sources are kept together
7745 anyway. In a normal installation, you need not specify these directory
7746 names when compiling or binding. Either the environment variables or
7747 the built-in defaults cause these files to be found.
7749 In addition to the language-defined hierarchies (@code{System}, @code{Ada} and
7750 @code{Interfaces}), the GNAT distribution provides a fourth hierarchy,
7751 consisting of child units of @code{GNAT}. This is a collection of generally
7752 useful types, subprograms, etc. @xref{Top, GNAT Reference Manual, About
7753 This Guid, gnat_rm, GNAT Reference Manual}, for further details.
7755 Besides simplifying access to the RTL, a major use of search paths is
7756 in compiling sources from multiple directories. This can make
7757 development environments much more flexible.
7759 @node Order of Compilation Issues
7760 @section Order of Compilation Issues
7762 @noindent
7763 If, in our earlier example, there was a spec for the @code{hello}
7764 procedure, it would be contained in the file @file{hello.ads}; yet this
7765 file would not have to be explicitly compiled. This is the result of the
7766 model we chose to implement library management. Some of the consequences
7767 of this model are as follows:
7769 @itemize @bullet
7770 @item
7771 There is no point in compiling specs (except for package
7772 specs with no bodies) because these are compiled as needed by clients. If
7773 you attempt a useless compilation, you will receive an error message.
7774 It is also useless to compile subunits because they are compiled as needed
7775 by the parent.
7777 @item
7778 There are no order of compilation requirements: performing a
7779 compilation never obsoletes anything. The only way you can obsolete
7780 something and require recompilations is to modify one of the
7781 source files on which it depends.
7783 @item
7784 There is no library as such, apart from the ALI files
7785 (@pxref{The Ada Library Information Files}, for information on the format
7786 of these files). For now we find it convenient to create separate ALI files,
7787 but eventually the information therein may be incorporated into the object
7788 file directly.
7790 @item
7791 When you compile a unit, the source files for the specs of all units
7792 that it @code{with}'s, all its subunits, and the bodies of any generics it
7793 instantiates must be available (reachable by the search-paths mechanism
7794 described above), or you will receive a fatal error message.
7795 @end itemize
7797 @node Examples
7798 @section Examples
7800 @noindent
7801 The following are some typical Ada compilation command line examples:
7803 @table @code
7804 @item $ gcc -c xyz.adb
7805 Compile body in file @file{xyz.adb} with all default options.
7807 @ifclear vms
7808 @item $ gcc -c -O2 -gnata xyz-def.adb
7809 @end ifclear
7810 @ifset vms
7811 @item $ GNAT COMPILE /OPTIMIZE=ALL -gnata xyz-def.adb
7812 @end ifset
7814 Compile the child unit package in file @file{xyz-def.adb} with extensive
7815 optimizations, and pragma @code{Assert}/@code{Debug} statements
7816 enabled.
7818 @item $ gcc -c -gnatc abc-def.adb
7819 Compile the subunit in file @file{abc-def.adb} in semantic-checking-only
7820 mode.
7821 @end table
7823 @node Binding with gnatbind
7824 @chapter Binding with @code{gnatbind}
7825 @findex gnatbind
7827 @menu
7828 * Running gnatbind::
7829 * Switches for gnatbind::
7830 * Command-Line Access::
7831 * Search Paths for gnatbind::
7832 * Examples of gnatbind Usage::
7833 @end menu
7835 @noindent
7836 This chapter describes the GNAT binder, @code{gnatbind}, which is used
7837 to bind compiled GNAT objects.
7839 Note: to invoke @code{gnatbind} with a project file, use the @code{gnat}
7840 driver (see @ref{The GNAT Driver and Project Files}).
7842 The @code{gnatbind} program performs four separate functions:
7844 @enumerate
7845 @item
7846 Checks that a program is consistent, in accordance with the rules in
7847 Chapter 10 of the Ada Reference Manual. In particular, error
7848 messages are generated if a program uses inconsistent versions of a
7849 given unit.
7851 @item
7852 Checks that an acceptable order of elaboration exists for the program
7853 and issues an error message if it cannot find an order of elaboration
7854 that satisfies the rules in Chapter 10 of the Ada Language Manual.
7856 @item
7857 Generates a main program incorporating the given elaboration order.
7858 This program is a small Ada package (body and spec) that
7859 must be subsequently compiled
7860 using the GNAT compiler. The necessary compilation step is usually
7861 performed automatically by @command{gnatlink}. The two most important
7862 functions of this program
7863 are to call the elaboration routines of units in an appropriate order
7864 and to call the main program.
7866 @item
7867 Determines the set of object files required by the given main program.
7868 This information is output in the forms of comments in the generated program,
7869 to be read by the @command{gnatlink} utility used to link the Ada application.
7870 @end enumerate
7872 @node Running gnatbind
7873 @section Running @code{gnatbind}
7875 @noindent
7876 The form of the @code{gnatbind} command is
7878 @smallexample
7879 @c $ gnatbind @ovar{switches} @var{mainprog}@r{[}.ali@r{]} @ovar{switches}
7880 @c Expanding @ovar macro inline (explanation in macro def comments)
7881 $ gnatbind @r{[}@var{switches}@r{]} @var{mainprog}@r{[}.ali@r{]} @r{[}@var{switches}@r{]}
7882 @end smallexample
7884 @noindent
7885 where @file{@var{mainprog}.adb} is the Ada file containing the main program
7886 unit body. @code{gnatbind} constructs an Ada
7887 package in two files whose names are
7888 @file{b~@var{mainprog}.ads}, and @file{b~@var{mainprog}.adb}.
7889 For example, if given the
7890 parameter @file{hello.ali}, for a main program contained in file
7891 @file{hello.adb}, the binder output files would be @file{b~hello.ads}
7892 and @file{b~hello.adb}.
7894 When doing consistency checking, the binder takes into consideration
7895 any source files it can locate. For example, if the binder determines
7896 that the given main program requires the package @code{Pack}, whose
7897 @file{.ALI}
7898 file is @file{pack.ali} and whose corresponding source spec file is
7899 @file{pack.ads}, it attempts to locate the source file @file{pack.ads}
7900 (using the same search path conventions as previously described for the
7901 @command{gcc} command). If it can locate this source file, it checks that
7902 the time stamps
7903 or source checksums of the source and its references to in @file{ALI} files
7904 match. In other words, any @file{ALI} files that mentions this spec must have
7905 resulted from compiling this version of the source file (or in the case
7906 where the source checksums match, a version close enough that the
7907 difference does not matter).
7909 @cindex Source files, use by binder
7910 The effect of this consistency checking, which includes source files, is
7911 that the binder ensures that the program is consistent with the latest
7912 version of the source files that can be located at bind time. Editing a
7913 source file without compiling files that depend on the source file cause
7914 error messages to be generated by the binder.
7916 For example, suppose you have a main program @file{hello.adb} and a
7917 package @code{P}, from file @file{p.ads} and you perform the following
7918 steps:
7920 @enumerate
7921 @item
7922 Enter @code{gcc -c hello.adb} to compile the main program.
7924 @item
7925 Enter @code{gcc -c p.ads} to compile package @code{P}.
7927 @item
7928 Edit file @file{p.ads}.
7930 @item
7931 Enter @code{gnatbind hello}.
7932 @end enumerate
7934 @noindent
7935 At this point, the file @file{p.ali} contains an out-of-date time stamp
7936 because the file @file{p.ads} has been edited. The attempt at binding
7937 fails, and the binder generates the following error messages:
7939 @smallexample
7940 error: "hello.adb" must be recompiled ("p.ads" has been modified)
7941 error: "p.ads" has been modified and must be recompiled
7942 @end smallexample
7944 @noindent
7945 Now both files must be recompiled as indicated, and then the bind can
7946 succeed, generating a main program. You need not normally be concerned
7947 with the contents of this file, but for reference purposes a sample
7948 binder output file is given in @ref{Example of Binder Output File}.
7950 In most normal usage, the default mode of @command{gnatbind} which is to
7951 generate the main package in Ada, as described in the previous section.
7952 In particular, this means that any Ada programmer can read and understand
7953 the generated main program. It can also be debugged just like any other
7954 Ada code provided the @option{^-g^/DEBUG^} switch is used for
7955 @command{gnatbind} and @command{gnatlink}.
7957 @node Switches for gnatbind
7958 @section Switches for @command{gnatbind}
7960 @noindent
7961 The following switches are available with @code{gnatbind}; details will
7962 be presented in subsequent sections.
7964 @menu
7965 * Consistency-Checking Modes::
7966 * Binder Error Message Control::
7967 * Elaboration Control::
7968 * Output Control::
7969 * Dynamic Allocation Control::
7970 * Binding with Non-Ada Main Programs::
7971 * Binding Programs with No Main Subprogram::
7972 @end menu
7974 @table @option
7975 @c !sort!
7977 @item --version
7978 @cindex @option{--version} @command{gnatbind}
7979 Display Copyright and version, then exit disregarding all other options.
7981 @item --help
7982 @cindex @option{--help} @command{gnatbind}
7983 If @option{--version} was not used, display usage, then exit disregarding
7984 all other options.
7986 @item -a
7987 @cindex @option{-a} @command{gnatbind}
7988 Indicates that, if supported by the platform, the adainit procedure should
7989 be treated as an initialisation routine by the linker (a constructor). This
7990 is intended to be used by the Project Manager to automatically initialize
7991 shared Stand-Alone Libraries.
7993 @item ^-aO^/OBJECT_SEARCH^
7994 @cindex @option{^-aO^/OBJECT_SEARCH^} (@command{gnatbind})
7995 Specify directory to be searched for ALI files.
7997 @item ^-aI^/SOURCE_SEARCH^
7998 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatbind})
7999 Specify directory to be searched for source file.
8001 @item ^-A^/ALI_LIST^@r{[=}@var{filename}@r{]}
8002 @cindex @option{^-A^/ALI_LIST^} (@command{gnatbind})
8003 Output ALI list (to standard output or to the named file).
8005 @item ^-b^/REPORT_ERRORS=BRIEF^
8006 @cindex @option{^-b^/REPORT_ERRORS=BRIEF^} (@command{gnatbind})
8007 Generate brief messages to @file{stderr} even if verbose mode set.
8009 @item ^-c^/NOOUTPUT^
8010 @cindex @option{^-c^/NOOUTPUT^} (@command{gnatbind})
8011 Check only, no generation of binder output file.
8013 @item ^-d^/DEFAULT_STACK_SIZE=^@var{nn}@r{[}k@r{|}m@r{]}
8014 @cindex @option{^-d^/DEFAULT_STACK_SIZE=^@var{nn}@r{[}k@r{|}m@r{]}} (@command{gnatbind})
8015 This switch can be used to change the default task stack size value
8016 to a specified size @var{nn}, which is expressed in bytes by default, or
8017 in kilobytes when suffixed with @var{k} or in megabytes when suffixed
8018 with @var{m}.
8019 In the absence of a @samp{@r{[}k@r{|}m@r{]}} suffix, this switch is equivalent,
8020 in effect, to completing all task specs with
8021 @smallexample @c ada
8022    pragma Storage_Size (nn);
8023 @end smallexample
8024 When they do not already have such a pragma.
8026 @item ^-D^/DEFAULT_SECONDARY_STACK_SIZE=^@var{nn}@r{[}k@r{|}m@r{]}
8027 @cindex @option{^-D^/DEFAULT_SECONDARY_STACK_SIZE=nnnnn^} (@command{gnatbind})
8028 This switch can be used to change the default secondary stack size value
8029 to a specified size @var{nn}, which is expressed in bytes by default, or
8030 in kilobytes when suffixed with @var{k} or in megabytes when suffixed
8031 with @var{m}.
8033 The secondary stack is used to deal with functions that return a variable
8034 sized result, for example a function returning an unconstrained
8035 String. There are two ways in which this secondary stack is allocated.
8037 For most targets, the secondary stack is growing on demand and is allocated
8038 as a chain of blocks in the heap. The -D option is not very
8039 relevant. It only give some control over the size of the allocated
8040 blocks (whose size is the minimum of the default secondary stack size value,
8041 and the actual size needed for the current allocation request).
8043 For certain targets, notably VxWorks 653,
8044 the secondary stack is allocated by carving off a fixed ratio chunk of the
8045 primary task stack. The -D option is used to define the
8046 size of the environment task's secondary stack.
8048 @item ^-e^/ELABORATION_DEPENDENCIES^
8049 @cindex @option{^-e^/ELABORATION_DEPENDENCIES^} (@command{gnatbind})
8050 Output complete list of elaboration-order dependencies.
8052 @item ^-E^/STORE_TRACEBACKS^
8053 @cindex @option{^-E^/STORE_TRACEBACKS^} (@command{gnatbind})
8054 Store tracebacks in exception occurrences when the target supports it.
8055 @ignore
8056 @c The following may get moved to an appendix
8057 This option is currently supported on the following targets:
8058 all x86 ports, Solaris, Windows, HP-UX, AIX, PowerPC VxWorks and Alpha VxWorks.
8059 @end ignore
8060 See also the packages @code{GNAT.Traceback} and
8061 @code{GNAT.Traceback.Symbolic} for more information.
8062 @ifclear vms
8063 Note that on x86 ports, you must not use @option{-fomit-frame-pointer}
8064 @command{gcc} option.
8065 @end ifclear
8067 @item ^-F^/FORCE_ELABS_FLAGS^
8068 @cindex @option{^-F^/FORCE_ELABS_FLAGS^} (@command{gnatbind})
8069 Force the checks of elaboration flags. @command{gnatbind} does not normally
8070 generate checks of elaboration flags for the main executable, except when
8071 a Stand-Alone Library is used. However, there are cases when this cannot be
8072 detected by gnatbind. An example is importing an interface of a Stand-Alone
8073 Library through a pragma Import and only specifying through a linker switch
8074 this Stand-Alone Library. This switch is used to guarantee that elaboration
8075 flag checks are generated.
8077 @item ^-h^/HELP^
8078 @cindex @option{^-h^/HELP^} (@command{gnatbind})
8079 Output usage (help) information
8081 @item ^-H32^/32_MALLOC^
8082 @cindex @option{^-H32^/32_MALLOC^} (@command{gnatbind})
8083 Use 32-bit allocations for @code{__gnat_malloc} (and thus for access types).
8084 For further details see @ref{Dynamic Allocation Control}.
8086 @item ^-H64^/64_MALLOC^
8087 @cindex @option{^-H64^/64_MALLOC^} (@command{gnatbind})
8088 Use 64-bit allocations for @code{__gnat_malloc} (and thus for access types).
8089 @cindex @code{__gnat_malloc}
8090 For further details see @ref{Dynamic Allocation Control}.
8092 @item ^-I^/SEARCH^
8093 @cindex @option{^-I^/SEARCH^} (@command{gnatbind})
8094 Specify directory to be searched for source and ALI files.
8096 @item ^-I-^/NOCURRENT_DIRECTORY^
8097 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gnatbind})
8098 Do not look for sources in the current directory where @code{gnatbind} was
8099 invoked, and do not look for ALI files in the directory containing the
8100 ALI file named in the @code{gnatbind} command line.
8102 @item ^-l^/ORDER_OF_ELABORATION^
8103 @cindex @option{^-l^/ORDER_OF_ELABORATION^} (@command{gnatbind})
8104 Output chosen elaboration order.
8106 @item ^-L@var{xxx}^/BUILD_LIBRARY=@var{xxx}^
8107 @cindex @option{^-L^/BUILD_LIBRARY^} (@command{gnatbind})
8108 Bind the units for library building. In this case the adainit and
8109 adafinal procedures (@pxref{Binding with Non-Ada Main Programs})
8110 are renamed to ^@var{xxx}init^@var{XXX}INIT^ and
8111 ^@var{xxx}final^@var{XXX}FINAL^.
8112 Implies ^-n^/NOCOMPILE^.
8113 @ifclear vms
8114 (@xref{GNAT and Libraries}, for more details.)
8115 @end ifclear
8116 @ifset vms
8117 On OpenVMS, these init and final procedures are exported in uppercase
8118 letters. For example if /BUILD_LIBRARY=toto is used, the exported name of
8119 the init procedure will be "TOTOINIT" and the exported name of the final
8120 procedure will be "TOTOFINAL".
8121 @end ifset
8123 @item ^-Mxyz^/RENAME_MAIN=xyz^
8124 @cindex @option{^-M^/RENAME_MAIN^} (@command{gnatbind})
8125 Rename generated main program from main to xyz. This option is
8126 supported on cross environments only.
8128 @item ^-m^/ERROR_LIMIT=^@var{n}
8129 @cindex @option{^-m^/ERROR_LIMIT^} (@command{gnatbind})
8130 Limit number of detected errors or warnings to @var{n}, where @var{n} is
8131 in the range 1..999999. The default value if no switch is
8132 given is 9999. If the number of warnings reaches this limit, then a
8133 message is output and further warnings are suppressed, the bind
8134 continues in this case. If the number of errors reaches this
8135 limit, then a message is output and the bind is abandoned.
8136 A value of zero means that no limit is enforced. The equal
8137 sign is optional.
8139 @ifset unw
8140 Furthermore, under Windows, the sources pointed to by the libraries path
8141 set in the registry are not searched for.
8142 @end ifset
8144 @item ^-n^/NOMAIN^
8145 @cindex @option{^-n^/NOMAIN^} (@command{gnatbind})
8146 No main program.
8148 @item -nostdinc
8149 @cindex @option{-nostdinc} (@command{gnatbind})
8150 Do not look for sources in the system default directory.
8152 @item -nostdlib
8153 @cindex @option{-nostdlib} (@command{gnatbind})
8154 Do not look for library files in the system default directory.
8156 @item --RTS=@var{rts-path}
8157 @cindex @option{--RTS} (@code{gnatbind})
8158 Specifies the default location of the runtime library. Same meaning as the
8159 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
8161 @item ^-o ^/OUTPUT=^@var{file}
8162 @cindex @option{^-o ^/OUTPUT^} (@command{gnatbind})
8163 Name the output file @var{file} (default is @file{b~@var{xxx}.adb}).
8164 Note that if this option is used, then linking must be done manually,
8165 gnatlink cannot be used.
8167 @item ^-O^/OBJECT_LIST^@r{[=}@var{filename}@r{]}
8168 @cindex @option{^-O^/OBJECT_LIST^} (@command{gnatbind})
8169 Output object list (to standard output or to the named file).
8171 @item ^-p^/PESSIMISTIC_ELABORATION^
8172 @cindex @option{^-p^/PESSIMISTIC_ELABORATION^} (@command{gnatbind})
8173 Pessimistic (worst-case) elaboration order
8175 @item ^-P^-P^
8176 @cindex @option{^-P^/CODEPEER^} (@command{gnatbind})
8177 Generate binder file suitable for CodePeer.
8179 @item ^-R^-R^
8180 @cindex @option{^-R^-R^} (@command{gnatbind})
8181 Output closure source list.
8183 @item ^-s^/READ_SOURCES=ALL^
8184 @cindex @option{^-s^/READ_SOURCES=ALL^} (@command{gnatbind})
8185 Require all source files to be present.
8187 @item ^-S@var{xxx}^/INITIALIZE_SCALARS=@var{xxx}^
8188 @cindex @option{^-S^/INITIALIZE_SCALARS^} (@command{gnatbind})
8189 Specifies the value to be used when detecting uninitialized scalar
8190 objects with pragma Initialize_Scalars.
8191 The @var{xxx} ^string specified with the switch^option^ may be either
8192 @itemize @bullet
8193 @item ``@option{^in^INVALID^}'' requesting an invalid value where possible
8194 @item ``@option{^lo^LOW^}'' for the lowest possible value
8195 @item ``@option{^hi^HIGH^}'' for the highest possible value
8196 @item ``@option{@var{xx}}'' for a value consisting of repeated bytes with the
8197 value @code{16#@var{xx}#} (i.e., @var{xx} is a string of two hexadecimal digits).
8198 @end itemize
8200 In addition, you can specify @option{-Sev} to indicate that the value is
8201 to be set at run time. In this case, the program will look for an environment
8202 @cindex GNAT_INIT_SCALARS
8203 variable of the form @env{GNAT_INIT_SCALARS=@var{xx}}, where @var{xx} is one
8204 of @option{in/lo/hi/@var{xx}} with the same meanings as above.
8205 If no environment variable is found, or if it does not have a valid value,
8206 then the default is @option{in} (invalid values).
8208 @ifclear vms
8209 @item -static
8210 @cindex @option{-static} (@code{gnatbind})
8211 Link against a static GNAT run time.
8213 @item -shared
8214 @cindex @option{-shared} (@code{gnatbind})
8215 Link against a shared GNAT run time when available.
8216 @end ifclear
8218 @item ^-t^/NOTIME_STAMP_CHECK^
8219 @cindex @option{^-t^/NOTIME_STAMP_CHECK^} (@code{gnatbind})
8220 Tolerate time stamp and other consistency errors
8222 @item ^-T@var{n}^/TIME_SLICE=@var{n}^
8223 @cindex @option{^-T^/TIME_SLICE^} (@code{gnatbind})
8224 Set the time slice value to @var{n} milliseconds. If the system supports
8225 the specification of a specific time slice value, then the indicated value
8226 is used. If the system does not support specific time slice values, but
8227 does support some general notion of round-robin scheduling, then any
8228 nonzero value will activate round-robin scheduling.
8230 A value of zero is treated specially. It turns off time
8231 slicing, and in addition, indicates to the tasking run time that the
8232 semantics should match as closely as possible the Annex D
8233 requirements of the Ada RM, and in particular sets the default
8234 scheduling policy to @code{FIFO_Within_Priorities}.
8236 @item ^-u@var{n}^/DYNAMIC_STACK_USAGE=@var{n}^
8237 @cindex @option{^-u^/DYNAMIC_STACK_USAGE^} (@code{gnatbind})
8238 Enable dynamic stack usage, with @var{n} results stored and displayed
8239 at program termination. A result is generated when a task
8240 terminates. Results that can't be stored are displayed on the fly, at
8241 task termination. This option is currently not supported on Itanium
8242 platforms. (See @ref{Dynamic Stack Usage Analysis} for details.)
8244 @item ^-v^/REPORT_ERRORS=VERBOSE^
8245 @cindex @option{^-v^/REPORT_ERRORS=VERBOSE^} (@code{gnatbind})
8246 Verbose mode. Write error messages, header, summary output to
8247 @file{stdout}.
8249 @ifclear vms
8250 @item -w@var{x}
8251 @cindex @option{-w} (@code{gnatbind})
8252 Warning mode (@var{x}=s/e for suppress/treat as error)
8253 @end ifclear
8255 @ifset vms
8256 @item /WARNINGS=NORMAL
8257 @cindex @option{/WARNINGS} (@code{gnatbind})
8258 Normal warnings mode. Warnings are issued but ignored
8260 @item /WARNINGS=SUPPRESS
8261 @cindex @option{/WARNINGS} (@code{gnatbind})
8262 All warning messages are suppressed
8264 @item /WARNINGS=ERROR
8265 @cindex @option{/WARNINGS} (@code{gnatbind})
8266 Warning messages are treated as fatal errors
8267 @end ifset
8269 @item ^-Wx^/WIDE_CHARACTER_ENCODING=^@var{e}
8270 @cindex @option{^-Wx^/WIDE_CHARACTER_ENCODING^} (@code{gnatbind})
8271 Override default wide character encoding for standard Text_IO files.
8273 @item ^-x^/READ_SOURCES=NONE^
8274 @cindex @option{^-x^/READ_SOURCES^} (@code{gnatbind})
8275 Exclude source files (check object consistency only).
8277 @ifset vms
8278 @item /READ_SOURCES=AVAILABLE
8279 @cindex @option{/READ_SOURCES} (@code{gnatbind})
8280 Default mode, in which sources are checked for consistency only if
8281 they are available.
8282 @end ifset
8284 @item ^-y^/ENABLE_LEAP_SECONDS^
8285 @cindex @option{^-y^/ENABLE_LEAP_SECONDS^} (@code{gnatbind})
8286 Enable leap seconds support in @code{Ada.Calendar} and its children.
8288 @item ^-z^/ZERO_MAIN^
8289 @cindex @option{^-z^/ZERO_MAIN^} (@code{gnatbind})
8290 No main subprogram.
8291 @end table
8293 @ifclear vms
8294 @noindent
8295 You may obtain this listing of switches by running @code{gnatbind} with
8296 no arguments.
8297 @end ifclear
8299 @node Consistency-Checking Modes
8300 @subsection Consistency-Checking Modes
8302 @noindent
8303 As described earlier, by default @code{gnatbind} checks
8304 that object files are consistent with one another and are consistent
8305 with any source files it can locate. The following switches control binder
8306 access to sources.
8308 @table @option
8309 @c !sort!
8310 @item ^-s^/READ_SOURCES=ALL^
8311 @cindex @option{^-s^/READ_SOURCES=ALL^} (@code{gnatbind})
8312 Require source files to be present. In this mode, the binder must be
8313 able to locate all source files that are referenced, in order to check
8314 their consistency. In normal mode, if a source file cannot be located it
8315 is simply ignored. If you specify this switch, a missing source
8316 file is an error.
8318 @item ^-Wx^/WIDE_CHARACTER_ENCODING=^@var{e}
8319 @cindex @option{^-Wx^/WIDE_CHARACTER_ENCODING^} (@code{gnatbind})
8320 Override default wide character encoding for standard Text_IO files.
8321 Normally the default wide character encoding method used for standard
8322 [Wide_[Wide_]]Text_IO files is taken from the encoding specified for
8323 the main source input (see description of switch
8324 @option{^-gnatWx^/WIDE_CHARACTER_ENCODING^} for the compiler). The
8325 use of this switch for the binder (which has the same set of
8326 possible arguments) overrides this default as specified.
8328 @item ^-x^/READ_SOURCES=NONE^
8329 @cindex @option{^-x^/READ_SOURCES=NONE^} (@code{gnatbind})
8330 Exclude source files. In this mode, the binder only checks that ALI
8331 files are consistent with one another. Source files are not accessed.
8332 The binder runs faster in this mode, and there is still a guarantee that
8333 the resulting program is self-consistent.
8334 If a source file has been edited since it was last compiled, and you
8335 specify this switch, the binder will not detect that the object
8336 file is out of date with respect to the source file. Note that this is the
8337 mode that is automatically used by @command{gnatmake} because in this
8338 case the checking against sources has already been performed by
8339 @command{gnatmake} in the course of compilation (i.e.@: before binding).
8341 @ifset vms
8342 @item /READ_SOURCES=AVAILABLE
8343 @cindex @code{/READ_SOURCES=AVAILABLE} (@code{gnatbind})
8344 This is the default mode in which source files are checked if they are
8345 available, and ignored if they are not available.
8346 @end ifset
8347 @end table
8349 @node Binder Error Message Control
8350 @subsection Binder Error Message Control
8352 @noindent
8353 The following switches provide control over the generation of error
8354 messages from the binder:
8356 @table @option
8357 @c !sort!
8358 @item ^-v^/REPORT_ERRORS=VERBOSE^
8359 @cindex @option{^-v^/REPORT_ERRORS=VERBOSE^} (@code{gnatbind})
8360 Verbose mode. In the normal mode, brief error messages are generated to
8361 @file{stderr}. If this switch is present, a header is written
8362 to @file{stdout} and any error messages are directed to @file{stdout}.
8363 All that is written to @file{stderr} is a brief summary message.
8365 @item ^-b^/REPORT_ERRORS=BRIEF^
8366 @cindex @option{^-b^/REPORT_ERRORS=BRIEF^} (@code{gnatbind})
8367 Generate brief error messages to @file{stderr} even if verbose mode is
8368 specified. This is relevant only when used with the
8369 @option{^-v^/REPORT_ERRORS=VERBOSE^} switch.
8371 @ifclear vms
8372 @item -m@var{n}
8373 @cindex @option{-m} (@code{gnatbind})
8374 Limits the number of error messages to @var{n}, a decimal integer in the
8375 range 1-999. The binder terminates immediately if this limit is reached.
8377 @item -M@var{xxx}
8378 @cindex @option{-M} (@code{gnatbind})
8379 Renames the generated main program from @code{main} to @code{xxx}.
8380 This is useful in the case of some cross-building environments, where
8381 the actual main program is separate from the one generated
8382 by @code{gnatbind}.
8383 @end ifclear
8385 @item ^-ws^/WARNINGS=SUPPRESS^
8386 @cindex @option{^-ws^/WARNINGS=SUPPRESS^} (@code{gnatbind})
8387 @cindex Warnings
8388 Suppress all warning messages.
8390 @item ^-we^/WARNINGS=ERROR^
8391 @cindex @option{^-we^/WARNINGS=ERROR^} (@code{gnatbind})
8392 Treat any warning messages as fatal errors.
8394 @ifset vms
8395 @item /WARNINGS=NORMAL
8396 Standard mode with warnings generated, but warnings do not get treated
8397 as errors.
8398 @end ifset
8400 @item ^-t^/NOTIME_STAMP_CHECK^
8401 @cindex @option{^-t^/NOTIME_STAMP_CHECK^} (@code{gnatbind})
8402 @cindex Time stamp checks, in binder
8403 @cindex Binder consistency checks
8404 @cindex Consistency checks, in binder
8405 The binder performs a number of consistency checks including:
8407 @itemize @bullet
8408 @item
8409 Check that time stamps of a given source unit are consistent
8410 @item
8411 Check that checksums of a given source unit are consistent
8412 @item
8413 Check that consistent versions of @code{GNAT} were used for compilation
8414 @item
8415 Check consistency of configuration pragmas as required
8416 @end itemize
8418 @noindent
8419 Normally failure of such checks, in accordance with the consistency
8420 requirements of the Ada Reference Manual, causes error messages to be
8421 generated which abort the binder and prevent the output of a binder
8422 file and subsequent link to obtain an executable.
8424 The @option{^-t^/NOTIME_STAMP_CHECK^} switch converts these error messages
8425 into warnings, so that
8426 binding and linking can continue to completion even in the presence of such
8427 errors. The result may be a failed link (due to missing symbols), or a
8428 non-functional executable which has undefined semantics.
8429 @emph{This means that
8430 @option{^-t^/NOTIME_STAMP_CHECK^} should be used only in unusual situations,
8431 with extreme care.}
8432 @end table
8434 @node Elaboration Control
8435 @subsection Elaboration Control
8437 @noindent
8438 The following switches provide additional control over the elaboration
8439 order. For full details see @ref{Elaboration Order Handling in GNAT}.
8441 @table @option
8442 @item ^-p^/PESSIMISTIC_ELABORATION^
8443 @cindex @option{^-p^/PESSIMISTIC_ELABORATION^} (@code{gnatbind})
8444 Normally the binder attempts to choose an elaboration order that is
8445 likely to minimize the likelihood of an elaboration order error resulting
8446 in raising a @code{Program_Error} exception. This switch reverses the
8447 action of the binder, and requests that it deliberately choose an order
8448 that is likely to maximize the likelihood of an elaboration error.
8449 This is useful in ensuring portability and avoiding dependence on
8450 accidental fortuitous elaboration ordering.
8452 Normally it only makes sense to use the @option{^-p^/PESSIMISTIC_ELABORATION^}
8453 switch if dynamic
8454 elaboration checking is used (@option{-gnatE} switch used for compilation).
8455 This is because in the default static elaboration mode, all necessary
8456 @code{Elaborate} and @code{Elaborate_All} pragmas are implicitly inserted.
8457 These implicit pragmas are still respected by the binder in
8458 @option{^-p^/PESSIMISTIC_ELABORATION^} mode, so a
8459 safe elaboration order is assured.
8461 Note that @option{^-p^/PESSIMISTIC_ELABORATION^} is not intended for
8462 production use; it is more for debugging/experimental use.
8463 @end table
8465 @node Output Control
8466 @subsection Output Control
8468 @noindent
8469 The following switches allow additional control over the output
8470 generated by the binder.
8472 @table @option
8473 @c !sort!
8475 @item ^-c^/NOOUTPUT^
8476 @cindex @option{^-c^/NOOUTPUT^} (@code{gnatbind})
8477 Check only. Do not generate the binder output file. In this mode the
8478 binder performs all error checks but does not generate an output file.
8480 @item ^-e^/ELABORATION_DEPENDENCIES^
8481 @cindex @option{^-e^/ELABORATION_DEPENDENCIES^} (@code{gnatbind})
8482 Output complete list of elaboration-order dependencies, showing the
8483 reason for each dependency. This output can be rather extensive but may
8484 be useful in diagnosing problems with elaboration order. The output is
8485 written to @file{stdout}.
8487 @item ^-h^/HELP^
8488 @cindex @option{^-h^/HELP^} (@code{gnatbind})
8489 Output usage information. The output is written to @file{stdout}.
8491 @item ^-K^/LINKER_OPTION_LIST^
8492 @cindex @option{^-K^/LINKER_OPTION_LIST^} (@code{gnatbind})
8493 Output linker options to @file{stdout}. Includes library search paths,
8494 contents of pragmas Ident and Linker_Options, and libraries added
8495 by @code{gnatbind}.
8497 @item ^-l^/ORDER_OF_ELABORATION^
8498 @cindex @option{^-l^/ORDER_OF_ELABORATION^} (@code{gnatbind})
8499 Output chosen elaboration order. The output is written to @file{stdout}.
8501 @item ^-O^/OBJECT_LIST^
8502 @cindex @option{^-O^/OBJECT_LIST^} (@code{gnatbind})
8503 Output full names of all the object files that must be linked to provide
8504 the Ada component of the program. The output is written to @file{stdout}.
8505 This list includes the files explicitly supplied and referenced by the user
8506 as well as implicitly referenced run-time unit files. The latter are
8507 omitted if the corresponding units reside in shared libraries. The
8508 directory names for the run-time units depend on the system configuration.
8510 @item ^-o ^/OUTPUT=^@var{file}
8511 @cindex @option{^-o^/OUTPUT^} (@code{gnatbind})
8512 Set name of output file to @var{file} instead of the normal
8513 @file{b~@var{mainprog}.adb} default. Note that @var{file} denote the Ada
8514 binder generated body filename.
8515 Note that if this option is used, then linking must be done manually.
8516 It is not possible to use gnatlink in this case, since it cannot locate
8517 the binder file.
8519 @item ^-r^/RESTRICTION_LIST^
8520 @cindex @option{^-r^/RESTRICTION_LIST^} (@code{gnatbind})
8521 Generate list of @code{pragma Restrictions} that could be applied to
8522 the current unit. This is useful for code audit purposes, and also may
8523 be used to improve code generation in some cases.
8525 @end table
8527 @node Dynamic Allocation Control
8528 @subsection Dynamic Allocation Control
8530 @noindent
8531 The heap control switches -- @option{-H32} and @option{-H64} --
8532 determine whether dynamic allocation uses 32-bit or 64-bit memory.
8533 They only affect compiler-generated allocations via @code{__gnat_malloc};
8534 explicit calls to @code{malloc} and related functions from the C
8535 run-time library are unaffected.
8537 @table @option
8538 @item -H32
8539 Allocate memory on 32-bit heap
8541 @item -H64
8542 Allocate memory on 64-bit heap.  This is the default
8543 unless explicitly overridden by a @code{'Size} clause on the access type.
8544 @end table
8546 @ifset vms
8547 @noindent
8548 See also @ref{Access types and 32/64-bit allocation}.
8549 @end ifset
8550 @ifclear vms
8551 @noindent
8552 These switches are only effective on VMS platforms.
8553 @end ifclear
8556 @node Binding with Non-Ada Main Programs
8557 @subsection Binding with Non-Ada Main Programs
8559 @noindent
8560 In our description so far we have assumed that the main
8561 program is in Ada, and that the task of the binder is to generate a
8562 corresponding function @code{main} that invokes this Ada main
8563 program. GNAT also supports the building of executable programs where
8564 the main program is not in Ada, but some of the called routines are
8565 written in Ada and compiled using GNAT (@pxref{Mixed Language Programming}).
8566 The following switch is used in this situation:
8568 @table @option
8569 @item ^-n^/NOMAIN^
8570 @cindex @option{^-n^/NOMAIN^} (@code{gnatbind})
8571 No main program. The main program is not in Ada.
8572 @end table
8574 @noindent
8575 In this case, most of the functions of the binder are still required,
8576 but instead of generating a main program, the binder generates a file
8577 containing the following callable routines:
8579 @table @code
8580 @item adainit
8581 @findex adainit
8582 You must call this routine to initialize the Ada part of the program by
8583 calling the necessary elaboration routines. A call to @code{adainit} is
8584 required before the first call to an Ada subprogram.
8586 Note that it is assumed that the basic execution environment must be setup
8587 to be appropriate for Ada execution at the point where the first Ada
8588 subprogram is called. In particular, if the Ada code will do any
8589 floating-point operations, then the FPU must be setup in an appropriate
8590 manner. For the case of the x86, for example, full precision mode is
8591 required. The procedure GNAT.Float_Control.Reset may be used to ensure
8592 that the FPU is in the right state.
8594 @item adafinal
8595 @findex adafinal
8596 You must call this routine to perform any library-level finalization
8597 required by the Ada subprograms. A call to @code{adafinal} is required
8598 after the last call to an Ada subprogram, and before the program
8599 terminates.
8600 @end table
8602 @noindent
8603 If the @option{^-n^/NOMAIN^} switch
8604 @cindex @option{^-n^/NOMAIN^} (@command{gnatbind})
8605 @cindex Binder, multiple input files
8606 is given, more than one ALI file may appear on
8607 the command line for @code{gnatbind}. The normal @dfn{closure}
8608 calculation is performed for each of the specified units. Calculating
8609 the closure means finding out the set of units involved by tracing
8610 @code{with} references. The reason it is necessary to be able to
8611 specify more than one ALI file is that a given program may invoke two or
8612 more quite separate groups of Ada units.
8614 The binder takes the name of its output file from the last specified ALI
8615 file, unless overridden by the use of the @option{^-o file^/OUTPUT=file^}.
8616 @cindex @option{^-o^/OUTPUT^} (@command{gnatbind})
8617 The output is an Ada unit in source form that can be compiled with GNAT.
8618 This compilation occurs automatically as part of the @command{gnatlink}
8619 processing.
8621 Currently the GNAT run time requires a FPU using 80 bits mode
8622 precision. Under targets where this is not the default it is required to
8623 call GNAT.Float_Control.Reset before using floating point numbers (this
8624 include float computation, float input and output) in the Ada code. A
8625 side effect is that this could be the wrong mode for the foreign code
8626 where floating point computation could be broken after this call.
8628 @node Binding Programs with No Main Subprogram
8629 @subsection Binding Programs with No Main Subprogram
8631 @noindent
8632 It is possible to have an Ada program which does not have a main
8633 subprogram. This program will call the elaboration routines of all the
8634 packages, then the finalization routines.
8636 The following switch is used to bind programs organized in this manner:
8638 @table @option
8639 @item ^-z^/ZERO_MAIN^
8640 @cindex @option{^-z^/ZERO_MAIN^} (@code{gnatbind})
8641 Normally the binder checks that the unit name given on the command line
8642 corresponds to a suitable main subprogram. When this switch is used,
8643 a list of ALI files can be given, and the execution of the program
8644 consists of elaboration of these units in an appropriate order. Note
8645 that the default wide character encoding method for standard Text_IO
8646 files is always set to Brackets if this switch is set (you can use
8647 the binder switch
8648 @option{^-Wx^WIDE_CHARACTER_ENCODING^} to override this default).
8649 @end table
8651 @node Command-Line Access
8652 @section Command-Line Access
8654 @noindent
8655 The package @code{Ada.Command_Line} provides access to the command-line
8656 arguments and program name. In order for this interface to operate
8657 correctly, the two variables
8659 @smallexample
8660 @group
8661 int gnat_argc;
8662 char **gnat_argv;
8663 @end group
8664 @end smallexample
8666 @noindent
8667 @findex gnat_argv
8668 @findex gnat_argc
8669 are declared in one of the GNAT library routines. These variables must
8670 be set from the actual @code{argc} and @code{argv} values passed to the
8671 main program. With no @option{^n^/NOMAIN^} present, @code{gnatbind}
8672 generates the C main program to automatically set these variables.
8673 If the @option{^n^/NOMAIN^} switch is used, there is no automatic way to
8674 set these variables. If they are not set, the procedures in
8675 @code{Ada.Command_Line} will not be available, and any attempt to use
8676 them will raise @code{Constraint_Error}. If command line access is
8677 required, your main program must set @code{gnat_argc} and
8678 @code{gnat_argv} from the @code{argc} and @code{argv} values passed to
8681 @node Search Paths for gnatbind
8682 @section Search Paths for @code{gnatbind}
8684 @noindent
8685 The binder takes the name of an ALI file as its argument and needs to
8686 locate source files as well as other ALI files to verify object consistency.
8688 For source files, it follows exactly the same search rules as @command{gcc}
8689 (@pxref{Search Paths and the Run-Time Library (RTL)}). For ALI files the
8690 directories searched are:
8692 @enumerate
8693 @item
8694 The directory containing the ALI file named in the command line, unless
8695 the switch @option{^-I-^/NOCURRENT_DIRECTORY^} is specified.
8697 @item
8698 All directories specified by @option{^-I^/SEARCH^}
8699 switches on the @code{gnatbind}
8700 command line, in the order given.
8702 @item
8703 @findex ADA_PRJ_OBJECTS_FILE
8704 Each of the directories listed in the text file whose name is given
8705 by the @env{ADA_PRJ_OBJECTS_FILE} ^environment variable^logical name^.
8707 @noindent
8708 @env{ADA_PRJ_OBJECTS_FILE} is normally set by gnatmake or by the ^gnat^GNAT^
8709 driver when project files are used. It should not normally be set
8710 by other means.
8712 @item
8713 @findex ADA_OBJECTS_PATH
8714 Each of the directories listed in the value of the
8715 @env{ADA_OBJECTS_PATH} ^environment variable^logical name^.
8716 @ifset unw
8717 Construct this value
8718 exactly as the @env{PATH} environment variable: a list of directory
8719 names separated by colons (semicolons when working with the NT version
8720 of GNAT).
8721 @end ifset
8722 @ifset vms
8723 Normally, define this value as a logical name containing a comma separated
8724 list of directory names.
8726 This variable can also be defined by means of an environment string
8727 (an argument to the HP C exec* set of functions).
8729 Logical Name:
8730 @smallexample
8731 DEFINE ANOTHER_PATH FOO:[BAG]
8732 DEFINE ADA_OBJECTS_PATH ANOTHER_PATH,FOO:[BAM],FOO:[BAR]
8733 @end smallexample
8735 By default, the path includes GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB]
8736 first, followed by the standard Ada
8737 libraries in GNU:[LIB.OPENVMS7_x.2_8_x.ADALIB].
8738 If this is not redefined, the user will obtain the HP Ada 83 IO packages
8739 (Text_IO, Sequential_IO, etc)
8740 instead of the standard Ada packages. Thus, in order to get the standard Ada
8741 packages by default, ADA_OBJECTS_PATH must be redefined.
8742 @end ifset
8744 @item
8745 The content of the @file{ada_object_path} file which is part of the GNAT
8746 installation tree and is used to store standard libraries such as the
8747 GNAT Run Time Library (RTL) unless the switch @option{-nostdlib} is
8748 specified.
8749 @ifclear vms
8750 @ref{Installing a library}
8751 @end ifclear
8752 @end enumerate
8754 @noindent
8755 In the binder the switch @option{^-I^/SEARCH^}
8756 @cindex @option{^-I^/SEARCH^} (@command{gnatbind})
8757 is used to specify both source and
8758 library file paths. Use @option{^-aI^/SOURCE_SEARCH^}
8759 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatbind})
8760 instead if you want to specify
8761 source paths only, and @option{^-aO^/LIBRARY_SEARCH^}
8762 @cindex @option{^-aO^/LIBRARY_SEARCH^} (@command{gnatbind})
8763 if you want to specify library paths
8764 only. This means that for the binder
8765 @option{^-I^/SEARCH=^}@var{dir} is equivalent to
8766 @option{^-aI^/SOURCE_SEARCH=^}@var{dir}
8767 @option{^-aO^/OBJECT_SEARCH=^}@var{dir}.
8768 The binder generates the bind file (a C language source file) in the
8769 current working directory.
8771 @findex Ada
8772 @findex System
8773 @findex Interfaces
8774 @findex GNAT
8775 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
8776 children make up the GNAT Run-Time Library, together with the package
8777 GNAT and its children, which contain a set of useful additional
8778 library functions provided by GNAT. The sources for these units are
8779 needed by the compiler and are kept together in one directory. The ALI
8780 files and object files generated by compiling the RTL are needed by the
8781 binder and the linker and are kept together in one directory, typically
8782 different from the directory containing the sources. In a normal
8783 installation, you need not specify these directory names when compiling
8784 or binding. Either the environment variables or the built-in defaults
8785 cause these files to be found.
8787 Besides simplifying access to the RTL, a major use of search paths is
8788 in compiling sources from multiple directories. This can make
8789 development environments much more flexible.
8791 @node Examples of gnatbind Usage
8792 @section Examples of @code{gnatbind} Usage
8794 @noindent
8795 This section contains a number of examples of using the GNAT binding
8796 utility @code{gnatbind}.
8798 @table @code
8799 @item gnatbind hello
8800 The main program @code{Hello} (source program in @file{hello.adb}) is
8801 bound using the standard switch settings. The generated main program is
8802 @file{b~hello.adb}. This is the normal, default use of the binder.
8804 @ifclear vms
8805 @item gnatbind hello -o mainprog.adb
8806 @end ifclear
8807 @ifset vms
8808 @item gnatbind HELLO.ALI /OUTPUT=Mainprog.ADB
8809 @end ifset
8810 The main program @code{Hello} (source program in @file{hello.adb}) is
8811 bound using the standard switch settings. The generated main program is
8812 @file{mainprog.adb} with the associated spec in
8813 @file{mainprog.ads}. Note that you must specify the body here not the
8814 spec. Note that if this option is used, then linking must be done manually,
8815 since gnatlink will not be able to find the generated file.
8816 @end table
8818 @c ------------------------------------
8819 @node Linking with gnatlink
8820 @chapter Linking with @command{gnatlink}
8821 @c ------------------------------------
8822 @findex gnatlink
8824 @noindent
8825 This chapter discusses @command{gnatlink}, a tool that links
8826 an Ada program and builds an executable file. This utility
8827 invokes the system linker ^(via the @command{gcc} command)^^
8828 with a correct list of object files and library references.
8829 @command{gnatlink} automatically determines the list of files and
8830 references for the Ada part of a program. It uses the binder file
8831 generated by the @command{gnatbind} to determine this list.
8833 Note: to invoke @code{gnatlink} with a project file, use the @code{gnat}
8834 driver (see @ref{The GNAT Driver and Project Files}).
8836 @menu
8837 * Running gnatlink::
8838 * Switches for gnatlink::
8839 @end menu
8841 @node Running gnatlink
8842 @section Running @command{gnatlink}
8844 @noindent
8845 The form of the @command{gnatlink} command is
8847 @smallexample
8848 @c $ gnatlink @ovar{switches} @var{mainprog}@r{[}.ali@r{]}
8849 @c            @ovar{non-Ada objects} @ovar{linker options}
8850 @c Expanding @ovar macro inline (explanation in macro def comments)
8851 $ gnatlink @r{[}@var{switches}@r{]} @var{mainprog}@r{[}.ali@r{]}
8852            @r{[}@var{non-Ada objects}@r{]} @r{[}@var{linker options}@r{]}
8854 @end smallexample
8856 @noindent
8857 The arguments of @command{gnatlink} (switches, main @file{ALI} file,
8858 non-Ada objects
8859 or linker options) may be in any order, provided that no non-Ada object may
8860 be mistaken for a main @file{ALI} file.
8861 Any file name @file{F} without the @file{.ali}
8862 extension will be taken as the main @file{ALI} file if a file exists
8863 whose name is the concatenation of @file{F} and @file{.ali}.
8865 @noindent
8866 @file{@var{mainprog}.ali} references the ALI file of the main program.
8867 The @file{.ali} extension of this file can be omitted. From this
8868 reference, @command{gnatlink} locates the corresponding binder file
8869 @file{b~@var{mainprog}.adb} and, using the information in this file along
8870 with the list of non-Ada objects and linker options, constructs a
8871 linker command file to create the executable.
8873 The arguments other than the @command{gnatlink} switches and the main
8874 @file{ALI} file are passed to the linker uninterpreted.
8875 They typically include the names of
8876 object files for units written in other languages than Ada and any library
8877 references required to resolve references in any of these foreign language
8878 units, or in @code{Import} pragmas in any Ada units.
8880 @var{linker options} is an optional list of linker specific
8881 switches.
8882 The default linker called by gnatlink is @command{gcc} which in
8883 turn calls the appropriate system linker.
8885 One useful option for the linker is @option{-s}: it reduces the size of the
8886 executable by removing all symbol table and relocation information from the
8887 executable.
8889 Standard options for the linker such as @option{-lmy_lib} or
8890 @option{-Ldir} can be added as is.
8891 For options that are not recognized by
8892 @command{gcc} as linker options, use the @command{gcc} switches
8893 @option{-Xlinker} or @option{-Wl,}.
8895 Refer to the GCC documentation for
8896 details.
8898 Here is an example showing how to generate a linker map:
8900 @smallexample
8901 $ ^gnatlink my_prog -Wl,-Map,MAPFILE^GNAT LINK my_prog.ali /MAP^
8902 @end smallexample
8904 Using @var{linker options} it is possible to set the program stack and
8905 heap size.
8906 @ifset unw
8907 See @ref{Setting Stack Size from gnatlink} and
8908 @ref{Setting Heap Size from gnatlink}.
8909 @end ifset
8911 @command{gnatlink} determines the list of objects required by the Ada
8912 program and prepends them to the list of objects passed to the linker.
8913 @command{gnatlink} also gathers any arguments set by the use of
8914 @code{pragma Linker_Options} and adds them to the list of arguments
8915 presented to the linker.
8917 @ifset vms
8918 @command{gnatlink} accepts the following types of extra files on the command
8919 line: objects (@file{.OBJ}), libraries (@file{.OLB}), sharable images
8920 (@file{.EXE}), and options files (@file{.OPT}). These are recognized and
8921 handled according to their extension.
8922 @end ifset
8924 @node Switches for gnatlink
8925 @section Switches for @command{gnatlink}
8927 @noindent
8928 The following switches are available with the @command{gnatlink} utility:
8930 @table @option
8931 @c !sort!
8933 @item --version
8934 @cindex @option{--version} @command{gnatlink}
8935 Display Copyright and version, then exit disregarding all other options.
8937 @item --help
8938 @cindex @option{--help} @command{gnatlink}
8939 If @option{--version} was not used, display usage, then exit disregarding
8940 all other options.
8942 @item ^-f^/FORCE_OBJECT_FILE_LIST^
8943 @cindex Command line length
8944 @cindex @option{^-f^/FORCE_OBJECT_FILE_LIST^} (@command{gnatlink})
8945 On some targets, the command line length is limited, and @command{gnatlink}
8946 will generate a separate file for the linker if the list of object files
8947 is too long.
8948 The @option{^-f^/FORCE_OBJECT_FILE_LIST^} switch forces this file
8949 to be generated even if
8950 the limit is not exceeded. This is useful in some cases to deal with
8951 special situations where the command line length is exceeded.
8953 @item ^-g^/DEBUG^
8954 @cindex Debugging information, including
8955 @cindex @option{^-g^/DEBUG^} (@command{gnatlink})
8956 The option to include debugging information causes the Ada bind file (in
8957 other words, @file{b~@var{mainprog}.adb}) to be compiled with
8958 @option{^-g^/DEBUG^}.
8959 In addition, the binder does not delete the @file{b~@var{mainprog}.adb},
8960 @file{b~@var{mainprog}.o} and @file{b~@var{mainprog}.ali} files.
8961 Without @option{^-g^/DEBUG^}, the binder removes these files by
8962 default. The same procedure apply if a C bind file was generated using
8963 @option{^-C^/BIND_FILE=C^} @code{gnatbind} option, in this case the filenames
8964 are @file{b_@var{mainprog}.c} and @file{b_@var{mainprog}.o}.
8966 @item ^-n^/NOCOMPILE^
8967 @cindex @option{^-n^/NOCOMPILE^} (@command{gnatlink})
8968 Do not compile the file generated by the binder. This may be used when
8969 a link is rerun with different options, but there is no need to recompile
8970 the binder file.
8972 @item ^-v^/VERBOSE^
8973 @cindex @option{^-v^/VERBOSE^} (@command{gnatlink})
8974 Causes additional information to be output, including a full list of the
8975 included object files. This switch option is most useful when you want
8976 to see what set of object files are being used in the link step.
8978 @item ^-v -v^/VERBOSE/VERBOSE^
8979 @cindex @option{^-v -v^/VERBOSE/VERBOSE^} (@command{gnatlink})
8980 Very verbose mode. Requests that the compiler operate in verbose mode when
8981 it compiles the binder file, and that the system linker run in verbose mode.
8983 @item ^-o ^/EXECUTABLE=^@var{exec-name}
8984 @cindex @option{^-o^/EXECUTABLE^} (@command{gnatlink})
8985 @var{exec-name} specifies an alternate name for the generated
8986 executable program. If this switch is omitted, the executable has the same
8987 name as the main unit. For example, @code{gnatlink try.ali} creates
8988 an executable called @file{^try^TRY.EXE^}.
8990 @ifclear vms
8991 @item -b @var{target}
8992 @cindex @option{-b} (@command{gnatlink})
8993 Compile your program to run on @var{target}, which is the name of a
8994 system configuration. You must have a GNAT cross-compiler built if
8995 @var{target} is not the same as your host system.
8997 @item -B@var{dir}
8998 @cindex @option{-B} (@command{gnatlink})
8999 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
9000 from @var{dir} instead of the default location. Only use this switch
9001 when multiple versions of the GNAT compiler are available.
9002 @xref{Directory Options,,, gcc, The GNU Compiler Collection},
9003 for further details. You would normally use the @option{-b} or
9004 @option{-V} switch instead.
9006 @item -M
9007 When linking an executable, create a map file. The name of the map file
9008 has the same name as the executable with extension ".map".
9010 @item -M=mapfile
9011 When linking an executable, create a map file. The name of the map file is
9012 "mapfile".
9014 @item --GCC=@var{compiler_name}
9015 @cindex @option{--GCC=compiler_name} (@command{gnatlink})
9016 Program used for compiling the binder file. The default is
9017 @command{gcc}. You need to use quotes around @var{compiler_name} if
9018 @code{compiler_name} contains spaces or other separator characters.
9019 As an example @option{--GCC="foo -x -y"} will instruct @command{gnatlink} to
9020 use @code{foo -x -y} as your compiler. Note that switch @option{-c} is always
9021 inserted after your command name. Thus in the above example the compiler
9022 command that will be used by @command{gnatlink} will be @code{foo -c -x -y}.
9023 A limitation of this syntax is that the name and path name of the executable
9024 itself must not include any embedded spaces. If the compiler executable is
9025 different from the default one (gcc or <prefix>-gcc), then the back-end
9026 switches in the ALI file are not used to compile the binder generated source.
9027 For example, this is the case with @option{--GCC="foo -x -y"}. But the back end
9028 switches will be used for @option{--GCC="gcc -gnatv"}. If several
9029 @option{--GCC=compiler_name} are used, only the last @var{compiler_name}
9030 is taken into account. However, all the additional switches are also taken
9031 into account. Thus,
9032 @option{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
9033 @option{--GCC="bar -x -y -z -t"}.
9035 @item --LINK=@var{name}
9036 @cindex @option{--LINK=} (@command{gnatlink})
9037 @var{name} is the name of the linker to be invoked. This is especially
9038 useful in mixed language programs since languages such as C++ require
9039 their own linker to be used. When this switch is omitted, the default
9040 name for the linker is @command{gcc}. When this switch is used, the
9041 specified linker is called instead of @command{gcc} with exactly the same
9042 parameters that would have been passed to @command{gcc} so if the desired
9043 linker requires different parameters it is necessary to use a wrapper
9044 script that massages the parameters before invoking the real linker. It
9045 may be useful to control the exact invocation by using the verbose
9046 switch.
9048 @end ifclear
9050 @ifset vms
9051 @item /DEBUG=TRACEBACK
9052 @cindex @code{/DEBUG=TRACEBACK} (@command{gnatlink})
9053 This qualifier causes sufficient information to be included in the
9054 executable file to allow a traceback, but does not include the full
9055 symbol information needed by the debugger.
9057 @item /IDENTIFICATION="<string>"
9058 @code{"<string>"} specifies the string to be stored in the image file
9059 identification field in the image header.
9060 It overrides any pragma @code{Ident} specified string.
9062 @item /NOINHIBIT-EXEC
9063 Generate the executable file even if there are linker warnings.
9065 @item /NOSTART_FILES
9066 Don't link in the object file containing the ``main'' transfer address.
9067 Used when linking with a foreign language main program compiled with an
9068 HP compiler.
9070 @item /STATIC
9071 Prefer linking with object libraries over sharable images, even without
9072 /DEBUG.
9073 @end ifset
9075 @end table
9077 @node The GNAT Make Program gnatmake
9078 @chapter The GNAT Make Program @command{gnatmake}
9079 @findex gnatmake
9081 @menu
9082 * Running gnatmake::
9083 * Switches for gnatmake::
9084 * Mode Switches for gnatmake::
9085 * Notes on the Command Line::
9086 * How gnatmake Works::
9087 * Examples of gnatmake Usage::
9088 @end menu
9089 @noindent
9090 A typical development cycle when working on an Ada program consists of
9091 the following steps:
9093 @enumerate
9094 @item
9095 Edit some sources to fix bugs.
9097 @item
9098 Add enhancements.
9100 @item
9101 Compile all sources affected.
9103 @item
9104 Rebind and relink.
9106 @item
9107 Test.
9108 @end enumerate
9110 @noindent
9111 The third step can be tricky, because not only do the modified files
9112 @cindex Dependency rules
9113 have to be compiled, but any files depending on these files must also be
9114 recompiled. The dependency rules in Ada can be quite complex, especially
9115 in the presence of overloading, @code{use} clauses, generics and inlined
9116 subprograms.
9118 @command{gnatmake} automatically takes care of the third and fourth steps
9119 of this process. It determines which sources need to be compiled,
9120 compiles them, and binds and links the resulting object files.
9122 Unlike some other Ada make programs, the dependencies are always
9123 accurately recomputed from the new sources. The source based approach of
9124 the GNAT compilation model makes this possible. This means that if
9125 changes to the source program cause corresponding changes in
9126 dependencies, they will always be tracked exactly correctly by
9127 @command{gnatmake}.
9129 @node Running gnatmake
9130 @section Running @command{gnatmake}
9132 @noindent
9133 The usual form of the @command{gnatmake} command is
9135 @smallexample
9136 @c $ gnatmake @ovar{switches} @var{file_name}
9137 @c       @ovar{file_names} @ovar{mode_switches}
9138 @c Expanding @ovar macro inline (explanation in macro def comments)
9139 $ gnatmake @r{[}@var{switches}@r{]} @var{file_name}
9140       @r{[}@var{file_names}@r{]} @r{[}@var{mode_switches}@r{]}
9141 @end smallexample
9143 @noindent
9144 The only required argument is one @var{file_name}, which specifies
9145 a compilation unit that is a main program. Several @var{file_names} can be
9146 specified: this will result in several executables being built.
9147 If @code{switches} are present, they can be placed before the first
9148 @var{file_name}, between @var{file_names} or after the last @var{file_name}.
9149 If @var{mode_switches} are present, they must always be placed after
9150 the last @var{file_name} and all @code{switches}.
9152 If you are using standard file extensions (@file{.adb} and @file{.ads}), then the
9153 extension may be omitted from the @var{file_name} arguments. However, if
9154 you are using non-standard extensions, then it is required that the
9155 extension be given. A relative or absolute directory path can be
9156 specified in a @var{file_name}, in which case, the input source file will
9157 be searched for in the specified directory only. Otherwise, the input
9158 source file will first be searched in the directory where
9159 @command{gnatmake} was invoked and if it is not found, it will be search on
9160 the source path of the compiler as described in
9161 @ref{Search Paths and the Run-Time Library (RTL)}.
9163 All @command{gnatmake} output (except when you specify
9164 @option{^-M^/DEPENDENCIES_LIST^}) is to
9165 @file{stderr}. The output produced by the
9166 @option{^-M^/DEPENDENCIES_LIST^} switch is send to
9167 @file{stdout}.
9169 @node Switches for gnatmake
9170 @section Switches for @command{gnatmake}
9172 @noindent
9173 You may specify any of the following switches to @command{gnatmake}:
9175 @table @option
9176 @c !sort!
9178 @item --version
9179 @cindex @option{--version} @command{gnatmake}
9180 Display Copyright and version, then exit disregarding all other options.
9182 @item --help
9183 @cindex @option{--help} @command{gnatmake}
9184 If @option{--version} was not used, display usage, then exit disregarding
9185 all other options.
9187 @ifclear vms
9188 @item --GCC=@var{compiler_name}
9189 @cindex @option{--GCC=compiler_name} (@command{gnatmake})
9190 Program used for compiling. The default is `@command{gcc}'. You need to use
9191 quotes around @var{compiler_name} if @code{compiler_name} contains
9192 spaces or other separator characters. As an example @option{--GCC="foo -x
9193 -y"} will instruct @command{gnatmake} to use @code{foo -x -y} as your
9194 compiler. A limitation of this syntax is that the name and path name of
9195 the executable itself must not include any embedded spaces. Note that
9196 switch @option{-c} is always inserted after your command name. Thus in the
9197 above example the compiler command that will be used by @command{gnatmake}
9198 will be @code{foo -c -x -y}. If several @option{--GCC=compiler_name} are
9199 used, only the last @var{compiler_name} is taken into account. However,
9200 all the additional switches are also taken into account. Thus,
9201 @option{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
9202 @option{--GCC="bar -x -y -z -t"}.
9204 @item --GNATBIND=@var{binder_name}
9205 @cindex @option{--GNATBIND=binder_name} (@command{gnatmake})
9206 Program used for binding. The default is `@code{gnatbind}'. You need to
9207 use quotes around @var{binder_name} if @var{binder_name} contains spaces
9208 or other separator characters. As an example @option{--GNATBIND="bar -x
9209 -y"} will instruct @command{gnatmake} to use @code{bar -x -y} as your
9210 binder. Binder switches that are normally appended by @command{gnatmake}
9211 to `@code{gnatbind}' are now appended to the end of @code{bar -x -y}.
9212 A limitation of this syntax is that the name and path name of the executable
9213 itself must not include any embedded spaces.
9215 @item --GNATLINK=@var{linker_name}
9216 @cindex @option{--GNATLINK=linker_name} (@command{gnatmake})
9217 Program used for linking. The default is `@command{gnatlink}'. You need to
9218 use quotes around @var{linker_name} if @var{linker_name} contains spaces
9219 or other separator characters. As an example @option{--GNATLINK="lan -x
9220 -y"} will instruct @command{gnatmake} to use @code{lan -x -y} as your
9221 linker. Linker switches that are normally appended by @command{gnatmake} to
9222 `@command{gnatlink}' are now appended to the end of @code{lan -x -y}.
9223 A limitation of this syntax is that the name and path name of the executable
9224 itself must not include any embedded spaces.
9226 @end ifclear
9228 @item ^--subdirs^/SUBDIRS^=subdir
9229 Actual object directory of each project file is the subdirectory subdir of the
9230 object directory specified or defaulted in the project file.
9232 @item ^--single-compile-per-obj-dir^/SINGLE_COMPILE_PER_OBJ_DIR^
9233 Disallow simultaneous compilations in the same object directory when
9234 project files are used.
9236 @item ^--unchecked-shared-lib-imports^/UNCHECKED_SHARED_LIB_IMPORTS^
9237 By default, shared library projects are not allowed to import static library
9238 projects. When this switch is used on the command line, this restriction is
9239 relaxed.
9241 @item ^--source-info=<source info file>^/SRC_INFO=source-info-file^
9242 Specify a source info file. This switch is active only when project files
9243 are used. If the source info file is specified as a relative path, then it is
9244 relative to the object directory of the main project. If the source info file
9245 does not exist, then after the Project Manager has successfully parsed and
9246 processed the project files and found the sources, it creates the source info
9247 file. If the source info file already exists and can be read successfully,
9248 then the Project Manager will get all the needed information about the sources
9249 from the source info file and will not look for them. This reduces the time
9250 to process the project files, especially when looking for sources that take a
9251 long time. If the source info file exists but cannot be parsed successfully,
9252 the Project Manager will attempt to recreate it. If the Project Manager fails
9253 to create the source info file, a message is issued, but gnatmake does not
9254 fail. @command{gnatmake} "trusts" the source info file. This means that
9255 if the source files have changed (addition, deletion, moving to a different
9256 source directory), then the source info file need to be deleted and recreated.
9258 @ifclear vms
9259 @item --create-map-file
9260 When linking an executable, create a map file. The name of the map file
9261 has the same name as the executable with extension ".map".
9263 @item --create-map-file=mapfile
9264 When linking an executable, create a map file. The name of the map file is
9265 "mapfile".
9267 @end ifclear
9269 @item ^-a^/ALL_FILES^
9270 @cindex @option{^-a^/ALL_FILES^} (@command{gnatmake})
9271 Consider all files in the make process, even the GNAT internal system
9272 files (for example, the predefined Ada library files), as well as any
9273 locked files. Locked files are files whose ALI file is write-protected.
9274 By default,
9275 @command{gnatmake} does not check these files,
9276 because the assumption is that the GNAT internal files are properly up
9277 to date, and also that any write protected ALI files have been properly
9278 installed. Note that if there is an installation problem, such that one
9279 of these files is not up to date, it will be properly caught by the
9280 binder.
9281 You may have to specify this switch if you are working on GNAT
9282 itself. The switch @option{^-a^/ALL_FILES^} is also useful
9283 in conjunction with @option{^-f^/FORCE_COMPILE^}
9284 if you need to recompile an entire application,
9285 including run-time files, using special configuration pragmas,
9286 such as a @code{Normalize_Scalars} pragma.
9288 By default
9289 @code{gnatmake ^-a^/ALL_FILES^} compiles all GNAT
9290 internal files with
9291 @ifclear vms
9292 @code{gcc -c -gnatpg} rather than @code{gcc -c}.
9293 @end ifclear
9294 @ifset vms
9295 the @code{/CHECKS=SUPPRESS_ALL /STYLE_CHECKS=GNAT} switch.
9296 @end ifset
9298 @item ^-b^/ACTIONS=BIND^
9299 @cindex @option{^-b^/ACTIONS=BIND^} (@command{gnatmake})
9300 Bind only. Can be combined with @option{^-c^/ACTIONS=COMPILE^} to do
9301 compilation and binding, but no link.
9302 Can be combined with @option{^-l^/ACTIONS=LINK^}
9303 to do binding and linking. When not combined with
9304 @option{^-c^/ACTIONS=COMPILE^}
9305 all the units in the closure of the main program must have been previously
9306 compiled and must be up to date. The root unit specified by @var{file_name}
9307 may be given without extension, with the source extension or, if no GNAT
9308 Project File is specified, with the ALI file extension.
9310 @item ^-c^/ACTIONS=COMPILE^
9311 @cindex @option{^-c^/ACTIONS=COMPILE^} (@command{gnatmake})
9312 Compile only. Do not perform binding, except when @option{^-b^/ACTIONS=BIND^}
9313 is also specified. Do not perform linking, except if both
9314 @option{^-b^/ACTIONS=BIND^} and
9315 @option{^-l^/ACTIONS=LINK^} are also specified.
9316 If the root unit specified by @var{file_name} is not a main unit, this is the
9317 default. Otherwise @command{gnatmake} will attempt binding and linking
9318 unless all objects are up to date and the executable is more recent than
9319 the objects.
9321 @item ^-C^/MAPPING^
9322 @cindex @option{^-C^/MAPPING^} (@command{gnatmake})
9323 Use a temporary mapping file. A mapping file is a way to communicate
9324 to the compiler two mappings: from unit names to file names (without
9325 any directory information) and from file names to path names (with
9326 full directory information). A mapping file can make the compiler's
9327 file searches faster, especially if there are many source directories,
9328 or the sources are read over a slow network connection. If
9329 @option{^-P^/PROJECT_FILE^} is used, a mapping file is always used, so
9330 @option{^-C^/MAPPING^} is unnecessary; in this case the mapping file
9331 is initially populated based on the project file. If
9332 @option{^-C^/MAPPING^} is used without
9333 @option{^-P^/PROJECT_FILE^},
9334 the mapping file is initially empty. Each invocation of the compiler
9335 will add any newly accessed sources to the mapping file.
9337 @item ^-C=^/USE_MAPPING_FILE=^@var{file}
9338 @cindex @option{^-C=^/USE_MAPPING^} (@command{gnatmake})
9339 Use a specific mapping file. The file, specified as a path name (absolute or
9340 relative) by this switch, should already exist, otherwise the switch is
9341 ineffective. The specified mapping file will be communicated to the compiler.
9342 This switch is not compatible with a project file
9343 (^-P^/PROJECT_FILE=^@var{file}) or with multiple compiling processes
9344 (^-j^/PROCESSES=^nnn, when nnn is greater than 1).
9346 @item ^-d^/DISPLAY_PROGRESS^
9347 @cindex @option{^-d^/DISPLAY_PROGRESS^} (@command{gnatmake})
9348 Display progress for each source, up to date or not, as a single line
9350 @smallexample
9351 completed x out of y (zz%)
9352 @end smallexample
9354 If the file needs to be compiled this is displayed after the invocation of
9355 the compiler. These lines are displayed even in quiet output mode.
9357 @item ^-D ^/DIRECTORY_OBJECTS=^@var{dir}
9358 @cindex @option{^-D^/DIRECTORY_OBJECTS^} (@command{gnatmake})
9359 Put all object files and ALI file in directory @var{dir}.
9360 If the @option{^-D^/DIRECTORY_OBJECTS^} switch is not used, all object files
9361 and ALI files go in the current working directory.
9363 This switch cannot be used when using a project file.
9365 @item -eInnn
9366 @cindex @option{-eI} (@command{gnatmake})
9367 Indicates that the main source is a multi-unit source and the rank of the unit
9368 in the source file is nnn. nnn needs to be a positive number and a valid
9369 index in the source. This switch cannot be used when @command{gnatmake} is
9370 invoked for several mains.
9372 @ifclear vms
9373 @item -eL
9374 @cindex @option{-eL} (@command{gnatmake})
9375 @cindex symbolic links
9376 Follow all symbolic links when processing project files.
9377 This should be used if your project uses symbolic links for files or
9378 directories, but is not needed in other cases.
9380 @cindex naming scheme
9381 This also assumes that no directory matches the naming scheme for files (for
9382 instance that you do not have a directory called "sources.ads" when using the
9383 default GNAT naming scheme).
9385 When you do not have to use this switch (i.e.@: by default), gnatmake is able to
9386 save a lot of system calls (several per source file and object file), which
9387 can result in a significant speed up to load and manipulate a project file,
9388 especially when using source files from a remote system.
9390 @end ifclear
9392 @item ^-eS^/STANDARD_OUTPUT_FOR_COMMANDS^
9393 @cindex @option{^-eS^/STANDARD_OUTPUT_FOR_COMMANDS^} (@command{gnatmake})
9394 Output the commands for the compiler, the binder and the linker
9395 on ^standard output^SYS$OUTPUT^,
9396 instead of ^standard error^SYS$ERROR^.
9398 @item ^-f^/FORCE_COMPILE^
9399 @cindex @option{^-f^/FORCE_COMPILE^} (@command{gnatmake})
9400 Force recompilations. Recompile all sources, even though some object
9401 files may be up to date, but don't recompile predefined or GNAT internal
9402 files or locked files (files with a write-protected ALI file),
9403 unless the @option{^-a^/ALL_FILES^} switch is also specified.
9405 @item ^-F^/FULL_PATH_IN_BRIEF_MESSAGES^
9406 @cindex @option{^-F^/FULL_PATH_IN_BRIEF_MESSAGES^} (@command{gnatmake})
9407 When using project files, if some errors or warnings are detected during
9408 parsing and verbose mode is not in effect (no use of switch
9409 ^-v^/VERBOSE^), then error lines start with the full path name of the project
9410 file, rather than its simple file name.
9412 @item ^-g^/DEBUG^
9413 @cindex @option{^-g^/DEBUG^} (@command{gnatmake})
9414 Enable debugging. This switch is simply passed to the compiler and to the
9415 linker.
9417 @item ^-i^/IN_PLACE^
9418 @cindex @option{^-i^/IN_PLACE^} (@command{gnatmake})
9419 In normal mode, @command{gnatmake} compiles all object files and ALI files
9420 into the current directory. If the @option{^-i^/IN_PLACE^} switch is used,
9421 then instead object files and ALI files that already exist are overwritten
9422 in place. This means that once a large project is organized into separate
9423 directories in the desired manner, then @command{gnatmake} will automatically
9424 maintain and update this organization. If no ALI files are found on the
9425 Ada object path (@ref{Search Paths and the Run-Time Library (RTL)}),
9426 the new object and ALI files are created in the
9427 directory containing the source being compiled. If another organization
9428 is desired, where objects and sources are kept in different directories,
9429 a useful technique is to create dummy ALI files in the desired directories.
9430 When detecting such a dummy file, @command{gnatmake} will be forced to
9431 recompile the corresponding source file, and it will be put the resulting
9432 object and ALI files in the directory where it found the dummy file.
9434 @item ^-j^/PROCESSES=^@var{n}
9435 @cindex @option{^-j^/PROCESSES^} (@command{gnatmake})
9436 @cindex Parallel make
9437 Use @var{n} processes to carry out the (re)compilations. On a multiprocessor
9438 machine compilations will occur in parallel. If @var{n} is 0, then the
9439 maximum number of parallel compilations is the number of core processors
9440 on the platform. In the event of compilation errors, messages from various
9441 compilations might get interspersed (but @command{gnatmake} will give you the
9442 full ordered list of failing compiles at the end). If this is problematic,
9443 rerun the make process with n set to 1 to get a clean list of messages.
9445 @item ^-k^/CONTINUE_ON_ERROR^
9446 @cindex @option{^-k^/CONTINUE_ON_ERROR^} (@command{gnatmake})
9447 Keep going. Continue as much as possible after a compilation error. To
9448 ease the programmer's task in case of compilation errors, the list of
9449 sources for which the compile fails is given when @command{gnatmake}
9450 terminates.
9452 If @command{gnatmake} is invoked with several @file{file_names} and with this
9453 switch, if there are compilation errors when building an executable,
9454 @command{gnatmake} will not attempt to build the following executables.
9456 @item ^-l^/ACTIONS=LINK^
9457 @cindex @option{^-l^/ACTIONS=LINK^} (@command{gnatmake})
9458 Link only. Can be combined with @option{^-b^/ACTIONS=BIND^} to binding
9459 and linking. Linking will not be performed if combined with
9460 @option{^-c^/ACTIONS=COMPILE^}
9461 but not with @option{^-b^/ACTIONS=BIND^}.
9462 When not combined with @option{^-b^/ACTIONS=BIND^}
9463 all the units in the closure of the main program must have been previously
9464 compiled and must be up to date, and the main program needs to have been bound.
9465 The root unit specified by @var{file_name}
9466 may be given without extension, with the source extension or, if no GNAT
9467 Project File is specified, with the ALI file extension.
9469 @item ^-m^/MINIMAL_RECOMPILATION^
9470 @cindex @option{^-m^/MINIMAL_RECOMPILATION^} (@command{gnatmake})
9471 Specify that the minimum necessary amount of recompilations
9472 be performed. In this mode @command{gnatmake} ignores time
9473 stamp differences when the only
9474 modifications to a source file consist in adding/removing comments,
9475 empty lines, spaces or tabs. This means that if you have changed the
9476 comments in a source file or have simply reformatted it, using this
9477 switch will tell @command{gnatmake} not to recompile files that depend on it
9478 (provided other sources on which these files depend have undergone no
9479 semantic modifications). Note that the debugging information may be
9480 out of date with respect to the sources if the @option{-m} switch causes
9481 a compilation to be switched, so the use of this switch represents a
9482 trade-off between compilation time and accurate debugging information.
9484 @item ^-M^/DEPENDENCIES_LIST^
9485 @cindex Dependencies, producing list
9486 @cindex @option{^-M^/DEPENDENCIES_LIST^} (@command{gnatmake})
9487 Check if all objects are up to date. If they are, output the object
9488 dependences to @file{stdout} in a form that can be directly exploited in
9489 a @file{Makefile}. By default, each source file is prefixed with its
9490 (relative or absolute) directory name. This name is whatever you
9491 specified in the various @option{^-aI^/SOURCE_SEARCH^}
9492 and @option{^-I^/SEARCH^} switches. If you use
9493 @code{gnatmake ^-M^/DEPENDENCIES_LIST^}
9494 @option{^-q^/QUIET^}
9495 (see below), only the source file names,
9496 without relative paths, are output. If you just specify the
9497 @option{^-M^/DEPENDENCIES_LIST^}
9498 switch, dependencies of the GNAT internal system files are omitted. This
9499 is typically what you want. If you also specify
9500 the @option{^-a^/ALL_FILES^} switch,
9501 dependencies of the GNAT internal files are also listed. Note that
9502 dependencies of the objects in external Ada libraries (see switch
9503 @option{^-aL^/SKIP_MISSING=^}@var{dir} in the following list)
9504 are never reported.
9506 @item ^-n^/DO_OBJECT_CHECK^
9507 @cindex @option{^-n^/DO_OBJECT_CHECK^} (@command{gnatmake})
9508 Don't compile, bind, or link. Checks if all objects are up to date.
9509 If they are not, the full name of the first file that needs to be
9510 recompiled is printed.
9511 Repeated use of this option, followed by compiling the indicated source
9512 file, will eventually result in recompiling all required units.
9514 @item ^-o ^/EXECUTABLE=^@var{exec_name}
9515 @cindex @option{^-o^/EXECUTABLE^} (@command{gnatmake})
9516 Output executable name. The name of the final executable program will be
9517 @var{exec_name}. If the @option{^-o^/EXECUTABLE^} switch is omitted the default
9518 name for the executable will be the name of the input file in appropriate form
9519 for an executable file on the host system.
9521 This switch cannot be used when invoking @command{gnatmake} with several
9522 @file{file_names}.
9524 @item ^-p or --create-missing-dirs^/CREATE_MISSING_DIRS^
9525 @cindex @option{^-p^/CREATE_MISSING_DIRS^} (@command{gnatmake})
9526 When using project files (^-P^/PROJECT_FILE=^@var{project}), create
9527 automatically missing object directories, library directories and exec
9528 directories.
9530 @item ^-P^/PROJECT_FILE=^@var{project}
9531 @cindex @option{^-P^/PROJECT_FILE^} (@command{gnatmake})
9532 Use project file @var{project}. Only one such switch can be used.
9533 @xref{gnatmake and Project Files}.
9535 @item ^-q^/QUIET^
9536 @cindex @option{^-q^/QUIET^} (@command{gnatmake})
9537 Quiet. When this flag is not set, the commands carried out by
9538 @command{gnatmake} are displayed.
9540 @item ^-s^/SWITCH_CHECK/^
9541 @cindex @option{^-s^/SWITCH_CHECK^} (@command{gnatmake})
9542 Recompile if compiler switches have changed since last compilation.
9543 All compiler switches but -I and -o are taken into account in the
9544 following way:
9545 orders between different ``first letter'' switches are ignored, but
9546 orders between same switches are taken into account. For example,
9547 @option{-O -O2} is different than @option{-O2 -O}, but @option{-g -O}
9548 is equivalent to @option{-O -g}.
9550 This switch is recommended when Integrated Preprocessing is used.
9552 @item ^-u^/UNIQUE^
9553 @cindex @option{^-u^/UNIQUE^} (@command{gnatmake})
9554 Unique. Recompile at most the main files. It implies -c. Combined with
9555 -f, it is equivalent to calling the compiler directly. Note that using
9556 ^-u^/UNIQUE^ with a project file and no main has a special meaning
9557 (@pxref{Project Files and Main Subprograms}).
9559 @item ^-U^/ALL_PROJECTS^
9560 @cindex @option{^-U^/ALL_PROJECTS^} (@command{gnatmake})
9561 When used without a project file or with one or several mains on the command
9562 line, is equivalent to ^-u^/UNIQUE^. When used with a project file and no main
9563 on the command line, all sources of all project files are checked and compiled
9564 if not up to date, and libraries are rebuilt, if necessary.
9566 @item ^-v^/REASONS^
9567 @cindex @option{^-v^/REASONS^} (@command{gnatmake})
9568 Verbose. Display the reason for all recompilations @command{gnatmake}
9569 decides are necessary, with the highest verbosity level.
9571 @item ^-vl^/LOW_VERBOSITY^
9572 @cindex @option{^-vl^/LOW_VERBOSITY^} (@command{gnatmake})
9573 Verbosity level Low. Display fewer lines than in verbosity Medium.
9575 @item ^-vm^/MEDIUM_VERBOSITY^
9576 @cindex @option{^-vm^/MEDIUM_VERBOSITY^} (@command{gnatmake})
9577 Verbosity level Medium. Potentially display fewer lines than in verbosity High.
9579 @item ^-vh^/HIGH_VERBOSITY^
9580 @cindex @option{^-vm^/HIGH_VERBOSITY^} (@command{gnatmake})
9581 Verbosity level High. Equivalent to ^-v^/REASONS^.
9583 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
9584 Indicate the verbosity of the parsing of GNAT project files.
9585 @xref{Switches Related to Project Files}.
9587 @item ^-x^/NON_PROJECT_UNIT_COMPILATION^
9588 @cindex @option{^-x^/NON_PROJECT_UNIT_COMPILATION^} (@command{gnatmake})
9589 Indicate that sources that are not part of any Project File may be compiled.
9590 Normally, when using Project Files, only sources that are part of a Project
9591 File may be compile. When this switch is used, a source outside of all Project
9592 Files may be compiled. The ALI file and the object file will be put in the
9593 object directory of the main Project. The compilation switches used will only
9594 be those specified on the command line. Even when
9595 @option{^-x^/NON_PROJECT_UNIT_COMPILATION^} is used, mains specified on the
9596 command line need to be sources of a project file.
9598 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
9599 Indicate that external variable @var{name} has the value @var{value}.
9600 The Project Manager will use this value for occurrences of
9601 @code{external(name)} when parsing the project file.
9602 @xref{Switches Related to Project Files}.
9604 @item ^-z^/NOMAIN^
9605 @cindex @option{^-z^/NOMAIN^} (@command{gnatmake})
9606 No main subprogram. Bind and link the program even if the unit name
9607 given on the command line is a package name. The resulting executable
9608 will execute the elaboration routines of the package and its closure,
9609 then the finalization routines.
9611 @end table
9613 @table @asis
9614 @item @command{gcc} @asis{switches}
9615 @ifclear vms
9616 Any uppercase or multi-character switch that is not a @command{gnatmake} switch
9617 is passed to @command{gcc} (e.g.@: @option{-O}, @option{-gnato,} etc.)
9618 @end ifclear
9619 @ifset vms
9620 Any qualifier that cannot be recognized as a qualifier for @code{GNAT MAKE}
9621 but is recognizable as a valid qualifier for @code{GNAT COMPILE} is
9622 automatically treated as a compiler switch, and passed on to all
9623 compilations that are carried out.
9624 @end ifset
9625 @end table
9627 @noindent
9628 Source and library search path switches:
9630 @table @option
9631 @c !sort!
9632 @item ^-aI^/SOURCE_SEARCH=^@var{dir}
9633 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatmake})
9634 When looking for source files also look in directory @var{dir}.
9635 The order in which source files search is undertaken is
9636 described in @ref{Search Paths and the Run-Time Library (RTL)}.
9638 @item ^-aL^/SKIP_MISSING=^@var{dir}
9639 @cindex @option{^-aL^/SKIP_MISSING^} (@command{gnatmake})
9640 Consider @var{dir} as being an externally provided Ada library.
9641 Instructs @command{gnatmake} to skip compilation units whose @file{.ALI}
9642 files have been located in directory @var{dir}. This allows you to have
9643 missing bodies for the units in @var{dir} and to ignore out of date bodies
9644 for the same units. You still need to specify
9645 the location of the specs for these units by using the switches
9646 @option{^-aI^/SOURCE_SEARCH=^@var{dir}}
9647 or @option{^-I^/SEARCH=^@var{dir}}.
9648 Note: this switch is provided for compatibility with previous versions
9649 of @command{gnatmake}. The easier method of causing standard libraries
9650 to be excluded from consideration is to write-protect the corresponding
9651 ALI files.
9653 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
9654 @cindex @option{^-aO^/OBJECT_SEARCH^} (@command{gnatmake})
9655 When searching for library and object files, look in directory
9656 @var{dir}. The order in which library files are searched is described in
9657 @ref{Search Paths for gnatbind}.
9659 @item ^-A^/CONDITIONAL_SOURCE_SEARCH=^@var{dir}
9660 @cindex Search paths, for @command{gnatmake}
9661 @cindex @option{^-A^/CONDITIONAL_SOURCE_SEARCH^} (@command{gnatmake})
9662 Equivalent to @option{^-aL^/SKIP_MISSING=^@var{dir}
9663 ^-aI^/SOURCE_SEARCH=^@var{dir}}.
9665 @item ^-I^/SEARCH=^@var{dir}
9666 @cindex @option{^-I^/SEARCH^} (@command{gnatmake})
9667 Equivalent to @option{^-aO^/OBJECT_SEARCH=^@var{dir}
9668 ^-aI^/SOURCE_SEARCH=^@var{dir}}.
9670 @item ^-I-^/NOCURRENT_DIRECTORY^
9671 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gnatmake})
9672 @cindex Source files, suppressing search
9673 Do not look for source files in the directory containing the source
9674 file named in the command line.
9675 Do not look for ALI or object files in the directory
9676 where @command{gnatmake} was invoked.
9678 @item ^-L^/LIBRARY_SEARCH=^@var{dir}
9679 @cindex @option{^-L^/LIBRARY_SEARCH^} (@command{gnatmake})
9680 @cindex Linker libraries
9681 Add directory @var{dir} to the list of directories in which the linker
9682 will search for libraries. This is equivalent to
9683 @option{-largs ^-L^/LIBRARY_SEARCH=^}@var{dir}.
9684 @ifclear vms
9685 Furthermore, under Windows, the sources pointed to by the libraries path
9686 set in the registry are not searched for.
9687 @end ifclear
9689 @item -nostdinc
9690 @cindex @option{-nostdinc} (@command{gnatmake})
9691 Do not look for source files in the system default directory.
9693 @item -nostdlib
9694 @cindex @option{-nostdlib} (@command{gnatmake})
9695 Do not look for library files in the system default directory.
9697 @item --RTS=@var{rts-path}
9698 @cindex @option{--RTS} (@command{gnatmake})
9699 Specifies the default location of the runtime library. GNAT looks for the
9700 runtime
9701 in the following directories, and stops as soon as a valid runtime is found
9702 (@file{adainclude} or @file{ada_source_path}, and @file{adalib} or
9703 @file{ada_object_path} present):
9705 @itemize @bullet
9706 @item <current directory>/$rts_path
9708 @item <default-search-dir>/$rts_path
9710 @item <default-search-dir>/rts-$rts_path
9711 @end itemize
9713 @noindent
9714 The selected path is handled like a normal RTS path.
9716 @end table
9718 @node Mode Switches for gnatmake
9719 @section Mode Switches for @command{gnatmake}
9721 @noindent
9722 The mode switches (referred to as @code{mode_switches}) allow the
9723 inclusion of switches that are to be passed to the compiler itself, the
9724 binder or the linker. The effect of a mode switch is to cause all
9725 subsequent switches up to the end of the switch list, or up to the next
9726 mode switch, to be interpreted as switches to be passed on to the
9727 designated component of GNAT.
9729 @table @option
9730 @c !sort!
9731 @item -cargs @var{switches}
9732 @cindex @option{-cargs} (@command{gnatmake})
9733 Compiler switches. Here @var{switches} is a list of switches
9734 that are valid switches for @command{gcc}. They will be passed on to
9735 all compile steps performed by @command{gnatmake}.
9737 @item -bargs @var{switches}
9738 @cindex @option{-bargs} (@command{gnatmake})
9739 Binder switches. Here @var{switches} is a list of switches
9740 that are valid switches for @code{gnatbind}. They will be passed on to
9741 all bind steps performed by @command{gnatmake}.
9743 @item -largs @var{switches}
9744 @cindex @option{-largs} (@command{gnatmake})
9745 Linker switches. Here @var{switches} is a list of switches
9746 that are valid switches for @command{gnatlink}. They will be passed on to
9747 all link steps performed by @command{gnatmake}.
9749 @item -margs @var{switches}
9750 @cindex @option{-margs} (@command{gnatmake})
9751 Make switches. The switches are directly interpreted by @command{gnatmake},
9752 regardless of any previous occurrence of @option{-cargs}, @option{-bargs}
9753 or @option{-largs}.
9754 @end table
9756 @node Notes on the Command Line
9757 @section Notes on the Command Line
9759 @noindent
9760 This section contains some additional useful notes on the operation
9761 of the @command{gnatmake} command.
9763 @itemize @bullet
9764 @item
9765 @cindex Recompilation, by @command{gnatmake}
9766 If @command{gnatmake} finds no ALI files, it recompiles the main program
9767 and all other units required by the main program.
9768 This means that @command{gnatmake}
9769 can be used for the initial compile, as well as during subsequent steps of
9770 the development cycle.
9772 @item
9773 If you enter @code{gnatmake @var{file}.adb}, where @file{@var{file}.adb}
9774 is a subunit or body of a generic unit, @command{gnatmake} recompiles
9775 @file{@var{file}.adb} (because it finds no ALI) and stops, issuing a
9776 warning.
9778 @item
9779 In @command{gnatmake} the switch @option{^-I^/SEARCH^}
9780 is used to specify both source and
9781 library file paths. Use @option{^-aI^/SOURCE_SEARCH^}
9782 instead if you just want to specify
9783 source paths only and @option{^-aO^/OBJECT_SEARCH^}
9784 if you want to specify library paths
9785 only.
9787 @item
9788 @command{gnatmake} will ignore any files whose ALI file is write-protected.
9789 This may conveniently be used to exclude standard libraries from
9790 consideration and in particular it means that the use of the
9791 @option{^-f^/FORCE_COMPILE^} switch will not recompile these files
9792 unless @option{^-a^/ALL_FILES^} is also specified.
9794 @item
9795 @command{gnatmake} has been designed to make the use of Ada libraries
9796 particularly convenient. Assume you have an Ada library organized
9797 as follows: @i{^obj-dir^[OBJ_DIR]^} contains the objects and ALI files for
9798 of your Ada compilation units,
9799 whereas @i{^include-dir^[INCLUDE_DIR]^} contains the
9800 specs of these units, but no bodies. Then to compile a unit
9801 stored in @code{main.adb}, which uses this Ada library you would just type
9803 @smallexample
9804 @ifclear vms
9805 $ gnatmake -aI@var{include-dir}  -aL@var{obj-dir}  main
9806 @end ifclear
9807 @ifset vms
9808 $ gnatmake /SOURCE_SEARCH=@i{[INCLUDE_DIR]}
9809            /SKIP_MISSING=@i{[OBJ_DIR]} main
9810 @end ifset
9811 @end smallexample
9813 @item
9814 Using @command{gnatmake} along with the
9815 @option{^-m (minimal recompilation)^/MINIMAL_RECOMPILATION^}
9816 switch provides a mechanism for avoiding unnecessary recompilations. Using
9817 this switch,
9818 you can update the comments/format of your
9819 source files without having to recompile everything. Note, however, that
9820 adding or deleting lines in a source files may render its debugging
9821 info obsolete. If the file in question is a spec, the impact is rather
9822 limited, as that debugging info will only be useful during the
9823 elaboration phase of your program. For bodies the impact can be more
9824 significant. In all events, your debugger will warn you if a source file
9825 is more recent than the corresponding object, and alert you to the fact
9826 that the debugging information may be out of date.
9827 @end itemize
9829 @node How gnatmake Works
9830 @section How @command{gnatmake} Works
9832 @noindent
9833 Generally @command{gnatmake} automatically performs all necessary
9834 recompilations and you don't need to worry about how it works. However,
9835 it may be useful to have some basic understanding of the @command{gnatmake}
9836 approach and in particular to understand how it uses the results of
9837 previous compilations without incorrectly depending on them.
9839 First a definition: an object file is considered @dfn{up to date} if the
9840 corresponding ALI file exists and if all the source files listed in the
9841 dependency section of this ALI file have time stamps matching those in
9842 the ALI file. This means that neither the source file itself nor any
9843 files that it depends on have been modified, and hence there is no need
9844 to recompile this file.
9846 @command{gnatmake} works by first checking if the specified main unit is up
9847 to date. If so, no compilations are required for the main unit. If not,
9848 @command{gnatmake} compiles the main program to build a new ALI file that
9849 reflects the latest sources. Then the ALI file of the main unit is
9850 examined to find all the source files on which the main program depends,
9851 and @command{gnatmake} recursively applies the above procedure on all these
9852 files.
9854 This process ensures that @command{gnatmake} only trusts the dependencies
9855 in an existing ALI file if they are known to be correct. Otherwise it
9856 always recompiles to determine a new, guaranteed accurate set of
9857 dependencies. As a result the program is compiled ``upside down'' from what may
9858 be more familiar as the required order of compilation in some other Ada
9859 systems. In particular, clients are compiled before the units on which
9860 they depend. The ability of GNAT to compile in any order is critical in
9861 allowing an order of compilation to be chosen that guarantees that
9862 @command{gnatmake} will recompute a correct set of new dependencies if
9863 necessary.
9865 When invoking @command{gnatmake} with several @var{file_names}, if a unit is
9866 imported by several of the executables, it will be recompiled at most once.
9868 Note: when using non-standard naming conventions
9869 (@pxref{Using Other File Names}), changing through a configuration pragmas
9870 file the version of a source and invoking @command{gnatmake} to recompile may
9871 have no effect, if the previous version of the source is still accessible
9872 by @command{gnatmake}. It may be necessary to use the switch
9873 ^-f^/FORCE_COMPILE^.
9875 @node Examples of gnatmake Usage
9876 @section Examples of @command{gnatmake} Usage
9878 @table @code
9879 @item gnatmake hello.adb
9880 Compile all files necessary to bind and link the main program
9881 @file{hello.adb} (containing unit @code{Hello}) and bind and link the
9882 resulting object files to generate an executable file @file{^hello^HELLO.EXE^}.
9884 @item gnatmake main1 main2 main3
9885 Compile all files necessary to bind and link the main programs
9886 @file{main1.adb} (containing unit @code{Main1}), @file{main2.adb}
9887 (containing unit @code{Main2}) and @file{main3.adb}
9888 (containing unit @code{Main3}) and bind and link the resulting object files
9889 to generate three executable files @file{^main1^MAIN1.EXE^},
9890 @file{^main2^MAIN2.EXE^}
9891 and @file{^main3^MAIN3.EXE^}.
9893 @ifclear vms
9894 @item gnatmake -q Main_Unit -cargs -O2 -bargs -l
9895 @end ifclear
9897 @ifset vms
9898 @item gnatmake Main_Unit /QUIET
9899 /COMPILER_QUALIFIERS /OPTIMIZE=ALL
9900 /BINDER_QUALIFIERS /ORDER_OF_ELABORATION
9901 @end ifset
9902 Compile all files necessary to bind and link the main program unit
9903 @code{Main_Unit} (from file @file{main_unit.adb}). All compilations will
9904 be done with optimization level 2 and the order of elaboration will be
9905 listed by the binder. @command{gnatmake} will operate in quiet mode, not
9906 displaying commands it is executing.
9907 @end table
9909 @c *************************
9910 @node Improving Performance
9911 @chapter Improving Performance
9912 @cindex Improving performance
9914 @noindent
9915 This chapter presents several topics related to program performance.
9916 It first describes some of the tradeoffs that need to be considered
9917 and some of the techniques for making your program run faster.
9918 It then documents the @command{gnatelim} tool and unused subprogram/data
9919 elimination feature, which can reduce the size of program executables.
9921 @ifnottex
9922 @menu
9923 * Performance Considerations::
9924 * Text_IO Suggestions::
9925 * Reducing Size of Ada Executables with gnatelim::
9926 * Reducing Size of Executables with unused subprogram/data elimination::
9927 @end menu
9928 @end ifnottex
9930 @c *****************************
9931 @node Performance Considerations
9932 @section Performance Considerations
9934 @noindent
9935 The GNAT system provides a number of options that allow a trade-off
9936 between
9938 @itemize @bullet
9939 @item
9940 performance of the generated code
9942 @item
9943 speed of compilation
9945 @item
9946 minimization of dependences and recompilation
9948 @item
9949 the degree of run-time checking.
9950 @end itemize
9952 @noindent
9953 The defaults (if no options are selected) aim at improving the speed
9954 of compilation and minimizing dependences, at the expense of performance
9955 of the generated code:
9957 @itemize @bullet
9958 @item
9959 no optimization
9961 @item
9962 no inlining of subprogram calls
9964 @item
9965 all run-time checks enabled except overflow and elaboration checks
9966 @end itemize
9968 @noindent
9969 These options are suitable for most program development purposes. This
9970 chapter describes how you can modify these choices, and also provides
9971 some guidelines on debugging optimized code.
9973 @menu
9974 * Controlling Run-Time Checks::
9975 * Use of Restrictions::
9976 * Optimization Levels::
9977 * Debugging Optimized Code::
9978 * Inlining of Subprograms::
9979 * Vectorization of loops::
9980 * Other Optimization Switches::
9981 * Optimization and Strict Aliasing::
9983 @ifset vms
9984 * Coverage Analysis::
9985 @end ifset
9986 @end menu
9988 @node Controlling Run-Time Checks
9989 @subsection Controlling Run-Time Checks
9991 @noindent
9992 By default, GNAT generates all run-time checks, except integer overflow
9993 checks, stack overflow checks, and checks for access before elaboration on
9994 subprogram calls. The latter are not required in default mode, because all
9995 necessary checking is done at compile time.
9996 @cindex @option{-gnatp} (@command{gcc})
9997 @cindex @option{-gnato} (@command{gcc})
9998 Two gnat switches, @option{-gnatp} and @option{-gnato} allow this default to
9999 be modified. @xref{Run-Time Checks}.
10001 Our experience is that the default is suitable for most development
10002 purposes.
10004 We treat integer overflow specially because these
10005 are quite expensive and in our experience are not as important as other
10006 run-time checks in the development process. Note that division by zero
10007 is not considered an overflow check, and divide by zero checks are
10008 generated where required by default.
10010 Elaboration checks are off by default, and also not needed by default, since
10011 GNAT uses a static elaboration analysis approach that avoids the need for
10012 run-time checking. This manual contains a full chapter discussing the issue
10013 of elaboration checks, and if the default is not satisfactory for your use,
10014 you should read this chapter.
10016 For validity checks, the minimal checks required by the Ada Reference
10017 Manual (for case statements and assignments to array elements) are on
10018 by default. These can be suppressed by use of the @option{-gnatVn} switch.
10019 Note that in Ada 83, there were no validity checks, so if the Ada 83 mode
10020 is acceptable (or when comparing GNAT performance with an Ada 83 compiler),
10021 it may be reasonable to routinely use @option{-gnatVn}. Validity checks
10022 are also suppressed entirely if @option{-gnatp} is used.
10024 @cindex Overflow checks
10025 @cindex Checks, overflow
10026 @findex Suppress
10027 @findex Unsuppress
10028 @cindex pragma Suppress
10029 @cindex pragma Unsuppress
10030 Note that the setting of the switches controls the default setting of
10031 the checks. They may be modified using either @code{pragma Suppress} (to
10032 remove checks) or @code{pragma Unsuppress} (to add back suppressed
10033 checks) in the program source.
10035 @node Use of Restrictions
10036 @subsection Use of Restrictions
10038 @noindent
10039 The use of pragma Restrictions allows you to control which features are
10040 permitted in your program. Apart from the obvious point that if you avoid
10041 relatively expensive features like finalization (enforceable by the use
10042 of pragma Restrictions (No_Finalization), the use of this pragma does not
10043 affect the generated code in most cases.
10045 One notable exception to this rule is that the possibility of task abort
10046 results in some distributed overhead, particularly if finalization or
10047 exception handlers are used. The reason is that certain sections of code
10048 have to be marked as non-abortable.
10050 If you use neither the @code{abort} statement, nor asynchronous transfer
10051 of control (@code{select @dots{} then abort}), then this distributed overhead
10052 is removed, which may have a general positive effect in improving
10053 overall performance.  Especially code involving frequent use of tasking
10054 constructs and controlled types will show much improved performance.
10055 The relevant restrictions pragmas are
10057 @smallexample @c ada
10058    pragma Restrictions (No_Abort_Statements);
10059    pragma Restrictions (Max_Asynchronous_Select_Nesting => 0);
10060 @end smallexample
10062 @noindent
10063 It is recommended that these restriction pragmas be used if possible. Note
10064 that this also means that you can write code without worrying about the
10065 possibility of an immediate abort at any point.
10067 @node Optimization Levels
10068 @subsection Optimization Levels
10069 @cindex @option{^-O^/OPTIMIZE^} (@command{gcc})
10071 @noindent
10072 Without any optimization ^option,^qualifier,^
10073 the compiler's goal is to reduce the cost of
10074 compilation and to make debugging produce the expected results.
10075 Statements are independent: if you stop the program with a breakpoint between
10076 statements, you can then assign a new value to any variable or change
10077 the program counter to any other statement in the subprogram and get exactly
10078 the results you would expect from the source code.
10080 Turning on optimization makes the compiler attempt to improve the
10081 performance and/or code size at the expense of compilation time and
10082 possibly the ability to debug the program.
10084 If you use multiple
10085 ^-O options, with or without level numbers,^/OPTIMIZE qualifiers,^
10086 the last such option is the one that is effective.
10088 @noindent
10089 The default is optimization off. This results in the fastest compile
10090 times, but GNAT makes absolutely no attempt to optimize, and the
10091 generated programs are considerably larger and slower than when
10092 optimization is enabled. You can use the
10093 @ifclear vms
10094 @option{-O} switch (the permitted forms are @option{-O0}, @option{-O1}
10095 @option{-O2}, @option{-O3}, and @option{-Os})
10096 @end ifclear
10097 @ifset vms
10098 @code{OPTIMIZE} qualifier
10099 @end ifset
10100 to @command{gcc} to control the optimization level:
10102 @table @option
10103 @item ^-O0^/OPTIMIZE=NONE^
10104 No optimization (the default);
10105 generates unoptimized code but has
10106 the fastest compilation time.
10108 Note that many other compilers do fairly extensive optimization
10109 even if ``no optimization'' is specified. With gcc, it is
10110 very unusual to use ^-O0^/OPTIMIZE=NONE^ for production if
10111 execution time is of any concern, since ^-O0^/OPTIMIZE=NONE^
10112 really does mean no optimization at all. This difference between
10113 gcc and other compilers should be kept in mind when doing
10114 performance comparisons.
10116 @item ^-O1^/OPTIMIZE=SOME^
10117 Moderate optimization;
10118 optimizes reasonably well but does not
10119 degrade compilation time significantly.
10121 @item ^-O2^/OPTIMIZE=ALL^
10122 @ifset vms
10123 @itemx /OPTIMIZE=DEVELOPMENT
10124 @end ifset
10125 Full optimization;
10126 generates highly optimized code and has
10127 the slowest compilation time.
10129 @item ^-O3^/OPTIMIZE=INLINING^
10130 Full optimization as in @option{-O2};
10131 also uses more aggressive automatic inlining of subprograms within a unit
10132 (@pxref{Inlining of Subprograms}) and attempts to vectorize loops.
10134 @item ^-Os^/OPTIMIZE=SPACE^
10135 Optimize space usage (code and data) of resulting program.
10136 @end table
10138 @noindent
10139 Higher optimization levels perform more global transformations on the
10140 program and apply more expensive analysis algorithms in order to generate
10141 faster and more compact code. The price in compilation time, and the
10142 resulting improvement in execution time,
10143 both depend on the particular application and the hardware environment.
10144 You should experiment to find the best level for your application.
10146 Since the precise set of optimizations done at each level will vary from
10147 release to release (and sometime from target to target), it is best to think
10148 of the optimization settings in general terms.
10149 @xref{Optimize Options,, Options That Control Optimization, gcc, Using
10150 the GNU Compiler Collection (GCC)}, for details about
10151 ^the @option{-O} settings and a number of @option{-f} options that^how to^
10152 individually enable or disable specific optimizations.
10154 Unlike some other compilation systems, ^@command{gcc}^GNAT^ has
10155 been tested extensively at all optimization levels. There are some bugs
10156 which appear only with optimization turned on, but there have also been
10157 bugs which show up only in @emph{unoptimized} code. Selecting a lower
10158 level of optimization does not improve the reliability of the code
10159 generator, which in practice is highly reliable at all optimization
10160 levels.
10162 Note regarding the use of @option{-O3}: The use of this optimization level
10163 is generally discouraged with GNAT, since it often results in larger
10164 executables which may run more slowly. See further discussion of this point
10165 in @ref{Inlining of Subprograms}.
10167 @node Debugging Optimized Code
10168 @subsection Debugging Optimized Code
10169 @cindex Debugging optimized code
10170 @cindex Optimization and debugging
10172 @noindent
10173 Although it is possible to do a reasonable amount of debugging at
10174 @ifclear vms
10175 nonzero optimization levels,
10176 the higher the level the more likely that
10177 @end ifclear
10178 @ifset vms
10179 @option{/OPTIMIZE} settings other than @code{NONE},
10180 such settings will make it more likely that
10181 @end ifset
10182 source-level constructs will have been eliminated by optimization.
10183 For example, if a loop is strength-reduced, the loop
10184 control variable may be completely eliminated and thus cannot be
10185 displayed in the debugger.
10186 This can only happen at @option{-O2} or @option{-O3}.
10187 Explicit temporary variables that you code might be eliminated at
10188 ^level^setting^ @option{-O1} or higher.
10190 The use of the @option{^-g^/DEBUG^} switch,
10191 @cindex @option{^-g^/DEBUG^} (@command{gcc})
10192 which is needed for source-level debugging,
10193 affects the size of the program executable on disk,
10194 and indeed the debugging information can be quite large.
10195 However, it has no effect on the generated code (and thus does not
10196 degrade performance)
10198 Since the compiler generates debugging tables for a compilation unit before
10199 it performs optimizations, the optimizing transformations may invalidate some
10200 of the debugging data.  You therefore need to anticipate certain
10201 anomalous situations that may arise while debugging optimized code.
10202 These are the most common cases:
10204 @enumerate
10205 @item
10206 @i{The ``hopping Program Counter'':}  Repeated @code{step} or @code{next}
10207 commands show
10208 the PC bouncing back and forth in the code.  This may result from any of
10209 the following optimizations:
10211 @itemize @bullet
10212 @item
10213 @i{Common subexpression elimination:} using a single instance of code for a
10214 quantity that the source computes several times.  As a result you
10215 may not be able to stop on what looks like a statement.
10217 @item
10218 @i{Invariant code motion:} moving an expression that does not change within a
10219 loop, to the beginning of the loop.
10221 @item
10222 @i{Instruction scheduling:} moving instructions so as to
10223 overlap loads and stores (typically) with other code, or in
10224 general to move computations of values closer to their uses. Often
10225 this causes you to pass an assignment statement without the assignment
10226 happening and then later bounce back to the statement when the
10227 value is actually needed.  Placing a breakpoint on a line of code
10228 and then stepping over it may, therefore, not always cause all the
10229 expected side-effects.
10230 @end itemize
10232 @item
10233 @i{The ``big leap'':} More commonly known as @emph{cross-jumping}, in which
10234 two identical pieces of code are merged and the program counter suddenly
10235 jumps to a statement that is not supposed to be executed, simply because
10236 it (and the code following) translates to the same thing as the code
10237 that @emph{was} supposed to be executed.  This effect is typically seen in
10238 sequences that end in a jump, such as a @code{goto}, a @code{return}, or
10239 a @code{break} in a C @code{^switch^switch^} statement.
10241 @item
10242 @i{The ``roving variable'':} The symptom is an unexpected value in a variable.
10243 There are various reasons for this effect:
10245 @itemize @bullet
10246 @item
10247 In a subprogram prologue, a parameter may not yet have been moved to its
10248 ``home''.
10250 @item
10251 A variable may be dead, and its register re-used.  This is
10252 probably the most common cause.
10254 @item
10255 As mentioned above, the assignment of a value to a variable may
10256 have been moved.
10258 @item
10259 A variable may be eliminated entirely by value propagation or
10260 other means.  In this case, GCC may incorrectly generate debugging
10261 information for the variable
10262 @end itemize
10264 @noindent
10265 In general, when an unexpected value appears for a local variable or parameter
10266 you should first ascertain if that value was actually computed by
10267 your program, as opposed to being incorrectly reported by the debugger.
10268 Record fields or
10269 array elements in an object designated by an access value
10270 are generally less of a problem, once you have ascertained that the access
10271 value is sensible.
10272 Typically, this means checking variables in the preceding code and in the
10273 calling subprogram to verify that the value observed is explainable from other
10274 values (one must apply the procedure recursively to those
10275 other values); or re-running the code and stopping a little earlier
10276 (perhaps before the call) and stepping to better see how the variable obtained
10277 the value in question; or continuing to step @emph{from} the point of the
10278 strange value to see if code motion had simply moved the variable's
10279 assignments later.
10280 @end enumerate
10282 @noindent
10283 In light of such anomalies, a recommended technique is to use @option{-O0}
10284 early in the software development cycle, when extensive debugging capabilities
10285 are most needed, and then move to @option{-O1} and later @option{-O2} as
10286 the debugger becomes less critical.
10287 Whether to use the @option{^-g^/DEBUG^} switch in the release version is
10288 a release management issue.
10289 @ifclear vms
10290 Note that if you use @option{-g} you can then use the @command{strip} program
10291 on the resulting executable,
10292 which removes both debugging information and global symbols.
10293 @end ifclear
10295 @node Inlining of Subprograms
10296 @subsection Inlining of Subprograms
10298 @noindent
10299 A call to a subprogram in the current unit is inlined if all the
10300 following conditions are met:
10302 @itemize @bullet
10303 @item
10304 The optimization level is at least @option{-O1}.
10306 @item
10307 The called subprogram is suitable for inlining: It must be small enough
10308 and not contain something that @command{gcc} cannot support in inlined
10309 subprograms.
10311 @item
10312 @cindex pragma Inline
10313 @findex Inline
10314 Any one of the following applies: @code{pragma Inline} is applied to the
10315 subprogram and the @option{^-gnatn^/INLINE^} switch is specified; the
10316 subprogram is local to the unit and called once from within it; the
10317 subprogram is small and optimization level @option{-O2} is specified;
10318 optimization level @option{-O3} is specified.
10319 @end itemize
10321 @noindent
10322 Calls to subprograms in @code{with}'ed units are normally not inlined.
10323 To achieve actual inlining (that is, replacement of the call by the code
10324 in the body of the subprogram), the following conditions must all be true:
10326 @itemize @bullet
10327 @item
10328 The optimization level is at least @option{-O1}.
10330 @item
10331 The called subprogram is suitable for inlining: It must be small enough
10332 and not contain something that @command{gcc} cannot support in inlined
10333 subprograms.
10335 @item
10336 The call appears in a body (not in a package spec).
10338 @item
10339 There is a @code{pragma Inline} for the subprogram.
10341 @item
10342 The @option{^-gnatn^/INLINE^} switch is used on the command line.
10343 @end itemize
10345 Even if all these conditions are met, it may not be possible for
10346 the compiler to inline the call, due to the length of the body,
10347 or features in the body that make it impossible for the compiler
10348 to do the inlining.
10350 Note that specifying the @option{-gnatn} switch causes additional
10351 compilation dependencies. Consider the following:
10353 @smallexample @c ada
10354 @cartouche
10355 package R is
10356    procedure Q;
10357    pragma Inline (Q);
10358 end R;
10359 package body R is
10360    @dots{}
10361 end R;
10363 with R;
10364 procedure Main is
10365 begin
10366    @dots{}
10367    R.Q;
10368 end Main;
10369 @end cartouche
10370 @end smallexample
10372 @noindent
10373 With the default behavior (no @option{-gnatn} switch specified), the
10374 compilation of the @code{Main} procedure depends only on its own source,
10375 @file{main.adb}, and the spec of the package in file @file{r.ads}. This
10376 means that editing the body of @code{R} does not require recompiling
10377 @code{Main}.
10379 On the other hand, the call @code{R.Q} is not inlined under these
10380 circumstances. If the @option{-gnatn} switch is present when @code{Main}
10381 is compiled, the call will be inlined if the body of @code{Q} is small
10382 enough, but now @code{Main} depends on the body of @code{R} in
10383 @file{r.adb} as well as on the spec. This means that if this body is edited,
10384 the main program must be recompiled. Note that this extra dependency
10385 occurs whether or not the call is in fact inlined by @command{gcc}.
10387 The use of front end inlining with @option{-gnatN} generates similar
10388 additional dependencies.
10390 @cindex @option{^-fno-inline^/INLINE=SUPPRESS^} (@command{gcc})
10391 Note: The @option{^-fno-inline^/INLINE=SUPPRESS^} switch
10392 can be used to prevent
10393 all inlining. This switch overrides all other conditions and ensures
10394 that no inlining occurs. The extra dependences resulting from
10395 @option{-gnatn} will still be active, even if
10396 this switch is used to suppress the resulting inlining actions.
10398 @cindex @option{-fno-inline-functions} (@command{gcc})
10399 Note: The @option{-fno-inline-functions} switch can be used to prevent
10400 automatic inlining of subprograms if @option{-O3} is used.
10402 @cindex @option{-fno-inline-small-functions} (@command{gcc})
10403 Note: The @option{-fno-inline-small-functions} switch can be used to prevent
10404 automatic inlining of small subprograms if @option{-O2} is used.
10406 @cindex @option{-fno-inline-functions-called-once} (@command{gcc})
10407 Note: The @option{-fno-inline-functions-called-once} switch
10408 can be used to prevent inlining of subprograms local to the unit
10409 and called once from within it if @option{-O1} is used.
10411 Note regarding the use of @option{-O3}: @option{-gnatn} is made up of two
10412 sub-switches @option{-gnatn1} and @option{-gnatn2} that can be directly
10413 specified in lieu of it, @option{-gnatn} being translated into one of them
10414 based on the optimization level. With @option{-O2} or below, @option{-gnatn}
10415 is equivalent to @option{-gnatn1} which activates pragma @code{Inline} with
10416 moderate inlining across modules. With @option{-O3}, @option{-gnatn} is
10417 equivalent to @option{-gnatn2} which activates pragma @code{Inline} with
10418 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
10419 effect of inlining subprograms you did not think should be inlined. We have
10420 found that the use of @option{-O3} may slow down the compilation and increase
10421 the code size by performing excessive inlining, leading to increased
10422 instruction cache pressure from the increased code size and thus minor
10423 performance improvements. So the bottom line here is that you should not
10424 automatically assume that @option{-O3} is better than @option{-O2}, and
10425 indeed you should use @option{-O3} only if tests show that it actually
10426 improves performance for your program.
10428 @node Vectorization of loops
10429 @subsection Vectorization of loops
10430 @cindex Optimization Switches
10432 You can take advantage of the auto-vectorizer present in the @command{gcc}
10433 back end to vectorize loops with GNAT.  The corresponding command line switch
10434 is @option{-ftree-vectorize} but, as it is enabled by default at @option{-O3}
10435 and other aggressive optimizations helpful for vectorization also are enabled
10436 by default at this level, using @option{-O3} directly is recommended.
10438 You also need to make sure that the target architecture features a supported
10439 SIMD instruction set.  For example, for the x86 architecture, you should at
10440 least specify @option{-msse2} to get significant vectorization (but you don't
10441 need to specify it for x86-64 as it is part of the base 64-bit architecture).
10442 Similarly, for the PowerPC architecture, you should specify @option{-maltivec}.
10444 The preferred loop form for vectorization is the @code{for} iteration scheme.
10445 Loops with a @code{while} iteration scheme can also be vectorized if they are
10446 very simple, but the vectorizer will quickly give up otherwise.  With either
10447 iteration scheme, the flow of control must be straight, in particular no
10448 @code{exit} statement may appear in the loop body.  The loop may however
10449 contain a single nested loop, if it can be vectorized when considered alone:
10451 @smallexample @c ada
10452 @cartouche
10453    A : array (1..4, 1..4) of Long_Float;
10454    S : array (1..4) of Long_Float;
10456    procedure Sum is
10457    begin
10458       for I in A'Range(1) loop
10459          for J in A'Range(2) loop
10460             S (I) := S (I) + A (I, J);
10461          end loop;
10462       end loop;
10463    end Sum;
10464 @end cartouche
10465 @end smallexample
10467 The vectorizable operations depend on the targeted SIMD instruction set, but
10468 the adding and some of the multiplying operators are generally supported, as
10469 well as the logical operators for modular types.  Note that, in the former
10470 case, enabling overflow checks, for example with @option{-gnato}, totally
10471 disables vectorization.  The other checks are not supposed to have the same
10472 definitive effect, although compiling with @option{-gnatp} might well reveal
10473 cases where some checks do thwart vectorization.
10475 Type conversions may also prevent vectorization if they involve semantics that
10476 are not directly supported by the code generator or the SIMD instruction set.
10477 A typical example is direct conversion from floating-point to integer types.
10478 The solution in this case is to use the following idiom:
10480 @smallexample @c ada
10481    Integer (S'Truncation (F))
10482 @end smallexample
10484 @noindent
10485 if @code{S} is the subtype of floating-point object @code{F}.
10487 In most cases, the vectorizable loops are loops that iterate over arrays.
10488 All kinds of array types are supported, i.e. constrained array types with
10489 static bounds:
10491 @smallexample @c ada
10492    type Array_Type is array (1 .. 4) of Long_Float;
10493 @end smallexample
10495 @noindent
10496 constrained array types with dynamic bounds:
10498 @smallexample @c ada
10499    type Array_Type is array (1 .. Q.N) of Long_Float;
10501    type Array_Type is array (Q.K .. 4) of Long_Float;
10503    type Array_Type is array (Q.K .. Q.N) of Long_Float;
10504 @end smallexample
10506 @noindent
10507 or unconstrained array types:
10509 @smallexample @c ada
10510   type Array_Type is array (Positive range <>) of Long_Float;
10511 @end smallexample
10513 @noindent
10514 The quality of the generated code decreases when the dynamic aspect of the
10515 array type increases, the worst code being generated for unconstrained array
10516 types.  This is so because, the less information the compiler has about the
10517 bounds of the array, the more fallback code it needs to generate in order to
10518 fix things up at run time.
10520 It is possible to specify that a given loop should be subject to vectorization
10521 preferably to other optimizations by means of pragma @code{Loop_Optimize}:
10523 @smallexample @c ada
10524   pragma Loop_Optimize (Vector);
10525 @end smallexample
10527 @noindent
10528 placed immediately within the loop will convey the appropriate hint to the
10529 compiler for this loop.
10531 You can obtain information about the vectorization performed by the compiler
10532 by specifying @option{-ftree-vectorizer-verbose=N}.  For more details of
10533 this switch, see @ref{Debugging Options,,Options for Debugging Your Program
10534 or GCC, gcc, Using the GNU Compiler Collection (GCC)}.
10536 @node Other Optimization Switches
10537 @subsection Other Optimization Switches
10538 @cindex Optimization Switches
10540 Since @code{GNAT} uses the @command{gcc} back end, all the specialized
10541 @command{gcc} optimization switches are potentially usable. These switches
10542 have not been extensively tested with GNAT but can generally be expected
10543 to work. Examples of switches in this category are @option{-funroll-loops}
10544 and the various target-specific @option{-m} options (in particular, it has
10545 been observed that @option{-march=xxx} can significantly improve performance
10546 on appropriate machines). For full details of these switches, see
10547 @ref{Submodel Options,, Hardware Models and Configurations, gcc, Using
10548 the GNU Compiler Collection (GCC)}.
10550 @node Optimization and Strict Aliasing
10551 @subsection Optimization and Strict Aliasing
10552 @cindex Aliasing
10553 @cindex Strict Aliasing
10554 @cindex No_Strict_Aliasing
10556 @noindent
10557 The strong typing capabilities of Ada allow an optimizer to generate
10558 efficient code in situations where other languages would be forced to
10559 make worst case assumptions preventing such optimizations. Consider
10560 the following example:
10562 @smallexample @c ada
10563 @cartouche
10564 procedure R is
10565    type Int1 is new Integer;
10566    type Int2 is new Integer;
10567    type Int1A is access Int1;
10568    type Int2A is access Int2;
10569    Int1V : Int1A;
10570    Int2V : Int2A;
10571    @dots{}
10573 begin
10574    @dots{}
10575    for J in Data'Range loop
10576       if Data (J) = Int1V.all then
10577          Int2V.all := Int2V.all + 1;
10578       end if;
10579    end loop;
10580    @dots{}
10581 end R;
10582 @end cartouche
10583 @end smallexample
10585 @noindent
10586 In this example, since the variable @code{Int1V} can only access objects
10587 of type @code{Int1}, and @code{Int2V} can only access objects of type
10588 @code{Int2}, there is no possibility that the assignment to
10589 @code{Int2V.all} affects the value of @code{Int1V.all}. This means that
10590 the compiler optimizer can "know" that the value @code{Int1V.all} is constant
10591 for all iterations of the loop and avoid the extra memory reference
10592 required to dereference it each time through the loop.
10594 This kind of optimization, called strict aliasing analysis, is
10595 triggered by specifying an optimization level of @option{-O2} or
10596 higher or @option{-Os} and allows @code{GNAT} to generate more efficient code
10597 when access values are involved.
10599 However, although this optimization is always correct in terms of
10600 the formal semantics of the Ada Reference Manual, difficulties can
10601 arise if features like @code{Unchecked_Conversion} are used to break
10602 the typing system. Consider the following complete program example:
10604 @smallexample @c ada
10605 @cartouche
10606 package p1 is
10607    type int1 is new integer;
10608    type int2 is new integer;
10609    type a1 is access int1;
10610    type a2 is access int2;
10611 end p1;
10613 with p1; use p1;
10614 package p2 is
10615    function to_a2 (Input : a1) return a2;
10616 end p2;
10618 with Unchecked_Conversion;
10619 package body p2 is
10620    function to_a2 (Input : a1) return a2 is
10621       function to_a2u is
10622         new Unchecked_Conversion (a1, a2);
10623    begin
10624       return to_a2u (Input);
10625    end to_a2;
10626 end p2;
10628 with p2; use p2;
10629 with p1; use p1;
10630 with Text_IO; use Text_IO;
10631 procedure m is
10632    v1 : a1 := new int1;
10633    v2 : a2 := to_a2 (v1);
10634 begin
10635    v1.all := 1;
10636    v2.all := 0;
10637    put_line (int1'image (v1.all));
10638 end;
10639 @end cartouche
10640 @end smallexample
10642 @noindent
10643 This program prints out 0 in @option{-O0} or @option{-O1}
10644 mode, but it prints out 1 in @option{-O2} mode. That's
10645 because in strict aliasing mode, the compiler can and
10646 does assume that the assignment to @code{v2.all} could not
10647 affect the value of @code{v1.all}, since different types
10648 are involved.
10650 This behavior is not a case of non-conformance with the standard, since
10651 the Ada RM specifies that an unchecked conversion where the resulting
10652 bit pattern is not a correct value of the target type can result in an
10653 abnormal value and attempting to reference an abnormal value makes the
10654 execution of a program erroneous.  That's the case here since the result
10655 does not point to an object of type @code{int2}.  This means that the
10656 effect is entirely unpredictable.
10658 However, although that explanation may satisfy a language
10659 lawyer, in practice an applications programmer expects an
10660 unchecked conversion involving pointers to create true
10661 aliases and the behavior of printing 1 seems plain wrong.
10662 In this case, the strict aliasing optimization is unwelcome.
10664 Indeed the compiler recognizes this possibility, and the
10665 unchecked conversion generates a warning:
10667 @smallexample
10668 p2.adb:5:07: warning: possible aliasing problem with type "a2"
10669 p2.adb:5:07: warning: use -fno-strict-aliasing switch for references
10670 p2.adb:5:07: warning:  or use "pragma No_Strict_Aliasing (a2);"
10671 @end smallexample
10673 @noindent
10674 Unfortunately the problem is recognized when compiling the body of
10675 package @code{p2}, but the actual "bad" code is generated while
10676 compiling the body of @code{m} and this latter compilation does not see
10677 the suspicious @code{Unchecked_Conversion}.
10679 As implied by the warning message, there are approaches you can use to
10680 avoid the unwanted strict aliasing optimization in a case like this.
10682 One possibility is to simply avoid the use of @option{-O2}, but
10683 that is a bit drastic, since it throws away a number of useful
10684 optimizations that do not involve strict aliasing assumptions.
10686 A less drastic approach is to compile the program using the
10687 option @option{-fno-strict-aliasing}. Actually it is only the
10688 unit containing the dereferencing of the suspicious pointer
10689 that needs to be compiled. So in this case, if we compile
10690 unit @code{m} with this switch, then we get the expected
10691 value of zero printed. Analyzing which units might need
10692 the switch can be painful, so a more reasonable approach
10693 is to compile the entire program with options @option{-O2}
10694 and @option{-fno-strict-aliasing}. If the performance is
10695 satisfactory with this combination of options, then the
10696 advantage is that the entire issue of possible "wrong"
10697 optimization due to strict aliasing is avoided.
10699 To avoid the use of compiler switches, the configuration
10700 pragma @code{No_Strict_Aliasing} with no parameters may be
10701 used to specify that for all access types, the strict
10702 aliasing optimization should be suppressed.
10704 However, these approaches are still overkill, in that they causes
10705 all manipulations of all access values to be deoptimized. A more
10706 refined approach is to concentrate attention on the specific
10707 access type identified as problematic.
10709 First, if a careful analysis of uses of the pointer shows
10710 that there are no possible problematic references, then
10711 the warning can be suppressed by bracketing the
10712 instantiation of @code{Unchecked_Conversion} to turn
10713 the warning off:
10715 @smallexample @c ada
10716    pragma Warnings (Off);
10717    function to_a2u is
10718      new Unchecked_Conversion (a1, a2);
10719    pragma Warnings (On);
10720 @end smallexample
10722 @noindent
10723 Of course that approach is not appropriate for this particular
10724 example, since indeed there is a problematic reference. In this
10725 case we can take one of two other approaches.
10727 The first possibility is to move the instantiation of unchecked
10728 conversion to the unit in which the type is declared. In
10729 this example, we would move the instantiation of
10730 @code{Unchecked_Conversion} from the body of package
10731 @code{p2} to the spec of package @code{p1}. Now the
10732 warning disappears. That's because any use of the
10733 access type knows there is a suspicious unchecked
10734 conversion, and the strict aliasing optimization
10735 is automatically suppressed for the type.
10737 If it is not practical to move the unchecked conversion to the same unit
10738 in which the destination access type is declared (perhaps because the
10739 source type is not visible in that unit), you may use pragma
10740 @code{No_Strict_Aliasing} for the type. This pragma must occur in the
10741 same declarative sequence as the declaration of the access type:
10743 @smallexample @c ada
10744    type a2 is access int2;
10745    pragma No_Strict_Aliasing (a2);
10746 @end smallexample
10748 @noindent
10749 Here again, the compiler now knows that the strict aliasing optimization
10750 should be suppressed for any reference to type @code{a2} and the
10751 expected behavior is obtained.
10753 Finally, note that although the compiler can generate warnings for
10754 simple cases of unchecked conversions, there are tricker and more
10755 indirect ways of creating type incorrect aliases which the compiler
10756 cannot detect. Examples are the use of address overlays and unchecked
10757 conversions involving composite types containing access types as
10758 components. In such cases, no warnings are generated, but there can
10759 still be aliasing problems. One safe coding practice is to forbid the
10760 use of address clauses for type overlaying, and to allow unchecked
10761 conversion only for primitive types. This is not really a significant
10762 restriction since any possible desired effect can be achieved by
10763 unchecked conversion of access values.
10765 The aliasing analysis done in strict aliasing mode can certainly
10766 have significant benefits. We have seen cases of large scale
10767 application code where the time is increased by up to 5% by turning
10768 this optimization off. If you have code that includes significant
10769 usage of unchecked conversion, you might want to just stick with
10770 @option{-O1} and avoid the entire issue. If you get adequate
10771 performance at this level of optimization level, that's probably
10772 the safest approach. If tests show that you really need higher
10773 levels of optimization, then you can experiment with @option{-O2}
10774 and @option{-O2 -fno-strict-aliasing} to see how much effect this
10775 has on size and speed of the code. If you really need to use
10776 @option{-O2} with strict aliasing in effect, then you should
10777 review any uses of unchecked conversion of access types,
10778 particularly if you are getting the warnings described above.
10780 @ifset vms
10781 @node Coverage Analysis
10782 @subsection Coverage Analysis
10784 @noindent
10785 GNAT supports the HP Performance Coverage Analyzer (PCA), which allows
10786 the user to determine the distribution of execution time across a program,
10787 @pxref{Profiling} for details of usage.
10788 @end ifset
10791 @node Text_IO Suggestions
10792 @section @code{Text_IO} Suggestions
10793 @cindex @code{Text_IO} and performance
10795 @noindent
10796 The @code{Ada.Text_IO} package has fairly high overheads due in part to
10797 the requirement of maintaining page and line counts. If performance
10798 is critical, a recommendation is to use @code{Stream_IO} instead of
10799 @code{Text_IO} for volume output, since this package has less overhead.
10801 If @code{Text_IO} must be used, note that by default output to the standard
10802 output and standard error files is unbuffered (this provides better
10803 behavior when output statements are used for debugging, or if the
10804 progress of a program is observed by tracking the output, e.g. by
10805 using the Unix @command{tail -f} command to watch redirected output.
10807 If you are generating large volumes of output with @code{Text_IO} and
10808 performance is an important factor, use a designated file instead
10809 of the standard output file, or change the standard output file to
10810 be buffered using @code{Interfaces.C_Streams.setvbuf}.
10814 @node Reducing Size of Ada Executables with gnatelim
10815 @section Reducing Size of Ada Executables with @code{gnatelim}
10816 @findex gnatelim
10818 @noindent
10819 This section describes @command{gnatelim}, a tool which detects unused
10820 subprograms and helps the compiler to create a smaller executable for your
10821 program.
10823 @menu
10824 * About gnatelim::
10825 * Running gnatelim::
10826 * Processing Precompiled Libraries::
10827 * Correcting the List of Eliminate Pragmas::
10828 * Making Your Executables Smaller::
10829 * Summary of the gnatelim Usage Cycle::
10830 @end menu
10832 @node About gnatelim
10833 @subsection About @code{gnatelim}
10835 @noindent
10836 When a program shares a set of Ada
10837 packages with other programs, it may happen that this program uses
10838 only a fraction of the subprograms defined in these packages. The code
10839 created for these unused subprograms increases the size of the executable.
10841 @code{gnatelim} tracks unused subprograms in an Ada program and
10842 outputs a list of GNAT-specific pragmas @code{Eliminate} marking all the
10843 subprograms that are declared but never called. By placing the list of
10844 @code{Eliminate} pragmas in the GNAT configuration file @file{gnat.adc} and
10845 recompiling your program, you may decrease the size of its executable,
10846 because the compiler will not generate the code for 'eliminated' subprograms.
10847 @xref{Pragma Eliminate,,, gnat_rm, GNAT Reference Manual}, for more
10848 information about this pragma.
10850 @code{gnatelim} needs as its input data the name of the main subprogram.
10852 If a set of source files is specified as @code{gnatelim} arguments, it
10853 treats these files as a complete set of sources making up a program to
10854 analyse, and analyses only these sources.
10856 After a full successful build of the main subprogram @code{gnatelim} can be
10857 called without  specifying sources to analyse, in this case it computes
10858 the source closure of the main unit from the @file{ALI} files.
10860 The following command will create the set of @file{ALI} files needed for
10861 @code{gnatelim}:
10863 @smallexample
10864 $ gnatmake ^-c Main_Prog^/ACTIONS=COMPILE MAIN_PROG^
10865 @end smallexample
10867 Note that @code{gnatelim} does not need object files.
10869 @node Running gnatelim
10870 @subsection Running @code{gnatelim}
10872 @noindent
10873 @code{gnatelim} has the following command-line interface:
10875 @smallexample
10876 $ gnatelim [@var{switches}] ^-main^?MAIN^=@var{main_unit_name} @{@var{filename}@} @r{[}-cargs @var{gcc_switches}@r{]}
10877 @end smallexample
10879 @noindent
10880 @var{main_unit_name} should be a name of a source file that contains the main
10881 subprogram of a program (partition).
10883 Each @var{filename} is the name (including the extension) of a source
10884 file to process. ``Wildcards'' are allowed, and
10885 the file name may contain path information.
10887 @samp{@var{gcc_switches}} is a list of switches for
10888 @command{gcc}. They will be passed on to all compiler invocations made by
10889 @command{gnatelim} to generate the ASIS trees. Here you can provide
10890 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
10891 use the @option{-gnatec} switch to set the configuration file,
10892 use the @option{-gnat05} switch if sources should be compiled in
10893 Ada 2005 mode etc.
10895 @code{gnatelim} has the following switches:
10897 @table @option
10898 @c !sort!
10899 @item --version
10900 @cindex @option{--version} @command{gnatelim}
10901 Display Copyright and version, then exit disregarding all other options.
10903 @item --help
10904 @cindex @option{--help} @command{gnatelim}
10905 Display usage, then exit disregarding all other options.
10907 @item ^-files^/FILES^=@var{filename}
10908 @cindex @option{^-files^/FILES^} (@code{gnatelim})
10909 Take the argument source files from the specified file. This file should be an
10910 ordinary text file containing file names separated by spaces or
10911 line breaks. You can use this switch more than once in the same call to
10912 @command{gnatelim}. You also can combine this switch with
10913 an explicit list of files.
10915 @item ^-log^/LOG^
10916 @cindex @option{^-log^/LOG^} (@command{gnatelim})
10917 Duplicate all the output sent to @file{stderr} into a log file. The log file
10918 is named @file{gnatelim.log} and is located in the current directory.
10920 @item ^-log^/LOGFILE^=@var{filename}
10921 @cindex @option{^-log^/LOGFILE^} (@command{gnatelim})
10922 Duplicate all the output sent to @file{stderr} into a specified log file.
10924 @cindex @option{^--no-elim-dispatch^/NO_DISPATCH^} (@command{gnatelim})
10925 @item ^--no-elim-dispatch^/NO_DISPATCH^
10926 Do not generate pragmas for dispatching operations.
10928 @item ^--ignore^/IGNORE^=@var{filename}
10929 @cindex @option{^--ignore^/IGNORE^} (@command{gnatelim})
10930 Do not generate pragmas for subprograms declared in the sources
10931 listed in a specified file
10933 @cindex @option{^-o^/OUTPUT^} (@command{gnatelim})
10934 @item ^-o^/OUTPUT^=@var{report_file}
10935 Put @command{gnatelim} output into a specified file. If this file already exists,
10936 it is overridden. If this switch is not used, @command{gnatelim} outputs its results
10937 into @file{stderr}
10939 @item ^-q^/QUIET^
10940 @cindex @option{^-q^/QUIET^} (@command{gnatelim})
10941 Quiet mode: by default @code{gnatelim} outputs to the standard error
10942 stream the number of program units left to be processed. This option turns
10943 this trace off.
10945 @cindex @option{^-t^/TIME^} (@command{gnatelim})
10946 @item ^-t^/TIME^
10947 Print out execution time.
10949 @item ^-v^/VERBOSE^
10950 @cindex @option{^-v^/VERBOSE^} (@command{gnatelim})
10951 Verbose mode: @code{gnatelim} version information is printed as Ada
10952 comments to the standard output stream. Also, in addition to the number of
10953 program units left @code{gnatelim} will output the name of the current unit
10954 being processed.
10956 @item ^-wq^/WARNINGS=QUIET^
10957 @cindex @option{^-wq^/WARNINGS=QUIET^} (@command{gnatelim})
10958 Quiet warning mode - some warnings are suppressed. In particular warnings that
10959 indicate that the analysed set of sources is incomplete to make up a
10960 partition and that some subprogram bodies are missing are not generated.
10961 @end table
10963 @noindent
10964 Note: to invoke @command{gnatelim} with a project file, use the @code{gnat}
10965 driver (see @ref{The GNAT Driver and Project Files}).
10967 @node Processing Precompiled Libraries
10968 @subsection Processing Precompiled Libraries
10970 @noindent
10971 If some program uses a precompiled Ada library, it can be processed by
10972 @code{gnatelim} in a usual way. @code{gnatelim} will newer generate an
10973 Eliminate pragma for a subprogram if the body of this subprogram has not
10974 been analysed, this is a typical case for subprograms from precompiled
10975 libraries. Switch @option{^-wq^/WARNINGS=QUIET^} may be used to suppress
10976 warnings about missing source files and non-analyzed subprogram bodies
10977 that can be generated when processing precompiled Ada libraries.
10979 @node Correcting the List of Eliminate Pragmas
10980 @subsection Correcting the List of Eliminate Pragmas
10982 @noindent
10983 In some rare cases @code{gnatelim} may try to eliminate
10984 subprograms that are actually called in the program. In this case, the
10985 compiler will generate an error message of the form:
10987 @smallexample
10988 main.adb:4:08: cannot reference subprogram "P" eliminated at elim.out:5
10989 @end smallexample
10991 @noindent
10992 You will need to manually remove the wrong @code{Eliminate} pragmas from
10993 the configuration file indicated in the error message. You should recompile
10994 your program from scratch after that, because you need a consistent
10995 configuration file(s) during the entire compilation.
10997 @node Making Your Executables Smaller
10998 @subsection Making Your Executables Smaller
11000 @noindent
11001 In order to get a smaller executable for your program you now have to
11002 recompile the program completely with the configuration file containing
11003 pragmas Eliminate generated by gnatelim. If these pragmas are placed in
11004 @file{gnat.adc} file located in your current directory, just do:
11006 @smallexample
11007 $ gnatmake ^-f main_prog^/FORCE_COMPILE MAIN_PROG^
11008 @end smallexample
11010 @noindent
11011 (Use the @option{^-f^/FORCE_COMPILE^} option for @command{gnatmake} to
11012 recompile everything
11013 with the set of pragmas @code{Eliminate} that you have obtained with
11014 @command{gnatelim}).
11016 Be aware that the set of @code{Eliminate} pragmas is specific to each
11017 program. It is not recommended to merge sets of @code{Eliminate}
11018 pragmas created for different programs in one configuration file.
11020 @node Summary of the gnatelim Usage Cycle
11021 @subsection Summary of the @code{gnatelim} Usage Cycle
11023 @noindent
11024 Here is a quick summary of the steps to be taken in order to reduce
11025 the size of your executables with @code{gnatelim}. You may use
11026 other GNAT options to control the optimization level,
11027 to produce the debugging information, to set search path, etc.
11029 @enumerate
11030 @item
11031 Create a complete set of @file{ALI} files (if the program has not been
11032 built already)
11034 @smallexample
11035 $ gnatmake ^-c main_prog^/ACTIONS=COMPILE MAIN_PROG^
11036 @end smallexample
11038 @item
11039 Generate a list of @code{Eliminate} pragmas in default configuration file
11040 @file{gnat.adc} in the current directory
11041 @smallexample
11042 @ifset vms
11043 $ PIPE GNAT ELIM MAIN_PROG > GNAT.ADC
11044 @end ifset
11045 @ifclear vms
11046 $ gnatelim main_prog >@r{[}>@r{]} gnat.adc
11047 @end ifclear
11048 @end smallexample
11050 @item
11051 Recompile the application
11053 @smallexample
11054 $ gnatmake ^-f main_prog^/FORCE_COMPILE MAIN_PROG^
11055 @end smallexample
11057 @end enumerate
11059 @node Reducing Size of Executables with unused subprogram/data elimination
11060 @section Reducing Size of Executables with Unused Subprogram/Data Elimination
11061 @findex unused subprogram/data elimination
11063 @noindent
11064 This section describes how you can eliminate unused subprograms and data from
11065 your executable just by setting options at compilation time.
11067 @menu
11068 * About unused subprogram/data elimination::
11069 * Compilation options::
11070 * Example of unused subprogram/data elimination::
11071 @end menu
11073 @node About unused subprogram/data elimination
11074 @subsection About unused subprogram/data elimination
11076 @noindent
11077 By default, an executable contains all code and data of its composing objects
11078 (directly linked or coming from statically linked libraries), even data or code
11079 never used by this executable.
11081 This feature will allow you to eliminate such unused code from your
11082 executable, making it smaller (in disk and in memory).
11084 This functionality is available on all Linux platforms except for the IA-64
11085 architecture and on all cross platforms using the ELF binary file format.
11086 In both cases GNU binutils version 2.16 or later are required to enable it.
11088 @node Compilation options
11089 @subsection Compilation options
11091 @noindent
11092 The operation of eliminating the unused code and data from the final executable
11093 is directly performed by the linker.
11095 In order to do this, it has to work with objects compiled with the
11096 following options:
11097 @option{-ffunction-sections} @option{-fdata-sections}.
11098 @cindex @option{-ffunction-sections} (@command{gcc})
11099 @cindex @option{-fdata-sections} (@command{gcc})
11100 These options are usable with C and Ada files.
11101 They will place respectively each
11102 function or data in a separate section in the resulting object file.
11104 Once the objects and static libraries are created with these options, the
11105 linker can perform the dead code elimination. You can do this by setting
11106 the @option{-Wl,--gc-sections} option to gcc command or in the
11107 @option{-largs} section of @command{gnatmake}. This will perform a
11108 garbage collection of code and data never referenced.
11110 If the linker performs a partial link (@option{-r} ld linker option), then you
11111 will need to provide one or several entry point using the
11112 @option{-e} / @option{--entry} ld option.
11114 Note that objects compiled without the @option{-ffunction-sections} and
11115 @option{-fdata-sections} options can still be linked with the executable.
11116 However, no dead code elimination will be performed on those objects (they will
11117 be linked as is).
11119 The GNAT static library is now compiled with -ffunction-sections and
11120 -fdata-sections on some platforms. This allows you to eliminate the unused code
11121 and data of the GNAT library from your executable.
11123 @node Example of unused subprogram/data elimination
11124 @subsection Example of unused subprogram/data elimination
11126 @noindent
11127 Here is a simple example:
11129 @smallexample @c ada
11130 with Aux;
11132 procedure Test is
11133 begin
11134    Aux.Used (10);
11135 end Test;
11137 package Aux is
11138    Used_Data   : Integer;
11139    Unused_Data : Integer;
11141    procedure Used   (Data : Integer);
11142    procedure Unused (Data : Integer);
11143 end Aux;
11145 package body Aux is
11146    procedure Used (Data : Integer) is
11147    begin
11148       Used_Data := Data;
11149    end Used;
11151    procedure Unused (Data : Integer) is
11152    begin
11153       Unused_Data := Data;
11154    end Unused;
11155 end Aux;
11156 @end smallexample
11158 @noindent
11159 @code{Unused} and @code{Unused_Data} are never referenced in this code
11160 excerpt, and hence they may be safely removed from the final executable.
11162 @smallexample
11163 $ gnatmake test
11165 $ nm test | grep used
11166 020015f0 T aux__unused
11167 02005d88 B aux__unused_data
11168 020015cc T aux__used
11169 02005d84 B aux__used_data
11171 $ gnatmake test -cargs -fdata-sections -ffunction-sections \
11172      -largs -Wl,--gc-sections
11174 $ nm test | grep used
11175 02005350 T aux__used
11176 0201ffe0 B aux__used_data
11177 @end smallexample
11179 @noindent
11180 It can be observed that the procedure @code{Unused} and the object
11181 @code{Unused_Data} are removed by the linker when using the
11182 appropriate options.
11184 @c ********************************
11185 @node Renaming Files with gnatchop
11186 @chapter Renaming Files with @code{gnatchop}
11187 @findex gnatchop
11189 @noindent
11190 This chapter discusses how to handle files with multiple units by using
11191 the @code{gnatchop} utility. This utility is also useful in renaming
11192 files to meet the standard GNAT default file naming conventions.
11194 @menu
11195 * Handling Files with Multiple Units::
11196 * Operating gnatchop in Compilation Mode::
11197 * Command Line for gnatchop::
11198 * Switches for gnatchop::
11199 * Examples of gnatchop Usage::
11200 @end menu
11202 @node Handling Files with Multiple Units
11203 @section Handling Files with Multiple Units
11205 @noindent
11206 The basic compilation model of GNAT requires that a file submitted to the
11207 compiler have only one unit and there be a strict correspondence
11208 between the file name and the unit name.
11210 The @code{gnatchop} utility allows both of these rules to be relaxed,
11211 allowing GNAT to process files which contain multiple compilation units
11212 and files with arbitrary file names. @code{gnatchop}
11213 reads the specified file and generates one or more output files,
11214 containing one unit per file. The unit and the file name correspond,
11215 as required by GNAT.
11217 If you want to permanently restructure a set of ``foreign'' files so that
11218 they match the GNAT rules, and do the remaining development using the
11219 GNAT structure, you can simply use @command{gnatchop} once, generate the
11220 new set of files and work with them from that point on.
11222 Alternatively, if you want to keep your files in the ``foreign'' format,
11223 perhaps to maintain compatibility with some other Ada compilation
11224 system, you can set up a procedure where you use @command{gnatchop} each
11225 time you compile, regarding the source files that it writes as temporary
11226 files that you throw away.
11228 Note that if your file containing multiple units starts with a byte order
11229 mark (BOM) specifying UTF-8 encoding, then the files generated by gnatchop
11230 will each start with a copy of this BOM, meaning that they can be compiled
11231 automatically in UTF-8 mode without needing to specify an explicit encoding.
11233 @node Operating gnatchop in Compilation Mode
11234 @section Operating gnatchop in Compilation Mode
11236 @noindent
11237 The basic function of @code{gnatchop} is to take a file with multiple units
11238 and split it into separate files. The boundary between files is reasonably
11239 clear, except for the issue of comments and pragmas. In default mode, the
11240 rule is that any pragmas between units belong to the previous unit, except
11241 that configuration pragmas always belong to the following unit. Any comments
11242 belong to the following unit. These rules
11243 almost always result in the right choice of
11244 the split point without needing to mark it explicitly and most users will
11245 find this default to be what they want. In this default mode it is incorrect to
11246 submit a file containing only configuration pragmas, or one that ends in
11247 configuration pragmas, to @code{gnatchop}.
11249 However, using a special option to activate ``compilation mode'',
11250 @code{gnatchop}
11251 can perform another function, which is to provide exactly the semantics
11252 required by the RM for handling of configuration pragmas in a compilation.
11253 In the absence of configuration pragmas (at the main file level), this
11254 option has no effect, but it causes such configuration pragmas to be handled
11255 in a quite different manner.
11257 First, in compilation mode, if @code{gnatchop} is given a file that consists of
11258 only configuration pragmas, then this file is appended to the
11259 @file{gnat.adc} file in the current directory. This behavior provides
11260 the required behavior described in the RM for the actions to be taken
11261 on submitting such a file to the compiler, namely that these pragmas
11262 should apply to all subsequent compilations in the same compilation
11263 environment. Using GNAT, the current directory, possibly containing a
11264 @file{gnat.adc} file is the representation
11265 of a compilation environment. For more information on the
11266 @file{gnat.adc} file, see @ref{Handling of Configuration Pragmas}.
11268 Second, in compilation mode, if @code{gnatchop}
11269 is given a file that starts with
11270 configuration pragmas, and contains one or more units, then these
11271 configuration pragmas are prepended to each of the chopped files. This
11272 behavior provides the required behavior described in the RM for the
11273 actions to be taken on compiling such a file, namely that the pragmas
11274 apply to all units in the compilation, but not to subsequently compiled
11275 units.
11277 Finally, if configuration pragmas appear between units, they are appended
11278 to the previous unit. This results in the previous unit being illegal,
11279 since the compiler does not accept configuration pragmas that follow
11280 a unit. This provides the required RM behavior that forbids configuration
11281 pragmas other than those preceding the first compilation unit of a
11282 compilation.
11284 For most purposes, @code{gnatchop} will be used in default mode. The
11285 compilation mode described above is used only if you need exactly
11286 accurate behavior with respect to compilations, and you have files
11287 that contain multiple units and configuration pragmas. In this
11288 circumstance the use of @code{gnatchop} with the compilation mode
11289 switch provides the required behavior, and is for example the mode
11290 in which GNAT processes the ACVC tests.
11292 @node Command Line for gnatchop
11293 @section Command Line for @code{gnatchop}
11295 @noindent
11296 The @code{gnatchop} command has the form:
11298 @smallexample
11299 @c $ gnatchop switches @var{file name} @r{[}@var{file name} @dots{}@r{]}
11300 @c      @ovar{directory}
11301 @c Expanding @ovar macro inline (explanation in macro def comments)
11302 $ gnatchop switches @var{file name} @r{[}@var{file name} @dots{}@r{]}
11303       @r{[}@var{directory}@r{]}
11304 @end smallexample
11306 @noindent
11307 The only required argument is the file name of the file to be chopped.
11308 There are no restrictions on the form of this file name. The file itself
11309 contains one or more Ada units, in normal GNAT format, concatenated
11310 together. As shown, more than one file may be presented to be chopped.
11312 When run in default mode, @code{gnatchop} generates one output file in
11313 the current directory for each unit in each of the files.
11315 @var{directory}, if specified, gives the name of the directory to which
11316 the output files will be written. If it is not specified, all files are
11317 written to the current directory.
11319 For example, given a
11320 file called @file{hellofiles} containing
11322 @smallexample @c ada
11323 @group
11324 @cartouche
11325 procedure hello;
11327 with Text_IO; use Text_IO;
11328 procedure hello is
11329 begin
11330    Put_Line ("Hello");
11331 end hello;
11332 @end cartouche
11333 @end group
11334 @end smallexample
11336 @noindent
11337 the command
11339 @smallexample
11340 $ gnatchop ^hellofiles^HELLOFILES.^
11341 @end smallexample
11343 @noindent
11344 generates two files in the current directory, one called
11345 @file{hello.ads} containing the single line that is the procedure spec,
11346 and the other called @file{hello.adb} containing the remaining text. The
11347 original file is not affected. The generated files can be compiled in
11348 the normal manner.
11350 @noindent
11351 When gnatchop is invoked on a file that is empty or that contains only empty
11352 lines and/or comments, gnatchop will not fail, but will not produce any
11353 new sources.
11355 For example, given a
11356 file called @file{toto.txt} containing
11358 @smallexample @c ada
11359 @group
11360 @cartouche
11361 --  Just a comment
11362 @end cartouche
11363 @end group
11364 @end smallexample
11366 @noindent
11367 the command
11369 @smallexample
11370 $ gnatchop ^toto.txt^TOT.TXT^
11371 @end smallexample
11373 @noindent
11374 will not produce any new file and will result in the following warnings:
11376 @smallexample
11377 toto.txt:1:01: warning: empty file, contains no compilation units
11378 no compilation units found
11379 no source files written
11380 @end smallexample
11382 @node Switches for gnatchop
11383 @section Switches for @code{gnatchop}
11385 @noindent
11386 @command{gnatchop} recognizes the following switches:
11388 @table @option
11389 @c !sort!
11391 @item --version
11392 @cindex @option{--version} @command{gnatchop}
11393 Display Copyright and version, then exit disregarding all other options.
11395 @item --help
11396 @cindex @option{--help} @command{gnatchop}
11397 If @option{--version} was not used, display usage, then exit disregarding
11398 all other options.
11400 @item ^-c^/COMPILATION^
11401 @cindex @option{^-c^/COMPILATION^} (@code{gnatchop})
11402 Causes @code{gnatchop} to operate in compilation mode, in which
11403 configuration pragmas are handled according to strict RM rules. See
11404 previous section for a full description of this mode.
11406 @ifclear vms
11407 @item -gnat@var{xxx}
11408 This passes the given @option{-gnat@var{xxx}} switch to @code{gnat} which is
11409 used to parse the given file. Not all @var{xxx} options make sense,
11410 but for example, the use of @option{-gnati2} allows @code{gnatchop} to
11411 process a source file that uses Latin-2 coding for identifiers.
11412 @end ifclear
11414 @item ^-h^/HELP^
11415 Causes @code{gnatchop} to generate a brief help summary to the standard
11416 output file showing usage information.
11418 @item ^-k@var{mm}^/FILE_NAME_MAX_LENGTH=@var{mm}^
11419 @cindex @option{^-k^/FILE_NAME_MAX_LENGTH^} (@code{gnatchop})
11420 Limit generated file names to the specified number @code{mm}
11421 of characters.
11422 This is useful if the
11423 resulting set of files is required to be interoperable with systems
11424 which limit the length of file names.
11425 @ifset vms
11426 If no value is given, or
11427 if no @code{/FILE_NAME_MAX_LENGTH} qualifier is given,
11428 a default of 39, suitable for OpenVMS Alpha
11429 Systems, is assumed
11430 @end ifset
11431 @ifclear vms
11432 No space is allowed between the @option{-k} and the numeric value. The numeric
11433 value may be omitted in which case a default of @option{-k8},
11434 suitable for use
11435 with DOS-like file systems, is used. If no @option{-k} switch
11436 is present then
11437 there is no limit on the length of file names.
11438 @end ifclear
11440 @item ^-p^/PRESERVE^
11441 @cindex @option{^-p^/PRESERVE^} (@code{gnatchop})
11442 Causes the file ^modification^creation^ time stamp of the input file to be
11443 preserved and used for the time stamp of the output file(s). This may be
11444 useful for preserving coherency of time stamps in an environment where
11445 @code{gnatchop} is used as part of a standard build process.
11447 @item ^-q^/QUIET^
11448 @cindex @option{^-q^/QUIET^} (@code{gnatchop})
11449 Causes output of informational messages indicating the set of generated
11450 files to be suppressed. Warnings and error messages are unaffected.
11452 @item ^-r^/REFERENCE^
11453 @cindex @option{^-r^/REFERENCE^} (@code{gnatchop})
11454 @findex Source_Reference
11455 Generate @code{Source_Reference} pragmas. Use this switch if the output
11456 files are regarded as temporary and development is to be done in terms
11457 of the original unchopped file. This switch causes
11458 @code{Source_Reference} pragmas to be inserted into each of the
11459 generated files to refers back to the original file name and line number.
11460 The result is that all error messages refer back to the original
11461 unchopped file.
11462 In addition, the debugging information placed into the object file (when
11463 the @option{^-g^/DEBUG^} switch of @command{gcc} or @command{gnatmake} is
11464 specified)
11465 also refers back to this original file so that tools like profilers and
11466 debuggers will give information in terms of the original unchopped file.
11468 If the original file to be chopped itself contains
11469 a @code{Source_Reference}
11470 pragma referencing a third file, then gnatchop respects
11471 this pragma, and the generated @code{Source_Reference} pragmas
11472 in the chopped file refer to the original file, with appropriate
11473 line numbers. This is particularly useful when @code{gnatchop}
11474 is used in conjunction with @code{gnatprep} to compile files that
11475 contain preprocessing statements and multiple units.
11477 @item ^-v^/VERBOSE^
11478 @cindex @option{^-v^/VERBOSE^} (@code{gnatchop})
11479 Causes @code{gnatchop} to operate in verbose mode. The version
11480 number and copyright notice are output, as well as exact copies of
11481 the gnat1 commands spawned to obtain the chop control information.
11483 @item ^-w^/OVERWRITE^
11484 @cindex @option{^-w^/OVERWRITE^} (@code{gnatchop})
11485 Overwrite existing file names. Normally @code{gnatchop} regards it as a
11486 fatal error if there is already a file with the same name as a
11487 file it would otherwise output, in other words if the files to be
11488 chopped contain duplicated units. This switch bypasses this
11489 check, and causes all but the last instance of such duplicated
11490 units to be skipped.
11492 @ifclear vms
11493 @item --GCC=@var{xxxx}
11494 @cindex @option{--GCC=} (@code{gnatchop})
11495 Specify the path of the GNAT parser to be used. When this switch is used,
11496 no attempt is made to add the prefix to the GNAT parser executable.
11497 @end ifclear
11498 @end table
11500 @node Examples of gnatchop Usage
11501 @section Examples of @code{gnatchop} Usage
11503 @table @code
11504 @ifset vms
11505 @item gnatchop /OVERWRITE HELLO_S.ADA [PRERELEASE.FILES]
11506 @end ifset
11507 @ifclear vms
11508 @item gnatchop -w hello_s.ada prerelease/files
11509 @end ifclear
11511 Chops the source file @file{hello_s.ada}. The output files will be
11512 placed in the directory @file{^prerelease/files^[PRERELEASE.FILES]^},
11513 overwriting any
11514 files with matching names in that directory (no files in the current
11515 directory are modified).
11517 @item gnatchop ^archive^ARCHIVE.^
11518 Chops the source file @file{^archive^ARCHIVE.^}
11519 into the current directory. One
11520 useful application of @code{gnatchop} is in sending sets of sources
11521 around, for example in email messages. The required sources are simply
11522 concatenated (for example, using a ^Unix @code{cat}^VMS @code{APPEND/NEW}^
11523 command), and then
11524 @command{gnatchop} is used at the other end to reconstitute the original
11525 file names.
11527 @item gnatchop file1 file2 file3 direc
11528 Chops all units in files @file{file1}, @file{file2}, @file{file3}, placing
11529 the resulting files in the directory @file{direc}. Note that if any units
11530 occur more than once anywhere within this set of files, an error message
11531 is generated, and no files are written. To override this check, use the
11532 @option{^-w^/OVERWRITE^} switch,
11533 in which case the last occurrence in the last file will
11534 be the one that is output, and earlier duplicate occurrences for a given
11535 unit will be skipped.
11536 @end table
11538 @node Configuration Pragmas
11539 @chapter Configuration Pragmas
11540 @cindex Configuration pragmas
11541 @cindex Pragmas, configuration
11543 @menu
11544 * Handling of Configuration Pragmas::
11545 * The Configuration Pragmas Files::
11546 @end menu
11548 @noindent
11549 Configuration pragmas include those pragmas described as
11550 such in the Ada Reference Manual, as well as
11551 implementation-dependent pragmas that are configuration pragmas.
11552 @xref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference Manual},
11553 for details on these additional GNAT-specific configuration pragmas.
11554 Most notably, the pragma @code{Source_File_Name}, which allows
11555 specifying non-default names for source files, is a configuration
11556 pragma. The following is a complete list of configuration pragmas
11557 recognized by GNAT:
11559 @smallexample
11560    Ada_83
11561    Ada_95
11562    Ada_05
11563    Ada_2005
11564    Ada_12
11565    Ada_2012
11566    Annotate
11567    Assertion_Policy
11568    Assume_No_Invalid_Values
11569    C_Pass_By_Copy
11570    Check_Name
11571    Check_Policy
11572    Compile_Time_Error
11573    Compile_Time_Warning
11574    Compiler_Unit
11575    Component_Alignment
11576    Convention_Identifier
11577    Debug_Policy
11578    Detect_Blocking
11579    Default_Storage_Pool
11580    Discard_Names
11581    Elaboration_Checks
11582    Eliminate
11583    Extend_System
11584    Extensions_Allowed
11585    External_Name_Casing
11586    Fast_Math
11587    Favor_Top_Level
11588    Float_Representation
11589    Implicit_Packing
11590    Initialize_Scalars
11591    Interrupt_State
11592    License
11593    Locking_Policy
11594    Long_Float
11595    No_Run_Time
11596    No_Strict_Aliasing
11597    Normalize_Scalars
11598    Optimize_Alignment
11599    Persistent_BSS
11600    Polling
11601    Priority_Specific_Dispatching
11602    Profile
11603    Profile_Warnings
11604    Propagate_Exceptions
11605    Queuing_Policy
11606    Ravenscar
11607    Restricted_Run_Time
11608    Restrictions
11609    Restrictions_Warnings
11610    Reviewable
11611    Short_Circuit_And_Or
11612    Source_File_Name
11613    Source_File_Name_Project
11614    SPARK_Mode
11615    Style_Checks
11616    Suppress
11617    Suppress_Exception_Locations
11618    Task_Dispatching_Policy
11619    Universal_Data
11620    Unsuppress
11621    Use_VADS_Size
11622    Validity_Checks
11623    Warnings
11624    Wide_Character_Encoding
11625 @end smallexample
11627 @node Handling of Configuration Pragmas
11628 @section Handling of Configuration Pragmas
11630 Configuration pragmas may either appear at the start of a compilation
11631 unit, or they can appear in a configuration pragma file to apply to
11632 all compilations performed in a given compilation environment.
11634 GNAT also provides the @code{gnatchop} utility to provide an automatic
11635 way to handle configuration pragmas following the semantics for
11636 compilations (that is, files with multiple units), described in the RM.
11637 See @ref{Operating gnatchop in Compilation Mode} for details.
11638 However, for most purposes, it will be more convenient to edit the
11639 @file{gnat.adc} file that contains configuration pragmas directly,
11640 as described in the following section.
11642 In the case of @code{Restrictions} pragmas appearing as configuration
11643 pragmas in individual compilation units, the exact handling depends on
11644 the type of restriction.
11646 Restrictions that require partition-wide consistency (like
11647 @code{No_Tasking}) are
11648 recognized wherever they appear
11649 and can be freely inherited, e.g. from a with'ed unit to the with'ing
11650 unit. This makes sense since the binder will in any case insist on seeing
11651 consistent use, so any unit not conforming to any restrictions that are
11652 anywhere in the partition will be rejected, and you might as well find
11653 that out at compile time rather than at bind time.
11655 For restrictions that do not require partition-wide consistency, e.g.
11656 SPARK or No_Implementation_Attributes, in general the restriction applies
11657 only to the unit in which the pragma appears, and not to any other units.
11659 The exception is No_Elaboration_Code which always applies to the entire
11660 object file from a compilation, i.e. to the body, spec, and all subunits.
11661 This restriction can be specified in a configuration pragma file, or it
11662 can be on the body and/or the spec (in eithe case it applies to all the
11663 relevant units). It can appear on a subunit only if it has previously
11664 appeared in the body of spec.
11666 @node The Configuration Pragmas Files
11667 @section The Configuration Pragmas Files
11668 @cindex @file{gnat.adc}
11670 @noindent
11671 In GNAT a compilation environment is defined by the current
11672 directory at the time that a compile command is given. This current
11673 directory is searched for a file whose name is @file{gnat.adc}. If
11674 this file is present, it is expected to contain one or more
11675 configuration pragmas that will be applied to the current compilation.
11676 However, if the switch @option{-gnatA} is used, @file{gnat.adc} is not
11677 considered.
11679 Configuration pragmas may be entered into the @file{gnat.adc} file
11680 either by running @code{gnatchop} on a source file that consists only of
11681 configuration pragmas, or more conveniently  by
11682 direct editing of the @file{gnat.adc} file, which is a standard format
11683 source file.
11685 In addition to @file{gnat.adc}, additional files containing configuration
11686 pragmas may be applied to the current compilation using the switch
11687 @option{-gnatec}@var{path}. @var{path} must designate an existing file that
11688 contains only configuration pragmas. These configuration pragmas are
11689 in addition to those found in @file{gnat.adc} (provided @file{gnat.adc}
11690 is present and switch @option{-gnatA} is not used).
11692 It is allowed to specify several switches @option{-gnatec}, all of which
11693 will be taken into account.
11695 If you are using project file, a separate mechanism is provided using
11696 project attributes, see @ref{Specifying Configuration Pragmas} for more
11697 details.
11699 @ifset vms
11700 Of special interest to GNAT OpenVMS Alpha is the following
11701 configuration pragma:
11703 @smallexample @c ada
11704 @cartouche
11705 pragma Extend_System (Aux_DEC);
11706 @end cartouche
11707 @end smallexample
11709 @noindent
11710 In the presence of this pragma, GNAT adds to the definition of the
11711 predefined package SYSTEM all the additional types and subprograms that are
11712 defined in HP Ada. See @ref{Compatibility with HP Ada} for details.
11713 @end ifset
11715 @node Handling Arbitrary File Naming Conventions with gnatname
11716 @chapter Handling Arbitrary File Naming Conventions with @code{gnatname}
11717 @cindex Arbitrary File Naming Conventions
11719 @menu
11720 * Arbitrary File Naming Conventions::
11721 * Running gnatname::
11722 * Switches for gnatname::
11723 * Examples of gnatname Usage::
11724 @end menu
11726 @node Arbitrary File Naming Conventions
11727 @section Arbitrary File Naming Conventions
11729 @noindent
11730 The GNAT compiler must be able to know the source file name of a compilation
11731 unit.  When using the standard GNAT default file naming conventions
11732 (@code{.ads} for specs, @code{.adb} for bodies), the GNAT compiler
11733 does not need additional information.
11735 @noindent
11736 When the source file names do not follow the standard GNAT default file naming
11737 conventions, the GNAT compiler must be given additional information through
11738 a configuration pragmas file (@pxref{Configuration Pragmas})
11739 or a project file.
11740 When the non-standard file naming conventions are well-defined,
11741 a small number of pragmas @code{Source_File_Name} specifying a naming pattern
11742 (@pxref{Alternative File Naming Schemes}) may be sufficient. However,
11743 if the file naming conventions are irregular or arbitrary, a number
11744 of pragma @code{Source_File_Name} for individual compilation units
11745 must be defined.
11746 To help maintain the correspondence between compilation unit names and
11747 source file names within the compiler,
11748 GNAT provides a tool @code{gnatname} to generate the required pragmas for a
11749 set of files.
11751 @node Running gnatname
11752 @section Running @code{gnatname}
11754 @noindent
11755 The usual form of the @code{gnatname} command is
11757 @smallexample
11758 @c $ gnatname @ovar{switches} @var{naming_pattern} @ovar{naming_patterns}
11759 @c       @r{[}--and @ovar{switches} @var{naming_pattern} @ovar{naming_patterns}@r{]}
11760 @c Expanding @ovar macro inline (explanation in macro def comments)
11761 $ gnatname @r{[}@var{switches}@r{]} @var{naming_pattern} @r{[}@var{naming_patterns}@r{]}
11762       @r{[}--and @r{[}@var{switches}@r{]} @var{naming_pattern} @r{[}@var{naming_patterns}@r{]}@r{]}
11763 @end smallexample
11765 @noindent
11766 All of the arguments are optional. If invoked without any argument,
11767 @code{gnatname} will display its usage.
11769 @noindent
11770 When used with at least one naming pattern, @code{gnatname} will attempt to
11771 find all the compilation units in files that follow at least one of the
11772 naming patterns. To find these compilation units,
11773 @code{gnatname} will use the GNAT compiler in syntax-check-only mode on all
11774 regular files.
11776 @noindent
11777 One or several Naming Patterns may be given as arguments to @code{gnatname}.
11778 Each Naming Pattern is enclosed between double quotes (or single
11779 quotes on Windows).
11780 A Naming Pattern is a regular expression similar to the wildcard patterns
11781 used in file names by the Unix shells or the DOS prompt.
11783 @noindent
11784 @code{gnatname} may be called with several sections of directories/patterns.
11785 Sections are separated by switch @code{--and}. In each section, there must be
11786 at least one pattern. If no directory is specified in a section, the current
11787 directory (or the project directory is @code{-P} is used) is implied.
11788 The options other that the directory switches and the patterns apply globally
11789 even if they are in different sections.
11791 @noindent
11792 Examples of Naming Patterns are
11794 @smallexample
11795    "*.[12].ada"
11796    "*.ad[sb]*"
11797    "body_*"    "spec_*"
11798 @end smallexample
11800 @noindent
11801 For a more complete description of the syntax of Naming Patterns,
11802 see the second kind of regular expressions described in @file{g-regexp.ads}
11803 (the ``Glob'' regular expressions).
11805 @noindent
11806 When invoked with no switch @code{-P}, @code{gnatname} will create a
11807 configuration pragmas file @file{gnat.adc} in the current working directory,
11808 with pragmas @code{Source_File_Name} for each file that contains a valid Ada
11809 unit.
11811 @node Switches for gnatname
11812 @section Switches for @code{gnatname}
11814 @noindent
11815 Switches for @code{gnatname} must precede any specified Naming Pattern.
11817 @noindent
11818 You may specify any of the following switches to @code{gnatname}:
11820 @table @option
11821 @c !sort!
11823 @item --version
11824 @cindex @option{--version} @command{gnatname}
11825 Display Copyright and version, then exit disregarding all other options.
11827 @item --help
11828 @cindex @option{--help} @command{gnatname}
11829 If @option{--version} was not used, display usage, then exit disregarding
11830 all other options.
11832 @item --subdirs=<dir>
11833 Real object, library or exec directories are subdirectories <dir> of the
11834 specified ones.
11836 @item --no-backup
11837 Do not create a backup copy of an existing project file.
11839 @item --and
11840 Start another section of directories/patterns.
11842 @item ^-c^/CONFIG_FILE=^@file{file}
11843 @cindex @option{^-c^/CONFIG_FILE^} (@code{gnatname})
11844 Create a configuration pragmas file @file{file} (instead of the default
11845 @file{gnat.adc}).
11846 @ifclear vms
11847 There may be zero, one or more space between @option{-c} and
11848 @file{file}.
11849 @end ifclear
11850 @file{file} may include directory information. @file{file} must be
11851 writable. There may be only one switch @option{^-c^/CONFIG_FILE^}.
11852 When a switch @option{^-c^/CONFIG_FILE^} is
11853 specified, no switch @option{^-P^/PROJECT_FILE^} may be specified (see below).
11855 @item ^-d^/SOURCE_DIRS=^@file{dir}
11856 @cindex @option{^-d^/SOURCE_DIRS^} (@code{gnatname})
11857 Look for source files in directory @file{dir}. There may be zero, one or more
11858 spaces between @option{^-d^/SOURCE_DIRS=^} and @file{dir}.
11859 @file{dir} may end with @code{/**}, that is it may be of the form
11860 @code{root_dir/**}. In this case, the directory @code{root_dir} and all of its
11861 subdirectories, recursively, have to be searched for sources.
11862 When a switch @option{^-d^/SOURCE_DIRS^}
11863 is specified, the current working directory will not be searched for source
11864 files, unless it is explicitly specified with a @option{^-d^/SOURCE_DIRS^}
11865 or @option{^-D^/DIR_FILES^} switch.
11866 Several switches @option{^-d^/SOURCE_DIRS^} may be specified.
11867 If @file{dir} is a relative path, it is relative to the directory of
11868 the configuration pragmas file specified with switch
11869 @option{^-c^/CONFIG_FILE^},
11870 or to the directory of the project file specified with switch
11871 @option{^-P^/PROJECT_FILE^} or,
11872 if neither switch @option{^-c^/CONFIG_FILE^}
11873 nor switch @option{^-P^/PROJECT_FILE^} are specified, it is relative to the
11874 current working directory. The directory
11875 specified with switch @option{^-d^/SOURCE_DIRS^} must exist and be readable.
11877 @item ^-D^/DIRS_FILE=^@file{file}
11878 @cindex @option{^-D^/DIRS_FILE^} (@code{gnatname})
11879 Look for source files in all directories listed in text file @file{file}.
11880 There may be zero, one or more spaces between @option{^-D^/DIRS_FILE=^}
11881 and @file{file}.
11882 @file{file} must be an existing, readable text file.
11883 Each nonempty line in @file{file} must be a directory.
11884 Specifying switch @option{^-D^/DIRS_FILE^} is equivalent to specifying as many
11885 switches @option{^-d^/SOURCE_DIRS^} as there are nonempty lines in
11886 @file{file}.
11888 @item -eL
11889 Follow symbolic links when processing project files.
11891 @item ^-f^/FOREIGN_PATTERN=^@file{pattern}
11892 @cindex @option{^-f^/FOREIGN_PATTERN^} (@code{gnatname})
11893 Foreign patterns. Using this switch, it is possible to add sources of languages
11894 other than Ada to the list of sources of a project file.
11895 It is only useful if a ^-P^/PROJECT_FILE^ switch is used.
11896 For example,
11897 @smallexample
11898 gnatname ^-Pprj -f"*.c"^/PROJECT_FILE=PRJ /FOREIGN_PATTERN=*.C^ "*.ada"
11899 @end smallexample
11900 @noindent
11901 will look for Ada units in all files with the @file{.ada} extension,
11902 and will add to the list of file for project @file{prj.gpr} the C files
11903 with extension @file{.^c^C^}.
11905 @item ^-h^/HELP^
11906 @cindex @option{^-h^/HELP^} (@code{gnatname})
11907 Output usage (help) information. The output is written to @file{stdout}.
11909 @item ^-P^/PROJECT_FILE=^@file{proj}
11910 @cindex @option{^-P^/PROJECT_FILE^} (@code{gnatname})
11911 Create or update project file @file{proj}. There may be zero, one or more space
11912 between @option{-P} and @file{proj}. @file{proj} may include directory
11913 information. @file{proj} must be writable.
11914 There may be only one switch @option{^-P^/PROJECT_FILE^}.
11915 When a switch @option{^-P^/PROJECT_FILE^} is specified,
11916 no switch @option{^-c^/CONFIG_FILE^} may be specified.
11917 On all platforms, except on VMS, when @code{gnatname} is invoked for an
11918 existing project file <proj>.gpr, a backup copy of the project file is created
11919 in the project directory with file name <proj>.gpr.saved_x. 'x' is the first
11920 non negative number that makes this backup copy a new file.
11922 @item ^-v^/VERBOSE^
11923 @cindex @option{^-v^/VERBOSE^} (@code{gnatname})
11924 Verbose mode. Output detailed explanation of behavior to @file{stdout}.
11925 This includes name of the file written, the name of the directories to search
11926 and, for each file in those directories whose name matches at least one of
11927 the Naming Patterns, an indication of whether the file contains a unit,
11928 and if so the name of the unit.
11930 @item ^-v -v^/VERBOSE /VERBOSE^
11931 @cindex @option{^-v -v^/VERBOSE /VERBOSE^} (@code{gnatname})
11932 Very Verbose mode. In addition to the output produced in verbose mode,
11933 for each file in the searched directories whose name matches none of
11934 the Naming Patterns, an indication is given that there is no match.
11936 @item ^-x^/EXCLUDED_PATTERN=^@file{pattern}
11937 @cindex @option{^-x^/EXCLUDED_PATTERN^} (@code{gnatname})
11938 Excluded patterns. Using this switch, it is possible to exclude some files
11939 that would match the name patterns. For example,
11940 @smallexample
11941 gnatname ^-x "*_nt.ada"^/EXCLUDED_PATTERN=*_nt.ada^ "*.ada"
11942 @end smallexample
11943 @noindent
11944 will look for Ada units in all files with the @file{.ada} extension,
11945 except those whose names end with @file{_nt.ada}.
11947 @end table
11949 @node Examples of gnatname Usage
11950 @section Examples of @code{gnatname} Usage
11952 @ifset vms
11953 @smallexample
11954 $ gnatname /CONFIG_FILE=[HOME.ME]NAMES.ADC /SOURCE_DIRS=SOURCES "[a-z]*.ada*"
11955 @end smallexample
11956 @end ifset
11958 @ifclear vms
11959 @smallexample
11960 $ gnatname -c /home/me/names.adc -d sources "[a-z]*.ada*"
11961 @end smallexample
11962 @end ifclear
11964 @noindent
11965 In this example, the directory @file{^/home/me^[HOME.ME]^} must already exist
11966 and be writable. In addition, the directory
11967 @file{^/home/me/sources^[HOME.ME.SOURCES]^} (specified by
11968 @option{^-d sources^/SOURCE_DIRS=SOURCES^}) must exist and be readable.
11970 @ifclear vms
11971 Note the optional spaces after @option{-c} and @option{-d}.
11972 @end ifclear
11974 @smallexample
11975 @ifclear vms
11976 $ gnatname -P/home/me/proj -x "*_nt_body.ada"
11977   -dsources -dsources/plus -Dcommon_dirs.txt "body_*" "spec_*"
11978 @end ifclear
11979 @ifset vms
11980 $ gnatname  /PROJECT_FILE=[HOME.ME]PROJ
11981   /EXCLUDED_PATTERN=*_nt_body.ada
11982   /SOURCE_DIRS=(SOURCES,[SOURCES.PLUS])
11983   /DIRS_FILE=COMMON_DIRS.TXT "body_*" "spec_*"
11984 @end ifset
11985 @end smallexample
11987 Note that several switches @option{^-d^/SOURCE_DIRS^} may be used,
11988 even in conjunction with one or several switches
11989 @option{^-D^/DIRS_FILE^}. Several Naming Patterns and one excluded pattern
11990 are used in this example.
11992 @c *****************************************
11993 @c * G N A T  P r o j e c t  M a n a g e r *
11994 @c *****************************************
11996 @c ------ macros for projects.texi
11997 @c These macros are needed when building the gprbuild documentation, but
11998 @c should have no effect in the gnat user's guide
12000 @macro CODESAMPLE{TXT}
12001 @smallexample
12002 @group
12003 \TXT\
12004 @end group
12005 @end smallexample
12006 @end macro
12008 @macro PROJECTFILE{TXT}
12009 @CODESAMPLE{\TXT\}
12010 @end macro
12012 @c simulates a newline when in a @CODESAMPLE
12013 @macro NL{}
12014 @end macro
12016 @macro TIP{TXT}
12017 @quotation
12018 @noindent
12019 \TXT\
12020 @end quotation
12021 @end macro
12023 @macro TIPHTML{TXT}
12024 \TXT\
12025 @end macro
12027 @macro IMPORTANT{TXT}
12028 @quotation
12029 @noindent
12030 \TXT\
12031 @end quotation
12033 @end macro
12035 @macro NOTE{TXT}
12036 @quotation
12037 @noindent
12038 \TXT\
12039 @end quotation
12040 @end macro
12042 @include projects.texi
12044 @c ---------------------------------------------
12045 @c Tools Supporting Project Files
12046 @c ---------------------------------------------
12048 @node Tools Supporting Project Files
12049 @chapter Tools Supporting Project Files
12051 @noindent
12053 @menu
12054 * gnatmake and Project Files::
12055 * The GNAT Driver and Project Files::
12056 @end menu
12058 @c ---------------------------------------------
12059 @node gnatmake and Project Files
12060 @section gnatmake and Project Files
12061 @c ---------------------------------------------
12063 @noindent
12064 This section covers several topics related to @command{gnatmake} and
12065 project files: defining ^switches^switches^ for @command{gnatmake}
12066 and for the tools that it invokes; specifying configuration pragmas;
12067 the use of the @code{Main} attribute; building and rebuilding library project
12068 files.
12070 @menu
12071 * Switches Related to Project Files::
12072 * Switches and Project Files::
12073 * Specifying Configuration Pragmas::
12074 * Project Files and Main Subprograms::
12075 * Library Project Files::
12076 @end menu
12078 @c ---------------------------------------------
12079 @node Switches Related to Project Files
12080 @subsection Switches Related to Project Files
12081 @c ---------------------------------------------
12083 @noindent
12084 The following switches are used by GNAT tools that support project files:
12086 @table @option
12088 @item ^-P^/PROJECT_FILE=^@var{project}
12089 @cindex @option{^-P^/PROJECT_FILE^} (any project-aware tool)
12090 Indicates the name of a project file. This project file will be parsed with
12091 the verbosity indicated by @option{^-vP^MESSAGE_PROJECT_FILES=^@emph{x}},
12092 if any, and using the external references indicated
12093 by @option{^-X^/EXTERNAL_REFERENCE^} switches, if any.
12094 @ifclear vms
12095 There may zero, one or more spaces between @option{-P} and @var{project}.
12096 @end ifclear
12098 There must be only one @option{^-P^/PROJECT_FILE^} switch on the command line.
12100 Since the Project Manager parses the project file only after all the switches
12101 on the command line are checked, the order of the switches
12102 @option{^-P^/PROJECT_FILE^},
12103 @option{^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}}
12104 or @option{^-X^/EXTERNAL_REFERENCE^} is not significant.
12106 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
12107 @cindex @option{^-X^/EXTERNAL_REFERENCE^} (any project-aware tool)
12108 Indicates that external variable @var{name} has the value @var{value}.
12109 The Project Manager will use this value for occurrences of
12110 @code{external(name)} when parsing the project file.
12112 @ifclear vms
12113 If @var{name} or @var{value} includes a space, then @var{name=value} should be
12114 put between quotes.
12115 @smallexample
12116   -XOS=NT
12117   -X"user=John Doe"
12118 @end smallexample
12119 @end ifclear
12121 Several @option{^-X^/EXTERNAL_REFERENCE^} switches can be used simultaneously.
12122 If several @option{^-X^/EXTERNAL_REFERENCE^} switches specify the same
12123 @var{name}, only the last one is used.
12125 An external variable specified with a @option{^-X^/EXTERNAL_REFERENCE^} switch
12126 takes precedence over the value of the same name in the environment.
12128 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
12129 @cindex @option{^-vP^/MESSAGES_PROJECT_FILE^} (any project-aware tool)
12130 Indicates the verbosity of the parsing of GNAT project files.
12132 @ifclear vms
12133 @option{-vP0} means Default;
12134 @option{-vP1} means Medium;
12135 @option{-vP2} means High.
12136 @end ifclear
12138 @ifset vms
12139 There are three possible options for this qualifier: DEFAULT, MEDIUM and
12140 HIGH.
12141 @end ifset
12143 The default is ^Default^DEFAULT^: no output for syntactically correct
12144 project files.
12145 If several @option{^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}} switches are present,
12146 only the last one is used.
12148 @item ^-aP^/ADD_PROJECT_SEARCH_DIR=^<dir>
12149 @cindex @option{^-aP^/ADD_PROJECT_SEARCH_DIR=^} (any project-aware tool)
12150 Add directory <dir> at the beginning of the project search path, in order,
12151 after the current working directory.
12153 @ifclear vms
12154 @item -eL
12155 @cindex @option{-eL} (any project-aware tool)
12156 Follow all symbolic links when processing project files.
12157 @end ifclear
12159 @item ^--subdirs^/SUBDIRS^=<subdir>
12160 @cindex @option{^--subdirs^/SUBDIRS^=} (gnatmake and gnatclean)
12161 This switch is recognized by @command{gnatmake} and @command{gnatclean}. It
12162 indicate that the real directories (except the source directories) are the
12163 subdirectories <subdir> of the directories specified in the project files.
12164 This applies in particular to object directories, library directories and
12165 exec directories. If the subdirectories do not exist, they are created
12166 automatically.
12168 @end table
12170 @c ---------------------------------------------
12171 @node Switches and Project Files
12172 @subsection Switches and Project Files
12173 @c ---------------------------------------------
12175 @noindent
12176 @ifset vms
12177 It is not currently possible to specify VMS style qualifiers in the project
12178 files; only Unix style ^switches^switches^ may be specified.
12179 @end ifset
12181 For each of the packages @code{Builder}, @code{Compiler}, @code{Binder}, and
12182 @code{Linker}, you can specify a @code{^Default_Switches^Default_Switches^}
12183 attribute, a @code{Switches} attribute, or both;
12184 as their names imply, these ^switch^switch^-related
12185 attributes affect the ^switches^switches^ that are used for each of these GNAT
12186 components when
12187 @command{gnatmake} is invoked.  As will be explained below, these
12188 component-specific ^switches^switches^ precede
12189 the ^switches^switches^ provided on the @command{gnatmake} command line.
12191 The @code{^Default_Switches^Default_Switches^} attribute is an attribute
12192 indexed by language name (case insensitive) whose value is a string list.
12193 For example:
12195 @smallexample @c projectfile
12196 @group
12197 package Compiler is
12198   for ^Default_Switches^Default_Switches^ ("Ada")
12199       use ("^-gnaty^-gnaty^",
12200            "^-v^-v^");
12201 end Compiler;
12202 @end group
12203 @end smallexample
12205 @noindent
12206 The @code{Switches} attribute is indexed on a file name (which may or may
12207 not be case sensitive, depending
12208 on the operating system) whose value is a string list.  For example:
12210 @smallexample @c projectfile
12211 @group
12212 package Builder is
12213    for Switches ("main1.adb")
12214        use ("^-O2^-O2^");
12215    for Switches ("main2.adb")
12216        use ("^-g^-g^");
12217 end Builder;
12218 @end group
12219 @end smallexample
12221 @noindent
12222 For the @code{Builder} package, the file names must designate source files
12223 for main subprograms.  For the @code{Binder} and @code{Linker} packages, the
12224 file names must designate @file{ALI} or source files for main subprograms.
12225 In each case just the file name without an explicit extension is acceptable.
12227 For each tool used in a program build (@command{gnatmake}, the compiler, the
12228 binder, and the linker), the corresponding package @dfn{contributes} a set of
12229 ^switches^switches^ for each file on which the tool is invoked, based on the
12230 ^switch^switch^-related attributes defined in the package.
12231 In particular, the ^switches^switches^
12232 that each of these packages contributes for a given file @var{f} comprise:
12234 @itemize @bullet
12235 @item the value of attribute @code{Switches (@var{f})},
12236   if it is specified in the package for the given file,
12237 @item otherwise, the value of @code{^Default_Switches^Default_Switches^ ("Ada")},
12238   if it is specified in the package.
12240 @end itemize
12242 @noindent
12243 If neither of these attributes is defined in the package, then the package does
12244 not contribute any ^switches^switches^ for the given file.
12246 When @command{gnatmake} is invoked on a file, the ^switches^switches^ comprise
12247 two sets, in the following order: those contributed for the file
12248 by the @code{Builder} package;
12249 and the switches passed on the command line.
12251 When @command{gnatmake} invokes a tool (compiler, binder, linker) on a file,
12252 the ^switches^switches^ passed to the tool comprise three sets,
12253 in the following order:
12255 @enumerate
12256 @item
12257 the applicable ^switches^switches^ contributed for the file
12258 by the @code{Builder} package in the project file supplied on the command line;
12260 @item
12261 those contributed for the file by the package (in the relevant project file --
12262 see below) corresponding to the tool; and
12264 @item
12265 the applicable switches passed on the command line.
12266 @end enumerate
12268 The term @emph{applicable ^switches^switches^} reflects the fact that
12269 @command{gnatmake} ^switches^switches^ may or may not be passed to individual
12270 tools, depending on the individual ^switch^switch^.
12272 @command{gnatmake} may invoke the compiler on source files from different
12273 projects. The Project Manager will use the appropriate project file to
12274 determine the @code{Compiler} package for each source file being compiled.
12275 Likewise for the @code{Binder} and @code{Linker} packages.
12277 As an example, consider the following package in a project file:
12279 @smallexample @c projectfile
12280 @group
12281 project Proj1 is
12282    package Compiler is
12283       for ^Default_Switches^Default_Switches^ ("Ada")
12284           use ("^-g^-g^");
12285       for Switches ("a.adb")
12286           use ("^-O1^-O1^");
12287       for Switches ("b.adb")
12288           use ("^-O2^-O2^",
12289                "^-gnaty^-gnaty^");
12290    end Compiler;
12291 end Proj1;
12292 @end group
12293 @end smallexample
12295 @noindent
12296 If @command{gnatmake} is invoked with this project file, and it needs to
12297 compile, say, the files @file{a.adb}, @file{b.adb}, and @file{c.adb}, then
12298 @file{a.adb} will be compiled with the ^switch^switch^
12299 @option{^-O1^-O1^},
12300 @file{b.adb} with ^switches^switches^
12301 @option{^-O2^-O2^}
12302 and @option{^-gnaty^-gnaty^},
12303 and @file{c.adb} with @option{^-g^-g^}.
12305 The following example illustrates the ordering of the ^switches^switches^
12306 contributed by different packages:
12308 @smallexample @c projectfile
12309 @group
12310 project Proj2 is
12311    package Builder is
12312       for Switches ("main.adb")
12313           use ("^-g^-g^",
12314                "^-O1^-)1^",
12315                "^-f^-f^");
12316    end Builder;
12317 @end group
12319 @group
12320    package Compiler is
12321       for Switches ("main.adb")
12322           use ("^-O2^-O2^");
12323    end Compiler;
12324 end Proj2;
12325 @end group
12326 @end smallexample
12328 @noindent
12329 If you issue the command:
12331 @smallexample
12332     gnatmake ^-Pproj2^/PROJECT_FILE=PROJ2^ -O0 main
12333 @end smallexample
12335 @noindent
12336 then the compiler will be invoked on @file{main.adb} with the following
12337 sequence of ^switches^switches^
12339 @smallexample
12340    ^-g -O1 -O2 -O0^-g -O1 -O2 -O0^
12341 @end smallexample
12343 @noindent
12344 with the last @option{^-O^-O^}
12345 ^switch^switch^ having precedence over the earlier ones;
12346 several other ^switches^switches^
12347 (such as @option{^-c^-c^}) are added implicitly.
12349 The ^switches^switches^
12350 @option{^-g^-g^}
12351 and @option{^-O1^-O1^} are contributed by package
12352 @code{Builder},  @option{^-O2^-O2^} is contributed
12353 by the package @code{Compiler}
12354 and @option{^-O0^-O0^} comes from the command line.
12356 The @option{^-g^-g^}
12357 ^switch^switch^ will also be passed in the invocation of
12358 @command{Gnatlink.}
12360 A final example illustrates switch contributions from packages in different
12361 project files:
12363 @smallexample @c projectfile
12364 @group
12365 project Proj3 is
12366    for Source_Files use ("pack.ads", "pack.adb");
12367    package Compiler is
12368       for ^Default_Switches^Default_Switches^ ("Ada")
12369           use ("^-gnata^-gnata^");
12370    end Compiler;
12371 end Proj3;
12372 @end group
12374 @group
12375 with "Proj3";
12376 project Proj4 is
12377    for Source_Files use ("foo_main.adb", "bar_main.adb");
12378    package Builder is
12379       for Switches ("foo_main.adb")
12380           use ("^-s^-s^",
12381                "^-g^-g^");
12382    end Builder;
12383 end Proj4;
12384 @end group
12386 @group
12387 -- Ada source file:
12388 with Pack;
12389 procedure Foo_Main is
12390    @dots{}
12391 end Foo_Main;
12392 @end group
12393 @end smallexample
12395 @noindent
12396 If the command is
12397 @smallexample
12398 gnatmake ^-PProj4^/PROJECT_FILE=PROJ4^ foo_main.adb -cargs -gnato
12399 @end smallexample
12401 @noindent
12402 then the ^switches^switches^ passed to the compiler for @file{foo_main.adb} are
12403 @option{^-g^-g^} (contributed by the package @code{Proj4.Builder}) and
12404 @option{^-gnato^-gnato^} (passed on the command line).
12405 When the imported package @code{Pack} is compiled, the ^switches^switches^ used
12406 are @option{^-g^-g^} from @code{Proj4.Builder},
12407 @option{^-gnata^-gnata^} (contributed from package @code{Proj3.Compiler},
12408 and @option{^-gnato^-gnato^} from the command line.
12410 When using @command{gnatmake} with project files, some ^switches^switches^ or
12411 arguments may be expressed as relative paths. As the working directory where
12412 compilation occurs may change, these relative paths are converted to absolute
12413 paths. For the ^switches^switches^ found in a project file, the relative paths
12414 are relative to the project file directory, for the switches on the command
12415 line, they are relative to the directory where @command{gnatmake} is invoked.
12416 The ^switches^switches^ for which this occurs are:
12417 ^-I^-I^,
12418 ^-A^-A^,
12419 ^-L^-L^,
12420 ^-aO^-aO^,
12421 ^-aL^-aL^,
12422 ^-aI^-aI^, as well as all arguments that are not switches (arguments to
12423 ^switch^switch^
12424 ^-o^-o^, object files specified in package @code{Linker} or after
12425 -largs on the command line). The exception to this rule is the ^switch^switch^
12426 ^--RTS=^--RTS=^ for which a relative path argument is never converted.
12428 @c ---------------------------------------------
12429 @node Specifying Configuration Pragmas
12430 @subsection Specifying Configuration Pragmas
12431 @c ---------------------------------------------
12433 @noindent
12434 When using @command{gnatmake} with project files, if there exists a file
12435 @file{gnat.adc} that contains configuration pragmas, this file will be
12436 ignored.
12438 Configuration pragmas can be defined by means of the following attributes in
12439 project files: @code{Global_Configuration_Pragmas} in package @code{Builder}
12440 and @code{Local_Configuration_Pragmas} in package @code{Compiler}.
12442 Both these attributes are single string attributes. Their values is the path
12443 name of a file containing configuration pragmas. If a path name is relative,
12444 then it is relative to the project directory of the project file where the
12445 attribute is defined.
12447 When compiling a source, the configuration pragmas used are, in order,
12448 those listed in the file designated by attribute
12449 @code{Global_Configuration_Pragmas} in package @code{Builder} of the main
12450 project file, if it is specified, and those listed in the file designated by
12451 attribute @code{Local_Configuration_Pragmas} in package @code{Compiler} of
12452 the project file of the source, if it exists.
12454 @c ---------------------------------------------
12455 @node Project Files and Main Subprograms
12456 @subsection Project Files and Main Subprograms
12457 @c ---------------------------------------------
12459 @noindent
12460 When using a project file, you can invoke @command{gnatmake}
12461 with one or several main subprograms, by specifying their source files on the
12462 command line.
12464 @smallexample
12465     gnatmake ^-P^/PROJECT_FILE=^prj main1.adb main2.adb main3.adb
12466 @end smallexample
12468 @noindent
12469 Each of these needs to be a source file of the same project, except
12470 when the switch ^-u^/UNIQUE^ is used.
12472 When ^-u^/UNIQUE^ is not used, all the mains need to be sources of the
12473 same project, one of the project in the tree rooted at the project specified
12474 on the command line. The package @code{Builder} of this common project, the
12475 "main project" is the one that is considered by @command{gnatmake}.
12477 When ^-u^/UNIQUE^ is used, the specified source files may be in projects
12478 imported directly or indirectly by the project specified on the command line.
12479 Note that if such a source file is not part of the project specified on the
12480 command line, the ^switches^switches^ found in package @code{Builder} of the
12481 project specified on the command line, if any, that are transmitted
12482 to the compiler will still be used, not those found in the project file of
12483 the source file.
12485 When using a project file, you can also invoke @command{gnatmake} without
12486 explicitly specifying any main, and the effect depends on whether you have
12487 defined the @code{Main} attribute.  This attribute has a string list value,
12488 where each element in the list is the name of a source file (the file
12489 extension is optional) that contains a unit that can be a main subprogram.
12491 If the @code{Main} attribute is defined in a project file as a non-empty
12492 string list and the switch @option{^-u^/UNIQUE^} is not used on the command
12493 line, then invoking @command{gnatmake} with this project file but without any
12494 main on the command line is equivalent to invoking @command{gnatmake} with all
12495 the file names in the @code{Main} attribute on the command line.
12497 Example:
12498 @smallexample @c projectfile
12499 @group
12500    project Prj is
12501       for Main use ("main1.adb", "main2.adb", "main3.adb");
12502    end Prj;
12503 @end group
12504 @end smallexample
12506 @noindent
12507 With this project file, @code{"gnatmake ^-Pprj^/PROJECT_FILE=PRJ^"}
12508 is equivalent to
12509 @code{"gnatmake ^-Pprj^/PROJECT_FILE=PRJ^ main1.adb main2.adb main3.adb"}.
12511 When the project attribute @code{Main} is not specified, or is specified
12512 as an empty string list, or when the switch @option{-u} is used on the command
12513 line, then invoking @command{gnatmake} with no main on the command line will
12514 result in all immediate sources of the project file being checked, and
12515 potentially recompiled. Depending on the presence of the switch @option{-u},
12516 sources from other project files on which the immediate sources of the main
12517 project file depend are also checked and potentially recompiled. In other
12518 words, the @option{-u} switch is applied to all of the immediate sources of the
12519 main project file.
12521 When no main is specified on the command line and attribute @code{Main} exists
12522 and includes several mains, or when several mains are specified on the
12523 command line, the default ^switches^switches^ in package @code{Builder} will
12524 be used for all mains, even if there are specific ^switches^switches^
12525 specified for one or several mains.
12527 But the ^switches^switches^ from package @code{Binder} or @code{Linker} will be
12528 the specific ^switches^switches^ for each main, if they are specified.
12530 @c ---------------------------------------------
12531 @node Library Project Files
12532 @subsection Library Project Files
12533 @c ---------------------------------------------
12535 @noindent
12536 When @command{gnatmake} is invoked with a main project file that is a library
12537 project file, it is not allowed to specify one or more mains on the command
12538 line.
12540 When a library project file is specified, switches ^-b^/ACTION=BIND^ and
12541 ^-l^/ACTION=LINK^ have special meanings.
12543 @itemize @bullet
12544 @item ^-b^/ACTION=BIND^ is only allowed for stand-alone libraries. It indicates
12545   to @command{gnatmake} that @command{gnatbind} should be invoked for the
12546   library.
12548 @item ^-l^/ACTION=LINK^ may be used for all library projects. It indicates
12549   to @command{gnatmake} that the binder generated file should be compiled
12550   (in the case of a stand-alone library) and that the library should be built.
12551 @end itemize
12553 @c ---------------------------------------------
12554 @node The GNAT Driver and Project Files
12555 @section The GNAT Driver and Project Files
12556 @c ---------------------------------------------
12558 @noindent
12559 A number of GNAT tools, other than @command{^gnatmake^gnatmake^}
12560 can benefit from project files:
12561 (@command{^gnatbind^gnatbind^},
12562 @command{^gnatcheck^gnatcheck^},
12563 @command{^gnatclean^gnatclean^},
12564 @command{^gnatelim^gnatelim^},
12565 @command{^gnatfind^gnatfind^},
12566 @command{^gnatlink^gnatlink^},
12567 @command{^gnatls^gnatls^},
12568 @command{^gnatmetric^gnatmetric^},
12569 @command{^gnatpp^gnatpp^},
12570 @command{^gnatstub^gnatstub^},
12571 and @command{^gnatxref^gnatxref^}). However, none of these tools can be invoked
12572 directly with a project file switch (@option{^-P^/PROJECT_FILE=^}).
12573 They must be invoked through the @command{gnat} driver.
12575 The @command{gnat} driver is a wrapper that accepts a number of commands and
12576 calls the corresponding tool. It was designed initially for VMS platforms (to
12577 convert VMS qualifiers to Unix-style switches), but it is now available on all
12578 GNAT platforms.
12580 On non-VMS platforms, the @command{gnat} driver accepts the following commands
12581 (case insensitive):
12583 @itemize @bullet
12584 @item BIND to invoke @command{^gnatbind^gnatbind^}
12585 @item CHOP to invoke @command{^gnatchop^gnatchop^}
12586 @item CLEAN to invoke @command{^gnatclean^gnatclean^}
12587 @item COMP or COMPILE to invoke the compiler
12588 @item ELIM to invoke @command{^gnatelim^gnatelim^}
12589 @item FIND to invoke @command{^gnatfind^gnatfind^}
12590 @item KR or KRUNCH to invoke @command{^gnatkr^gnatkr^}
12591 @item LINK to invoke @command{^gnatlink^gnatlink^}
12592 @item LS or LIST to invoke @command{^gnatls^gnatls^}
12593 @item MAKE to invoke @command{^gnatmake^gnatmake^}
12594 @item NAME to invoke @command{^gnatname^gnatname^}
12595 @item PREP or PREPROCESS to invoke @command{^gnatprep^gnatprep^}
12596 @item PP or PRETTY to invoke @command{^gnatpp^gnatpp^}
12597 @item METRIC to invoke @command{^gnatmetric^gnatmetric^}
12598 @item STUB to invoke @command{^gnatstub^gnatstub^}
12599 @item XREF to invoke @command{^gnatxref^gnatxref^}
12601 @end itemize
12603 @noindent
12604 (note that the compiler is invoked using the command
12605 @command{^gnatmake -f -u -c^gnatmake -f -u -c^}).
12607 On non-VMS platforms, between @command{gnat} and the command, two
12608 special switches may be used:
12610 @itemize @bullet
12611 @item @command{-v} to display the invocation of the tool.
12612 @item @command{-dn} to prevent the @command{gnat} driver from removing
12613   the temporary files it has created. These temporary files are
12614   configuration files and temporary file list files.
12616 @end itemize
12618 @noindent
12619 The command may be followed by switches and arguments for the invoked
12620 tool.
12622 @smallexample
12623   gnat bind -C main.ali
12624   gnat ls -a main
12625   gnat chop foo.txt
12626 @end smallexample
12628 @noindent
12629 Switches may also be put in text files, one switch per line, and the text
12630 files may be specified with their path name preceded by '@@'.
12632 @smallexample
12633    gnat bind @@args.txt main.ali
12634 @end smallexample
12636 @noindent
12637 In addition, for commands BIND, COMP or COMPILE, FIND, ELIM, LS or LIST, LINK,
12638 METRIC, PP or PRETTY, STUB and XREF, the project file related switches
12639 (@option{^-P^/PROJECT_FILE^},
12640 @option{^-X^/EXTERNAL_REFERENCE^} and
12641 @option{^-vP^/MESSAGES_PROJECT_FILE=^x}) may be used in addition to
12642 the switches of the invoking tool.
12644 When GNAT PP or GNAT PRETTY is used with a project file, but with no source
12645 specified on the command line, it invokes @command{^gnatpp^gnatpp^} with all
12646 the immediate sources of the specified project file.
12648 When GNAT METRIC is used with a project file, but with no source
12649 specified on the command line, it invokes @command{^gnatmetric^gnatmetric^}
12650 with all the immediate sources of the specified project file and with
12651 @option{^-d^/DIRECTORY^} with the parameter pointing to the object directory
12652 of the project.
12654 In addition, when GNAT PP, GNAT PRETTY or GNAT METRIC is used with
12655 a project file, no source is specified on the command line and
12656 switch ^-U^/ALL_PROJECTS^ is specified on the command line, then
12657 the underlying tool (^gnatpp^gnatpp^ or
12658 ^gnatmetric^gnatmetric^) is invoked for all sources of all projects,
12659 not only for the immediate sources of the main project.
12660 @ifclear vms
12661 (-U stands for Universal or Union of the project files of the project tree)
12662 @end ifclear
12664 For each of the following commands, there is optionally a corresponding
12665 package in the main project.
12667 @itemize @bullet
12668 @item package @code{Binder} for command BIND (invoking @code{^gnatbind^gnatbind^})
12670 @item package @code{Check} for command CHECK (invoking
12671   @code{^gnatcheck^gnatcheck^})
12673 @item package @code{Compiler} for command COMP or COMPILE (invoking the compiler)
12675 @item package @code{Cross_Reference} for command XREF (invoking
12676   @code{^gnatxref^gnatxref^})
12678 @item package @code{Eliminate} for command ELIM (invoking
12679   @code{^gnatelim^gnatelim^})
12681 @item package @code{Finder} for command FIND (invoking @code{^gnatfind^gnatfind^})
12683 @item package @code{Gnatls} for command LS or LIST (invoking @code{^gnatls^gnatls^})
12685 @item package @code{Gnatstub} for command STUB
12686   (invoking @code{^gnatstub^gnatstub^})
12688 @item package @code{Linker} for command LINK (invoking @code{^gnatlink^gnatlink^})
12690 @item package @code{Check} for command CHECK
12691   (invoking @code{^gnatcheck^gnatcheck^})
12693 @item package @code{Metrics} for command METRIC
12694   (invoking @code{^gnatmetric^gnatmetric^})
12696 @item package @code{Pretty_Printer} for command PP or PRETTY
12697   (invoking @code{^gnatpp^gnatpp^})
12699 @end itemize
12701 @noindent
12702 Package @code{Gnatls} has a unique attribute @code{Switches},
12703 a simple variable with a string list value. It contains ^switches^switches^
12704 for the invocation of @code{^gnatls^gnatls^}.
12706 @smallexample @c projectfile
12707 @group
12708 project Proj1 is
12709    package gnatls is
12710       for Switches
12711           use ("^-a^-a^",
12712                "^-v^-v^");
12713    end gnatls;
12714 end Proj1;
12715 @end group
12716 @end smallexample
12718 @noindent
12719 All other packages have two attribute @code{Switches} and
12720 @code{^Default_Switches^Default_Switches^}.
12722 @code{Switches} is an indexed attribute, indexed by the
12723 source file name, that has a string list value: the ^switches^switches^ to be
12724 used when the tool corresponding to the package is invoked for the specific
12725 source file.
12727 @code{^Default_Switches^Default_Switches^} is an attribute,
12728 indexed by  the programming language that has a string list value.
12729 @code{^Default_Switches^Default_Switches^ ("Ada")} contains the
12730 ^switches^switches^ for the invocation of the tool corresponding
12731 to the package, except if a specific @code{Switches} attribute
12732 is specified for the source file.
12734 @smallexample @c projectfile
12735 @group
12736 project Proj is
12738    for Source_Dirs use ("**");
12740    package gnatls is
12741       for Switches use
12742           ("^-a^-a^",
12743            "^-v^-v^");
12744    end gnatls;
12745 @end group
12746 @group
12748    package Compiler is
12749       for ^Default_Switches^Default_Switches^ ("Ada")
12750           use ("^-gnatv^-gnatv^",
12751                "^-gnatwa^-gnatwa^");
12752    end Binder;
12753 @end group
12754 @group
12756    package Binder is
12757       for ^Default_Switches^Default_Switches^ ("Ada")
12758           use ("^-C^-C^",
12759                "^-e^-e^");
12760    end Binder;
12761 @end group
12762 @group
12764    package Linker is
12765       for ^Default_Switches^Default_Switches^ ("Ada")
12766           use ("^-C^-C^");
12767       for Switches ("main.adb")
12768           use ("^-C^-C^",
12769                "^-v^-v^",
12770                "^-v^-v^");
12771    end Linker;
12772 @end group
12773 @group
12775    package Finder is
12776       for ^Default_Switches^Default_Switches^ ("Ada")
12777            use ("^-a^-a^",
12778                 "^-f^-f^");
12779    end Finder;
12780 @end group
12781 @group
12783    package Cross_Reference is
12784       for ^Default_Switches^Default_Switches^ ("Ada")
12785           use ("^-a^-a^",
12786                "^-f^-f^",
12787                "^-d^-d^",
12788                "^-u^-u^");
12789    end Cross_Reference;
12790 end Proj;
12791 @end group
12792 @end smallexample
12794 @noindent
12795 With the above project file, commands such as
12797 @smallexample
12798    ^gnat comp -Pproj main^GNAT COMP /PROJECT_FILE=PROJ MAIN^
12799    ^gnat ls -Pproj main^GNAT LIST /PROJECT_FILE=PROJ MAIN^
12800    ^gnat xref -Pproj main^GNAT XREF /PROJECT_FILE=PROJ MAIN^
12801    ^gnat bind -Pproj main.ali^GNAT BIND /PROJECT_FILE=PROJ MAIN.ALI^
12802    ^gnat link -Pproj main.ali^GNAT LINK /PROJECT_FILE=PROJ MAIN.ALI^
12803 @end smallexample
12805 @noindent
12806 will set up the environment properly and invoke the tool with the switches
12807 found in the package corresponding to the tool:
12808 @code{^Default_Switches^Default_Switches^ ("Ada")} for all tools,
12809 except @code{Switches ("main.adb")}
12810 for @code{^gnatlink^gnatlink^}.
12811 It is also possible to invoke some of the tools,
12812 (@code{^gnatcheck^gnatcheck^},
12813 @code{^gnatmetric^gnatmetric^},
12814 and @code{^gnatpp^gnatpp^})
12815 on a set of project units thanks to the combination of the switches
12816 @option{-P}, @option{-U} and possibly the main unit when one is interested
12817 in its closure. For instance,
12818 @smallexample
12819 gnat metric -Pproj
12820 @end smallexample
12822 @noindent
12823 will compute the metrics for all the immediate units of project
12824 @code{proj}.
12825 @smallexample
12826 gnat metric -Pproj -U
12827 @end smallexample
12829 @noindent
12830 will compute the metrics for all the units of the closure of projects
12831 rooted at @code{proj}.
12832 @smallexample
12833 gnat metric -Pproj -U main_unit
12834 @end smallexample
12836 @noindent
12837 will compute the metrics for the closure of units rooted at
12838 @code{main_unit}. This last possibility relies implicitly
12839 on @command{gnatbind}'s option @option{-R}. But if the argument files for the
12840 tool invoked by the @command{gnat} driver are explicitly  specified
12841 either directly or through the tool @option{-files} option, then the tool
12842 is called only for these explicitly specified files.
12844 @c *****************************************
12845 @c * Cross-referencing tools
12846 @c *****************************************
12848 @node The Cross-Referencing Tools gnatxref and gnatfind
12849 @chapter  The Cross-Referencing Tools @code{gnatxref} and @code{gnatfind}
12850 @findex gnatxref
12851 @findex gnatfind
12853 @noindent
12854 The compiler generates cross-referencing information (unless
12855 you set the @samp{-gnatx} switch), which are saved in the @file{.ali} files.
12856 This information indicates where in the source each entity is declared and
12857 referenced. Note that entities in package Standard are not included, but
12858 entities in all other predefined units are included in the output.
12860 Before using any of these two tools, you need to compile successfully your
12861 application, so that GNAT gets a chance to generate the cross-referencing
12862 information.
12864 The two tools @code{gnatxref} and @code{gnatfind} take advantage of this
12865 information to provide the user with the capability to easily locate the
12866 declaration and references to an entity. These tools are quite similar,
12867 the difference being that @code{gnatfind} is intended for locating
12868 definitions and/or references to a specified entity or entities, whereas
12869 @code{gnatxref} is oriented to generating a full report of all
12870 cross-references.
12872 To use these tools, you must not compile your application using the
12873 @option{-gnatx} switch on the @command{gnatmake} command line
12874 (@pxref{The GNAT Make Program gnatmake}). Otherwise, cross-referencing
12875 information will not be generated.
12877 Note: to invoke @code{gnatxref} or @code{gnatfind} with a project file,
12878 use the @code{gnat} driver (see @ref{The GNAT Driver and Project Files}).
12880 @menu
12881 * Switches for gnatxref::
12882 * Switches for gnatfind::
12883 * Project Files for gnatxref and gnatfind::
12884 * Regular Expressions in gnatfind and gnatxref::
12885 * Examples of gnatxref Usage::
12886 * Examples of gnatfind Usage::
12887 @end menu
12889 @node Switches for gnatxref
12890 @section @code{gnatxref} Switches
12892 @noindent
12893 The command invocation for @code{gnatxref} is:
12894 @smallexample
12895 @c $ gnatxref @ovar{switches} @var{sourcefile1} @r{[}@var{sourcefile2} @dots{}@r{]}
12896 @c Expanding @ovar macro inline (explanation in macro def comments)
12897 $ gnatxref @r{[}@var{switches}@r{]} @var{sourcefile1} @r{[}@var{sourcefile2} @dots{}@r{]}
12898 @end smallexample
12900 @noindent
12901 where
12903 @table @var
12904 @item sourcefile1
12905 @itemx sourcefile2
12906 identifies the source files for which a report is to be generated. The
12907 ``with''ed units will be processed too. You must provide at least one file.
12909 These file names are considered to be regular expressions, so for instance
12910 specifying @file{source*.adb} is the same as giving every file in the current
12911 directory whose name starts with @file{source} and whose extension is
12912 @file{adb}.
12914 You shouldn't specify any directory name, just base names. @command{gnatxref}
12915 and @command{gnatfind} will be able to locate these files by themselves using
12916 the source path. If you specify directories, no result is produced.
12918 @end table
12920 @noindent
12921 The switches can be:
12922 @table @option
12923 @c !sort!
12924 @item --version
12925 @cindex @option{--version} @command{gnatxref}
12926 Display Copyright and version, then exit disregarding all other options.
12928 @item --help
12929 @cindex @option{--help} @command{gnatxref}
12930 If @option{--version} was not used, display usage, then exit disregarding
12931 all other options.
12933 @item ^-a^/ALL_FILES^
12934 @cindex @option{^-a^/ALL_FILES^} (@command{gnatxref})
12935 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
12936 the read-only files found in the library search path. Otherwise, these files
12937 will be ignored. This option can be used to protect Gnat sources or your own
12938 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
12939 much faster, and their output much smaller. Read-only here refers to access
12940 or permissions status in the file system for the current user.
12942 @item -aIDIR
12943 @cindex @option{-aIDIR} (@command{gnatxref})
12944 When looking for source files also look in directory DIR. The order in which
12945 source file search is undertaken is the same as for @command{gnatmake}.
12947 @item -aODIR
12948 @cindex @option{-aODIR} (@command{gnatxref})
12949 When searching for library and object files, look in directory
12950 DIR. The order in which library files are searched is the same as for
12951 @command{gnatmake}.
12953 @item -nostdinc
12954 @cindex @option{-nostdinc} (@command{gnatxref})
12955 Do not look for sources in the system default directory.
12957 @item -nostdlib
12958 @cindex @option{-nostdlib} (@command{gnatxref})
12959 Do not look for library files in the system default directory.
12961 @item --ext=@var{extension}
12962 @cindex @option{--ext} (@command{gnatxref})
12963 Specify an alternate ali file extension. The default is @code{ali} and other
12964 extensions (e.g. @code{sli} for SPARK library files) may be specified via this
12965 switch. Note that if this switch overrides the default, which means that only
12966 the new extension will be considered.
12968 @item --RTS=@var{rts-path}
12969 @cindex @option{--RTS} (@command{gnatxref})
12970 Specifies the default location of the runtime library. Same meaning as the
12971 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
12973 @item ^-d^/DERIVED_TYPES^
12974 @cindex @option{^-d^/DERIVED_TYPES^} (@command{gnatxref})
12975 If this switch is set @code{gnatxref} will output the parent type
12976 reference for each matching derived types.
12978 @item ^-f^/FULL_PATHNAME^
12979 @cindex @option{^-f^/FULL_PATHNAME^} (@command{gnatxref})
12980 If this switch is set, the output file names will be preceded by their
12981 directory (if the file was found in the search path). If this switch is
12982 not set, the directory will not be printed.
12984 @item ^-g^/IGNORE_LOCALS^
12985 @cindex @option{^-g^/IGNORE_LOCALS^} (@command{gnatxref})
12986 If this switch is set, information is output only for library-level
12987 entities, ignoring local entities. The use of this switch may accelerate
12988 @code{gnatfind} and @code{gnatxref}.
12990 @item -IDIR
12991 @cindex @option{-IDIR} (@command{gnatxref})
12992 Equivalent to @samp{-aODIR -aIDIR}.
12994 @item -pFILE
12995 @cindex @option{-pFILE} (@command{gnatxref})
12996 Specify a project file to use @xref{GNAT Project Manager}.
12997 If you need to use the @file{.gpr}
12998 project files, you should use gnatxref through the GNAT driver
12999 (@command{gnat xref -Pproject}).
13001 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
13002 project file in the current directory.
13004 If a project file is either specified or found by the tools, then the content
13005 of the source directory and object directory lines are added as if they
13006 had been specified respectively by @samp{^-aI^/SOURCE_SEARCH^}
13007 and @samp{^-aO^OBJECT_SEARCH^}.
13008 @item ^-u^/UNUSED^
13009 Output only unused symbols. This may be really useful if you give your
13010 main compilation unit on the command line, as @code{gnatxref} will then
13011 display every unused entity and 'with'ed package.
13013 @ifclear vms
13014 @item -v
13015 Instead of producing the default output, @code{gnatxref} will generate a
13016 @file{tags} file that can be used by vi. For examples how to use this
13017 feature, see @ref{Examples of gnatxref Usage}. The tags file is output
13018 to the standard output, thus you will have to redirect it to a file.
13019 @end ifclear
13021 @end table
13023 @noindent
13024 All these switches may be in any order on the command line, and may even
13025 appear after the file names. They need not be separated by spaces, thus
13026 you can say @samp{gnatxref ^-ag^/ALL_FILES/IGNORE_LOCALS^} instead of
13027 @samp{gnatxref ^-a -g^/ALL_FILES /IGNORE_LOCALS^}.
13029 @node Switches for gnatfind
13030 @section @code{gnatfind} Switches
13032 @noindent
13033 The command line for @code{gnatfind} is:
13035 @smallexample
13036 @c $ gnatfind @ovar{switches} @var{pattern}@r{[}:@var{sourcefile}@r{[}:@var{line}@r{[}:@var{column}@r{]]]}
13037 @c       @r{[}@var{file1} @var{file2} @dots{}]
13038 @c Expanding @ovar macro inline (explanation in macro def comments)
13039 $ gnatfind @r{[}@var{switches}@r{]} @var{pattern}@r{[}:@var{sourcefile}@r{[}:@var{line}@r{[}:@var{column}@r{]]]}
13040       @r{[}@var{file1} @var{file2} @dots{}@r{]}
13041 @end smallexample
13043 @noindent
13044 where
13046 @table @var
13047 @item pattern
13048 An entity will be output only if it matches the regular expression found
13049 in @var{pattern}, see @ref{Regular Expressions in gnatfind and gnatxref}.
13051 Omitting the pattern is equivalent to specifying @samp{*}, which
13052 will match any entity. Note that if you do not provide a pattern, you
13053 have to provide both a sourcefile and a line.
13055 Entity names are given in Latin-1, with uppercase/lowercase equivalence
13056 for matching purposes. At the current time there is no support for
13057 8-bit codes other than Latin-1, or for wide characters in identifiers.
13059 @item sourcefile
13060 @code{gnatfind} will look for references, bodies or declarations
13061 of symbols referenced in @file{@var{sourcefile}}, at line @var{line}
13062 and column @var{column}. See @ref{Examples of gnatfind Usage}
13063 for syntax examples.
13065 @item line
13066 is a decimal integer identifying the line number containing
13067 the reference to the entity (or entities) to be located.
13069 @item column
13070 is a decimal integer identifying the exact location on the
13071 line of the first character of the identifier for the
13072 entity reference. Columns are numbered from 1.
13074 @item file1 file2 @dots{}
13075 The search will be restricted to these source files. If none are given, then
13076 the search will be done for every library file in the search path.
13077 These file must appear only after the pattern or sourcefile.
13079 These file names are considered to be regular expressions, so for instance
13080 specifying @file{source*.adb} is the same as giving every file in the current
13081 directory whose name starts with @file{source} and whose extension is
13082 @file{adb}.
13084 The location of the spec of the entity will always be displayed, even if it
13085 isn't in one of @file{@var{file1}}, @file{@var{file2}},@enddots{}  The
13086 occurrences of the entity in the separate units of the ones given on the
13087 command line will also be displayed.
13089 Note that if you specify at least one file in this part, @code{gnatfind} may
13090 sometimes not be able to find the body of the subprograms.
13092 @end table
13094 @noindent
13095 At least one of 'sourcefile' or 'pattern' has to be present on
13096 the command line.
13098 The following switches are available:
13099 @table @option
13100 @c !sort!
13102 @cindex @option{--version} @command{gnatfind}
13103 Display Copyright and version, then exit disregarding all other options.
13105 @item --help
13106 @cindex @option{--help} @command{gnatfind}
13107 If @option{--version} was not used, display usage, then exit disregarding
13108 all other options.
13110 @item ^-a^/ALL_FILES^
13111 @cindex @option{^-a^/ALL_FILES^} (@command{gnatfind})
13112 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
13113 the read-only files found in the library search path. Otherwise, these files
13114 will be ignored. This option can be used to protect Gnat sources or your own
13115 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
13116 much faster, and their output much smaller. Read-only here refers to access
13117 or permission status in the file system for the current user.
13119 @item -aIDIR
13120 @cindex @option{-aIDIR} (@command{gnatfind})
13121 When looking for source files also look in directory DIR. The order in which
13122 source file search is undertaken is the same as for @command{gnatmake}.
13124 @item -aODIR
13125 @cindex @option{-aODIR} (@command{gnatfind})
13126 When searching for library and object files, look in directory
13127 DIR. The order in which library files are searched is the same as for
13128 @command{gnatmake}.
13130 @item -nostdinc
13131 @cindex @option{-nostdinc} (@command{gnatfind})
13132 Do not look for sources in the system default directory.
13134 @item -nostdlib
13135 @cindex @option{-nostdlib} (@command{gnatfind})
13136 Do not look for library files in the system default directory.
13138 @item --ext=@var{extension}
13139 @cindex @option{--ext} (@command{gnatfind})
13140 Specify an alternate ali file extension. The default is @code{ali} and other
13141 extensions (e.g. @code{sli} for SPARK library files) may be specified via this
13142 switch. Note that if this switch overrides the default, which means that only
13143 the new extension will be considered.
13145 @item --RTS=@var{rts-path}
13146 @cindex @option{--RTS} (@command{gnatfind})
13147 Specifies the default location of the runtime library. Same meaning as the
13148 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
13150 @item ^-d^/DERIVED_TYPE_INFORMATION^
13151 @cindex @option{^-d^/DERIVED_TYPE_INFORMATION^} (@code{gnatfind})
13152 If this switch is set, then @code{gnatfind} will output the parent type
13153 reference for each matching derived types.
13155 @item ^-e^/EXPRESSIONS^
13156 @cindex @option{^-e^/EXPRESSIONS^} (@command{gnatfind})
13157 By default, @code{gnatfind} accept the simple regular expression set for
13158 @samp{pattern}. If this switch is set, then the pattern will be
13159 considered as full Unix-style regular expression.
13161 @item ^-f^/FULL_PATHNAME^
13162 @cindex @option{^-f^/FULL_PATHNAME^} (@command{gnatfind})
13163 If this switch is set, the output file names will be preceded by their
13164 directory (if the file was found in the search path). If this switch is
13165 not set, the directory will not be printed.
13167 @item ^-g^/IGNORE_LOCALS^
13168 @cindex @option{^-g^/IGNORE_LOCALS^} (@command{gnatfind})
13169 If this switch is set, information is output only for library-level
13170 entities, ignoring local entities. The use of this switch may accelerate
13171 @code{gnatfind} and @code{gnatxref}.
13173 @item -IDIR
13174 @cindex @option{-IDIR} (@command{gnatfind})
13175 Equivalent to @samp{-aODIR -aIDIR}.
13177 @item -pFILE
13178 @cindex @option{-pFILE} (@command{gnatfind})
13179 Specify a project file (@pxref{GNAT Project Manager}) to use.
13180 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
13181 project file in the current directory.
13183 If a project file is either specified or found by the tools, then the content
13184 of the source directory and object directory lines are added as if they
13185 had been specified respectively by @samp{^-aI^/SOURCE_SEARCH^} and
13186 @samp{^-aO^/OBJECT_SEARCH^}.
13188 @item ^-r^/REFERENCES^
13189 @cindex @option{^-r^/REFERENCES^} (@command{gnatfind})
13190 By default, @code{gnatfind} will output only the information about the
13191 declaration, body or type completion of the entities. If this switch is
13192 set, the @code{gnatfind} will locate every reference to the entities in
13193 the files specified on the command line (or in every file in the search
13194 path if no file is given on the command line).
13196 @item ^-s^/PRINT_LINES^
13197 @cindex @option{^-s^/PRINT_LINES^} (@command{gnatfind})
13198 If this switch is set, then @code{gnatfind} will output the content
13199 of the Ada source file lines were the entity was found.
13201 @item ^-t^/TYPE_HIERARCHY^
13202 @cindex @option{^-t^/TYPE_HIERARCHY^} (@command{gnatfind})
13203 If this switch is set, then @code{gnatfind} will output the type hierarchy for
13204 the specified type. It act like -d option but recursively from parent
13205 type to parent type. When this switch is set it is not possible to
13206 specify more than one file.
13208 @end table
13210 @noindent
13211 All these switches may be in any order on the command line, and may even
13212 appear after the file names. They need not be separated by spaces, thus
13213 you can say @samp{gnatxref ^-ag^/ALL_FILES/IGNORE_LOCALS^} instead of
13214 @samp{gnatxref ^-a -g^/ALL_FILES /IGNORE_LOCALS^}.
13216 As stated previously, gnatfind will search in every directory in the
13217 search path. You can force it to look only in the current directory if
13218 you specify @code{*} at the end of the command line.
13220 @node Project Files for gnatxref and gnatfind
13221 @section Project Files for @command{gnatxref} and @command{gnatfind}
13223 @noindent
13224 Project files allow a programmer to specify how to compile its
13225 application, where to find sources, etc.  These files are used
13226 @ifclear vms
13227 primarily by GPS, but they can also be used
13228 @end ifclear
13229 by the two tools
13230 @code{gnatxref} and @code{gnatfind}.
13232 A project file name must end with @file{.gpr}. If a single one is
13233 present in the current directory, then @code{gnatxref} and @code{gnatfind} will
13234 extract the information from it. If multiple project files are found, none of
13235 them is read, and you have to use the @samp{-p} switch to specify the one
13236 you want to use.
13238 The following lines can be included, even though most of them have default
13239 values which can be used in most cases.
13240 The lines can be entered in any order in the file.
13241 Except for @file{src_dir} and @file{obj_dir}, you can only have one instance of
13242 each line. If you have multiple instances, only the last one is taken into
13243 account.
13245 @table @code
13246 @item src_dir=DIR
13247 [default: @code{"^./^[]^"}]
13248 specifies a directory where to look for source files. Multiple @code{src_dir}
13249 lines can be specified and they will be searched in the order they
13250 are specified.
13252 @item obj_dir=DIR
13253 [default: @code{"^./^[]^"}]
13254 specifies a directory where to look for object and library files. Multiple
13255 @code{obj_dir} lines can be specified, and they will be searched in the order
13256 they are specified
13258 @item comp_opt=SWITCHES
13259 [default: @code{""}]
13260 creates a variable which can be referred to subsequently by using
13261 the @code{$@{comp_opt@}} notation. This is intended to store the default
13262 switches given to @command{gnatmake} and @command{gcc}.
13264 @item bind_opt=SWITCHES
13265 [default: @code{""}]
13266 creates a variable which can be referred to subsequently by using
13267 the @samp{$@{bind_opt@}} notation. This is intended to store the default
13268 switches given to @command{gnatbind}.
13270 @item link_opt=SWITCHES
13271 [default: @code{""}]
13272 creates a variable which can be referred to subsequently by using
13273 the @samp{$@{link_opt@}} notation. This is intended to store the default
13274 switches given to @command{gnatlink}.
13276 @item main=EXECUTABLE
13277 [default: @code{""}]
13278 specifies the name of the executable for the application. This variable can
13279 be referred to in the following lines by using the @samp{$@{main@}} notation.
13281 @ifset vms
13282 @item comp_cmd=COMMAND
13283 [default: @code{"GNAT COMPILE /SEARCH=$@{src_dir@} /DEBUG /TRY_SEMANTICS"}]
13284 @end ifset
13285 @ifclear vms
13286 @item comp_cmd=COMMAND
13287 [default: @code{"gcc -c -I$@{src_dir@} -g -gnatq"}]
13288 @end ifclear
13289 specifies the command used to compile a single file in the application.
13291 @ifset vms
13292 @item make_cmd=COMMAND
13293 [default: @code{"GNAT MAKE $@{main@}
13294 /SOURCE_SEARCH=$@{src_dir@} /OBJECT_SEARCH=$@{obj_dir@}
13295 /DEBUG /TRY_SEMANTICS /COMPILER_QUALIFIERS $@{comp_opt@}
13296 /BINDER_QUALIFIERS $@{bind_opt@} /LINKER_QUALIFIERS $@{link_opt@}"}]
13297 @end ifset
13298 @ifclear vms
13299 @item make_cmd=COMMAND
13300 [default: @code{"gnatmake $@{main@} -aI$@{src_dir@}
13301 -aO$@{obj_dir@} -g -gnatq -cargs $@{comp_opt@}
13302 -bargs $@{bind_opt@} -largs $@{link_opt@}"}]
13303 @end ifclear
13304 specifies the command used to recompile the whole application.
13306 @item run_cmd=COMMAND
13307 [default: @code{"$@{main@}"}]
13308 specifies the command used to run the application.
13310 @item debug_cmd=COMMAND
13311 [default: @code{"gdb $@{main@}"}]
13312 specifies the command used to debug the application
13314 @end table
13316 @noindent
13317 @command{gnatxref} and @command{gnatfind} only take into account the
13318 @code{src_dir} and @code{obj_dir} lines, and ignore the others.
13320 @node Regular Expressions in gnatfind and gnatxref
13321 @section  Regular Expressions in @code{gnatfind} and @code{gnatxref}
13323 @noindent
13324 As specified in the section about @command{gnatfind}, the pattern can be a
13325 regular expression. Actually, there are to set of regular expressions
13326 which are recognized by the program:
13328 @table @code
13329 @item globbing patterns
13330 These are the most usual regular expression. They are the same that you
13331 generally used in a Unix shell command line, or in a DOS session.
13333 Here is a more formal grammar:
13334 @smallexample
13335 @group
13336 @iftex
13337 @leftskip=.5cm
13338 @end iftex
13339 regexp ::= term
13340 term   ::= elmt            -- matches elmt
13341 term   ::= elmt elmt       -- concatenation (elmt then elmt)
13342 term   ::= *               -- any string of 0 or more characters
13343 term   ::= ?               -- matches any character
13344 term   ::= [char @{char@}]   -- matches any character listed
13345 term   ::= [char - char]   -- matches any character in range
13346 @end group
13347 @end smallexample
13349 @item full regular expression
13350 The second set of regular expressions is much more powerful. This is the
13351 type of regular expressions recognized by utilities such a @file{grep}.
13353 The following is the form of a regular expression, expressed in Ada
13354 reference manual style BNF is as follows
13356 @smallexample
13357 @iftex
13358 @leftskip=.5cm
13359 @end iftex
13360 @group
13361 regexp ::= term @{| term@}   -- alternation (term or term @dots{})
13363 term ::= item @{item@}       -- concatenation (item then item)
13365 item ::= elmt              -- match elmt
13366 item ::= elmt *            -- zero or more elmt's
13367 item ::= elmt +            -- one or more elmt's
13368 item ::= elmt ?            -- matches elmt or nothing
13369 @end group
13370 @group
13371 elmt ::= nschar            -- matches given character
13372 elmt ::= [nschar @{nschar@}]   -- matches any character listed
13373 elmt ::= [^^^ nschar @{nschar@}] -- matches any character not listed
13374 elmt ::= [char - char]     -- matches chars in given range
13375 elmt ::= \ char            -- matches given character
13376 elmt ::= .                 -- matches any single character
13377 elmt ::= ( regexp )        -- parens used for grouping
13379 char ::= any character, including special characters
13380 nschar ::= any character except ()[].*+?^^^
13381 @end group
13382 @end smallexample
13384 Following are a few examples:
13386 @table @samp
13387 @item abcde|fghi
13388 will match any of the two strings @samp{abcde} and @samp{fghi},
13390 @item abc*d
13391 will match any string like @samp{abd}, @samp{abcd}, @samp{abccd},
13392 @samp{abcccd}, and so on,
13394 @item [a-z]+
13395 will match any string which has only lowercase characters in it (and at
13396 least one character.
13398 @end table
13399 @end table
13401 @node Examples of gnatxref Usage
13402 @section Examples of @code{gnatxref} Usage
13404 @subsection General Usage
13406 @noindent
13407 For the following examples, we will consider the following units:
13409 @smallexample @c ada
13410 @group
13411 @cartouche
13412 main.ads:
13413 1: with Bar;
13414 2: package Main is
13415 3:     procedure Foo (B : in Integer);
13416 4:     C : Integer;
13417 5: private
13418 6:     D : Integer;
13419 7: end Main;
13421 main.adb:
13422 1: package body Main is
13423 2:     procedure Foo (B : in Integer) is
13424 3:     begin
13425 4:        C := B;
13426 5:        D := B;
13427 6:        Bar.Print (B);
13428 7:        Bar.Print (C);
13429 8:     end Foo;
13430 9: end Main;
13432 bar.ads:
13433 1: package Bar is
13434 2:     procedure Print (B : Integer);
13435 3: end bar;
13436 @end cartouche
13437 @end group
13438 @end smallexample
13440 @table @code
13442 @noindent
13443 The first thing to do is to recompile your application (for instance, in
13444 that case just by doing a @samp{gnatmake main}, so that GNAT generates
13445 the cross-referencing information.
13446 You can then issue any of the following commands:
13448 @item gnatxref main.adb
13449 @code{gnatxref} generates cross-reference information for main.adb
13450 and every unit 'with'ed by main.adb.
13452 The output would be:
13453 @smallexample
13454 @iftex
13455 @leftskip=0cm
13456 @end iftex
13457 B                                                      Type: Integer
13458   Decl: bar.ads           2:22
13459 B                                                      Type: Integer
13460   Decl: main.ads          3:20
13461   Body: main.adb          2:20
13462   Ref:  main.adb          4:13     5:13     6:19
13463 Bar                                                    Type: Unit
13464   Decl: bar.ads           1:9
13465   Ref:  main.adb          6:8      7:8
13466        main.ads           1:6
13467 C                                                      Type: Integer
13468   Decl: main.ads          4:5
13469   Modi: main.adb          4:8
13470   Ref:  main.adb          7:19
13471 D                                                      Type: Integer
13472   Decl: main.ads          6:5
13473   Modi: main.adb          5:8
13474 Foo                                                    Type: Unit
13475   Decl: main.ads          3:15
13476   Body: main.adb          2:15
13477 Main                                                    Type: Unit
13478   Decl: main.ads          2:9
13479   Body: main.adb          1:14
13480 Print                                                   Type: Unit
13481   Decl: bar.ads           2:15
13482   Ref:  main.adb          6:12     7:12
13483 @end smallexample
13485 @noindent
13486 that is the entity @code{Main} is declared in main.ads, line 2, column 9,
13487 its body is in main.adb, line 1, column 14 and is not referenced any where.
13489 The entity @code{Print} is declared in bar.ads, line 2, column 15 and it
13490 is referenced in main.adb, line 6 column 12 and line 7 column 12.
13492 @item gnatxref package1.adb package2.ads
13493 @code{gnatxref} will generates cross-reference information for
13494 package1.adb, package2.ads and any other package 'with'ed by any
13495 of these.
13497 @end table
13499 @ifclear vms
13500 @subsection Using gnatxref with vi
13502 @code{gnatxref} can generate a tags file output, which can be used
13503 directly from @command{vi}. Note that the standard version of @command{vi}
13504 will not work properly with overloaded symbols. Consider using another
13505 free implementation of @command{vi}, such as @command{vim}.
13507 @smallexample
13508 $ gnatxref -v gnatfind.adb > tags
13509 @end smallexample
13511 @noindent
13512 will generate the tags file for @code{gnatfind} itself (if the sources
13513 are in the search path!).
13515 From @command{vi}, you can then use the command @samp{:tag @var{entity}}
13516 (replacing @var{entity} by whatever you are looking for), and vi will
13517 display a new file with the corresponding declaration of entity.
13518 @end ifclear
13520 @node Examples of gnatfind Usage
13521 @section Examples of @code{gnatfind} Usage
13523 @table @code
13525 @item gnatfind ^-f^/FULL_PATHNAME^ xyz:main.adb
13526 Find declarations for all entities xyz referenced at least once in
13527 main.adb. The references are search in every library file in the search
13528 path.
13530 The directories will be printed as well (as the @samp{^-f^/FULL_PATHNAME^}
13531 switch is set)
13533 The output will look like:
13534 @smallexample
13535 ^directory/^[directory]^main.ads:106:14: xyz <= declaration
13536 ^directory/^[directory]^main.adb:24:10: xyz <= body
13537 ^directory/^[directory]^foo.ads:45:23: xyz <= declaration
13538 @end smallexample
13540 @noindent
13541 that is to say, one of the entities xyz found in main.adb is declared at
13542 line 12 of main.ads (and its body is in main.adb), and another one is
13543 declared at line 45 of foo.ads
13545 @item gnatfind ^-fs^/FULL_PATHNAME/SOURCE_LINE^ xyz:main.adb
13546 This is the same command as the previous one, instead @code{gnatfind} will
13547 display the content of the Ada source file lines.
13549 The output will look like:
13551 @smallexample
13552 ^directory/^[directory]^main.ads:106:14: xyz <= declaration
13553    procedure xyz;
13554 ^directory/^[directory]^main.adb:24:10: xyz <= body
13555    procedure xyz is
13556 ^directory/^[directory]^foo.ads:45:23: xyz <= declaration
13557    xyz : Integer;
13558 @end smallexample
13560 @noindent
13561 This can make it easier to find exactly the location your are looking
13562 for.
13564 @item gnatfind ^-r^/REFERENCES^ "*x*":main.ads:123 foo.adb
13565 Find references to all entities containing an x that are
13566 referenced on line 123 of main.ads.
13567 The references will be searched only in main.ads and foo.adb.
13569 @item gnatfind main.ads:123
13570 Find declarations and bodies for all entities that are referenced on
13571 line 123 of main.ads.
13573 This is the same as @code{gnatfind "*":main.adb:123}.
13575 @item gnatfind ^mydir/^[mydir]^main.adb:123:45
13576 Find the declaration for the entity referenced at column 45 in
13577 line 123 of file main.adb in directory mydir. Note that it
13578 is usual to omit the identifier name when the column is given,
13579 since the column position identifies a unique reference.
13581 The column has to be the beginning of the identifier, and should not
13582 point to any character in the middle of the identifier.
13584 @end table
13586 @c *********************************
13587 @node The GNAT Pretty-Printer gnatpp
13588 @chapter The GNAT Pretty-Printer @command{gnatpp}
13589 @findex gnatpp
13590 @cindex Pretty-Printer
13592 @menu
13593 * Switches for gnatpp::
13594 * Formatting Rules::
13595 @end menu
13597 @noindent
13598 ^The @command{gnatpp} tool^GNAT PRETTY^ is an ASIS-based utility
13599 for source reformatting / pretty-printing.
13600 It takes an Ada source file as input and generates a reformatted
13601 version as output.
13602 You can specify various style directives via switches; e.g.,
13603 identifier case conventions, rules of indentation, and comment layout.
13605 To produce a reformatted file, @command{gnatpp} generates and uses the ASIS
13606 tree for the input source and thus requires the input to be syntactically and
13607 semantically legal.
13608 If this condition is not met, @command{gnatpp} will terminate with an
13609 error message; no output file will be generated.
13611 @command{gnatpp} cannot process sources that contain
13612 preprocessing directives.
13614 If the compilation unit
13615 contained in the input source depends semantically upon units located
13616 outside the current directory, you have to provide the source search path
13617 when invoking @command{gnatpp}, if these units are contained in files with
13618 names that do not follow the GNAT file naming rules, you have to provide
13619 the configuration file describing the corresponding naming scheme;
13620 see the description of the @command{gnatpp}
13621 switches below. Another possibility is to use a project file and to
13622 call @command{gnatpp} through the @command{gnat} driver
13623 (see @ref{The GNAT Driver and Project Files}).
13625 The @command{gnatpp} command has the form
13627 @smallexample
13628 @c $ gnatpp @ovar{switches} @var{filename}
13629 @c Expanding @ovar macro inline (explanation in macro def comments)
13630 $ gnatpp @r{[}@var{switches}@r{]} @var{filename} @r{[}-cargs @var{gcc_switches}@r{]}
13631 @end smallexample
13633 @noindent
13634 where
13635 @itemize @bullet
13636 @item
13637 @var{switches} is an optional sequence of switches defining such properties as
13638 the formatting rules, the source search path, and the destination for the
13639 output source file
13641 @item
13642 @var{filename} is the name (including the extension) of the source file to
13643 reformat; ``wildcards'' or several file names on the same gnatpp command are
13644 allowed.  The file name may contain path information; it does not have to
13645 follow the GNAT file naming rules
13647 @item
13648 @samp{@var{gcc_switches}} is a list of switches for
13649 @command{gcc}. They will be passed on to all compiler invocations made by
13650 @command{gnatelim} to generate the ASIS trees. Here you can provide
13651 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
13652 use the @option{-gnatec} switch to set the configuration file,
13653 use the @option{-gnat05} switch if sources should be compiled in
13654 Ada 2005 mode  etc.
13655 @end itemize
13657 @node Switches for gnatpp
13658 @section Switches for @command{gnatpp}
13660 @noindent
13661 The following subsections describe the various switches accepted by
13662 @command{gnatpp}, organized by category.
13664 @ifclear vms
13665 You specify a switch by supplying a name and generally also a value.
13666 In many cases the values for a switch with a given name are incompatible with
13667 each other
13668 (for example the switch that controls the casing of a reserved word may have
13669 exactly one value: upper case, lower case, or
13670 mixed case) and thus exactly one such switch can be in effect for an
13671 invocation of @command{gnatpp}.
13672 If more than one is supplied, the last one is used.
13673 However, some values for the same switch are mutually compatible.
13674 You may supply several such switches to @command{gnatpp}, but then
13675 each must be specified in full, with both the name and the value.
13676 Abbreviated forms (the name appearing once, followed by each value) are
13677 not permitted.
13678 For example, to set
13679 the alignment of the assignment delimiter both in declarations and in
13680 assignment statements, you must write @option{-A2A3}
13681 (or @option{-A2 -A3}), but not @option{-A23}.
13682 @end ifclear
13684 @ifset vms
13685 In many cases the set of options for a given qualifier are incompatible with
13686 each other (for example the qualifier that controls the casing of a reserved
13687 word may have exactly one option, which specifies either upper case, lower
13688 case, or mixed case), and thus exactly one such option can be in effect for
13689 an invocation of @command{gnatpp}.
13690 If more than one is supplied, the last one is used.
13691 However, some qualifiers have options that are mutually compatible,
13692 and then you may then supply several such options when invoking
13693 @command{gnatpp}.
13694 @end ifset
13696 In most cases, it is obvious whether or not the
13697 ^values for a switch with a given name^options for a given qualifier^
13698 are compatible with each other.
13699 When the semantics might not be evident, the summaries below explicitly
13700 indicate the effect.
13702 @menu
13703 * Alignment Control::
13704 * Casing Control::
13705 * Construct Layout Control::
13706 * General Text Layout Control::
13707 * Other Formatting Options::
13708 * Setting the Source Search Path::
13709 * Output File Control::
13710 * Other gnatpp Switches::
13711 @end menu
13713 @node Alignment Control
13714 @subsection Alignment Control
13715 @cindex Alignment control in @command{gnatpp}
13717 @noindent
13718 Programs can be easier to read if certain constructs are vertically aligned.
13719 By default all alignments are set ON.
13720 Through the @option{^-A0^/ALIGN=OFF^} switch you may reset the default to
13721 OFF, and then use one or more of the other
13722 ^@option{-A@var{n}} switches^@option{/ALIGN} options^
13723 to activate alignment for specific constructs.
13725 @table @option
13726 @cindex @option{^-A@var{n}^/ALIGN^} (@command{gnatpp})
13728 @ifset vms
13729 @item /ALIGN=ON
13730 Set all alignments to ON
13731 @end ifset
13733 @item ^-A0^/ALIGN=OFF^
13734 Set all alignments to OFF
13736 @item ^-A1^/ALIGN=COLONS^
13737 Align @code{:} in declarations
13739 @item ^-A2^/ALIGN=DECLARATIONS^
13740 Align @code{:=} in initializations in declarations
13742 @item ^-A3^/ALIGN=STATEMENTS^
13743 Align @code{:=} in assignment statements
13745 @item ^-A4^/ALIGN=ARROWS^
13746 Align @code{=>} in associations
13748 @item ^-A5^/ALIGN=COMPONENT_CLAUSES^
13749 Align @code{at} keywords in the component clauses in record
13750 representation clauses
13751 @end table
13753 @noindent
13754 The @option{^-A^/ALIGN^} switches are mutually compatible; any combination
13755 is allowed.
13757 @node Casing Control
13758 @subsection Casing Control
13759 @cindex Casing control in @command{gnatpp}
13761 @noindent
13762 @command{gnatpp} allows you to specify the casing for reserved words,
13763 pragma names, attribute designators and identifiers.
13764 For identifiers you may define a
13765 general rule for name casing but also override this rule
13766 via a set of dictionary files.
13768 Three types of casing are supported: lower case, upper case, and mixed case.
13769 Lower and upper case are self-explanatory (but since some letters in
13770 Latin1 and other GNAT-supported character sets
13771 exist only in lower-case form, an upper case conversion will have no
13772 effect on them.)
13773 ``Mixed case'' means that the first letter, and also each letter immediately
13774 following an underscore, are converted to their uppercase forms;
13775 all the other letters are converted to their lowercase forms.
13777 @table @option
13778 @cindex @option{^-a@var{x}^/ATTRIBUTE^} (@command{gnatpp})
13779 @item ^-aL^/ATTRIBUTE_CASING=LOWER_CASE^
13780 Attribute designators are lower case
13782 @item ^-aU^/ATTRIBUTE_CASING=UPPER_CASE^
13783 Attribute designators are upper case
13785 @item ^-aM^/ATTRIBUTE_CASING=MIXED_CASE^
13786 Attribute designators are mixed case (this is the default)
13788 @cindex @option{^-k@var{x}^/KEYWORD_CASING^} (@command{gnatpp})
13789 @item ^-kL^/KEYWORD_CASING=LOWER_CASE^
13790 Keywords (technically, these are known in Ada as @emph{reserved words}) are
13791 lower case (this is the default)
13793 @item ^-kU^/KEYWORD_CASING=UPPER_CASE^
13794 Keywords are upper case
13796 @cindex @option{^-n@var{x}^/NAME_CASING^} (@command{gnatpp})
13797 @item ^-nD^/NAME_CASING=AS_DECLARED^
13798 Name casing for defining occurrences are as they appear in the source file
13799 (this is the default)
13801 @item ^-nU^/NAME_CASING=UPPER_CASE^
13802 Names are in upper case
13804 @item ^-nL^/NAME_CASING=LOWER_CASE^
13805 Names are in lower case
13807 @item ^-nM^/NAME_CASING=MIXED_CASE^
13808 Names are in mixed case
13810 @cindex @option{^-ne@var{x}^/ENUM_CASING^} (@command{gnatpp})
13811 @item ^-neD^/ENUM_CASING=AS_DECLARED^
13812 Enumeration literal casing for defining occurrences are as they appear in the
13813 source file. Overrides ^-n^/NAME_CASING^ casing setting.
13815 @item ^-neU^/ENUM_CASING=UPPER_CASE^
13816 Enumeration literals are in upper case.  Overrides ^-n^/NAME_CASING^ casing
13817 setting.
13819 @item ^-neL^/ENUM_CASING=LOWER_CASE^
13820 Enumeration literals are in lower case. Overrides ^-n^/NAME_CASING^ casing
13821 setting.
13823 @item ^-neM^/ENUM_CASING=MIXED_CASE^
13824 Enumeration literals are in mixed case. Overrides ^-n^/NAME_CASING^ casing
13825 setting.
13827 @cindex @option{^-nt@var{x}^/TYPE_CASING^} (@command{gnatpp})
13828 @item ^-neD^/TYPE_CASING=AS_DECLARED^
13829 Names introduced by type and subtype declarations are always
13830 cased as they appear in the declaration in the source file.
13831 Overrides ^-n^/NAME_CASING^ casing setting.
13833 @item ^-ntU^/TYPE_CASING=UPPER_CASE^
13834 Names introduced by type and subtype declarations are always in
13835 upper case. Overrides ^-n^/NAME_CASING^ casing setting.
13837 @item ^-ntL^/TYPE_CASING=LOWER_CASE^
13838 Names introduced by type and subtype declarations are always in
13839 lower case. Overrides ^-n^/NAME_CASING^ casing setting.
13841 @item ^-ntM^/TYPE_CASING=MIXED_CASE^
13842 Names introduced by type and subtype declarations are always in
13843 mixed case. Overrides ^-n^/NAME_CASING^ casing setting.
13845 @item ^-nnU^/NUMBER_CASING=UPPER_CASE^
13846 Names introduced by number declarations are always in
13847 upper case. Overrides ^-n^/NAME_CASING^ casing setting.
13849 @item ^-nnL^/NUMBER_CASING=LOWER_CASE^
13850 Names introduced by number declarations are always in
13851 lower case. Overrides ^-n^/NAME_CASING^ casing setting.
13853 @item ^-nnM^/NUMBER_CASING=MIXED_CASE^
13854 Names introduced by number declarations are always in
13855 mixed case. Overrides ^-n^/NAME_CASING^ casing setting.
13857 @cindex @option{^-p@var{x}^/PRAGMA_CASING^} (@command{gnatpp})
13858 @item ^-pL^/PRAGMA_CASING=LOWER_CASE^
13859 Pragma names are lower case
13861 @item ^-pU^/PRAGMA_CASING=UPPER_CASE^
13862 Pragma names are upper case
13864 @item ^-pM^/PRAGMA_CASING=MIXED_CASE^
13865 Pragma names are mixed case (this is the default)
13867 @item ^-D@var{file}^/DICTIONARY=@var{file}^
13868 @cindex @option{^-D^/DICTIONARY^} (@command{gnatpp})
13869 Use @var{file} as a @emph{dictionary file} that defines
13870 the casing for a set of specified names,
13871 thereby overriding the effect on these names by
13872 any explicit or implicit
13873 ^-n^/NAME_CASING^ switch.
13874 To supply more than one dictionary file,
13875 use ^several @option{-D} switches^a list of files as options^.
13877 @noindent
13878 @option{gnatpp} implicitly uses a @emph{default dictionary file}
13879 to define the casing for the Ada predefined names and
13880 the names declared in the GNAT libraries.
13882 @item ^-D-^/SPECIFIC_CASING^
13883 @cindex @option{^-D-^/SPECIFIC_CASING^} (@command{gnatpp})
13884 Do not use the default dictionary file;
13885 instead, use the casing
13886 defined by a @option{^-n^/NAME_CASING^} switch and any explicit
13887 dictionary file(s)
13888 @end table
13890 @noindent
13891 The structure of a dictionary file, and details on the conventions
13892 used in the default dictionary file, are defined in @ref{Name Casing}.
13894 The @option{^-D-^/SPECIFIC_CASING^} and
13895 @option{^-D@var{file}^/DICTIONARY=@var{file}^} switches are mutually
13896 compatible.
13898 @node Construct Layout Control
13899 @subsection Construct Layout Control
13900 @cindex Layout control in @command{gnatpp}
13902 @noindent
13903 This group of @command{gnatpp} switches controls the layout of comments and
13904 complex syntactic constructs.  See @ref{Formatting Comments} for details
13905 on their effect.
13907 @table @option
13908 @cindex @option{^-c@var{n}^/COMMENTS_LAYOUT^} (@command{gnatpp})
13909 @item ^-c0^/COMMENTS_LAYOUT=UNTOUCHED^
13910 All the comments remain unchanged
13912 @item ^-c1^/COMMENTS_LAYOUT=DEFAULT^
13913 GNAT-style comment line indentation (this is the default).
13915 @item ^-c2^/COMMENTS_LAYOUT=STANDARD_INDENT^
13916 Reference-manual comment line indentation.
13918 @item ^-c3^/COMMENTS_LAYOUT=GNAT_BEGINNING^
13919 GNAT-style comment beginning
13921 @item ^-c4^/COMMENTS_LAYOUT=REFORMAT^
13922 Reformat comment blocks
13924 @item ^-c5^/COMMENTS_LAYOUT=KEEP_SPECIAL^
13925 Keep unchanged special form comments
13927 @cindex @option{^-l@var{n}^/CONSTRUCT_LAYOUT^} (@command{gnatpp})
13928 @item ^-l1^/CONSTRUCT_LAYOUT=GNAT^
13929 GNAT-style layout (this is the default)
13931 @item ^-l2^/CONSTRUCT_LAYOUT=COMPACT^
13932 Compact layout
13934 @item ^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^
13935 Uncompact layout
13937 @cindex @option{^-N^/NOTABS^} (@command{gnatpp})
13938 @item ^-N^/NOTABS^
13939 All the VT characters are removed from the comment text. All the HT characters
13940 are expanded with the sequences of space characters to get to the next tab
13941 stops.
13943 @cindex @option{^--no-separate-is^/NO_SEPARATE_IS^} (@command{gnatpp})
13944 @item ^--no-separate-is^/NO_SEPARATE_IS^
13945 Do not place the keyword @code{is} on a separate line in a subprogram body in
13946 case if the spec occupies more than one line.
13948 @cindex @option{^--separate-label^/SEPARATE_LABEL^} (@command{gnatpp})
13949 @item ^--separate-label^/SEPARATE_LABEL^
13950 Place statement label(s) on a separate line, with the following statement
13951 on the next line.
13953 @cindex @option{^--separate-loop-then^/SEPARATE_LOOP_THEN^} (@command{gnatpp})
13954 @item ^--separate-loop-then^/SEPARATE_LOOP_THEN^
13955 Place the keyword @code{loop} in FOR and WHILE loop statements and the
13956 keyword @code{then} in IF statements on a separate line.
13958 @cindex @option{^--no-separate-loop-then^/NO_SEPARATE_LOOP_THEN^} (@command{gnatpp})
13959 @item ^--no-separate-loop-then^/NO_SEPARATE_LOOP_THEN^
13960 Do not place the keyword @code{loop} in FOR and WHILE loop statements and the
13961 keyword @code{then} in IF statements on a separate line. This option is
13962 incompatible with @option{^--separate-loop-then^/SEPARATE_LOOP_THEN^} option.
13964 @cindex @option{^--use-on-new-line^/USE_ON_NEW_LINE^} (@command{gnatpp})
13965 @item ^--use-on-new-line^/USE_ON_NEW_LINE^
13966 Start each USE clause in a context clause from a separate line.
13968 @cindex @option{^--separate-stmt-name^/STMT_NAME_ON_NEW_LINE^} (@command{gnatpp})
13969 @item ^--separate-stmt-name^/STMT_NAME_ON_NEW_LINE^
13970 Use a separate line for a loop or block statement name, but do not use an extra
13971 indentation level for the statement itself.
13973 @end table
13975 @ifclear vms
13976 @noindent
13977 The @option{-c1} and @option{-c2} switches are incompatible.
13978 The @option{-c3} and @option{-c4} switches are compatible with each other and
13979 also with @option{-c1} and @option{-c2}. The @option{-c0} switch disables all
13980 the other comment formatting switches.
13982 The @option{-l1}, @option{-l2}, and @option{-l3} switches are incompatible.
13983 @end ifclear
13985 @ifset vms
13986 @noindent
13987 For the @option{/COMMENTS_LAYOUT} qualifier:
13988 @itemize @bullet
13989 @item
13990 The @option{DEFAULT} and @option{STANDARD_INDENT} options are incompatible.
13991 @item
13992 The @option{GNAT_BEGINNING} and @option{REFORMAT} options are compatible with
13993 each other and also with @option{DEFAULT} and @option{STANDARD_INDENT}.
13994 @end itemize
13996 @noindent
13997 The @option{GNAT}, @option{COMPACT}, and @option{UNCOMPACT} options for the
13998 @option{/CONSTRUCT_LAYOUT} qualifier are incompatible.
13999 @end ifset
14001 @node General Text Layout Control
14002 @subsection General Text Layout Control
14004 @noindent
14005 These switches allow control over line length and indentation.
14007 @table @option
14008 @item ^-M@var{nnn}^/LINE_LENGTH_MAX=@var{nnn}^
14009 @cindex @option{^-M^/LINE_LENGTH^} (@command{gnatpp})
14010 Maximum line length, @var{nnn} from 32@dots{}256, the default value is 79
14012 @item ^-i@var{nnn}^/INDENTATION_LEVEL=@var{nnn}^
14013 @cindex @option{^-i^/INDENTATION_LEVEL^} (@command{gnatpp})
14014 Indentation level, @var{nnn} from 1@dots{}9, the default value is 3
14016 @item ^-cl@var{nnn}^/CONTINUATION_INDENT=@var{nnn}^
14017 @cindex @option{^-cl^/CONTINUATION_INDENT^} (@command{gnatpp})
14018 Indentation level for continuation lines (relative to the line being
14019 continued), @var{nnn} from 1@dots{}9.
14020 The default
14021 value is one less than the (normal) indentation level, unless the
14022 indentation is set to 1 (in which case the default value for continuation
14023 line indentation is also 1)
14024 @end table
14026 @node Other Formatting Options
14027 @subsection Other Formatting Options
14029 @noindent
14030 These switches control the inclusion of missing end/exit labels, and
14031 the indentation level in @b{case} statements.
14033 @table @option
14034 @item ^-e^/NO_MISSED_LABELS^
14035 @cindex @option{^-e^/NO_MISSED_LABELS^} (@command{gnatpp})
14036 Do not insert missing end/exit labels. An end label is the name of
14037 a construct that may optionally be repeated at the end of the
14038 construct's declaration;
14039 e.g., the names of packages, subprograms, and tasks.
14040 An exit label is the name of a loop that may appear as target
14041 of an exit statement within the loop.
14042 By default, @command{gnatpp} inserts these end/exit labels when
14043 they are absent from the original source. This option suppresses such
14044 insertion, so that the formatted source reflects the original.
14046 @item ^-ff^/FORM_FEED_AFTER_PRAGMA_PAGE^
14047 @cindex @option{^-ff^/FORM_FEED_AFTER_PRAGMA_PAGE^} (@command{gnatpp})
14048 Insert a Form Feed character after a pragma Page.
14050 @item ^-T@var{nnn}^/MAX_INDENT=@var{nnn}^
14051 @cindex @option{^-T^/MAX_INDENT^} (@command{gnatpp})
14052 Do not use an additional indentation level for @b{case} alternatives
14053 and variants if there are @var{nnn} or more (the default
14054 value is 10).
14055 If @var{nnn} is 0, an additional indentation level is
14056 used for @b{case} alternatives and variants regardless of their number.
14058 @item ^--call_threshold=@var{nnn}^/MAX_ACT=@var{nnn}^
14059 @cindex @option{^--call_threshold^/MAX_ACT^} (@command{gnatpp})
14060 If the number of parameter associations is greater than @var{nnn} and if at
14061 least one association uses named notation, start each association from
14062 a new line. If @var{nnn} is 0, no check for the number of associations
14063 is made, this is the default.
14065 @item ^--par_threshold=@var{nnn}^/MAX_PAR=@var{nnn}^
14066 @cindex @option{^--par_threshold^/MAX_PAR^} (@command{gnatpp})
14067 If the number of parameter specifications is greater than @var{nnn}
14068 (or equal to @var{nnn} in case of a function), start each specification from
14069 a new line. The default for @var{nnn} is 3.
14070 @end table
14072 @node Setting the Source Search Path
14073 @subsection Setting the Source Search Path
14075 @noindent
14076 To define the search path for the input source file, @command{gnatpp}
14077 uses the same switches as the GNAT compiler, with the same effects.
14079 @table @option
14080 @item ^-I^/SEARCH=^@var{dir}
14081 @cindex @option{^-I^/SEARCH^} (@code{gnatpp})
14082 The same as the corresponding gcc switch
14084 @item ^-I-^/NOCURRENT_DIRECTORY^
14085 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatpp})
14086 The same as the corresponding gcc switch
14088 @item ^-gnatec^/CONFIGURATION_PRAGMAS_FILE^=@var{path}
14089 @cindex @option{^-gnatec^/CONFIGURATION_PRAGMAS_FILE^} (@code{gnatpp})
14090 The same as the corresponding gcc switch
14092 @item ^--RTS^/RUNTIME_SYSTEM^=@var{path}
14093 @cindex @option{^--RTS^/RUNTIME_SYSTEM^} (@code{gnatpp})
14094 The same as the corresponding gcc switch
14096 @end table
14098 @node Output File Control
14099 @subsection Output File Control
14101 @noindent
14102 By default the output is sent to the file whose name is obtained by appending
14103 the ^@file{.pp}^@file{$PP}^ suffix to the name of the input file
14104 (if the file with this name already exists, it is unconditionally overwritten).
14105 Thus if the input file is @file{^my_ada_proc.adb^MY_ADA_PROC.ADB^} then
14106 @command{gnatpp} will produce @file{^my_ada_proc.adb.pp^MY_ADA_PROC.ADB$PP^}
14107 as output file.
14108 The output may be redirected by the following switches:
14110 @table @option
14111 @item ^-pipe^/STANDARD_OUTPUT^
14112 @cindex @option{^-pipe^/STANDARD_OUTPUT^} (@code{gnatpp})
14113 Send the output to @code{Standard_Output}
14115 @item ^-o @var{output_file}^/OUTPUT=@var{output_file}^
14116 @cindex @option{^-o^/OUTPUT^} (@code{gnatpp})
14117 Write the output into @var{output_file}.
14118 If @var{output_file} already exists, @command{gnatpp} terminates without
14119 reading or processing the input file.
14121 @item ^-of ^/FORCED_OUTPUT=^@var{output_file}
14122 @cindex @option{^-of^/FORCED_OUTPUT^} (@code{gnatpp})
14123 Write the output into @var{output_file}, overwriting the existing file
14124 (if one is present).
14126 @item ^-r^/REPLACE^
14127 @cindex @option{^-r^/REPLACE^} (@code{gnatpp})
14128 Replace the input source file with the reformatted output, and copy the
14129 original input source into the file whose name is obtained by appending the
14130 ^@file{.npp}^@file{$NPP}^ suffix to the name of the input file.
14131 If a file with this name already exists, @command{gnatpp} terminates without
14132 reading or processing the input file.
14134 @item ^-rf^/OVERRIDING_REPLACE^
14135 @cindex @option{^-rf^/OVERRIDING_REPLACE^} (@code{gnatpp})
14136 Like @option{^-r^/REPLACE^} except that if the file with the specified name
14137 already exists, it is overwritten.
14139 @item ^-rnb^/REPLACE_NO_BACKUP^
14140 @cindex @option{^-rnb^/REPLACE_NO_BACKUP^} (@code{gnatpp})
14141 Replace the input source file with the reformatted output without
14142 creating any backup copy of the input source.
14144 @item ^--eol=@var{xxx}^/END_OF_LINE=@var{xxx}^
14145 @cindex @option{^--eol^/END_OF_LINE^} (@code{gnatpp})
14146 Specifies the format of the reformatted output file. The @var{xxx}
14147 ^string specified with the switch^option^ may be either
14148 @itemize @bullet
14149 @item ``@option{^dos^DOS^}'' MS DOS style, lines end with CR LF characters
14150 @item ``@option{^crlf^CRLF^}''
14151 the same as @option{^crlf^CRLF^}
14152 @item ``@option{^unix^UNIX^}'' UNIX style, lines end with LF character
14153 @item ``@option{^lf^LF^}''
14154 the same as @option{^unix^UNIX^}
14155 @end itemize
14157 @item ^-W^/RESULT_ENCODING=^@var{e}
14158 @cindex @option{^-W^/RESULT_ENCODING=^} (@command{gnatpp})
14159 Specify the wide character encoding method used to write the code in the
14160 result file
14161 @var{e} is one of the following:
14163 @itemize @bullet
14165 @item ^h^HEX^
14166 Hex encoding
14168 @item ^u^UPPER^
14169 Upper half encoding
14171 @item ^s^SHIFT_JIS^
14172 Shift/JIS encoding
14174 @item ^e^EUC^
14175 EUC encoding
14177 @item ^8^UTF8^
14178 UTF-8 encoding
14180 @item ^b^BRACKETS^
14181 Brackets encoding (default value)
14182 @end itemize
14184 @end table
14186 @noindent
14187 Options @option{^-pipe^/STANDARD_OUTPUT^},
14188 @option{^-o^/OUTPUT^} and
14189 @option{^-of^/FORCED_OUTPUT^} are allowed only if the call to gnatpp
14190 contains only one file to reformat.
14191 Option
14192 @option{^--eol^/END_OF_LINE^}
14194 @option{^-W^/RESULT_ENCODING^}
14195 cannot be used together
14196 with @option{^-pipe^/STANDARD_OUTPUT^} option.
14198 @node Other gnatpp Switches
14199 @subsection Other @code{gnatpp} Switches
14201 @noindent
14202 The additional @command{gnatpp} switches are defined in this subsection.
14204 @table @option
14205 @item --version
14206 @cindex @option{--version} @command{gnatpp}
14207 Display Copyright and version, then exit disregarding all other options.
14209 @item --help
14210 @cindex @option{--help} @command{gnatpp}
14211 Display usage, then exit disregarding all other options.
14213 @item ^-files @var{filename}^/FILES=@var{filename}^
14214 @cindex @option{^-files^/FILES^} (@code{gnatpp})
14215 Take the argument source files from the specified file. This file should be an
14216 ordinary text file containing file names separated by spaces or
14217 line breaks. You can use this switch more than once in the same call to
14218 @command{gnatpp}. You also can combine this switch with an explicit list of
14219 files.
14221 @item ^-v^/VERBOSE^
14222 @cindex @option{^-v^/VERBOSE^} (@code{gnatpp})
14223 Verbose mode;
14224 @command{gnatpp} generates version information and then
14225 a trace of the actions it takes to produce or obtain the ASIS tree.
14227 @item ^-w^/WARNINGS^
14228 @cindex @option{^-w^/WARNINGS^} (@code{gnatpp})
14229 Warning mode;
14230 @command{gnatpp} generates a warning whenever it cannot provide
14231 a required layout in the result source.
14232 @end table
14234 @node Formatting Rules
14235 @section Formatting Rules
14237 @noindent
14238 The following subsections show how @command{gnatpp} treats ``white space'',
14239 comments, program layout, and name casing.
14240 They provide the detailed descriptions of the switches shown above.
14242 @menu
14243 * White Space and Empty Lines::
14244 * Formatting Comments::
14245 * Construct Layout::
14246 * Name Casing::
14247 @end menu
14249 @node White Space and Empty Lines
14250 @subsection White Space and Empty Lines
14252 @noindent
14253 @command{gnatpp} does not have an option to control space characters.
14254 It will add or remove spaces according to the style illustrated by the
14255 examples in the @cite{Ada Reference Manual}.
14257 The only format effectors
14258 (see @cite{Ada Reference Manual}, paragraph 2.1(13))
14259 that will appear in the output file are platform-specific line breaks,
14260 and also format effectors within (but not at the end of) comments.
14261 In particular, each horizontal tab character that is not inside
14262 a comment will be treated as a space and thus will appear in the
14263 output file as zero or more spaces depending on
14264 the reformatting of the line in which it appears.
14265 The only exception is a Form Feed character, which is inserted after a
14266 pragma @code{Page} when @option{-ff} is set.
14268 The output file will contain no lines with trailing ``white space'' (spaces,
14269 format effectors).
14271 Empty lines in the original source are preserved
14272 only if they separate declarations or statements.
14273 In such contexts, a
14274 sequence of two or more empty lines is replaced by exactly one empty line.
14275 Note that a blank line will be removed if it separates two ``comment blocks''
14276 (a comment block is a sequence of whole-line comments).
14277 In order to preserve a visual separation between comment blocks, use an
14278 ``empty comment'' (a line comprising only hyphens) rather than an empty line.
14279 Likewise, if for some reason you wish to have a sequence of empty lines,
14280 use a sequence of empty comments instead.
14282 @node Formatting Comments
14283 @subsection Formatting Comments
14285 @noindent
14286 Comments in Ada code are of two kinds:
14287 @itemize @bullet
14288 @item
14289 a @emph{whole-line comment}, which appears by itself (possibly preceded by
14290 ``white space'') on a line
14292 @item
14293 an @emph{end-of-line comment}, which follows some other Ada lexical element
14294 on the same line.
14295 @end itemize
14297 @noindent
14298 The indentation of a whole-line comment is that of either
14299 the preceding or following line in
14300 the formatted source, depending on switch settings as will be described below.
14302 For an end-of-line comment, @command{gnatpp} leaves the same number of spaces
14303 between the end of the preceding Ada lexical element and the beginning
14304 of the comment as appear in the original source,
14305 unless either the comment has to be split to
14306 satisfy the line length limitation, or else the next line contains a
14307 whole line comment that is considered a continuation of this end-of-line
14308 comment (because it starts at the same position).
14309 In the latter two
14310 cases, the start of the end-of-line comment is moved right to the nearest
14311 multiple of the indentation level.
14312 This may result in a ``line overflow'' (the right-shifted comment extending
14313 beyond the maximum line length), in which case the comment is split as
14314 described below.
14316 There is a difference between @option{^-c1^/COMMENTS_LAYOUT=DEFAULT^}
14317 (GNAT-style comment line indentation)
14318 and @option{^-c2^/COMMENTS_LAYOUT=STANDARD_INDENT^}
14319 (reference-manual comment line indentation).
14320 With reference-manual style, a whole-line comment is indented as if it
14321 were a declaration or statement at the same place
14322 (i.e., according to the indentation of the preceding line(s)).
14323 With GNAT style, a whole-line comment that is immediately followed by an
14324 @b{if} or @b{case} statement alternative, a record variant, or the reserved
14325 word @b{begin}, is indented based on the construct that follows it.
14327 For example:
14328 @smallexample @c ada
14329 @cartouche
14330 if A then
14331     null;
14332        -- some comment
14333 else
14334    null;
14335 end if;
14336 @end cartouche
14337 @end smallexample
14339 @noindent
14340 Reference-manual indentation produces:
14342 @smallexample @c ada
14343 @cartouche
14344 if A then
14345    null;
14346    --  some comment
14347 else
14348    null;
14349 end if;
14350 @end cartouche
14351 @end smallexample
14353 @noindent
14354 while GNAT-style indentation produces:
14356 @smallexample @c ada
14357 @cartouche
14358 if A then
14359    null;
14360 --  some comment
14361 else
14362    null;
14363 end if;
14364 @end cartouche
14365 @end smallexample
14367 @noindent
14368 The @option{^-c3^/COMMENTS_LAYOUT=GNAT_BEGINNING^} switch
14369 (GNAT style comment beginning) has the following
14370 effect:
14372 @itemize @bullet
14373 @item
14374 For each whole-line comment that does not end with two hyphens,
14375 @command{gnatpp} inserts spaces if necessary after the starting two hyphens
14376 to ensure that there are at least two spaces between these hyphens and the
14377 first non-blank character of the comment.
14378 @end itemize
14380 @noindent
14381 For an end-of-line comment, if in the original source the next line is a
14382 whole-line comment that starts at the same position
14383 as the end-of-line comment,
14384 then the whole-line comment (and all whole-line comments
14385 that follow it and that start at the same position)
14386 will start at this position in the output file.
14388 @noindent
14389 That is, if in the original source we have:
14391 @smallexample @c ada
14392 @cartouche
14393 begin
14394 A := B + C;            --  B must be in the range Low1..High1
14395                        --  C must be in the range Low2..High2
14396              --B+C will be in the range Low1+Low2..High1+High2
14397 X := X + 1;
14398 @end cartouche
14399 @end smallexample
14401 @noindent
14402 Then in the formatted source we get
14404 @smallexample @c ada
14405 @cartouche
14406 begin
14407    A := B + C;            --  B must be in the range Low1..High1
14408                           --  C must be in the range Low2..High2
14409    --  B+C will be in the range Low1+Low2..High1+High2
14410    X := X + 1;
14411 @end cartouche
14412 @end smallexample
14414 @noindent
14415 A comment that exceeds the line length limit will be split.
14416 Unless switch
14417 @option{^-c4^/COMMENTS_LAYOUT=REFORMAT^} (reformat comment blocks) is set and
14418 the line belongs to a reformattable block, splitting the line generates a
14419 @command{gnatpp} warning.
14420 The @option{^-c4^/COMMENTS_LAYOUT=REFORMAT^} switch specifies that whole-line
14421 comments may be reformatted in typical
14422 word processor style (that is, moving words between lines and putting as
14423 many words in a line as possible).
14425 @noindent
14426 The @option{^-c5^/COMMENTS_LAYOUT=KEEP_SPECIAL^} switch specifies, that comments
14427 that has a special format (that is, a character that is neither a letter nor digit
14428 not white space nor line break immediately following the leading @code{--} of
14429 the comment) should be without any change moved from the argument source
14430 into reformatted source. This switch allows to preserve comments that are used
14431 as a special marks in the code (e.g.@: SPARK annotation).
14433 @node Construct Layout
14434 @subsection Construct Layout
14436 @noindent
14437 In several cases the suggested layout in the Ada Reference Manual includes
14438 an extra level of indentation that many programmers prefer to avoid. The
14439 affected cases include:
14441 @itemize @bullet
14443 @item Record type declaration (RM 3.8)
14445 @item Record representation clause (RM 13.5.1)
14447 @item Loop statement in case if a loop has a statement identifier (RM 5.6)
14449 @item Block statement in case if a block has a statement identifier (RM 5.6)
14450 @end itemize
14452 @noindent
14453 In compact mode (when GNAT style layout or compact layout is set),
14454 the pretty printer uses one level of indentation instead
14455 of two. This is achieved in the record definition and record representation
14456 clause cases by putting the @code{record} keyword on the same line as the
14457 start of the declaration or representation clause, and in the block and loop
14458 case by putting the block or loop header on the same line as the statement
14459 identifier.
14461 @noindent
14462 The difference between GNAT style @option{^-l1^/CONSTRUCT_LAYOUT=GNAT^}
14463 and compact @option{^-l2^/CONSTRUCT_LAYOUT=COMPACT^}
14464 layout on the one hand, and uncompact layout
14465 @option{^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^} on the other hand,
14466 can be illustrated by the following examples:
14468 @iftex
14469 @cartouche
14470 @multitable @columnfractions .5 .5
14471 @item @i{GNAT style, compact layout} @tab @i{Uncompact layout}
14473 @item
14474 @smallexample @c ada
14475 type q is record
14476    a : integer;
14477    b : integer;
14478 end record;
14479 @end smallexample
14480 @tab
14481 @smallexample @c ada
14482 type q is
14483    record
14484       a : integer;
14485       b : integer;
14486    end record;
14487 @end smallexample
14489 @item
14490 @smallexample @c ada
14491 for q use record
14492    a at 0 range  0 .. 31;
14493    b at 4 range  0 .. 31;
14494 end record;
14495 @end smallexample
14496 @tab
14497 @smallexample @c ada
14498 for q use
14499    record
14500       a at 0 range  0 .. 31;
14501       b at 4 range  0 .. 31;
14502    end record;
14503 @end smallexample
14505 @item
14506 @smallexample @c ada
14507 Block : declare
14508    A : Integer := 3;
14509 begin
14510    Proc (A, A);
14511 end Block;
14512 @end smallexample
14513 @tab
14514 @smallexample @c ada
14515 Block :
14516    declare
14517       A : Integer := 3;
14518    begin
14519       Proc (A, A);
14520    end Block;
14521 @end smallexample
14523 @item
14524 @smallexample @c ada
14525 Clear : for J in 1 .. 10 loop
14526    A (J) := 0;
14527 end loop Clear;
14528 @end smallexample
14529 @tab
14530 @smallexample @c ada
14531 Clear :
14532    for J in 1 .. 10 loop
14533       A (J) := 0;
14534    end loop Clear;
14535 @end smallexample
14536 @end multitable
14537 @end cartouche
14538 @end iftex
14540 @ifnottex
14541 @smallexample
14542 @cartouche
14543 GNAT style, compact layout              Uncompact layout
14545 type q is record                        type q is
14546    a : integer;                            record
14547    b : integer;                               a : integer;
14548 end record;                                   b : integer;
14549                                            end record;
14551 for q use record                        for q use
14552    a at 0 range  0 .. 31;                  record
14553    b at 4 range  0 .. 31;                     a at 0 range  0 .. 31;
14554 end record;                                   b at 4 range  0 .. 31;
14555                                            end record;
14557 Block : declare                         Block :
14558    A : Integer := 3;                       declare
14559 begin                                         A : Integer := 3;
14560    Proc (A, A);                            begin
14561 end Block;                                    Proc (A, A);
14562                                            end Block;
14564 Clear : for J in 1 .. 10 loop           Clear :
14565    A (J) := 0;                             for J in 1 .. 10 loop
14566 end loop Clear;                               A (J) := 0;
14567                                            end loop Clear;
14568 @end cartouche
14569 @end smallexample
14570 @end ifnottex
14572 @noindent
14573 A further difference between GNAT style layout and compact layout is that
14574 GNAT style layout inserts empty lines as separation for
14575 compound statements, return statements and bodies.
14577 Note that the layout specified by
14578 @option{^--separate-stmt-name^/STMT_NAME_ON_NEW_LINE^}
14579 for named block and loop statements overrides the layout defined by these
14580 constructs by @option{^-l1^/CONSTRUCT_LAYOUT=GNAT^},
14581 @option{^-l2^/CONSTRUCT_LAYOUT=COMPACT^} or
14582 @option{^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^} option.
14584 @node Name Casing
14585 @subsection Name Casing
14587 @noindent
14588 @command{gnatpp} always converts the usage occurrence of a (simple) name to
14589 the same casing as the corresponding defining identifier.
14591 You control the casing for defining occurrences via the
14592 @option{^-n^/NAME_CASING^} switch.
14593 @ifclear vms
14594 With @option{-nD} (``as declared'', which is the default),
14595 @end ifclear
14596 @ifset vms
14597 With @option{/NAME_CASING=AS_DECLARED}, which is the default,
14598 @end ifset
14599 defining occurrences appear exactly as in the source file
14600 where they are declared.
14601 The other ^values for this switch^options for this qualifier^ ---
14602 @option{^-nU^UPPER_CASE^},
14603 @option{^-nL^LOWER_CASE^},
14604 @option{^-nM^MIXED_CASE^} ---
14605 result in
14606 ^upper, lower, or mixed case, respectively^the corresponding casing^.
14607 If @command{gnatpp} changes the casing of a defining
14608 occurrence, it analogously changes the casing of all the
14609 usage occurrences of this name.
14611 If the defining occurrence of a name is not in the source compilation unit
14612 currently being processed by @command{gnatpp}, the casing of each reference to
14613 this name is changed according to the value of the @option{^-n^/NAME_CASING^}
14614 switch (subject to the dictionary file mechanism described below).
14615 Thus @command{gnatpp} acts as though the @option{^-n^/NAME_CASING^} switch
14616 had affected the
14617 casing for the defining occurrence of the name.
14619 Some names may need to be spelled with casing conventions that are not
14620 covered by the upper-, lower-, and mixed-case transformations.
14621 You can arrange correct casing by placing such names in a
14622 @emph{dictionary file},
14623 and then supplying a @option{^-D^/DICTIONARY^} switch.
14624 The casing of names from dictionary files overrides
14625 any @option{^-n^/NAME_CASING^} switch.
14627 To handle the casing of Ada predefined names and the names from GNAT libraries,
14628 @command{gnatpp} assumes a default dictionary file.
14629 The name of each predefined entity is spelled with the same casing as is used
14630 for the entity in the @cite{Ada Reference Manual}.
14631 The name of each entity in the GNAT libraries is spelled with the same casing
14632 as is used in the declaration of that entity.
14634 The @w{@option{^-D-^/SPECIFIC_CASING^}} switch suppresses the use of the
14635 default dictionary file.
14636 Instead, the casing for predefined and GNAT-defined names will be established
14637 by the @option{^-n^/NAME_CASING^} switch or explicit dictionary files.
14638 For example, by default the names @code{Ada.Text_IO} and @code{GNAT.OS_Lib}
14639 will appear as just shown,
14640 even in the presence of a @option{^-nU^/NAME_CASING=UPPER_CASE^} switch.
14641 To ensure that even such names are rendered in uppercase,
14642 additionally supply the @w{@option{^-D-^/SPECIFIC_CASING^}} switch
14643 (or else, less conveniently, place these names in upper case in a dictionary
14644 file).
14646 A dictionary file is
14647 a plain text file; each line in this file can be either a blank line
14648 (containing only space characters and ASCII.HT characters), an Ada comment
14649 line, or the specification of exactly one @emph{casing schema}.
14651 A casing schema is a string that has the following syntax:
14653 @smallexample
14654 @cartouche
14655   @var{casing_schema} ::= @var{identifier} | *@var{simple_identifier}*
14657   @var{simple_identifier} ::= @var{letter}@{@var{letter_or_digit}@}
14658 @end cartouche
14659 @end smallexample
14661 @noindent
14662 (See @cite{Ada Reference Manual}, Section 2.3) for the definition of the
14663 @var{identifier} lexical element and the @var{letter_or_digit} category.)
14665 The casing schema string can be followed by white space and/or an Ada-style
14666 comment; any amount of white space is allowed before the string.
14668 If a dictionary file is passed as
14669 @ifclear vms
14670 the value of a @option{-D@var{file}} switch
14671 @end ifclear
14672 @ifset vms
14673 an option to the @option{/DICTIONARY} qualifier
14674 @end ifset
14675 then for every
14676 simple name and every identifier, @command{gnatpp} checks if the dictionary
14677 defines the casing for the name or for some of its parts (the term ``subword''
14678 is used below to denote the part of a name which is delimited by ``_'' or by
14679 the beginning or end of the word and which does not contain any ``_'' inside):
14681 @itemize @bullet
14682 @item
14683 if the whole name is in the dictionary, @command{gnatpp} uses for this name
14684 the casing defined by the dictionary; no subwords are checked for this word
14686 @item
14687 for every subword @command{gnatpp} checks if the dictionary contains the
14688 corresponding string of the form @code{*@var{simple_identifier}*},
14689 and if it does, the casing of this @var{simple_identifier} is used
14690 for this subword
14692 @item
14693 if the whole name does not contain any ``_'' inside, and if for this name
14694 the dictionary contains two entries - one of the form @var{identifier},
14695 and another - of the form *@var{simple_identifier}*, then the first one
14696 is applied to define the casing of this name
14698 @item
14699 if more than one dictionary file is passed as @command{gnatpp} switches, each
14700 dictionary adds new casing exceptions and overrides all the existing casing
14701 exceptions set by the previous dictionaries
14703 @item
14704 when @command{gnatpp} checks if the word or subword is in the dictionary,
14705 this check is not case sensitive
14706 @end itemize
14708 @noindent
14709 For example, suppose we have the following source to reformat:
14711 @smallexample @c ada
14712 @cartouche
14713 procedure test is
14714    name1 : integer := 1;
14715    name4_name3_name2 : integer := 2;
14716    name2_name3_name4 : Boolean;
14717    name1_var : Float;
14718 begin
14719    name2_name3_name4 := name4_name3_name2 > name1;
14720 end;
14721 @end cartouche
14722 @end smallexample
14724 @noindent
14725 And suppose we have two dictionaries:
14727 @smallexample
14728 @cartouche
14729 @i{dict1:}
14730    NAME1
14731    *NaMe3*
14732    *Name1*
14733 @end cartouche
14735 @cartouche
14736 @i{dict2:}
14737   *NAME3*
14738 @end cartouche
14739 @end smallexample
14741 @noindent
14742 If @command{gnatpp} is called with the following switches:
14744 @smallexample
14745 @ifclear vms
14746 @command{gnatpp -nM -D dict1 -D dict2 test.adb}
14747 @end ifclear
14748 @ifset vms
14749 @command{gnatpp test.adb /NAME_CASING=MIXED_CASE /DICTIONARY=(dict1, dict2)}
14750 @end ifset
14751 @end smallexample
14753 @noindent
14754 then we will get the following name casing in the @command{gnatpp} output:
14756 @smallexample @c ada
14757 @cartouche
14758 procedure Test is
14759    NAME1             : Integer := 1;
14760    Name4_NAME3_Name2 : Integer := 2;
14761    Name2_NAME3_Name4 : Boolean;
14762    Name1_Var         : Float;
14763 begin
14764    Name2_NAME3_Name4 := Name4_NAME3_Name2 > NAME1;
14765 end Test;
14766 @end cartouche
14767 @end smallexample
14769 @c *********************************
14770 @node The GNAT Metrics Tool gnatmetric
14771 @chapter The GNAT Metrics Tool @command{gnatmetric}
14772 @findex gnatmetric
14773 @cindex Metric tool
14775 @noindent
14776 ^The @command{gnatmetric} tool^@command{GNAT METRIC}^ is an ASIS-based utility
14777 for computing various program metrics.
14778 It takes an Ada source file as input and generates a file containing the
14779 metrics data as output. Various switches control which
14780 metrics are computed and output.
14782 @menu
14783 * Switches for gnatmetric::
14784 @end menu
14786 @command{gnatmetric} generates and uses the ASIS
14787 tree for the input source and thus requires the input to be syntactically and
14788 semantically legal.
14789 If this condition is not met, @command{gnatmetric} will generate
14790 an error message; no metric information for this file will be
14791 computed and reported.
14793 If the compilation unit contained in the input source depends semantically
14794 upon units in files located outside the current directory, you have to provide
14795 the source search path when invoking @command{gnatmetric}.
14796 If it depends semantically upon units that are contained
14797 in files with names that do not follow the GNAT file naming rules, you have to
14798 provide the configuration file describing the corresponding naming scheme (see
14799 the description of the @command{gnatmetric} switches below.)
14800 Alternatively, you may use a project file and invoke @command{gnatmetric}
14801 through the @command{gnat} driver (see @ref{The GNAT Driver and Project Files}).
14803 The @command{gnatmetric} command has the form
14805 @smallexample
14806 @c $ gnatmetric @ovar{switches} @{@var{filename}@} @r{[}-cargs @var{gcc_switches}@r{]}
14807 @c Expanding @ovar macro inline (explanation in macro def comments)
14808 $ gnatmetric @r{[}@var{switches}@r{]} @{@var{filename}@} @r{[}-cargs @var{gcc_switches}@r{]}
14809 @end smallexample
14811 @noindent
14812 where
14813 @itemize @bullet
14814 @item
14815 @var{switches} specify the metrics to compute and define the destination for
14816 the output
14818 @item
14819 Each @var{filename} is the name (including the extension) of a source
14820 file to process. ``Wildcards'' are allowed, and
14821 the file name may contain path information.
14822 If no @var{filename} is supplied, then the @var{switches} list must contain
14823 at least one
14824 @option{-files} switch (@pxref{Other gnatmetric Switches}).
14825 Including both a @option{-files} switch and one or more
14826 @var{filename} arguments is permitted.
14828 @item
14829 @samp{@var{gcc_switches}} is a list of switches for
14830 @command{gcc}. They will be passed on to all compiler invocations made by
14831 @command{gnatmetric} to generate the ASIS trees. Here you can provide
14832 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
14833 and use the @option{-gnatec} switch to set the configuration file,
14834 use the @option{-gnat05} switch if sources should be compiled in
14835 Ada 2005 mode etc.
14836 @end itemize
14838 @node Switches for gnatmetric
14839 @section Switches for @command{gnatmetric}
14841 @noindent
14842 The following subsections describe the various switches accepted by
14843 @command{gnatmetric}, organized by category.
14845 @menu
14846 * Output Files Control::
14847 * Disable Metrics For Local Units::
14848 * Specifying a set of metrics to compute::
14849 * Other gnatmetric Switches::
14850 * Generate project-wide metrics::
14851 @end menu
14853 @node Output Files Control
14854 @subsection Output File Control
14855 @cindex Output file control in @command{gnatmetric}
14857 @noindent
14858 @command{gnatmetric} has two output formats. It can generate a
14859 textual (human-readable) form, and also XML. By default only textual
14860 output is generated.
14862 When generating the output in textual form, @command{gnatmetric} creates
14863 for each Ada source file a corresponding text file
14864 containing the computed metrics, except for the case when the set of metrics
14865 specified by gnatmetric parameters consists only of metrics that are computed
14866 for the whole set of analyzed sources, but not for each Ada source.
14867 By default, this file is placed in the same directory as where the source
14868 file is located, and its name is obtained
14869 by appending the ^@file{.metrix}^@file{$METRIX}^ suffix to the name of the
14870 input file.
14872 All the output information generated in XML format is placed in a single
14873 file. By default this file is placed in the current directory and has the
14874 name ^@file{metrix.xml}^@file{METRIX$XML}^.
14876 Some of the computed metrics are summed over the units passed to
14877 @command{gnatmetric}; for example, the total number of lines of code.
14878 By default this information is sent to @file{stdout}, but a file
14879 can be specified with the @option{-og} switch.
14881 The following switches control the @command{gnatmetric} output:
14883 @table @option
14884 @cindex @option{^-x^/XML^} (@command{gnatmetric})
14885 @item ^-x^/XML^
14886 Generate the XML output
14888 @cindex @option{^-xs^/XSD^} (@command{gnatmetric})
14889 @item ^-xs^/XSD^
14890 Generate the XML output and the XML schema file that describes the structure
14891 of the XML metric report, this schema is assigned to the XML file. The schema
14892 file has the same name as the XML output file with @file{.xml} suffix replaced
14893 with @file{.xsd}
14895 @cindex @option{^-nt^/NO_TEXT^} (@command{gnatmetric})
14896 @item ^-nt^/NO_TEXT^
14897 Do not generate the output in text form (implies @option{^-x^/XML^})
14899 @cindex @option{^-d^/DIRECTORY^} (@command{gnatmetric})
14900 @item ^-d @var{output_dir}^/DIRECTORY=@var{output_dir}^
14901 Put text files with detailed metrics into @var{output_dir}
14903 @cindex @option{^-o^/SUFFIX_DETAILS^} (@command{gnatmetric})
14904 @item ^-o @var{file_suffix}^/SUFFIX_DETAILS=@var{file_suffix}^
14905 Use @var{file_suffix}, instead of ^@file{.metrix}^@file{$METRIX}^
14906 in the name of the output file.
14908 @cindex @option{^-og^/GLOBAL_OUTPUT^} (@command{gnatmetric})
14909 @item ^-og @var{file_name}^/GLOBAL_OUTPUT=@var{file_name}^
14910 Put global metrics into @var{file_name}
14912 @cindex @option{^-ox^/XML_OUTPUT^} (@command{gnatmetric})
14913 @item ^-ox @var{file_name}^/XML_OUTPUT=@var{file_name}^
14914 Put the XML output into @var{file_name} (also implies @option{^-x^/XML^})
14916 @cindex @option{^-sfn^/SHORT_SOURCE_FILE_NAME^} (@command{gnatmetric})
14917 @item ^-sfn^/SHORT_SOURCE_FILE_NAME^
14918 Use ``short'' source file names in the output.  (The @command{gnatmetric}
14919 output includes the name(s) of the Ada source file(s) from which the metrics
14920 are computed.  By default each name includes the absolute path. The
14921 @option{^-sfn^/SHORT_SOURCE_FILE_NAME^} switch causes @command{gnatmetric}
14922 to exclude all directory information from the file names that are output.)
14924 @end table
14926 @node Disable Metrics For Local Units
14927 @subsection Disable Metrics For Local Units
14928 @cindex Disable Metrics For Local Units in @command{gnatmetric}
14930 @noindent
14931 @command{gnatmetric} relies on the GNAT compilation model @minus{}
14932 one compilation
14933 unit per one source file. It computes line metrics for the whole source
14934 file, and it also computes syntax
14935 and complexity metrics for the file's outermost unit.
14937 By default, @command{gnatmetric} will also compute all metrics for certain
14938 kinds of locally declared program units:
14940 @itemize @bullet
14941 @item
14942 subprogram (and generic subprogram) bodies;
14944 @item
14945 package (and generic package) specs and bodies;
14947 @item
14948 task object and type specifications and bodies;
14950 @item
14951 protected object and type specifications and bodies.
14952 @end itemize
14954 @noindent
14955 These kinds of entities will be referred to as
14956 @emph{eligible local program units}, or simply @emph{eligible local units},
14957 @cindex Eligible local unit (for @command{gnatmetric})
14958 in the discussion below.
14960 Note that a subprogram declaration, generic instantiation,
14961 or renaming declaration only receives metrics
14962 computation when it appear as the outermost entity
14963 in a source file.
14965 Suppression of metrics computation for eligible local units can be
14966 obtained via the following switch:
14968 @table @option
14969 @cindex @option{^-n@var{x}^/SUPPRESS^} (@command{gnatmetric})
14970 @item ^-nolocal^/SUPPRESS=LOCAL_DETAILS^
14971 Do not compute detailed metrics for eligible local program units
14973 @end table
14975 @node Specifying a set of metrics to compute
14976 @subsection Specifying a set of metrics to compute
14978 @noindent
14979 By default all the metrics are computed and reported. The switches
14980 described in this subsection allow you to control, on an individual
14981 basis, whether metrics are computed and
14982 reported. If at least one positive metric
14983 switch is specified (that is, a switch that defines that a given
14984 metric or set of metrics is to be computed), then only
14985 explicitly specified metrics are reported.
14987 @menu
14988 * Line Metrics Control::
14989 * Syntax Metrics Control::
14990 * Complexity Metrics Control::
14991 * Coupling Metrics Control::
14992 @end menu
14994 @node Line Metrics Control
14995 @subsubsection Line Metrics Control
14996 @cindex Line metrics control in @command{gnatmetric}
14998 @noindent
14999 For any (legal) source file, and for each of its
15000 eligible local program units, @command{gnatmetric} computes the following
15001 metrics:
15003 @itemize @bullet
15004 @item
15005 the total number of lines;
15007 @item
15008 the total number of code lines (i.e., non-blank lines that are not comments)
15010 @item
15011 the number of comment lines
15013 @item
15014 the number of code lines containing end-of-line comments;
15016 @item
15017 the comment percentage: the ratio between the number of lines that contain
15018 comments and the number of all non-blank lines, expressed as a percentage;
15020 @item
15021 the number of empty lines and lines containing only space characters and/or
15022 format effectors (blank lines)
15024 @item
15025 the average number of code lines in subprogram bodies, task bodies, entry
15026 bodies and statement sequences in package bodies (this metric is only computed
15027 across the whole set of the analyzed units)
15029 @end itemize
15031 @noindent
15032 @command{gnatmetric} sums the values of the line metrics for all the
15033 files being processed and then generates the cumulative results. The tool
15034 also computes for all the files being processed the average number of code
15035 lines in bodies.
15037 You can use the following switches to select the specific line metrics
15038 to be computed and reported.
15040 @table @option
15041 @cindex @option{^--lines@var{x}^/LINE_COUNT_METRICS^} (@command{gnatmetric})
15043 @ifclear vms
15044 @cindex @option{--no-lines@var{x}}
15045 @end ifclear
15047 @item ^--lines-all^/LINE_COUNT_METRICS=ALL^
15048 Report all the line metrics
15050 @item ^--no-lines-all^/LINE_COUNT_METRICS=NONE^
15051 Do not report any of line metrics
15053 @item ^--lines^/LINE_COUNT_METRICS=ALL_LINES^
15054 Report the number of all lines
15056 @item ^--no-lines^/LINE_COUNT_METRICS=NOALL_LINES^
15057 Do not report the number of all lines
15059 @item ^--lines-code^/LINE_COUNT_METRICS=CODE_LINES^
15060 Report the number of code lines
15062 @item ^--no-lines-code^/LINE_COUNT_METRICS=NOCODE_LINES^
15063 Do not report the number of code lines
15065 @item ^--lines-comment^/LINE_COUNT_METRICS=COMMENT_LINES^
15066 Report the number of comment lines
15068 @item ^--no-lines-comment^/LINE_COUNT_METRICS=NOCOMMENT_LINES^
15069 Do not report the number of comment lines
15071 @item ^--lines-eol-comment^/LINE_COUNT_METRICS=CODE_COMMENT_LINES^
15072 Report the number of code lines containing
15073 end-of-line comments
15075 @item ^--no-lines-eol-comment^/LINE_COUNT_METRICS=NOCODE_COMMENT_LINES^
15076 Do not report the number of code lines containing
15077 end-of-line comments
15079 @item ^--lines-ratio^/LINE_COUNT_METRICS=COMMENT_PERCENTAGE^
15080 Report the comment percentage in the program text
15082 @item ^--no-lines-ratio^/LINE_COUNT_METRICS=NOCOMMENT_PERCENTAGE^
15083 Do not report the comment percentage in the program text
15085 @item ^--lines-blank^/LINE_COUNT_METRICS=BLANK_LINES^
15086 Report the number of blank lines
15088 @item ^--no-lines-blank^/LINE_COUNT_METRICS=NOBLANK_LINES^
15089 Do not report the number of blank lines
15091 @item ^--lines-average^/LINE_COUNT_METRICS=AVERAGE_BODY_LINES^
15092 Report the average number of code lines in subprogram bodies, task bodies,
15093 entry bodies and statement sequences in package bodies. The metric is computed
15094 and reported for the whole set of processed Ada sources only.
15096 @item ^--no-lines-average^/LINE_COUNT_METRICS=NOAVERAGE_BODY_LINES^
15097 Do not report the average number of code lines in subprogram bodies,
15098 task bodies, entry bodies and statement sequences in package bodies.
15100 @end table
15102 @node Syntax Metrics Control
15103 @subsubsection Syntax Metrics Control
15104 @cindex Syntax metrics control in @command{gnatmetric}
15106 @noindent
15107 @command{gnatmetric} computes various syntactic metrics for the
15108 outermost unit and for each eligible local unit:
15110 @table @emph
15111 @item LSLOC (``Logical Source Lines Of Code'')
15112 The total number of declarations and the total number of statements. Note
15113 that the definition of declarations is the one given in the reference
15114 manual:
15116 @noindent
15117 ``Each of the following is defined to be a declaration: any basic_declaration;
15118 an enumeration_literal_specification; a discriminant_specification;
15119 a component_declaration; a loop_parameter_specification; a
15120 parameter_specification; a subprogram_body; an entry_declaration;
15121 an entry_index_specification; a choice_parameter_specification;
15122 a generic_formal_parameter_declaration.''
15124 This means for example that each enumeration literal adds one to the count,
15125 as well as each subprogram parameter.
15127 Thus the results from this metric will be significantly greater than might
15128 be expected from a naive view of counting semicolons.
15130 @item Maximal static nesting level of inner program units
15131 According to
15132 @cite{Ada Reference Manual}, 10.1(1), ``A program unit is either a
15133 package, a task unit, a protected unit, a
15134 protected entry, a generic unit, or an explicitly declared subprogram other
15135 than an enumeration literal.''
15137 @item Maximal nesting level of composite syntactic constructs
15138 This corresponds to the notion of the
15139 maximum nesting level in the GNAT built-in style checks
15140 (@pxref{Style Checking})
15141 @end table
15143 @noindent
15144 For the outermost unit in the file, @command{gnatmetric} additionally computes
15145 the following metrics:
15147 @table @emph
15148 @item Public subprograms
15149 This metric is computed for package specs. It is the
15150 number of subprograms and generic subprograms declared in the visible
15151 part (including the visible part of nested packages, protected objects, and
15152 protected types).
15154 @item All subprograms
15155 This metric is computed for bodies and subunits. The
15156 metric is equal to a total number of subprogram bodies in the compilation
15157 unit.
15158 Neither generic instantiations nor renamings-as-a-body nor body stubs
15159 are counted. Any subprogram body is counted, independently of its nesting
15160 level and enclosing constructs. Generic bodies and bodies of protected
15161 subprograms are counted in the same way as ``usual'' subprogram bodies.
15163 @item Public types
15164 This metric is computed for package specs and
15165 generic package declarations. It is the total number of types
15166 that can be referenced from outside this compilation unit, plus the
15167 number of types from all the visible parts of all the visible generic
15168 packages. Generic formal types are not counted.  Only types, not subtypes,
15169 are included.
15171 @noindent
15172 Along with the total number of public types, the following
15173 types are counted and reported separately:
15175 @itemize @bullet
15176 @item
15177 Abstract types
15179 @item
15180 Root tagged types (abstract, non-abstract, private, non-private). Type
15181 extensions are @emph{not} counted
15183 @item
15184 Private types (including private extensions)
15186 @item
15187 Task types
15189 @item
15190 Protected types
15192 @end itemize
15194 @item All types
15195 This metric is computed for any compilation unit. It is equal to the total
15196 number of the declarations of different types given in the compilation unit.
15197 The private and the corresponding full type declaration are counted as one
15198 type declaration. Incomplete type declarations and generic formal types
15199 are not counted.
15200 No distinction is made among different kinds of types (abstract,
15201 private etc.); the total number of types is computed and reported.
15203 @end table
15205 @noindent
15206 By default, all the syntax metrics are computed and reported. You can use the
15207 following switches to select specific syntax metrics.
15209 @table @option
15211 @cindex @option{^--syntax@var{x}^/SYNTAX_METRICS^} (@command{gnatmetric})
15213 @ifclear vms
15214 @cindex @option{--no-syntax@var{x}} (@command{gnatmetric})
15215 @end ifclear
15217 @item ^--syntax-all^/SYNTAX_METRICS=ALL^
15218 Report all the syntax metrics
15220 @item ^--no-syntax-all^/SYNTAX_METRICS=NONE^
15221 Do not report any of syntax metrics
15223 @item ^--declarations^/SYNTAX_METRICS=DECLARATIONS^
15224 Report the total number of declarations
15226 @item ^--no-declarations^/SYNTAX_METRICS=NODECLARATIONS^
15227 Do not report the total number of declarations
15229 @item ^--statements^/SYNTAX_METRICS=STATEMENTS^
15230 Report the total number of statements
15232 @item ^--no-statements^/SYNTAX_METRICS=NOSTATEMENTS^
15233 Do not report the total number of statements
15235 @item ^--public-subprograms^/SYNTAX_METRICS=PUBLIC_SUBPROGRAMS^
15236 Report the number of public subprograms in a compilation unit
15238 @item ^--no-public-subprograms^/SYNTAX_METRICS=NOPUBLIC_SUBPROGRAMS^
15239 Do not report the number of public subprograms in a compilation unit
15241 @item ^--all-subprograms^/SYNTAX_METRICS=ALL_SUBPROGRAMS^
15242 Report the number of all the subprograms in a compilation unit
15244 @item ^--no-all-subprograms^/SYNTAX_METRICS=NOALL_SUBPROGRAMS^
15245 Do not report the number of all the subprograms in a compilation unit
15247 @item ^--public-types^/SYNTAX_METRICS=PUBLIC_TYPES^
15248 Report the number of public types in a compilation unit
15250 @item ^--no-public-types^/SYNTAX_METRICS=NOPUBLIC_TYPES^
15251 Do not report the number of public types in a compilation unit
15253 @item ^--all-types^/SYNTAX_METRICS=ALL_TYPES^
15254 Report the number of all the types in a compilation unit
15256 @item ^--no-all-types^/SYNTAX_METRICS=NOALL_TYPES^
15257 Do not report the number of all the types in a compilation unit
15259 @item ^--unit-nesting^/SYNTAX_METRICS=UNIT_NESTING^
15260 Report the maximal program unit nesting level
15262 @item ^--no-unit-nesting^/SYNTAX_METRICS=UNIT_NESTING_OFF^
15263 Do not report the maximal program unit nesting level
15265 @item ^--construct-nesting^/SYNTAX_METRICS=CONSTRUCT_NESTING^
15266 Report the maximal construct nesting level
15268 @item ^--no-construct-nesting^/SYNTAX_METRICS=NOCONSTRUCT_NESTING^
15269 Do not report the maximal construct nesting level
15271 @end table
15273 @node Complexity Metrics Control
15274 @subsubsection Complexity Metrics Control
15275 @cindex Complexity metrics control in @command{gnatmetric}
15277 @noindent
15278 For a program unit that is an executable body (a subprogram body (including
15279 generic bodies), task body, entry body or a package body containing
15280 its own statement sequence) @command{gnatmetric} computes the following
15281 complexity metrics:
15283 @itemize @bullet
15284 @item
15285 McCabe cyclomatic complexity;
15287 @item
15288 McCabe essential complexity;
15290 @item
15291 maximal loop nesting level;
15293 @item
15294 extra exit points (for subprograms);
15295 @end itemize
15297 @noindent
15298 The McCabe cyclomatic complexity metric is defined
15299 in @url{http://www.mccabe.com/pdf/mccabe-nist235r.pdf}
15301 According to McCabe, both control statements and short-circuit control forms
15302 should be taken into account when computing cyclomatic complexity.
15303 For Ada 2012 we have also take into account conditional expressions
15304 and quantified expressions. For each body, we compute three metric values:
15306 @itemize @bullet
15307 @item
15308 the complexity introduced by control
15309 statements only, without taking into account short-circuit forms,
15311 @item
15312 the complexity introduced by short-circuit control forms only, and
15314 @item
15315 the total
15316 cyclomatic complexity, which is the sum of these two values.
15317 @end itemize
15319 @noindent
15321 The cyclomatic complexity is also computed for Ada 2012 expression functions.
15322 An expression function cannot have statements as its components, so only one
15323 metric value is computed as a cyclomatic complexity of an expression function.
15325 The origin of cyclomatic complexity metric is the need to estimate the number
15326 of independent paths in the control flow graph that in turn gives the number
15327 of tests needed to satisfy paths coverage testing completeness criterion.
15328 Considered from the testing point of view, a static Ada @code{loop} (that is,
15329 the @code{loop} statement having static subtype in loop parameter
15330 specification) does not add to cyclomatic complexity. By providing
15331 @option{^--no-static-loop^NO_STATIC_LOOP^} option a user
15332 may specify that such loops should not be counted when computing the
15333 cyclomatic complexity metric
15335 The Ada essential complexity metric is a McCabe cyclomatic complexity metric
15336 counted for the code that is reduced by excluding all the pure structural Ada
15337 control statements. An compound statement is considered as a non-structural
15338 if it contains a @code{raise} or @code{return} statement as it subcomponent,
15339 or if it contains a @code{goto} statement that transfers the control outside
15340 the operator. A selective accept statement with @code{terminate} alternative
15341 is considered as non-structural statement. When computing this metric,
15342 @code{exit} statements are treated in the same way as @code{goto}
15343 statements unless @option{^-ne^NO_EXITS_AS_GOTOS^} option is specified.
15345 The Ada essential complexity metric defined here is intended to quantify
15346 the extent to which the software is unstructured. It is adapted from
15347 the McCabe essential complexity metric defined in
15348 @url{http://www.mccabe.com/pdf/mccabe-nist235r.pdf} but is modified to be more
15349 suitable for typical Ada usage. For example, short circuit forms
15350 are not penalized as unstructured in the Ada essential complexity metric.
15352 When computing cyclomatic and essential complexity, @command{gnatmetric} skips
15353 the code in the exception handlers and in all the nested program units. The
15354 code of assertions and predicates (that is, subprogram preconditions and
15355 postconditions, subtype predicates and type invariants) is also skipped.
15357 By default, all the complexity metrics are computed and reported.
15358 For more fine-grained control you can use
15359 the following switches:
15361 @table @option
15362 @cindex @option{^-complexity@var{x}^/COMPLEXITY_METRICS^} (@command{gnatmetric})
15364 @ifclear vms
15365 @cindex @option{--no-complexity@var{x}}
15366 @end ifclear
15368 @item ^--complexity-all^/COMPLEXITY_METRICS=ALL^
15369 Report all the complexity metrics
15371 @item ^--no-complexity-all^/COMPLEXITY_METRICS=NONE^
15372 Do not report any of complexity metrics
15374 @item ^--complexity-cyclomatic^/COMPLEXITY_METRICS=CYCLOMATIC^
15375 Report the McCabe Cyclomatic Complexity
15377 @item ^--no-complexity-cyclomatic^/COMPLEXITY_METRICS=NOCYCLOMATIC^
15378 Do not report the McCabe Cyclomatic Complexity
15380 @item ^--complexity-essential^/COMPLEXITY_METRICS=ESSENTIAL^
15381 Report the Essential Complexity
15383 @item ^--no-complexity-essential^/COMPLEXITY_METRICS=NOESSENTIAL^
15384 Do not report the Essential Complexity
15386 @item ^--loop-nesting^/COMPLEXITY_METRICS=LOOP_NESTING_ON^
15387 Report maximal loop nesting level
15389 @item ^--no-loop-nesting^/COMPLEXITY_METRICS=NOLOOP_NESTING^
15390 Do not report maximal loop nesting level
15392 @item ^--complexity-average^/COMPLEXITY_METRICS=AVERAGE_COMPLEXITY^
15393 Report the average McCabe Cyclomatic Complexity for all the subprogram bodies,
15394 task bodies, entry bodies and statement sequences in package bodies.
15395 The metric is computed and reported for whole set of processed Ada sources
15396 only.
15398 @item ^--no-complexity-average^/COMPLEXITY_METRICS=NOAVERAGE_COMPLEXITY^
15399 Do not report the average McCabe Cyclomatic Complexity for all the subprogram
15400 bodies, task bodies, entry bodies and statement sequences in package bodies
15402 @cindex @option{^-ne^/NO_EXITS_AS_GOTOS^} (@command{gnatmetric})
15403 @item ^-ne^/NO_EXITS_AS_GOTOS^
15404 Do not consider @code{exit} statements as @code{goto}s when
15405 computing Essential Complexity
15407 @cindex @option{^--no-static-loop^/NO_STATIC_LOOP^} (@command{gnatmetric})
15408 @item ^--no-static-loop^/NO_STATIC_LOOP^
15409 Do not consider static loops when computing cyclomatic complexity
15411 @item ^--extra-exit-points^/EXTRA_EXIT_POINTS^
15412 Report the extra exit points for subprogram bodies. As an exit point, this
15413 metric counts @code{return} statements and raise statements in case when the
15414 raised exception is not handled in the same body. In case of a function this
15415 metric subtracts 1 from the number of exit points, because a function body
15416 must contain at least one @code{return} statement.
15418 @item ^--no-extra-exit-points^/NOEXTRA_EXIT_POINTS^
15419 Do not report the extra exit points for subprogram bodies
15420 @end table
15423 @node Coupling Metrics Control
15424 @subsubsection Coupling Metrics Control
15425 @cindex Coupling metrics control in @command{gnatmetric}
15427 @noindent
15428 @cindex Coupling metrics (in in @command{gnatmetric})
15429 Coupling metrics measure the dependencies between a given entity and other
15430 entities the program consists of. The goal of these metrics is to estimate the
15431 stability of the whole program considered as the collection of entities
15432 (modules, classes etc.).
15434 Gnatmetric computes the following coupling metrics:
15436 @itemize @bullet
15438 @item
15439 @emph{object-oriented coupling} - for classes in traditional object-oriented
15440 sense;
15442 @item
15443 @emph{unit coupling} - for all the program units making up a program;
15445 @item
15446 @emph{control coupling} - this metric counts dependencies between a unit and
15447 only those units that define subprograms;
15448 @end itemize
15450 @noindent
15451 Two kinds of coupling metrics are computed:
15453 @table @asis
15454 @item fan-out coupling (efferent coupling)
15455 @cindex fan-out coupling
15456 @cindex efferent coupling
15457 the number of entities the given entity depends upon. It
15458 estimates in what extent the given entity depends on the changes in
15459 ``external world''
15461 @item fan-in coupling (afferent coupling)
15462 @cindex fan-in coupling
15463 @cindex afferent coupling
15464 the number of entities that depend on a given entity.
15465 It estimates in what extent the ``external world'' depends on the changes in a
15466 given entity
15467 @end table
15469 @noindent
15471 Object-oriented coupling metrics are metrics that measure the dependencies
15472 between a given class (or a group of classes) and the other classes in the
15473 program. In this subsection the term ``class'' is used in its traditional
15474 object-oriented programming sense (an instantiable module that contains data
15475 and/or method members). A @emph{category} (of classes) is a group of closely
15476 related classes that are reused and/or modified together.
15478 A class @code{K}'s fan-out coupling is the number of classes
15479 that @code{K} depends upon.
15480 A category's fan-out coupling is the number of classes outside the
15481 category that the classes inside the category depend upon.
15483 A class @code{K}'s fan-in coupling is the number of classes
15484 that depend upon @code{K}.
15485 A category's fan-in coupling is the number of classes outside the
15486 category that depend on classes belonging to the category.
15488 Ada's implementation of the object-oriented paradigm does not use the
15489 traditional class notion, so the definition of the coupling
15490 metrics for Ada maps the class and class category notions
15491 onto Ada constructs.
15493 For the coupling metrics, several kinds of modules -- a library package,
15494 a library generic package, and a library generic package instantiation --
15495 that define a tagged type or an interface type are
15496 considered to be a class. A category consists of a library package (or
15497 a library generic package) that defines a tagged or an interface type,
15498 together with all its descendant (generic) packages that define tagged
15499 or interface types. That is a
15500 category is an Ada hierarchy of library-level program units. So class coupling
15501 in case of Ada is called as tagged coupling, and category coupling - as
15502 hierarchy coupling.
15504 For any package counted as a class, its body and subunits (if any) are
15505 considered together with its spec when counting the dependencies, and coupling
15506 metrics are reported for spec units only. For dependencies between classes,
15507 the Ada semantic dependencies are considered. For object-oriented coupling
15508 metrics, only dependencies on units that are considered as classes, are
15509 considered.
15511 For unit and control coupling also not compilation units but program units are
15512 counted. That is, for a package, its spec, its body and its subunits (if any)
15513 are considered as making up one unit, and the dependencies that are counted
15514 are the dependencies of all these compilation units collected together as
15515 the dependencies as a (whole) unit. And metrics are reported for spec
15516 compilation units only (or for a subprogram body unit in case if there is no
15517 separate spec for the given subprogram).
15519 For unit coupling, dependencies between all kinds of program units are
15520 considered. For control coupling, for each unit the dependencies of this unit
15521 upon units that define subprograms are counted, so control fan-out coupling
15522 is reported for all units, but control fan-in coupling - only for the units
15523 that define subprograms.
15525 The following simple example illustrates the difference between unit coupling
15526 and control coupling metrics:
15528 @smallexample @c ada
15529 package Lib_1 is
15530     function F_1 (I : Integer) return Integer;
15531 end Lib_1;
15533 package Lib_2 is
15534     type T_2 is new Integer;
15535 end Lib_2;
15537 package body Lib_1 is
15538     function F_1 (I : Integer) return Integer is
15539     begin
15540        return I + 1;
15541     end F_1;
15542 end Lib_1;
15544 with Lib_2; use Lib_2;
15545 package Pack is
15546     Var : T_2;
15547     function Fun (I : Integer) return Integer;
15548 end Pack;
15550 with Lib_1; use Lib_1;
15551 package body Pack is
15552     function Fun (I : Integer) return Integer is
15553     begin
15554        return F_1 (I);
15555     end Fun;
15556 end Pack;
15557 @end smallexample
15559 @noindent
15560 if we apply @command{gnatmetric} with @code{--coupling-all} option to these
15561 units, the result will be:
15563 @smallexample
15564 Coupling metrics:
15565 =================
15566     Unit Lib_1 (C:\customers\662\L406-007\lib_1.ads)
15567        control fan-out coupling  : 0
15568        control fan-in coupling   : 1
15569        unit fan-out coupling     : 0
15570        unit fan-in coupling      : 1
15572     Unit Pack (C:\customers\662\L406-007\pack.ads)
15573        control fan-out coupling  : 1
15574        control fan-in coupling   : 0
15575        unit fan-out coupling     : 2
15576        unit fan-in coupling      : 0
15578     Unit Lib_2 (C:\customers\662\L406-007\lib_2.ads)
15579        control fan-out coupling  : 0
15580        unit fan-out coupling     : 0
15581        unit fan-in coupling      : 1
15582 @end smallexample
15584 @noindent
15585 The result does not contain values for object-oriented
15586 coupling because none of the argument unit contains a tagged type and
15587 therefore none of these units can be treated as a class.
15589 @code{Pack} (considered as a program unit, that is spec+body) depends on two
15590 units - @code{Lib_1} @code{and Lib_2}, therefore it has unit fan-out coupling
15591 equals to 2. And nothing depend on it, so its unit fan-in coupling is 0 as
15592 well as control fan-in coupling. Only one of the units @code{Pack} depends
15593 upon defines a subprogram, so its control fan-out coupling is 1.
15595 @code{Lib_2} depends on nothing, so fan-out metrics for it are 0. It does
15596 not define a subprogram, so control fan-in metric cannot be applied to it,
15597 and there is one unit that depends on it (@code{Pack}), so it has
15598 unit fan-in coupling equals to 1.
15600 @code{Lib_1} is similar to @code{Lib_2}, but it does define a subprogram.
15601 So it has control fan-in coupling equals to 1 (because there is a unit
15602 depending on it).
15604 When computing coupling metrics, @command{gnatmetric} counts only
15605 dependencies between units that are arguments of the @command{gnatmetric}
15606 call. Coupling metrics are program-wide (or project-wide) metrics, so to
15607 get a valid result, you should call @command{gnatmetric} for
15608 the whole set of sources that make up your program. It can be done
15609 by calling @command{gnatmetric} from the GNAT driver with @option{-U}
15610 option (see @ref{The GNAT Driver and Project Files} for details).
15612 By default, all the coupling metrics are disabled. You can use the following
15613 switches to specify the coupling metrics to be computed and reported:
15615 @table @option
15617 @ifclear vms
15618 @cindex @option{--tagged-coupling@var{x}} (@command{gnatmetric})
15619 @cindex @option{--hierarchy-coupling@var{x}} (@command{gnatmetric})
15620 @cindex @option{--unit-coupling@var{x}} (@command{gnatmetric})
15621 @cindex @option{--control-coupling@var{x}} (@command{gnatmetric})
15622 @end ifclear
15624 @ifset vms
15625 @cindex @option{/COUPLING_METRICS} (@command{gnatmetric})
15626 @end ifset
15628 @item ^--coupling-all^/COUPLING_METRICS=ALL^
15629 Report all the coupling metrics
15631 @item ^--tagged-coupling-out^/COUPLING_METRICS=TAGGED_OUT^
15632 Report tagged (class) fan-out coupling
15634 @item ^--tagged-coupling-in^/COUPLING_METRICS=TAGGED_IN^
15635 Report tagged (class) fan-in coupling
15637 @item ^--hierarchy-coupling-out^/COUPLING_METRICS=HIERARCHY_OUT^
15638 Report hierarchy (category) fan-out coupling
15640 @item ^--hierarchy-coupling-in^/COUPLING_METRICS=HIERARCHY_IN^
15641 Report hierarchy (category) fan-in coupling
15643 @item ^--unit-coupling-out^/COUPLING_METRICS=UNIT_OUT^
15644 Report unit fan-out coupling
15646 @item ^--unit-coupling-in^/COUPLING_METRICS=UNIT_IN^
15647 Report unit fan-in coupling
15649 @item ^--control-coupling-out^/COUPLING_METRICS=CONTROL_OUT^
15650 Report control fan-out coupling
15652 @item ^--control-coupling-in^/COUPLING_METRICS=CONTROL_IN^
15653 Report control fan-in coupling
15654 @end table
15656 @node Other gnatmetric Switches
15657 @subsection Other @code{gnatmetric} Switches
15659 @noindent
15660 Additional @command{gnatmetric} switches are as follows:
15662 @table @option
15663 @item --version
15664 @cindex @option{--version} @command{gnatmetric}
15665 Display Copyright and version, then exit disregarding all other options.
15667 @item --help
15668 @cindex @option{--help} @command{gnatmetric}
15669 Display usage, then exit disregarding all other options.
15671 @item ^-files @var{filename}^/FILES=@var{filename}^
15672 @cindex @option{^-files^/FILES^} (@code{gnatmetric})
15673 Take the argument source files from the specified file. This file should be an
15674 ordinary text file containing file names separated by spaces or
15675 line breaks. You can use this switch more than once in the same call to
15676 @command{gnatmetric}. You also can combine this switch with
15677 an explicit list of files.
15679 @item ^-v^/VERBOSE^
15680 @cindex @option{^-v^/VERBOSE^} (@code{gnatmetric})
15681 Verbose mode;
15682 @command{gnatmetric} generates version information and then
15683 a trace of sources being processed.
15685 @item ^-q^/QUIET^
15686 @cindex @option{^-q^/QUIET^} (@code{gnatmetric})
15687 Quiet mode.
15688 @end table
15690 @node Generate project-wide metrics
15691 @subsection Generate project-wide metrics
15693 In order to compute metrics on all units of a given project, you can use
15694 the @command{gnat} driver along with the @option{-P} option:
15695 @smallexample
15696    gnat metric -Pproj
15697 @end smallexample
15699 @noindent
15700 If the project @code{proj} depends upon other projects, you can compute
15701 the metrics on the project closure using the @option{-U} option:
15702 @smallexample
15703    gnat metric -Pproj -U
15704 @end smallexample
15706 @noindent
15707 Finally, if not all the units are relevant to a particular main
15708 program in the project closure, you can generate metrics for the set
15709 of units needed to create a given main program (unit closure) using
15710 the @option{-U} option followed by the name of the main unit:
15711 @smallexample
15712    gnat metric -Pproj -U main
15713 @end smallexample
15716 @c ***********************************
15717 @node File Name Krunching with gnatkr
15718 @chapter File Name Krunching with @code{gnatkr}
15719 @findex gnatkr
15721 @noindent
15722 This chapter discusses the method used by the compiler to shorten
15723 the default file names chosen for Ada units so that they do not
15724 exceed the maximum length permitted. It also describes the
15725 @code{gnatkr} utility that can be used to determine the result of
15726 applying this shortening.
15727 @menu
15728 * About gnatkr::
15729 * Using gnatkr::
15730 * Krunching Method::
15731 * Examples of gnatkr Usage::
15732 @end menu
15734 @node About gnatkr
15735 @section About @code{gnatkr}
15737 @noindent
15738 The default file naming rule in GNAT
15739 is that the file name must be derived from
15740 the unit name. The exact default rule is as follows:
15741 @itemize @bullet
15742 @item
15743 Take the unit name and replace all dots by hyphens.
15744 @item
15745 If such a replacement occurs in the
15746 second character position of a name, and the first character is
15747 ^@samp{a}, @samp{g}, @samp{s}, or @samp{i}, ^@samp{A}, @samp{G}, @samp{S}, or @samp{I},^
15748 then replace the dot by the character
15749 ^@samp{~} (tilde)^@samp{$} (dollar sign)^
15750 instead of a minus.
15751 @end itemize
15752 The reason for this exception is to avoid clashes
15753 with the standard names for children of System, Ada, Interfaces,
15754 and GNAT, which use the prefixes
15755 ^@samp{s-}, @samp{a-}, @samp{i-}, and @samp{g-},^@samp{S-}, @samp{A-}, @samp{I-}, and @samp{G-},^
15756 respectively.
15758 The @option{^-gnatk^/FILE_NAME_MAX_LENGTH=^@var{nn}}
15759 switch of the compiler activates a ``krunching''
15760 circuit that limits file names to nn characters (where nn is a decimal
15761 integer). For example, using OpenVMS,
15762 where the maximum file name length is
15763 39, the value of nn is usually set to 39, but if you want to generate
15764 a set of files that would be usable if ported to a system with some
15765 different maximum file length, then a different value can be specified.
15766 The default value of 39 for OpenVMS need not be specified.
15768 The @code{gnatkr} utility can be used to determine the krunched name for
15769 a given file, when krunched to a specified maximum length.
15771 @node Using gnatkr
15772 @section Using @code{gnatkr}
15774 @noindent
15775 The @code{gnatkr} command has the form
15777 @ifclear vms
15778 @smallexample
15779 @c $ gnatkr @var{name} @ovar{length}
15780 @c Expanding @ovar macro inline (explanation in macro def comments)
15781 $ gnatkr @var{name} @r{[}@var{length}@r{]}
15782 @end smallexample
15783 @end ifclear
15785 @ifset vms
15786 @smallexample
15787 $ gnatkr @var{name} /COUNT=nn
15788 @end smallexample
15789 @end ifset
15791 @noindent
15792 @var{name} is the uncrunched file name, derived from the name of the unit
15793 in the standard manner described in the previous section (i.e., in particular
15794 all dots are replaced by hyphens). The file name may or may not have an
15795 extension (defined as a suffix of the form period followed by arbitrary
15796 characters other than period). If an extension is present then it will
15797 be preserved in the output. For example, when krunching @file{hellofile.ads}
15798 to eight characters, the result will be hellofil.ads.
15800 Note: for compatibility with previous versions of @code{gnatkr} dots may
15801 appear in the name instead of hyphens, but the last dot will always be
15802 taken as the start of an extension. So if @code{gnatkr} is given an argument
15803 such as @file{Hello.World.adb} it will be treated exactly as if the first
15804 period had been a hyphen, and for example krunching to eight characters
15805 gives the result @file{hellworl.adb}.
15807 Note that the result is always all lower case (except on OpenVMS where it is
15808 all upper case). Characters of the other case are folded as required.
15810 @var{length} represents the length of the krunched name. The default
15811 when no argument is given is ^8^39^ characters. A length of zero stands for
15812 unlimited, in other words do not chop except for system files where the
15813 implied crunching length is always eight characters.
15815 @noindent
15816 The output is the krunched name. The output has an extension only if the
15817 original argument was a file name with an extension.
15819 @node Krunching Method
15820 @section Krunching Method
15822 @noindent
15823 The initial file name is determined by the name of the unit that the file
15824 contains. The name is formed by taking the full expanded name of the
15825 unit and replacing the separating dots with hyphens and
15826 using ^lowercase^uppercase^
15827 for all letters, except that a hyphen in the second character position is
15828 replaced by a ^tilde^dollar sign^ if the first character is
15829 ^@samp{a}, @samp{i}, @samp{g}, or @samp{s}^@samp{A}, @samp{I}, @samp{G}, or @samp{S}^.
15830 The extension is @code{.ads} for a
15831 spec and @code{.adb} for a body.
15832 Krunching does not affect the extension, but the file name is shortened to
15833 the specified length by following these rules:
15835 @itemize @bullet
15836 @item
15837 The name is divided into segments separated by hyphens, tildes or
15838 underscores and all hyphens, tildes, and underscores are
15839 eliminated. If this leaves the name short enough, we are done.
15841 @item
15842 If the name is too long, the longest segment is located (left-most
15843 if there are two of equal length), and shortened by dropping
15844 its last character. This is repeated until the name is short enough.
15846 As an example, consider the krunching of @*@file{our-strings-wide_fixed.adb}
15847 to fit the name into 8 characters as required by some operating systems.
15849 @smallexample
15850 our-strings-wide_fixed 22
15851 our strings wide fixed 19
15852 our string  wide fixed 18
15853 our strin   wide fixed 17
15854 our stri    wide fixed 16
15855 our stri    wide fixe  15
15856 our str     wide fixe  14
15857 our str     wid  fixe  13
15858 our str     wid  fix   12
15859 ou  str     wid  fix   11
15860 ou  st      wid  fix   10
15861 ou  st      wi   fix   9
15862 ou  st      wi   fi    8
15863 Final file name: oustwifi.adb
15864 @end smallexample
15866 @item
15867 The file names for all predefined units are always krunched to eight
15868 characters. The krunching of these predefined units uses the following
15869 special prefix replacements:
15871 @table @file
15872 @item ada-
15873 replaced by @file{^a^A^-}
15875 @item gnat-
15876 replaced by @file{^g^G^-}
15878 @item interfaces-
15879 replaced by @file{^i^I^-}
15881 @item system-
15882 replaced by @file{^s^S^-}
15883 @end table
15885 These system files have a hyphen in the second character position. That
15886 is why normal user files replace such a character with a
15887 ^tilde^dollar sign^, to
15888 avoid confusion with system file names.
15890 As an example of this special rule, consider
15891 @*@file{ada-strings-wide_fixed.adb}, which gets krunched as follows:
15893 @smallexample
15894 ada-strings-wide_fixed 22
15895 a-  strings wide fixed 18
15896 a-  string  wide fixed 17
15897 a-  strin   wide fixed 16
15898 a-  stri    wide fixed 15
15899 a-  stri    wide fixe  14
15900 a-  str     wide fixe  13
15901 a-  str     wid  fixe  12
15902 a-  str     wid  fix   11
15903 a-  st      wid  fix   10
15904 a-  st      wi   fix   9
15905 a-  st      wi   fi    8
15906 Final file name: a-stwifi.adb
15907 @end smallexample
15908 @end itemize
15910 Of course no file shortening algorithm can guarantee uniqueness over all
15911 possible unit names, and if file name krunching is used then it is your
15912 responsibility to ensure that no name clashes occur. The utility
15913 program @code{gnatkr} is supplied for conveniently determining the
15914 krunched name of a file.
15916 @node Examples of gnatkr Usage
15917 @section Examples of @code{gnatkr} Usage
15919 @smallexample
15920 @iftex
15921 @leftskip=0cm
15922 @end iftex
15923 @ifclear vms
15924 $ gnatkr very_long_unit_name.ads      --> velounna.ads
15925 $ gnatkr grandparent-parent-child.ads --> grparchi.ads
15926 $ gnatkr Grandparent.Parent.Child.ads --> grparchi.ads
15927 $ gnatkr grandparent-parent-child     --> grparchi
15928 @end ifclear
15929 $ gnatkr very_long_unit_name.ads/count=6 --> vlunna.ads
15930 $ gnatkr very_long_unit_name.ads/count=0 --> very_long_unit_name.ads
15931 @end smallexample
15933 @node Preprocessing with gnatprep
15934 @chapter Preprocessing with @code{gnatprep}
15935 @findex gnatprep
15937 @noindent
15938 This chapter discusses how to use GNAT's @code{gnatprep} utility for simple
15939 preprocessing.
15940 Although designed for use with GNAT, @code{gnatprep} does not depend on any
15941 special GNAT features.
15942 For further discussion of conditional compilation in general, see
15943 @ref{Conditional Compilation}.
15945 @menu
15946 * Preprocessing Symbols::
15947 * Using gnatprep::
15948 * Switches for gnatprep::
15949 * Form of Definitions File::
15950 * Form of Input Text for gnatprep::
15951 @end menu
15953 @node Preprocessing Symbols
15954 @section Preprocessing Symbols
15956 @noindent
15957 Preprocessing symbols are defined in definition files and referred to in
15958 sources to be preprocessed. A Preprocessing symbol is an identifier, following
15959 normal Ada (case-insensitive) rules for its syntax, with the restriction that
15960 all characters need to be in the ASCII set (no accented letters).
15962 @node Using gnatprep
15963 @section Using @code{gnatprep}
15965 @noindent
15966 To call @code{gnatprep} use
15968 @smallexample
15969 @c $ gnatprep @ovar{switches} @var{infile} @var{outfile} @ovar{deffile}
15970 @c Expanding @ovar macro inline (explanation in macro def comments)
15971 $ gnatprep @r{[}@var{switches}@r{]} @var{infile} @var{outfile} @r{[}@var{deffile}@r{]}
15972 @end smallexample
15974 @noindent
15975 where
15976 @table @var
15977 @item switches
15978 is an optional sequence of switches as described in the next section.
15980 @item infile
15981 is the full name of the input file, which is an Ada source
15982 file containing preprocessor directives.
15984 @item outfile
15985 is the full name of the output file, which is an Ada source
15986 in standard Ada form. When used with GNAT, this file name will
15987 normally have an ads or adb suffix.
15989 @item deffile
15990 is the full name of a text file containing definitions of
15991 preprocessing symbols to be referenced by the preprocessor. This argument is
15992 optional, and can be replaced by the use of the @option{-D} switch.
15994 @end table
15996 @node Switches for gnatprep
15997 @section Switches for @code{gnatprep}
15999 @table @option
16000 @c !sort!
16002 @item ^-b^/BLANK_LINES^
16003 @cindex @option{^-b^/BLANK_LINES^} (@command{gnatprep})
16004 Causes both preprocessor lines and the lines deleted by
16005 preprocessing to be replaced by blank lines in the output source file,
16006 preserving line numbers in the output file.
16008 @item ^-c^/COMMENTS^
16009 @cindex @option{^-c^/COMMENTS^} (@command{gnatprep})
16010 Causes both preprocessor lines and the lines deleted
16011 by preprocessing to be retained in the output source as comments marked
16012 with the special string @code{"--! "}. This option will result in line numbers
16013 being preserved in the output file.
16015 @item ^-C^/REPLACE_IN_COMMENTS^
16016 @cindex @option{^-C^/REPLACE_IN_COMMENTS^} (@command{gnatprep})
16017 Causes comments to be scanned. Normally comments are ignored by gnatprep.
16018 If this option is specified, then comments are scanned and any $symbol
16019 substitutions performed as in program text. This is particularly useful
16020 when structured comments are used (e.g., when writing programs in the
16021 SPARK dialect of Ada). Note that this switch is not available when
16022 doing integrated preprocessing (it would be useless in this context
16023 since comments are ignored by the compiler in any case).
16025 @item ^-Dsymbol=value^/ASSOCIATE="symbol=value"^
16026 @cindex @option{^-D^/ASSOCIATE^} (@command{gnatprep})
16027 Defines a new preprocessing symbol, associated with value. If no value is given
16028 on the command line, then symbol is considered to be @code{True}. This switch
16029 can be used in place of a definition file.
16031 @ifset vms
16032 @item /REMOVE
16033 @cindex @option{/REMOVE} (@command{gnatprep})
16034 This is the default setting which causes lines deleted by preprocessing
16035 to be entirely removed from the output file.
16036 @end ifset
16038 @item ^-r^/REFERENCE^
16039 @cindex @option{^-r^/REFERENCE^} (@command{gnatprep})
16040 Causes a @code{Source_Reference} pragma to be generated that
16041 references the original input file, so that error messages will use
16042 the file name of this original file. The use of this switch implies
16043 that preprocessor lines are not to be removed from the file, so its
16044 use will force @option{^-b^/BLANK_LINES^} mode if
16045 @option{^-c^/COMMENTS^}
16046 has not been specified explicitly.
16048 Note that if the file to be preprocessed contains multiple units, then
16049 it will be necessary to @code{gnatchop} the output file from
16050 @code{gnatprep}. If a @code{Source_Reference} pragma is present
16051 in the preprocessed file, it will be respected by
16052 @code{gnatchop ^-r^/REFERENCE^}
16053 so that the final chopped files will correctly refer to the original
16054 input source file for @code{gnatprep}.
16056 @item ^-s^/SYMBOLS^
16057 @cindex @option{^-s^/SYMBOLS^} (@command{gnatprep})
16058 Causes a sorted list of symbol names and values to be
16059 listed on the standard output file.
16061 @item ^-u^/UNDEFINED^
16062 @cindex @option{^-u^/UNDEFINED^} (@command{gnatprep})
16063 Causes undefined symbols to be treated as having the value FALSE in the context
16064 of a preprocessor test. In the absence of this option, an undefined symbol in
16065 a @code{#if} or @code{#elsif} test will be treated as an error.
16067 @end table
16069 @ifclear vms
16070 @noindent
16071 Note: if neither @option{-b} nor @option{-c} is present,
16072 then preprocessor lines and
16073 deleted lines are completely removed from the output, unless -r is
16074 specified, in which case -b is assumed.
16075 @end ifclear
16077 @node Form of Definitions File
16078 @section Form of Definitions File
16080 @noindent
16081 The definitions file contains lines of the form
16083 @smallexample
16084 symbol := value
16085 @end smallexample
16087 @noindent
16088 where symbol is a preprocessing symbol, and value is one of the following:
16090 @itemize @bullet
16091 @item
16092 Empty, corresponding to a null substitution
16093 @item
16094 A string literal using normal Ada syntax
16095 @item
16096 Any sequence of characters from the set
16097 (letters, digits, period, underline).
16098 @end itemize
16100 @noindent
16101 Comment lines may also appear in the definitions file, starting with
16102 the usual @code{--},
16103 and comments may be added to the definitions lines.
16105 @node Form of Input Text for gnatprep
16106 @section Form of Input Text for @code{gnatprep}
16108 @noindent
16109 The input text may contain preprocessor conditional inclusion lines,
16110 as well as general symbol substitution sequences.
16112 The preprocessor conditional inclusion commands have the form
16114 @smallexample
16115 @group
16116 @cartouche
16117 #if @i{expression} @r{[}then@r{]}
16118    lines
16119 #elsif @i{expression} @r{[}then@r{]}
16120    lines
16121 #elsif @i{expression} @r{[}then@r{]}
16122    lines
16123 @dots{}
16124 #else
16125    lines
16126 #end if;
16127 @end cartouche
16128 @end group
16129 @end smallexample
16131 @noindent
16132 In this example, @i{expression} is defined by the following grammar:
16133 @smallexample
16134 @i{expression} ::=  <symbol>
16135 @i{expression} ::=  <symbol> = "<value>"
16136 @i{expression} ::=  <symbol> = <symbol>
16137 @i{expression} ::=  <symbol> 'Defined
16138 @i{expression} ::=  not @i{expression}
16139 @i{expression} ::=  @i{expression} and @i{expression}
16140 @i{expression} ::=  @i{expression} or @i{expression}
16141 @i{expression} ::=  @i{expression} and then @i{expression}
16142 @i{expression} ::=  @i{expression} or else @i{expression}
16143 @i{expression} ::=  ( @i{expression} )
16144 @end smallexample
16146 The following restriction exists: it is not allowed to have "and" or "or"
16147 following "not" in the same expression without parentheses. For example, this
16148 is not allowed:
16150 @smallexample
16151    not X or Y
16152 @end smallexample
16154 This should be one of the following:
16156 @smallexample
16157    (not X) or Y
16158    not (X or Y)
16159 @end smallexample
16161 @noindent
16162 For the first test (@i{expression} ::= <symbol>) the symbol must have
16163 either the value true or false, that is to say the right-hand of the
16164 symbol definition must be one of the (case-insensitive) literals
16165 @code{True} or @code{False}. If the value is true, then the
16166 corresponding lines are included, and if the value is false, they are
16167 excluded.
16169 The test (@i{expression} ::= <symbol> @code{'Defined}) is true only if
16170 the symbol has been defined in the definition file or by a @option{-D}
16171 switch on the command line. Otherwise, the test is false.
16173 The equality tests are case insensitive, as are all the preprocessor lines.
16175 If the symbol referenced is not defined in the symbol definitions file,
16176 then the effect depends on whether or not switch @option{-u}
16177 is specified. If so, then the symbol is treated as if it had the value
16178 false and the test fails. If this switch is not specified, then
16179 it is an error to reference an undefined symbol. It is also an error to
16180 reference a symbol that is defined with a value other than @code{True}
16181 or @code{False}.
16183 The use of the @code{not} operator inverts the sense of this logical test.
16184 The @code{not} operator cannot be combined with the @code{or} or @code{and}
16185 operators, without parentheses. For example, "if not X or Y then" is not
16186 allowed, but "if (not X) or Y then" and "if not (X or Y) then" are.
16188 The @code{then} keyword is optional as shown
16190 The @code{#} must be the first non-blank character on a line, but
16191 otherwise the format is free form. Spaces or tabs may appear between
16192 the @code{#} and the keyword. The keywords and the symbols are case
16193 insensitive as in normal Ada code. Comments may be used on a
16194 preprocessor line, but other than that, no other tokens may appear on a
16195 preprocessor line. Any number of @code{elsif} clauses can be present,
16196 including none at all. The @code{else} is optional, as in Ada.
16198 The @code{#} marking the start of a preprocessor line must be the first
16199 non-blank character on the line, i.e., it must be preceded only by
16200 spaces or horizontal tabs.
16202 Symbol substitution outside of preprocessor lines is obtained by using
16203 the sequence
16205 @smallexample
16206 $symbol
16207 @end smallexample
16209 @noindent
16210 anywhere within a source line, except in a comment or within a
16211 string literal. The identifier
16212 following the @code{$} must match one of the symbols defined in the symbol
16213 definition file, and the result is to substitute the value of the
16214 symbol in place of @code{$symbol} in the output file.
16216 Note that although the substitution of strings within a string literal
16217 is not possible, it is possible to have a symbol whose defined value is
16218 a string literal. So instead of setting XYZ to @code{hello} and writing:
16220 @smallexample
16221 Header : String := "$XYZ";
16222 @end smallexample
16224 @noindent
16225 you should set XYZ to @code{"hello"} and write:
16227 @smallexample
16228 Header : String := $XYZ;
16229 @end smallexample
16231 @noindent
16232 and then the substitution will occur as desired.
16234 @node The GNAT Library Browser gnatls
16235 @chapter The GNAT Library Browser @code{gnatls}
16236 @findex gnatls
16237 @cindex Library browser
16239 @noindent
16240 @code{gnatls} is a tool that outputs information about compiled
16241 units. It gives the relationship between objects, unit names and source
16242 files. It can also be used to check the source dependencies of a unit
16243 as well as various characteristics.
16245 Note: to invoke @code{gnatls} with a project file, use the @code{gnat}
16246 driver (see @ref{The GNAT Driver and Project Files}).
16248 @menu
16249 * Running gnatls::
16250 * Switches for gnatls::
16251 * Examples of gnatls Usage::
16252 @end menu
16254 @node Running gnatls
16255 @section Running @code{gnatls}
16257 @noindent
16258 The @code{gnatls} command has the form
16260 @smallexample
16261 $ gnatls switches @var{object_or_ali_file}
16262 @end smallexample
16264 @noindent
16265 The main argument is the list of object or @file{ali} files
16266 (@pxref{The Ada Library Information Files})
16267 for which information is requested.
16269 In normal mode, without additional option, @code{gnatls} produces a
16270 four-column listing. Each line represents information for a specific
16271 object. The first column gives the full path of the object, the second
16272 column gives the name of the principal unit in this object, the third
16273 column gives the status of the source and the fourth column gives the
16274 full path of the source representing this unit.
16275 Here is a simple example of use:
16277 @smallexample
16278 $ gnatls *.o
16279 ^./^[]^demo1.o            demo1            DIF demo1.adb
16280 ^./^[]^demo2.o            demo2             OK demo2.adb
16281 ^./^[]^hello.o            h1                OK hello.adb
16282 ^./^[]^instr-child.o      instr.child      MOK instr-child.adb
16283 ^./^[]^instr.o            instr             OK instr.adb
16284 ^./^[]^tef.o              tef              DIF tef.adb
16285 ^./^[]^text_io_example.o  text_io_example   OK text_io_example.adb
16286 ^./^[]^tgef.o             tgef             DIF tgef.adb
16287 @end smallexample
16289 @noindent
16290 The first line can be interpreted as follows: the main unit which is
16291 contained in
16292 object file @file{demo1.o} is demo1, whose main source is in
16293 @file{demo1.adb}. Furthermore, the version of the source used for the
16294 compilation of demo1 has been modified (DIF). Each source file has a status
16295 qualifier which can be:
16297 @table @code
16298 @item OK (unchanged)
16299 The version of the source file used for the compilation of the
16300 specified unit corresponds exactly to the actual source file.
16302 @item MOK (slightly modified)
16303 The version of the source file used for the compilation of the
16304 specified unit differs from the actual source file but not enough to
16305 require recompilation. If you use gnatmake with the qualifier
16306 @option{^-m (minimal recompilation)^/MINIMAL_RECOMPILATION^}, a file marked
16307 MOK will not be recompiled.
16309 @item DIF (modified)
16310 No version of the source found on the path corresponds to the source
16311 used to build this object.
16313 @item ??? (file not found)
16314 No source file was found for this unit.
16316 @item HID (hidden,  unchanged version not first on PATH)
16317 The version of the source that corresponds exactly to the source used
16318 for compilation has been found on the path but it is hidden by another
16319 version of the same source that has been modified.
16321 @end table
16323 @node Switches for gnatls
16324 @section Switches for @code{gnatls}
16326 @noindent
16327 @code{gnatls} recognizes the following switches:
16329 @table @option
16330 @c !sort!
16331 @cindex @option{--version} @command{gnatls}
16332 Display Copyright and version, then exit disregarding all other options.
16334 @item --help
16335 @cindex @option{--help} @command{gnatls}
16336 If @option{--version} was not used, display usage, then exit disregarding
16337 all other options.
16339 @item ^-a^/ALL_UNITS^
16340 @cindex @option{^-a^/ALL_UNITS^} (@code{gnatls})
16341 Consider all units, including those of the predefined Ada library.
16342 Especially useful with @option{^-d^/DEPENDENCIES^}.
16344 @item ^-d^/DEPENDENCIES^
16345 @cindex @option{^-d^/DEPENDENCIES^} (@code{gnatls})
16346 List sources from which specified units depend on.
16348 @item ^-h^/OUTPUT=OPTIONS^
16349 @cindex @option{^-h^/OUTPUT=OPTIONS^} (@code{gnatls})
16350 Output the list of options.
16352 @item ^-o^/OUTPUT=OBJECTS^
16353 @cindex @option{^-o^/OUTPUT=OBJECTS^} (@code{gnatls})
16354 Only output information about object files.
16356 @item ^-s^/OUTPUT=SOURCES^
16357 @cindex @option{^-s^/OUTPUT=SOURCES^} (@code{gnatls})
16358 Only output information about source files.
16360 @item ^-u^/OUTPUT=UNITS^
16361 @cindex @option{^-u^/OUTPUT=UNITS^} (@code{gnatls})
16362 Only output information about compilation units.
16364 @item ^-files^/FILES^=@var{file}
16365 @cindex @option{^-files^/FILES^} (@code{gnatls})
16366 Take as arguments the files listed in text file @var{file}.
16367 Text file @var{file} may contain empty lines that are ignored.
16368 Each nonempty line should contain the name of an existing file.
16369 Several such switches may be specified simultaneously.
16371 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
16372 @itemx ^-aI^/SOURCE_SEARCH=^@var{dir}
16373 @itemx ^-I^/SEARCH=^@var{dir}
16374 @itemx  ^-I-^/NOCURRENT_DIRECTORY^
16375 @itemx -nostdinc
16376 @cindex @option{^-aO^/OBJECT_SEARCH^} (@code{gnatls})
16377 @cindex @option{^-aI^/SOURCE_SEARCH^} (@code{gnatls})
16378 @cindex @option{^-I^/SEARCH^} (@code{gnatls})
16379 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatls})
16380 Source path manipulation. Same meaning as the equivalent @command{gnatmake}
16381 flags (@pxref{Switches for gnatmake}).
16383 @item ^-aP^/ADD_PROJECT_SEARCH_DIR=^@var{dir}
16384 @cindex @option{^-aP^/ADD_PROJECT_SEARCH_DIR=^} (@code{gnatls})
16385 Add @var{dir} at the beginning of the project search dir.
16387 @item --RTS=@var{rts-path}
16388 @cindex @option{--RTS} (@code{gnatls})
16389 Specifies the default location of the runtime library. Same meaning as the
16390 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
16392 @item ^-v^/OUTPUT=VERBOSE^
16393 @cindex @option{^-v^/OUTPUT=VERBOSE^} (@code{gnatls})
16394 Verbose mode. Output the complete source, object and project paths. Do not use
16395 the default column layout but instead use long format giving as much as
16396 information possible on each requested units, including special
16397 characteristics such as:
16399 @table @code
16400 @item  Preelaborable
16401 The unit is preelaborable in the Ada sense.
16403 @item No_Elab_Code
16404 No elaboration code has been produced by the compiler for this unit.
16406 @item Pure
16407 The unit is pure in the Ada sense.
16409 @item Elaborate_Body
16410 The unit contains a pragma Elaborate_Body.
16412 @item Remote_Types
16413 The unit contains a pragma Remote_Types.
16415 @item Shared_Passive
16416 The unit contains a pragma Shared_Passive.
16418 @item Predefined
16419 This unit is part of the predefined environment and cannot be modified
16420 by the user.
16422 @item Remote_Call_Interface
16423 The unit contains a pragma Remote_Call_Interface.
16425 @end table
16427 @end table
16429 @node Examples of gnatls Usage
16430 @section Example of @code{gnatls} Usage
16431 @ifclear vms
16433 @noindent
16434 Example of using the verbose switch. Note how the source and
16435 object paths are affected by the -I switch.
16437 @smallexample
16438 $ gnatls -v -I.. demo1.o
16440 GNATLS 5.03w (20041123-34)
16441 Copyright 1997-2004 Free Software Foundation, Inc.
16443 Source Search Path:
16444    <Current_Directory>
16445    ../
16446    /home/comar/local/adainclude/
16448 Object Search Path:
16449    <Current_Directory>
16450    ../
16451    /home/comar/local/lib/gcc-lib/x86-linux/3.4.3/adalib/
16453 Project Search Path:
16454    <Current_Directory>
16455    /home/comar/local/lib/gnat/
16457 ./demo1.o
16458    Unit =>
16459      Name   => demo1
16460      Kind   => subprogram body
16461      Flags  => No_Elab_Code
16462      Source => demo1.adb    modified
16463 @end smallexample
16465 @noindent
16466 The following is an example of use of the dependency list.
16467 Note the use of the -s switch
16468 which gives a straight list of source files. This can be useful for
16469 building specialized scripts.
16471 @smallexample
16472 $ gnatls -d demo2.o
16473 ./demo2.o   demo2        OK demo2.adb
16474                          OK gen_list.ads
16475                          OK gen_list.adb
16476                          OK instr.ads
16477                          OK instr-child.ads
16479 $ gnatls -d -s -a demo1.o
16480 demo1.adb
16481 /home/comar/local/adainclude/ada.ads
16482 /home/comar/local/adainclude/a-finali.ads
16483 /home/comar/local/adainclude/a-filico.ads
16484 /home/comar/local/adainclude/a-stream.ads
16485 /home/comar/local/adainclude/a-tags.ads
16486 gen_list.ads
16487 gen_list.adb
16488 /home/comar/local/adainclude/gnat.ads
16489 /home/comar/local/adainclude/g-io.ads
16490 instr.ads
16491 /home/comar/local/adainclude/system.ads
16492 /home/comar/local/adainclude/s-exctab.ads
16493 /home/comar/local/adainclude/s-finimp.ads
16494 /home/comar/local/adainclude/s-finroo.ads
16495 /home/comar/local/adainclude/s-secsta.ads
16496 /home/comar/local/adainclude/s-stalib.ads
16497 /home/comar/local/adainclude/s-stoele.ads
16498 /home/comar/local/adainclude/s-stratt.ads
16499 /home/comar/local/adainclude/s-tasoli.ads
16500 /home/comar/local/adainclude/s-unstyp.ads
16501 /home/comar/local/adainclude/unchconv.ads
16502 @end smallexample
16503 @end ifclear
16505 @ifset vms
16506 @smallexample
16507 GNAT LIST /DEPENDENCIES /OUTPUT=SOURCES /ALL_UNITS DEMO1.ADB
16509 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]ada.ads
16510 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-finali.ads
16511 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-filico.ads
16512 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-stream.ads
16513 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-tags.ads
16514 demo1.adb
16515 gen_list.ads
16516 gen_list.adb
16517 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]gnat.ads
16518 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]g-io.ads
16519 instr.ads
16520 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]system.ads
16521 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-exctab.ads
16522 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-finimp.ads
16523 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-finroo.ads
16524 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-secsta.ads
16525 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stalib.ads
16526 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stoele.ads
16527 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stratt.ads
16528 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-tasoli.ads
16529 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-unstyp.ads
16530 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]unchconv.ads
16531 @end smallexample
16532 @end ifset
16534 @node Cleaning Up with gnatclean
16535 @chapter Cleaning Up with @code{gnatclean}
16536 @findex gnatclean
16537 @cindex Cleaning tool
16539 @noindent
16540 @code{gnatclean} is a tool that allows the deletion of files produced by the
16541 compiler, binder and linker, including ALI files, object files, tree files,
16542 expanded source files, library files, interface copy source files, binder
16543 generated files and executable files.
16545 @menu
16546 * Running gnatclean::
16547 * Switches for gnatclean::
16548 @c * Examples of gnatclean Usage::
16549 @end menu
16551 @node Running gnatclean
16552 @section Running @code{gnatclean}
16554 @noindent
16555 The @code{gnatclean} command has the form:
16557 @smallexample
16558 $ gnatclean switches @var{names}
16559 @end smallexample
16561 @noindent
16562 @var{names} is a list of source file names. Suffixes @code{.^ads^ADS^} and
16563 @code{^adb^ADB^} may be omitted. If a project file is specified using switch
16564 @code{^-P^/PROJECT_FILE=^}, then @var{names} may be completely omitted.
16566 @noindent
16567 In normal mode, @code{gnatclean} delete the files produced by the compiler and,
16568 if switch @code{^-c^/COMPILER_FILES_ONLY^} is not specified, by the binder and
16569 the linker. In informative-only mode, specified by switch
16570 @code{^-n^/NODELETE^}, the list of files that would have been deleted in
16571 normal mode is listed, but no file is actually deleted.
16573 @node Switches for gnatclean
16574 @section Switches for @code{gnatclean}
16576 @noindent
16577 @code{gnatclean} recognizes the following switches:
16579 @table @option
16580 @c !sort!
16581 @cindex @option{--version} @command{gnatclean}
16582 Display Copyright and version, then exit disregarding all other options.
16584 @item --help
16585 @cindex @option{--help} @command{gnatclean}
16586 If @option{--version} was not used, display usage, then exit disregarding
16587 all other options.
16589 @item ^--subdirs^/SUBDIRS^=subdir
16590 Actual object directory of each project file is the subdirectory subdir of the
16591 object directory specified or defaulted in the project file.
16593 @item ^--unchecked-shared-lib-imports^/UNCHECKED_SHARED_LIB_IMPORTS^
16594 By default, shared library projects are not allowed to import static library
16595 projects. When this switch is used on the command line, this restriction is
16596 relaxed.
16598 @item ^-c^/COMPILER_FILES_ONLY^
16599 @cindex @option{^-c^/COMPILER_FILES_ONLY^} (@code{gnatclean})
16600 Only attempt to delete the files produced by the compiler, not those produced
16601 by the binder or the linker. The files that are not to be deleted are library
16602 files, interface copy files, binder generated files and executable files.
16604 @item ^-D ^/DIRECTORY_OBJECTS=^@var{dir}
16605 @cindex @option{^-D^/DIRECTORY_OBJECTS^} (@code{gnatclean})
16606 Indicate that ALI and object files should normally be found in directory
16607 @var{dir}.
16609 @item ^-F^/FULL_PATH_IN_BRIEF_MESSAGES^
16610 @cindex @option{^-F^/FULL_PATH_IN_BRIEF_MESSAGES^} (@code{gnatclean})
16611 When using project files, if some errors or warnings are detected during
16612 parsing and verbose mode is not in effect (no use of switch
16613 ^-v^/VERBOSE^), then error lines start with the full path name of the project
16614 file, rather than its simple file name.
16616 @item ^-h^/HELP^
16617 @cindex @option{^-h^/HELP^} (@code{gnatclean})
16618 Output a message explaining the usage of @code{^gnatclean^gnatclean^}.
16620 @item ^-n^/NODELETE^
16621 @cindex @option{^-n^/NODELETE^} (@code{gnatclean})
16622 Informative-only mode. Do not delete any files. Output the list of the files
16623 that would have been deleted if this switch was not specified.
16625 @item ^-P^/PROJECT_FILE=^@var{project}
16626 @cindex @option{^-P^/PROJECT_FILE^} (@code{gnatclean})
16627 Use project file @var{project}. Only one such switch can be used.
16628 When cleaning a project file, the files produced by the compilation of the
16629 immediate sources or inherited sources of the project files are to be
16630 deleted. This is not depending on the presence or not of executable names
16631 on the command line.
16633 @item ^-q^/QUIET^
16634 @cindex @option{^-q^/QUIET^} (@code{gnatclean})
16635 Quiet output. If there are no errors, do not output anything, except in
16636 verbose mode (switch ^-v^/VERBOSE^) or in informative-only mode
16637 (switch ^-n^/NODELETE^).
16639 @item ^-r^/RECURSIVE^
16640 @cindex @option{^-r^/RECURSIVE^} (@code{gnatclean})
16641 When a project file is specified (using switch ^-P^/PROJECT_FILE=^),
16642 clean all imported and extended project files, recursively. If this switch
16643 is not specified, only the files related to the main project file are to be
16644 deleted. This switch has no effect if no project file is specified.
16646 @item ^-v^/VERBOSE^
16647 @cindex @option{^-v^/VERBOSE^} (@code{gnatclean})
16648 Verbose mode.
16650 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
16651 @cindex @option{^-vP^/MESSAGES_PROJECT_FILE^} (@code{gnatclean})
16652 Indicates the verbosity of the parsing of GNAT project files.
16653 @xref{Switches Related to Project Files}.
16655 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
16656 @cindex @option{^-X^/EXTERNAL_REFERENCE^} (@code{gnatclean})
16657 Indicates that external variable @var{name} has the value @var{value}.
16658 The Project Manager will use this value for occurrences of
16659 @code{external(name)} when parsing the project file.
16660 @xref{Switches Related to Project Files}.
16662 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
16663 @cindex @option{^-aO^/OBJECT_SEARCH^} (@code{gnatclean})
16664 When searching for ALI and object files, look in directory
16665 @var{dir}.
16667 @item ^-I^/SEARCH=^@var{dir}
16668 @cindex @option{^-I^/SEARCH^} (@code{gnatclean})
16669 Equivalent to @option{^-aO^/OBJECT_SEARCH=^@var{dir}}.
16671 @item ^-I-^/NOCURRENT_DIRECTORY^
16672 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatclean})
16673 @cindex Source files, suppressing search
16674 Do not look for ALI or object files in the directory
16675 where @code{gnatclean} was invoked.
16677 @end table
16679 @c @node Examples of gnatclean Usage
16680 @c @section Examples of @code{gnatclean} Usage
16682 @ifclear vms
16683 @node GNAT and Libraries
16684 @chapter GNAT and Libraries
16685 @cindex Library, building, installing, using
16687 @noindent
16688 This chapter describes how to build and use libraries with GNAT, and also shows
16689 how to recompile the GNAT run-time library. You should be familiar with the
16690 Project Manager facility (@pxref{GNAT Project Manager}) before reading this
16691 chapter.
16693 @menu
16694 * Introduction to Libraries in GNAT::
16695 * General Ada Libraries::
16696 * Stand-alone Ada Libraries::
16697 * Rebuilding the GNAT Run-Time Library::
16698 @end menu
16700 @node Introduction to Libraries in GNAT
16701 @section Introduction to Libraries in GNAT
16703 @noindent
16704 A library is, conceptually, a collection of objects which does not have its
16705 own main thread of execution, but rather provides certain services to the
16706 applications that use it. A library can be either statically linked with the
16707 application, in which case its code is directly included in the application,
16708 or, on platforms that support it, be dynamically linked, in which case
16709 its code is shared by all applications making use of this library.
16711 GNAT supports both types of libraries.
16712 In the static case, the compiled code can be provided in different ways. The
16713 simplest approach is to provide directly the set of objects resulting from
16714 compilation of the library source files. Alternatively, you can group the
16715 objects into an archive using whatever commands are provided by the operating
16716 system. For the latter case, the objects are grouped into a shared library.
16718 In the GNAT environment, a library has three types of components:
16719 @itemize @bullet
16720 @item
16721 Source files.
16722 @item
16723 @file{ALI} files.
16724 @xref{The Ada Library Information Files}.
16725 @item
16726 Object files, an archive or a shared library.
16727 @end itemize
16729 @noindent
16730 A GNAT library may expose all its source files, which is useful for
16731 documentation purposes. Alternatively, it may expose only the units needed by
16732 an external user to make use of the library. That is to say, the specs
16733 reflecting the library services along with all the units needed to compile
16734 those specs, which can include generic bodies or any body implementing an
16735 inlined routine. In the case of @emph{stand-alone libraries} those exposed
16736 units are called @emph{interface units} (@pxref{Stand-alone Ada Libraries}).
16738 All compilation units comprising an application, including those in a library,
16739 need to be elaborated in an order partially defined by Ada's semantics. GNAT
16740 computes the elaboration order from the @file{ALI} files and this is why they
16741 constitute a mandatory part of GNAT libraries.
16742 @emph{Stand-alone libraries} are the exception to this rule because a specific
16743 library elaboration routine is produced independently of the application(s)
16744 using the library.
16746 @node General Ada Libraries
16747 @section General Ada Libraries
16749 @menu
16750 * Building a library::
16751 * Installing a library::
16752 * Using a library::
16753 @end menu
16755 @node Building a library
16756 @subsection Building a library
16758 @noindent
16759 The easiest way to build a library is to use the Project Manager,
16760 which supports a special type of project called a @emph{Library Project}
16761 (@pxref{Library Projects}).
16763 A project is considered a library project, when two project-level attributes
16764 are defined in it: @code{Library_Name} and @code{Library_Dir}. In order to
16765 control different aspects of library configuration, additional optional
16766 project-level attributes can be specified:
16767 @table @code
16768 @item Library_Kind
16769 This attribute controls whether the library is to be static or dynamic
16771 @item Library_Version
16772 This attribute specifies the library version; this value is used
16773 during dynamic linking of shared libraries to determine if the currently
16774 installed versions of the binaries are compatible.
16776 @item Library_Options
16777 @item Library_GCC
16778 These attributes specify additional low-level options to be used during
16779 library generation, and redefine the actual application used to generate
16780 library.
16781 @end table
16783 @noindent
16784 The GNAT Project Manager takes full care of the library maintenance task,
16785 including recompilation of the source files for which objects do not exist
16786 or are not up to date, assembly of the library archive, and installation of
16787 the library (i.e., copying associated source, object and @file{ALI} files
16788 to the specified location).
16790 Here is a simple library project file:
16791 @smallexample @c ada
16792 project My_Lib is
16793    for Source_Dirs use ("src1", "src2");
16794    for Object_Dir use "obj";
16795    for Library_Name use "mylib";
16796    for Library_Dir use "lib";
16797    for Library_Kind use "dynamic";
16798 end My_lib;
16799 @end smallexample
16801 @noindent
16802 and the compilation command to build and install the library:
16804 @smallexample @c ada
16805   $ gnatmake -Pmy_lib
16806 @end smallexample
16808 @noindent
16809 It is not entirely trivial to perform manually all the steps required to
16810 produce a library. We recommend that you use the GNAT Project Manager
16811 for this task. In special cases where this is not desired, the necessary
16812 steps are discussed below.
16814 There are various possibilities for compiling the units that make up the
16815 library: for example with a Makefile (@pxref{Using the GNU make Utility}) or
16816 with a conventional script. For simple libraries, it is also possible to create
16817 a dummy main program which depends upon all the packages that comprise the
16818 interface of the library. This dummy main program can then be given to
16819 @command{gnatmake}, which will ensure that all necessary objects are built.
16821 After this task is accomplished, you should follow the standard procedure
16822 of the underlying operating system to produce the static or shared library.
16824 Here is an example of such a dummy program:
16825 @smallexample @c ada
16826 @group
16827 with My_Lib.Service1;
16828 with My_Lib.Service2;
16829 with My_Lib.Service3;
16830 procedure My_Lib_Dummy is
16831 begin
16832    null;
16833 end;
16834 @end group
16835 @end smallexample
16837 @noindent
16838 Here are the generic commands that will build an archive or a shared library.
16840 @smallexample
16841 # compiling the library
16842 $ gnatmake -c my_lib_dummy.adb
16844 # we don't need the dummy object itself
16845 $ rm my_lib_dummy.o my_lib_dummy.ali
16847 # create an archive with the remaining objects
16848 $ ar rc libmy_lib.a *.o
16849 # some systems may require "ranlib" to be run as well
16851 # or create a shared library
16852 $ gcc -shared -o libmy_lib.so *.o
16853 # some systems may require the code to have been compiled with -fPIC
16855 # remove the object files that are now in the library
16856 $ rm *.o
16858 # Make the ALI files read-only so that gnatmake will not try to
16859 # regenerate the objects that are in the library
16860 $ chmod -w *.ali
16861 @end smallexample
16863 @noindent
16864 Please note that the library must have a name of the form @file{lib@var{xxx}.a}
16865 or @file{lib@var{xxx}.so} (or @file{lib@var{xxx}.dll} on Windows) in order to
16866 be accessed by the directive @option{-l@var{xxx}} at link time.
16868 @node Installing a library
16869 @subsection Installing a library
16870 @cindex @code{ADA_PROJECT_PATH}
16871 @cindex @code{GPR_PROJECT_PATH}
16873 @noindent
16874 If you use project files, library installation is part of the library build
16875 process (@pxref{Installing a library with project files}).
16877 When project files are not an option, it is also possible, but not recommended,
16878 to install the library so that the sources needed to use the library are on the
16879 Ada source path and the ALI files & libraries be on the Ada Object path (see
16880 @ref{Search Paths and the Run-Time Library (RTL)}. Alternatively, the system
16881 administrator can place general-purpose libraries in the default compiler
16882 paths, by specifying the libraries' location in the configuration files
16883 @file{ada_source_path} and @file{ada_object_path}. These configuration files
16884 must be located in the GNAT installation tree at the same place as the gcc spec
16885 file. The location of the gcc spec file can be determined as follows:
16886 @smallexample
16887 $ gcc -v
16888 @end smallexample
16890 @noindent
16891 The configuration files mentioned above have a simple format: each line
16892 must contain one unique directory name.
16893 Those names are added to the corresponding path
16894 in their order of appearance in the file. The names can be either absolute
16895 or relative; in the latter case, they are relative to where theses files
16896 are located.
16898 The files @file{ada_source_path} and @file{ada_object_path} might not be
16899 present in a
16900 GNAT installation, in which case, GNAT will look for its run-time library in
16901 the directories @file{adainclude} (for the sources) and @file{adalib} (for the
16902 objects and @file{ALI} files). When the files exist, the compiler does not
16903 look in @file{adainclude} and @file{adalib}, and thus the
16904 @file{ada_source_path} file
16905 must contain the location for the GNAT run-time sources (which can simply
16906 be @file{adainclude}). In the same way, the @file{ada_object_path} file must
16907 contain the location for the GNAT run-time objects (which can simply
16908 be @file{adalib}).
16910 You can also specify a new default path to the run-time library at compilation
16911 time with the switch @option{--RTS=rts-path}. You can thus choose / change
16912 the run-time library you want your program to be compiled with. This switch is
16913 recognized by @command{gcc}, @command{gnatmake}, @command{gnatbind},
16914 @command{gnatls}, @command{gnatfind} and @command{gnatxref}.
16916 It is possible to install a library before or after the standard GNAT
16917 library, by reordering the lines in the configuration files. In general, a
16918 library must be installed before the GNAT library if it redefines
16919 any part of it.
16921 @node Using a library
16922 @subsection Using a library
16924 @noindent Once again, the project facility greatly simplifies the use of
16925 libraries. In this context, using a library is just a matter of adding a
16926 @code{with} clause in the user project. For instance, to make use of the
16927 library @code{My_Lib} shown in examples in earlier sections, you can
16928 write:
16930 @smallexample @c projectfile
16931 with "my_lib";
16932 project My_Proj is
16933   @dots{}
16934 end My_Proj;
16935 @end smallexample
16937 Even if you have a third-party, non-Ada library, you can still use GNAT's
16938 Project Manager facility to provide a wrapper for it. For example, the
16939 following project, when @code{with}ed by your main project, will link with the
16940 third-party library @file{liba.a}:
16942 @smallexample @c projectfile
16943 @group
16944 project Liba is
16945    for Externally_Built use "true";
16946    for Source_Files use ();
16947    for Library_Dir use "lib";
16948    for Library_Name use "a";
16949    for Library_Kind use "static";
16950 end Liba;
16951 @end group
16952 @end smallexample
16953 This is an alternative to the use of @code{pragma Linker_Options}. It is
16954 especially interesting in the context of systems with several interdependent
16955 static libraries where finding a proper linker order is not easy and best be
16956 left to the tools having visibility over project dependence information.
16958 @noindent
16959 In order to use an Ada library manually, you need to make sure that this
16960 library is on both your source and object path
16961 (see @ref{Search Paths and the Run-Time Library (RTL)}
16962 and @ref{Search Paths for gnatbind}). Furthermore, when the objects are grouped
16963 in an archive or a shared library, you need to specify the desired
16964 library at link time.
16966 For example, you can use the library @file{mylib} installed in
16967 @file{/dir/my_lib_src} and @file{/dir/my_lib_obj} with the following commands:
16969 @smallexample
16970 $ gnatmake -aI/dir/my_lib_src -aO/dir/my_lib_obj my_appl \
16971   -largs -lmy_lib
16972 @end smallexample
16974 @noindent
16975 This can be expressed more simply:
16976 @smallexample
16977 $ gnatmake my_appl
16978 @end smallexample
16979 @noindent
16980 when the following conditions are met:
16981 @itemize @bullet
16982 @item
16983 @file{/dir/my_lib_src} has been added by the user to the environment
16984 variable @env{ADA_INCLUDE_PATH}, or by the administrator to the file
16985 @file{ada_source_path}
16986 @item
16987 @file{/dir/my_lib_obj} has been added by the user to the environment
16988 variable @env{ADA_OBJECTS_PATH}, or by the administrator to the file
16989 @file{ada_object_path}
16990 @item
16991 a pragma @code{Linker_Options} has been added to one of the sources.
16992 For example:
16994 @smallexample @c ada
16995 pragma Linker_Options ("-lmy_lib");
16996 @end smallexample
16997 @end itemize
16999 @node Stand-alone Ada Libraries
17000 @section Stand-alone Ada Libraries
17001 @cindex Stand-alone library, building, using
17003 @menu
17004 * Introduction to Stand-alone Libraries::
17005 * Building a Stand-alone Library::
17006 * Creating a Stand-alone Library to be used in a non-Ada context::
17007 * Restrictions in Stand-alone Libraries::
17008 @end menu
17010 @node Introduction to Stand-alone Libraries
17011 @subsection Introduction to Stand-alone Libraries
17013 @noindent
17014 A Stand-alone Library (abbreviated ``SAL'') is a library that contains the
17015 necessary code to
17016 elaborate the Ada units that are included in the library. In contrast with
17017 an ordinary library, which consists of all sources, objects and @file{ALI}
17018 files of the
17019 library, a SAL may specify a restricted subset of compilation units
17020 to serve as a library interface. In this case, the fully
17021 self-sufficient set of files will normally consist of an objects
17022 archive, the sources of interface units' specs, and the @file{ALI}
17023 files of interface units.
17024 If an interface spec contains a generic unit or an inlined subprogram,
17025 the body's
17026 source must also be provided; if the units that must be provided in the source
17027 form depend on other units, the source and @file{ALI} files of those must
17028 also be provided.
17030 The main purpose of a SAL is to minimize the recompilation overhead of client
17031 applications when a new version of the library is installed. Specifically,
17032 if the interface sources have not changed, client applications do not need to
17033 be recompiled. If, furthermore, a SAL is provided in the shared form and its
17034 version, controlled by @code{Library_Version} attribute, is not changed,
17035 then the clients do not need to be relinked.
17037 SALs also allow the library providers to minimize the amount of library source
17038 text exposed to the clients.  Such ``information hiding'' might be useful or
17039 necessary for various reasons.
17041 Stand-alone libraries are also well suited to be used in an executable whose
17042 main routine is not written in Ada.
17044 @node Building a Stand-alone Library
17045 @subsection Building a Stand-alone Library
17047 @noindent
17048 GNAT's Project facility provides a simple way of building and installing
17049 stand-alone libraries; see @ref{Stand-alone Library Projects}.
17050 To be a Stand-alone Library Project, in addition to the two attributes
17051 that make a project a Library Project (@code{Library_Name} and
17052 @code{Library_Dir}; see @ref{Library Projects}), the attribute
17053 @code{Library_Interface} must be defined.  For example:
17055 @smallexample @c projectfile
17056 @group
17057    for Library_Dir use "lib_dir";
17058    for Library_Name use "dummy";
17059    for Library_Interface use ("int1", "int1.child");
17060 @end group
17061 @end smallexample
17063 @noindent
17064 Attribute @code{Library_Interface} has a non-empty string list value,
17065 each string in the list designating a unit contained in an immediate source
17066 of the project file.
17068 When a Stand-alone Library is built, first the binder is invoked to build
17069 a package whose name depends on the library name
17070 (@file{^b~dummy.ads/b^B$DUMMY.ADS/B^} in the example above).
17071 This binder-generated package includes initialization and
17072 finalization procedures whose
17073 names depend on the library name (@code{dummyinit} and @code{dummyfinal}
17074 in the example
17075 above). The object corresponding to this package is included in the library.
17077 You must ensure timely (e.g., prior to any use of interfaces in the SAL)
17078 calling of these procedures if a static SAL is built, or if a shared SAL
17079 is built
17080 with the project-level attribute @code{Library_Auto_Init} set to
17081 @code{"false"}.
17083 For a Stand-Alone Library, only the @file{ALI} files of the Interface Units
17084 (those that are listed in attribute @code{Library_Interface}) are copied to
17085 the Library Directory. As a consequence, only the Interface Units may be
17086 imported from Ada units outside of the library. If other units are imported,
17087 the binding phase will fail.
17089 @noindent
17090 It is also possible to build an encapsulated library where not only
17091 the code to elaborate and finalize the library is embedded but also
17092 ensuring that the library is linked only against static
17093 libraries. So an encapsulated library only depends on system
17094 libraries, all other code, including the GNAT runtime, is embedded. To
17095 build an encapsulated library the attribute
17096 @code{Library_Standalone} must be set to @code{encapsulated}:
17098 @smallexample @c projectfile
17099 @group
17100    for Library_Dir use "lib_dir";
17101    for Library_Name use "dummy";
17102    for Library_Kind use "dynamic";
17103    for Library_Interface use ("int1", "int1.child");
17104    for Library_Standalone use "encapsulated";
17105 @end group
17106 @end smallexample
17108 @noindent
17109 The default value for this attribute is @code{standard} in which case
17110 a stand-alone library is built.
17112 The attribute @code{Library_Src_Dir} may be specified for a
17113 Stand-Alone Library. @code{Library_Src_Dir} is a simple attribute that has a
17114 single string value. Its value must be the path (absolute or relative to the
17115 project directory) of an existing directory. This directory cannot be the
17116 object directory or one of the source directories, but it can be the same as
17117 the library directory. The sources of the Interface
17118 Units of the library that are needed by an Ada client of the library will be
17119 copied to the designated directory, called the Interface Copy directory.
17120 These sources include the specs of the Interface Units, but they may also
17121 include bodies and subunits, when pragmas @code{Inline} or @code{Inline_Always}
17122 are used, or when there is a generic unit in the spec. Before the sources
17123 are copied to the Interface Copy directory, an attempt is made to delete all
17124 files in the Interface Copy directory.
17126 Building stand-alone libraries by hand is somewhat tedious, but for those
17127 occasions when it is necessary here are the steps that you need to perform:
17128 @itemize @bullet
17129 @item
17130 Compile all library sources.
17132 @item
17133 Invoke the binder with the switch @option{-n} (No Ada main program),
17134 with all the @file{ALI} files of the interfaces, and
17135 with the switch @option{-L} to give specific names to the @code{init}
17136 and @code{final} procedures.  For example:
17137 @smallexample
17138   gnatbind -n int1.ali int2.ali -Lsal1
17139 @end smallexample
17141 @item
17142 Compile the binder generated file:
17143 @smallexample
17144   gcc -c b~int2.adb
17145 @end smallexample
17147 @item
17148 Link the dynamic library with all the necessary object files,
17149 indicating to the linker the names of the @code{init} (and possibly
17150 @code{final}) procedures for automatic initialization (and finalization).
17151 The built library should be placed in a directory different from
17152 the object directory.
17154 @item
17155 Copy the @code{ALI} files of the interface to the library directory,
17156 add in this copy an indication that it is an interface to a SAL
17157 (i.e., add a word @option{SL} on the line in the @file{ALI} file that starts
17158 with letter ``P'') and make the modified copy of the @file{ALI} file
17159 read-only.
17160 @end itemize
17162 @noindent
17163 Using SALs is not different from using other libraries
17164 (see @ref{Using a library}).
17166 @node Creating a Stand-alone Library to be used in a non-Ada context
17167 @subsection Creating a Stand-alone Library to be used in a non-Ada context
17169 @noindent
17170 It is easy to adapt the SAL build procedure discussed above for use of a SAL in
17171 a non-Ada context.
17173 The only extra step required is to ensure that library interface subprograms
17174 are compatible with the main program, by means of @code{pragma Export}
17175 or @code{pragma Convention}.
17177 Here is an example of simple library interface for use with C main program:
17179 @smallexample @c ada
17180 package My_Package is
17182    procedure Do_Something;
17183    pragma Export (C, Do_Something, "do_something");
17185    procedure Do_Something_Else;
17186    pragma Export (C, Do_Something_Else, "do_something_else");
17188 end My_Package;
17189 @end smallexample
17191 @noindent
17192 On the foreign language side, you must provide a ``foreign'' view of the
17193 library interface; remember that it should contain elaboration routines in
17194 addition to interface subprograms.
17196 The example below shows the content of @code{mylib_interface.h} (note
17197 that there is no rule for the naming of this file, any name can be used)
17198 @smallexample
17199 /* the library elaboration procedure */
17200 extern void mylibinit (void);
17202 /* the library finalization procedure */
17203 extern void mylibfinal (void);
17205 /* the interface exported by the library */
17206 extern void do_something (void);
17207 extern void do_something_else (void);
17208 @end smallexample
17210 @noindent
17211 Libraries built as explained above can be used from any program, provided
17212 that the elaboration procedures (named @code{mylibinit} in the previous
17213 example) are called before the library services are used. Any number of
17214 libraries can be used simultaneously, as long as the elaboration
17215 procedure of each library is called.
17217 Below is an example of a C program that uses the @code{mylib} library.
17219 @smallexample
17220 #include "mylib_interface.h"
17223 main (void)
17225    /* First, elaborate the library before using it */
17226    mylibinit ();
17228    /* Main program, using the library exported entities */
17229    do_something ();
17230    do_something_else ();
17232    /* Library finalization at the end of the program */
17233    mylibfinal ();
17234    return 0;
17236 @end smallexample
17238 @noindent
17239 Note that invoking any library finalization procedure generated by
17240 @code{gnatbind} shuts down the Ada run-time environment.
17241 Consequently, the
17242 finalization of all Ada libraries must be performed at the end of the program.
17243 No call to these libraries or to the Ada run-time library should be made
17244 after the finalization phase.
17246 @node Restrictions in Stand-alone Libraries
17247 @subsection Restrictions in Stand-alone Libraries
17249 @noindent
17250 The pragmas listed below should be used with caution inside libraries,
17251 as they can create incompatibilities with other Ada libraries:
17252 @itemize @bullet
17253 @item pragma @code{Locking_Policy}
17254 @item pragma @code{Partition_Elaboration_Policy}
17255 @item pragma @code{Queuing_Policy}
17256 @item pragma @code{Task_Dispatching_Policy}
17257 @item pragma @code{Unreserve_All_Interrupts}
17258 @end itemize
17260 @noindent
17261 When using a library that contains such pragmas, the user must make sure
17262 that all libraries use the same pragmas with the same values. Otherwise,
17263 @code{Program_Error} will
17264 be raised during the elaboration of the conflicting
17265 libraries. The usage of these pragmas and its consequences for the user
17266 should therefore be well documented.
17268 Similarly, the traceback in the exception occurrence mechanism should be
17269 enabled or disabled in a consistent manner across all libraries.
17270 Otherwise, Program_Error will be raised during the elaboration of the
17271 conflicting libraries.
17273 If the @code{Version} or @code{Body_Version}
17274 attributes are used inside a library, then you need to
17275 perform a @code{gnatbind} step that specifies all @file{ALI} files in all
17276 libraries, so that version identifiers can be properly computed.
17277 In practice these attributes are rarely used, so this is unlikely
17278 to be a consideration.
17280 @node  Rebuilding the GNAT Run-Time Library
17281 @section Rebuilding the GNAT Run-Time Library
17282 @cindex GNAT Run-Time Library, rebuilding
17283 @cindex Building the GNAT Run-Time Library
17284 @cindex Rebuilding the GNAT Run-Time Library
17285 @cindex Run-Time Library, rebuilding
17287 @noindent
17288 It may be useful to recompile the GNAT library in various contexts, the
17289 most important one being the use of partition-wide configuration pragmas
17290 such as @code{Normalize_Scalars}. A special Makefile called
17291 @code{Makefile.adalib} is provided to that effect and can be found in
17292 the directory containing the GNAT library. The location of this
17293 directory depends on the way the GNAT environment has been installed and can
17294 be determined by means of the command:
17296 @smallexample
17297 $ gnatls -v
17298 @end smallexample
17300 @noindent
17301 The last entry in the object search path usually contains the
17302 gnat library. This Makefile contains its own documentation and in
17303 particular the set of instructions needed to rebuild a new library and
17304 to use it.
17306 @node Using the GNU make Utility
17307 @chapter Using the GNU @code{make} Utility
17308 @findex make
17310 @noindent
17311 This chapter offers some examples of makefiles that solve specific
17312 problems. It does not explain how to write a makefile (@pxref{Top,, GNU
17313 make, make, GNU @code{make}}), nor does it try to replace the
17314 @command{gnatmake} utility (@pxref{The GNAT Make Program gnatmake}).
17316 All the examples in this section are specific to the GNU version of
17317 make. Although @command{make} is a standard utility, and the basic language
17318 is the same, these examples use some advanced features found only in
17319 @code{GNU make}.
17321 @menu
17322 * Using gnatmake in a Makefile::
17323 * Automatically Creating a List of Directories::
17324 * Generating the Command Line Switches::
17325 * Overcoming Command Line Length Limits::
17326 @end menu
17328 @node Using gnatmake in a Makefile
17329 @section Using gnatmake in a Makefile
17330 @findex makefile
17331 @cindex GNU make
17333 @noindent
17334 Complex project organizations can be handled in a very powerful way by
17335 using GNU make combined with gnatmake. For instance, here is a Makefile
17336 which allows you to build each subsystem of a big project into a separate
17337 shared library. Such a makefile allows you to significantly reduce the link
17338 time of very big applications while maintaining full coherence at
17339 each step of the build process.
17341 The list of dependencies are handled automatically by
17342 @command{gnatmake}. The Makefile is simply used to call gnatmake in each of
17343 the appropriate directories.
17345 Note that you should also read the example on how to automatically
17346 create the list of directories
17347 (@pxref{Automatically Creating a List of Directories})
17348 which might help you in case your project has a lot of subdirectories.
17350 @smallexample
17351 @iftex
17352 @leftskip=0cm
17353 @font@heightrm=cmr8
17354 @heightrm
17355 @end iftex
17356 ## This Makefile is intended to be used with the following directory
17357 ## configuration:
17358 ##  - The sources are split into a series of csc (computer software components)
17359 ##    Each of these csc is put in its own directory.
17360 ##    Their name are referenced by the directory names.
17361 ##    They will be compiled into shared library (although this would also work
17362 ##    with static libraries
17363 ##  - The main program (and possibly other packages that do not belong to any
17364 ##    csc is put in the top level directory (where the Makefile is).
17365 ##       toplevel_dir __ first_csc  (sources) __ lib (will contain the library)
17366 ##                    \_ second_csc (sources) __ lib (will contain the library)
17367 ##                    \_ @dots{}
17368 ## Although this Makefile is build for shared library, it is easy to modify
17369 ## to build partial link objects instead (modify the lines with -shared and
17370 ## gnatlink below)
17372 ## With this makefile, you can change any file in the system or add any new
17373 ## file, and everything will be recompiled correctly (only the relevant shared
17374 ## objects will be recompiled, and the main program will be re-linked).
17376 # The list of computer software component for your project. This might be
17377 # generated automatically.
17378 CSC_LIST=aa bb cc
17380 # Name of the main program (no extension)
17381 MAIN=main
17383 # If we need to build objects with -fPIC, uncomment the following line
17384 #NEED_FPIC=-fPIC
17386 # The following variable should give the directory containing libgnat.so
17387 # You can get this directory through 'gnatls -v'. This is usually the last
17388 # directory in the Object_Path.
17389 GLIB=@dots{}
17391 # The directories for the libraries
17392 # (This macro expands the list of CSC to the list of shared libraries, you
17393 # could simply use the expanded form:
17394 # LIB_DIR=aa/lib/libaa.so bb/lib/libbb.so cc/lib/libcc.so
17395 LIB_DIR=$@{foreach dir,$@{CSC_LIST@},$@{dir@}/lib/lib$@{dir@}.so@}
17397 $@{MAIN@}: objects $@{LIB_DIR@}
17398     gnatbind $@{MAIN@} $@{CSC_LIST:%=-aO%/lib@} -shared
17399     gnatlink $@{MAIN@} $@{CSC_LIST:%=-l%@}
17401 objects::
17402     # recompile the sources
17403     gnatmake -c -i $@{MAIN@}.adb $@{NEED_FPIC@} $@{CSC_LIST:%=-I%@}
17405 # Note: In a future version of GNAT, the following commands will be simplified
17406 # by a new tool, gnatmlib
17407 $@{LIB_DIR@}:
17408     mkdir -p $@{dir $@@ @}
17409     cd $@{dir $@@ @} && gcc -shared -o $@{notdir $@@ @} ../*.o -L$@{GLIB@} -lgnat
17410     cd $@{dir $@@ @} && cp -f ../*.ali .
17412 # The dependencies for the modules
17413 # Note that we have to force the expansion of *.o, since in some cases
17414 # make won't be able to do it itself.
17415 aa/lib/libaa.so: $@{wildcard aa/*.o@}
17416 bb/lib/libbb.so: $@{wildcard bb/*.o@}
17417 cc/lib/libcc.so: $@{wildcard cc/*.o@}
17419 # Make sure all of the shared libraries are in the path before starting the
17420 # program
17421 run::
17422     LD_LIBRARY_PATH=`pwd`/aa/lib:`pwd`/bb/lib:`pwd`/cc/lib ./$@{MAIN@}
17424 clean::
17425     $@{RM@} -rf $@{CSC_LIST:%=%/lib@}
17426     $@{RM@} $@{CSC_LIST:%=%/*.ali@}
17427     $@{RM@} $@{CSC_LIST:%=%/*.o@}
17428     $@{RM@} *.o *.ali $@{MAIN@}
17429 @end smallexample
17431 @node Automatically Creating a List of Directories
17432 @section Automatically Creating a List of Directories
17434 @noindent
17435 In most makefiles, you will have to specify a list of directories, and
17436 store it in a variable. For small projects, it is often easier to
17437 specify each of them by hand, since you then have full control over what
17438 is the proper order for these directories, which ones should be
17439 included.
17441 However, in larger projects, which might involve hundreds of
17442 subdirectories, it might be more convenient to generate this list
17443 automatically.
17445 The example below presents two methods. The first one, although less
17446 general, gives you more control over the list. It involves wildcard
17447 characters, that are automatically expanded by @command{make}. Its
17448 shortcoming is that you need to explicitly specify some of the
17449 organization of your project, such as for instance the directory tree
17450 depth, whether some directories are found in a separate tree, @enddots{}
17452 The second method is the most general one. It requires an external
17453 program, called @command{find}, which is standard on all Unix systems. All
17454 the directories found under a given root directory will be added to the
17455 list.
17457 @smallexample
17458 @iftex
17459 @leftskip=0cm
17460 @font@heightrm=cmr8
17461 @heightrm
17462 @end iftex
17463 # The examples below are based on the following directory hierarchy:
17464 # All the directories can contain any number of files
17465 # ROOT_DIRECTORY ->  a  ->  aa  ->  aaa
17466 #                       ->  ab
17467 #                       ->  ac
17468 #                ->  b  ->  ba  ->  baa
17469 #                       ->  bb
17470 #                       ->  bc
17471 # This Makefile creates a variable called DIRS, that can be reused any time
17472 # you need this list (see the other examples in this section)
17474 # The root of your project's directory hierarchy
17475 ROOT_DIRECTORY=.
17477 ####
17478 # First method: specify explicitly the list of directories
17479 # This allows you to specify any subset of all the directories you need.
17480 ####
17482 DIRS := a/aa/ a/ab/ b/ba/
17484 ####
17485 # Second method: use wildcards
17486 # Note that the argument(s) to wildcard below should end with a '/'.
17487 # Since wildcards also return file names, we have to filter them out
17488 # to avoid duplicate directory names.
17489 # We thus use make's @code{dir} and @code{sort} functions.
17490 # It sets DIRs to the following value (note that the directories aaa and baa
17491 # are not given, unless you change the arguments to wildcard).
17492 # DIRS= ./a/a/ ./b/ ./a/aa/ ./a/ab/ ./a/ac/ ./b/ba/ ./b/bb/ ./b/bc/
17493 ####
17495 DIRS := $@{sort $@{dir $@{wildcard $@{ROOT_DIRECTORY@}/*/
17496                     $@{ROOT_DIRECTORY@}/*/*/@}@}@}
17498 ####
17499 # Third method: use an external program
17500 # This command is much faster if run on local disks, avoiding NFS slowdowns.
17501 # This is the most complete command: it sets DIRs to the following value:
17502 # DIRS= ./a ./a/aa ./a/aa/aaa ./a/ab ./a/ac ./b ./b/ba ./b/ba/baa ./b/bb ./b/bc
17503 ####
17505 DIRS := $@{shell find $@{ROOT_DIRECTORY@} -type d -print@}
17507 @end smallexample
17509 @node Generating the Command Line Switches
17510 @section Generating the Command Line Switches
17512 @noindent
17513 Once you have created the list of directories as explained in the
17514 previous section (@pxref{Automatically Creating a List of Directories}),
17515 you can easily generate the command line arguments to pass to gnatmake.
17517 For the sake of completeness, this example assumes that the source path
17518 is not the same as the object path, and that you have two separate lists
17519 of directories.
17521 @smallexample
17522 # see "Automatically creating a list of directories" to create
17523 # these variables
17524 SOURCE_DIRS=
17525 OBJECT_DIRS=
17527 GNATMAKE_SWITCHES := $@{patsubst %,-aI%,$@{SOURCE_DIRS@}@}
17528 GNATMAKE_SWITCHES += $@{patsubst %,-aO%,$@{OBJECT_DIRS@}@}
17530 all:
17531         gnatmake $@{GNATMAKE_SWITCHES@} main_unit
17532 @end smallexample
17534 @node Overcoming Command Line Length Limits
17535 @section Overcoming Command Line Length Limits
17537 @noindent
17538 One problem that might be encountered on big projects is that many
17539 operating systems limit the length of the command line. It is thus hard to give
17540 gnatmake the list of source and object directories.
17542 This example shows how you can set up environment variables, which will
17543 make @command{gnatmake} behave exactly as if the directories had been
17544 specified on the command line, but have a much higher length limit (or
17545 even none on most systems).
17547 It assumes that you have created a list of directories in your Makefile,
17548 using one of the methods presented in
17549 @ref{Automatically Creating a List of Directories}.
17550 For the sake of completeness, we assume that the object
17551 path (where the ALI files are found) is different from the sources patch.
17553 Note a small trick in the Makefile below: for efficiency reasons, we
17554 create two temporary variables (SOURCE_LIST and OBJECT_LIST), that are
17555 expanded immediately by @code{make}. This way we overcome the standard
17556 make behavior which is to expand the variables only when they are
17557 actually used.
17559 On Windows, if you are using the standard Windows command shell, you must
17560 replace colons with semicolons in the assignments to these variables.
17562 @smallexample
17563 @iftex
17564 @leftskip=0cm
17565 @font@heightrm=cmr8
17566 @heightrm
17567 @end iftex
17568 # In this example, we create both ADA_INCLUDE_PATH and ADA_OBJECTS_PATH.
17569 # This is the same thing as putting the -I arguments on the command line.
17570 # (the equivalent of using -aI on the command line would be to define
17571 #  only ADA_INCLUDE_PATH, the equivalent of -aO is ADA_OBJECTS_PATH).
17572 # You can of course have different values for these variables.
17574 # Note also that we need to keep the previous values of these variables, since
17575 # they might have been set before running 'make' to specify where the GNAT
17576 # library is installed.
17578 # see "Automatically creating a list of directories" to create these
17579 # variables
17580 SOURCE_DIRS=
17581 OBJECT_DIRS=
17583 empty:=
17584 space:=$@{empty@} $@{empty@}
17585 SOURCE_LIST := $@{subst $@{space@},:,$@{SOURCE_DIRS@}@}
17586 OBJECT_LIST := $@{subst $@{space@},:,$@{OBJECT_DIRS@}@}
17587 ADA_INCLUDE_PATH += $@{SOURCE_LIST@}
17588 ADA_OBJECTS_PATH += $@{OBJECT_LIST@}
17589 export ADA_INCLUDE_PATH
17590 export ADA_OBJECTS_PATH
17592 all:
17593         gnatmake main_unit
17594 @end smallexample
17595 @end ifclear
17597 @node Memory Management Issues
17598 @chapter Memory Management Issues
17600 @noindent
17601 This chapter describes some useful memory pools provided in the GNAT library
17602 and in particular the GNAT Debug Pool facility, which can be used to detect
17603 incorrect uses of access values (including ``dangling references'').
17604 @ifclear vms
17605 It also describes the @command{gnatmem} tool, which can be used to track down
17606 ``memory leaks''.
17607 @end ifclear
17609 @menu
17610 * Some Useful Memory Pools::
17611 * The GNAT Debug Pool Facility::
17612 @ifclear vms
17613 * The gnatmem Tool::
17614 @end ifclear
17615 @end menu
17617 @node Some Useful Memory Pools
17618 @section Some Useful Memory Pools
17619 @findex Memory Pool
17620 @cindex storage, pool
17622 @noindent
17623 The @code{System.Pool_Global} package offers the Unbounded_No_Reclaim_Pool
17624 storage pool. Allocations use the standard system call @code{malloc} while
17625 deallocations use the standard system call @code{free}. No reclamation is
17626 performed when the pool goes out of scope. For performance reasons, the
17627 standard default Ada allocators/deallocators do not use any explicit storage
17628 pools but if they did, they could use this storage pool without any change in
17629 behavior. That is why this storage pool is used  when the user
17630 manages to make the default implicit allocator explicit as in this example:
17631 @smallexample @c ada
17632    type T1 is access Something;
17633     -- no Storage pool is defined for T2
17634    type T2 is access Something_Else;
17635    for T2'Storage_Pool use T1'Storage_Pool;
17636    -- the above is equivalent to
17637    for T2'Storage_Pool use System.Pool_Global.Global_Pool_Object;
17638 @end smallexample
17640 @noindent
17641 The @code{System.Pool_Local} package offers the Unbounded_Reclaim_Pool storage
17642 pool. The allocation strategy is similar to @code{Pool_Local}'s
17643 except that the all
17644 storage allocated with this pool is reclaimed when the pool object goes out of
17645 scope. This pool provides a explicit mechanism similar to the implicit one
17646 provided by several Ada 83 compilers for allocations performed through a local
17647 access type and whose purpose was to reclaim memory when exiting the
17648 scope of a given local access. As an example, the following program does not
17649 leak memory even though it does not perform explicit deallocation:
17651 @smallexample @c ada
17652 with System.Pool_Local;
17653 procedure Pooloc1 is
17654    procedure Internal is
17655       type A is access Integer;
17656       X : System.Pool_Local.Unbounded_Reclaim_Pool;
17657       for A'Storage_Pool use X;
17658       v : A;
17659    begin
17660       for I in  1 .. 50 loop
17661          v := new Integer;
17662       end loop;
17663    end Internal;
17664 begin
17665    for I in  1 .. 100 loop
17666       Internal;
17667    end loop;
17668 end Pooloc1;
17669 @end smallexample
17671 @noindent
17672 The @code{System.Pool_Size} package implements the Stack_Bounded_Pool used when
17673 @code{Storage_Size} is specified for an access type.
17674 The whole storage for the pool is
17675 allocated at once, usually on the stack at the point where the access type is
17676 elaborated. It is automatically reclaimed when exiting the scope where the
17677 access type is defined. This package is not intended to be used directly by the
17678 user and it is implicitly used for each such declaration:
17680 @smallexample @c ada
17681    type T1 is access Something;
17682    for T1'Storage_Size use 10_000;
17683 @end smallexample
17685 @node The GNAT Debug Pool Facility
17686 @section The GNAT Debug Pool Facility
17687 @findex Debug Pool
17688 @cindex storage, pool, memory corruption
17690 @noindent
17691 The use of unchecked deallocation and unchecked conversion can easily
17692 lead to incorrect memory references. The problems generated by such
17693 references are usually difficult to tackle because the symptoms can be
17694 very remote from the origin of the problem. In such cases, it is
17695 very helpful to detect the problem as early as possible. This is the
17696 purpose of the Storage Pool provided by @code{GNAT.Debug_Pools}.
17698 In order to use the GNAT specific debugging pool, the user must
17699 associate a debug pool object with each of the access types that may be
17700 related to suspected memory problems. See Ada Reference Manual 13.11.
17701 @smallexample @c ada
17702 type Ptr is access Some_Type;
17703 Pool : GNAT.Debug_Pools.Debug_Pool;
17704 for Ptr'Storage_Pool use Pool;
17705 @end smallexample
17707 @noindent
17708 @code{GNAT.Debug_Pools} is derived from a GNAT-specific kind of
17709 pool: the @code{Checked_Pool}. Such pools, like standard Ada storage pools,
17710 allow the user to redefine allocation and deallocation strategies. They
17711 also provide a checkpoint for each dereference, through the use of
17712 the primitive operation @code{Dereference} which is implicitly called at
17713 each dereference of an access value.
17715 Once an access type has been associated with a debug pool, operations on
17716 values of the type may raise four distinct exceptions,
17717 which correspond to four potential kinds of memory corruption:
17718 @itemize @bullet
17719 @item
17720 @code{GNAT.Debug_Pools.Accessing_Not_Allocated_Storage}
17721 @item
17722 @code{GNAT.Debug_Pools.Accessing_Deallocated_Storage}
17723 @item
17724 @code{GNAT.Debug_Pools.Freeing_Not_Allocated_Storage}
17725 @item
17726 @code{GNAT.Debug_Pools.Freeing_Deallocated_Storage }
17727 @end itemize
17729 @noindent
17730 For types associated with a Debug_Pool, dynamic allocation is performed using
17731 the standard GNAT allocation routine. References to all allocated chunks of
17732 memory are kept in an internal dictionary. Several deallocation strategies are
17733 provided, whereupon the user can choose to release the memory to the system,
17734 keep it allocated for further invalid access checks, or fill it with an easily
17735 recognizable pattern for debug sessions. The memory pattern is the old IBM
17736 hexadecimal convention: @code{16#DEADBEEF#}.
17738 See the documentation in the file g-debpoo.ads for more information on the
17739 various strategies.
17741 Upon each dereference, a check is made that the access value denotes a
17742 properly allocated memory location. Here is a complete example of use of
17743 @code{Debug_Pools}, that includes typical instances of  memory corruption:
17744 @smallexample @c ada
17745 @iftex
17746 @leftskip=0cm
17747 @end iftex
17748 with Gnat.Io; use Gnat.Io;
17749 with Unchecked_Deallocation;
17750 with Unchecked_Conversion;
17751 with GNAT.Debug_Pools;
17752 with System.Storage_Elements;
17753 with Ada.Exceptions; use Ada.Exceptions;
17754 procedure Debug_Pool_Test is
17756    type T is access Integer;
17757    type U is access all T;
17759    P : GNAT.Debug_Pools.Debug_Pool;
17760    for T'Storage_Pool use P;
17762    procedure Free is new Unchecked_Deallocation (Integer, T);
17763    function UC is new Unchecked_Conversion (U, T);
17764    A, B : aliased T;
17766    procedure Info is new GNAT.Debug_Pools.Print_Info(Put_Line);
17768 begin
17769    Info (P);
17770    A := new Integer;
17771    B := new Integer;
17772    B := A;
17773    Info (P);
17774    Free (A);
17775    begin
17776       Put_Line (Integer'Image(B.all));
17777    exception
17778       when E : others => Put_Line ("raised: " & Exception_Name (E));
17779    end;
17780    begin
17781       Free (B);
17782    exception
17783       when E : others => Put_Line ("raised: " & Exception_Name (E));
17784    end;
17785    B := UC(A'Access);
17786    begin
17787       Put_Line (Integer'Image(B.all));
17788    exception
17789       when E : others => Put_Line ("raised: " & Exception_Name (E));
17790    end;
17791    begin
17792       Free (B);
17793    exception
17794       when E : others => Put_Line ("raised: " & Exception_Name (E));
17795    end;
17796    Info (P);
17797 end Debug_Pool_Test;
17798 @end smallexample
17800 @noindent
17801 The debug pool mechanism provides the following precise diagnostics on the
17802 execution of this erroneous program:
17803 @smallexample
17804 Debug Pool info:
17805   Total allocated bytes :  0
17806   Total deallocated bytes :  0
17807   Current Water Mark:  0
17808   High Water Mark:  0
17810 Debug Pool info:
17811   Total allocated bytes :  8
17812   Total deallocated bytes :  0
17813   Current Water Mark:  8
17814   High Water Mark:  8
17816 raised: GNAT.DEBUG_POOLS.ACCESSING_DEALLOCATED_STORAGE
17817 raised: GNAT.DEBUG_POOLS.FREEING_DEALLOCATED_STORAGE
17818 raised: GNAT.DEBUG_POOLS.ACCESSING_NOT_ALLOCATED_STORAGE
17819 raised: GNAT.DEBUG_POOLS.FREEING_NOT_ALLOCATED_STORAGE
17820 Debug Pool info:
17821   Total allocated bytes :  8
17822   Total deallocated bytes :  4
17823   Current Water Mark:  4
17824   High Water Mark:  8
17825 @end smallexample
17827 @ifclear vms
17828 @node The gnatmem Tool
17829 @section The @command{gnatmem} Tool
17830 @findex gnatmem
17832 @noindent
17833 The @code{gnatmem} utility monitors dynamic allocation and
17834 deallocation activity in a program, and displays information about
17835 incorrect deallocations and possible sources of memory leaks.
17836 It is designed to work in association with a static runtime library
17837 only and in this context provides three types of information:
17838 @itemize @bullet
17839 @item
17840 General information concerning memory management, such as the total
17841 number of allocations and deallocations, the amount of allocated
17842 memory and the high water mark, i.e.@: the largest amount of allocated
17843 memory in the course of program execution.
17845 @item
17846 Backtraces for all incorrect deallocations, that is to say deallocations
17847 which do not correspond to a valid allocation.
17849 @item
17850 Information on each allocation that is potentially the origin of a memory
17851 leak.
17852 @end itemize
17854 @menu
17855 * Running gnatmem::
17856 * Switches for gnatmem::
17857 * Example of gnatmem Usage::
17858 @end menu
17860 @node Running gnatmem
17861 @subsection Running @code{gnatmem}
17863 @noindent
17864 @code{gnatmem} makes use of the output created by the special version of
17865 allocation and deallocation routines that record call information. This
17866 allows to obtain accurate dynamic memory usage history at a minimal cost to
17867 the execution speed. Note however, that @code{gnatmem} is not supported on
17868 all platforms (currently, it is supported on AIX, HP-UX, GNU/Linux,
17869 Solaris and Windows NT/2000/XP (x86).
17871 @noindent
17872 The @code{gnatmem} command has the form
17874 @smallexample
17875 @c    $ gnatmem @ovar{switches} user_program
17876 @c Expanding @ovar macro inline (explanation in macro def comments)
17877       $ gnatmem @r{[}@var{switches}@r{]} @var{user_program}
17878 @end smallexample
17880 @noindent
17881 The program must have been linked with the instrumented version of the
17882 allocation and deallocation routines. This is done by linking with the
17883 @file{libgmem.a} library. For correct symbolic backtrace information,
17884 the user program should be compiled with debugging options
17885 (see @ref{Switches for gcc}). For example to build @file{my_program}:
17887 @smallexample
17888 $ gnatmake -g my_program -largs -lgmem
17889 @end smallexample
17891 @noindent
17892 As library @file{libgmem.a} contains an alternate body for package
17893 @code{System.Memory}, @file{s-memory.adb} should not be compiled and linked
17894 when an executable is linked with library @file{libgmem.a}. It is then not
17895 recommended to use @command{gnatmake} with switch @option{^-a^/ALL_FILES^}.
17897 @noindent
17898 When @file{my_program} is executed, the file @file{gmem.out} is produced.
17899 This file contains information about all allocations and deallocations
17900 performed by the program. It is produced by the instrumented allocations and
17901 deallocations routines and will be used by @code{gnatmem}.
17903 In order to produce symbolic backtrace information for allocations and
17904 deallocations performed by the GNAT run-time library, you need to use a
17905 version of that library that has been compiled with the @option{-g} switch
17906 (see @ref{Rebuilding the GNAT Run-Time Library}).
17908 Gnatmem must be supplied with the @file{gmem.out} file and the executable to
17909 examine. If the location of @file{gmem.out} file was not explicitly supplied by
17910 @option{-i} switch, gnatmem will assume that this file can be found in the
17911 current directory. For example, after you have executed @file{my_program},
17912 @file{gmem.out} can be analyzed by @code{gnatmem} using the command:
17914 @smallexample
17915 $ gnatmem my_program
17916 @end smallexample
17918 @noindent
17919 This will produce the output with the following format:
17921 *************** debut cc
17922 @smallexample
17923 $ gnatmem my_program
17925 Global information
17926 ------------------
17927    Total number of allocations        :  45
17928    Total number of deallocations      :   6
17929    Final Water Mark (non freed mem)   :  11.29 Kilobytes
17930    High Water Mark                    :  11.40 Kilobytes
17935 Allocation Root # 2
17936 -------------------
17937  Number of non freed allocations    :  11
17938  Final Water Mark (non freed mem)   :   1.16 Kilobytes
17939  High Water Mark                    :   1.27 Kilobytes
17940  Backtrace                          :
17941    my_program.adb:23 my_program.alloc
17945 @end smallexample
17947 The first block of output gives general information. In this case, the
17948 Ada construct ``@code{@b{new}}'' was executed 45 times, and only 6 calls to an
17949 Unchecked_Deallocation routine occurred.
17951 @noindent
17952 Subsequent paragraphs display  information on all allocation roots.
17953 An allocation root is a specific point in the execution of the program
17954 that generates some dynamic allocation, such as a ``@code{@b{new}}''
17955 construct. This root is represented by an execution backtrace (or subprogram
17956 call stack). By default the backtrace depth for allocations roots is 1, so
17957 that a root corresponds exactly to a source location. The backtrace can
17958 be made deeper, to make the root more specific.
17960 @node Switches for gnatmem
17961 @subsection Switches for @code{gnatmem}
17963 @noindent
17964 @code{gnatmem} recognizes the following switches:
17966 @table @option
17968 @item -q
17969 @cindex @option{-q} (@code{gnatmem})
17970 Quiet. Gives the minimum output needed to identify the origin of the
17971 memory leaks. Omits statistical information.
17973 @item @var{N}
17974 @cindex @var{N} (@code{gnatmem})
17975 N is an integer literal (usually between 1 and 10) which controls the
17976 depth of the backtraces defining allocation root. The default value for
17977 N is 1. The deeper the backtrace, the more precise the localization of
17978 the root. Note that the total number of roots can depend on this
17979 parameter. This parameter must be specified @emph{before} the name of the
17980 executable to be analyzed, to avoid ambiguity.
17982 @item -b n
17983 @cindex @option{-b} (@code{gnatmem})
17984 This switch has the same effect as just depth parameter.
17986 @item -i @var{file}
17987 @cindex @option{-i} (@code{gnatmem})
17988 Do the @code{gnatmem} processing starting from @file{file}, rather than
17989 @file{gmem.out} in the current directory.
17991 @item -m n
17992 @cindex @option{-m} (@code{gnatmem})
17993 This switch causes @code{gnatmem} to mask the allocation roots that have less
17994 than n leaks. The default value is 1. Specifying the value of 0 will allow to
17995 examine even the roots that didn't result in leaks.
17997 @item -s order
17998 @cindex @option{-s} (@code{gnatmem})
17999 This switch causes @code{gnatmem} to sort the allocation roots according to the
18000 specified order of sort criteria, each identified by a single letter. The
18001 currently supported criteria are @code{n, h, w} standing respectively for
18002 number of unfreed allocations, high watermark, and final watermark
18003 corresponding to a specific root. The default order is @code{nwh}.
18005 @end table
18007 @node Example of gnatmem Usage
18008 @subsection Example of @code{gnatmem} Usage
18010 @noindent
18011 The following example shows the use of @code{gnatmem}
18012 on a simple memory-leaking program.
18013 Suppose that we have the following Ada program:
18015 @smallexample @c ada
18016 @group
18017 @cartouche
18018 with Unchecked_Deallocation;
18019 procedure Test_Gm is
18021    type T is array (1..1000) of Integer;
18022    type Ptr is access T;
18023    procedure Free is new Unchecked_Deallocation (T, Ptr);
18024    A : Ptr;
18026    procedure My_Alloc is
18027    begin
18028       A := new T;
18029    end My_Alloc;
18031    procedure My_DeAlloc is
18032       B : Ptr := A;
18033    begin
18034       Free (B);
18035    end My_DeAlloc;
18037 begin
18038    My_Alloc;
18039    for I in 1 .. 5 loop
18040       for J in I .. 5 loop
18041          My_Alloc;
18042       end loop;
18043       My_Dealloc;
18044    end loop;
18045 end;
18046 @end cartouche
18047 @end group
18048 @end smallexample
18050 @noindent
18051 The program needs to be compiled with debugging option and linked with
18052 @code{gmem} library:
18054 @smallexample
18055 $ gnatmake -g test_gm -largs -lgmem
18056 @end smallexample
18058 @noindent
18059 Then we execute the program as usual:
18061 @smallexample
18062 $ test_gm
18063 @end smallexample
18065 @noindent
18066 Then @code{gnatmem} is invoked simply with
18067 @smallexample
18068 $ gnatmem test_gm
18069 @end smallexample
18071 @noindent
18072 which produces the following output (result may vary on different platforms):
18074 @smallexample
18075 Global information
18076 ------------------
18077    Total number of allocations        :  18
18078    Total number of deallocations      :   5
18079    Final Water Mark (non freed mem)   :  53.00 Kilobytes
18080    High Water Mark                    :  56.90 Kilobytes
18082 Allocation Root # 1
18083 -------------------
18084  Number of non freed allocations    :  11
18085  Final Water Mark (non freed mem)   :  42.97 Kilobytes
18086  High Water Mark                    :  46.88 Kilobytes
18087  Backtrace                          :
18088    test_gm.adb:11 test_gm.my_alloc
18090 Allocation Root # 2
18091 -------------------
18092  Number of non freed allocations    :   1
18093  Final Water Mark (non freed mem)   :  10.02 Kilobytes
18094  High Water Mark                    :  10.02 Kilobytes
18095  Backtrace                          :
18096    s-secsta.adb:81 system.secondary_stack.ss_init
18098 Allocation Root # 3
18099 -------------------
18100  Number of non freed allocations    :   1
18101  Final Water Mark (non freed mem)   :  12 Bytes
18102  High Water Mark                    :  12 Bytes
18103  Backtrace                          :
18104    s-secsta.adb:181 system.secondary_stack.ss_init
18105 @end smallexample
18107 @noindent
18108 Note that the GNAT run time contains itself a certain number of
18109 allocations that have no  corresponding deallocation,
18110 as shown here for root #2 and root
18111 #3. This is a normal behavior when the number of non-freed allocations
18112 is one, it allocates dynamic data structures that the run time needs for
18113 the complete lifetime of the program. Note also that there is only one
18114 allocation root in the user program with a single line back trace:
18115 test_gm.adb:11 test_gm.my_alloc, whereas a careful analysis of the
18116 program shows that 'My_Alloc' is called at 2 different points in the
18117 source (line 21 and line 24). If those two allocation roots need to be
18118 distinguished, the backtrace depth parameter can be used:
18120 @smallexample
18121 $ gnatmem 3 test_gm
18122 @end smallexample
18124 @noindent
18125 which will give the following output:
18127 @smallexample
18128 Global information
18129 ------------------
18130    Total number of allocations        :  18
18131    Total number of deallocations      :   5
18132    Final Water Mark (non freed mem)   :  53.00 Kilobytes
18133    High Water Mark                    :  56.90 Kilobytes
18135 Allocation Root # 1
18136 -------------------
18137  Number of non freed allocations    :  10
18138  Final Water Mark (non freed mem)   :  39.06 Kilobytes
18139  High Water Mark                    :  42.97 Kilobytes
18140  Backtrace                          :
18141    test_gm.adb:11 test_gm.my_alloc
18142    test_gm.adb:24 test_gm
18143    b_test_gm.c:52 main
18145 Allocation Root # 2
18146 -------------------
18147  Number of non freed allocations    :   1
18148  Final Water Mark (non freed mem)   :  10.02 Kilobytes
18149  High Water Mark                    :  10.02 Kilobytes
18150  Backtrace                          :
18151    s-secsta.adb:81  system.secondary_stack.ss_init
18152    s-secsta.adb:283 <system__secondary_stack___elabb>
18153    b_test_gm.c:33   adainit
18155 Allocation Root # 3
18156 -------------------
18157  Number of non freed allocations    :   1
18158  Final Water Mark (non freed mem)   :   3.91 Kilobytes
18159  High Water Mark                    :   3.91 Kilobytes
18160  Backtrace                          :
18161    test_gm.adb:11 test_gm.my_alloc
18162    test_gm.adb:21 test_gm
18163    b_test_gm.c:52 main
18165 Allocation Root # 4
18166 -------------------
18167  Number of non freed allocations    :   1
18168  Final Water Mark (non freed mem)   :  12 Bytes
18169  High Water Mark                    :  12 Bytes
18170  Backtrace                          :
18171    s-secsta.adb:181 system.secondary_stack.ss_init
18172    s-secsta.adb:283 <system__secondary_stack___elabb>
18173    b_test_gm.c:33   adainit
18174 @end smallexample
18176 @noindent
18177 The allocation root #1 of the first example has been split in 2 roots #1
18178 and #3 thanks to the more precise associated backtrace.
18180 @end ifclear
18182 @node Stack Related Facilities
18183 @chapter Stack Related Facilities
18185 @noindent
18186 This chapter describes some useful tools associated with stack
18187 checking and analysis. In
18188 particular, it deals with dynamic and static stack usage measurements.
18190 @menu
18191 * Stack Overflow Checking::
18192 * Static Stack Usage Analysis::
18193 * Dynamic Stack Usage Analysis::
18194 @end menu
18196 @node Stack Overflow Checking
18197 @section Stack Overflow Checking
18198 @cindex Stack Overflow Checking
18199 @cindex -fstack-check
18201 @noindent
18202 For most operating systems, @command{gcc} does not perform stack overflow
18203 checking by default. This means that if the main environment task or
18204 some other task exceeds the available stack space, then unpredictable
18205 behavior will occur. Most native systems offer some level of protection by
18206 adding a guard page at the end of each task stack. This mechanism is usually
18207 not enough for dealing properly with stack overflow situations because
18208 a large local variable could ``jump'' above the guard page.
18209 Furthermore, when the
18210 guard page is hit, there may not be any space left on the stack for executing
18211 the exception propagation code. Enabling stack checking avoids
18212 such situations.
18214 To activate stack checking, compile all units with the gcc option
18215 @option{-fstack-check}. For example:
18217 @smallexample
18218 gcc -c -fstack-check package1.adb
18219 @end smallexample
18221 @noindent
18222 Units compiled with this option will generate extra instructions to check
18223 that any use of the stack (for procedure calls or for declaring local
18224 variables in declare blocks) does not exceed the available stack space.
18225 If the space is exceeded, then a @code{Storage_Error} exception is raised.
18227 For declared tasks, the stack size is controlled by the size
18228 given in an applicable @code{Storage_Size} pragma or by the value specified
18229 at bind time with @option{-d} (@pxref{Switches for gnatbind}) or is set to
18230 the default size as defined in the GNAT runtime otherwise.
18232 For the environment task, the stack size depends on
18233 system defaults and is unknown to the compiler. Stack checking
18234 may still work correctly if a fixed
18235 size stack is allocated, but this cannot be guaranteed.
18236 @ifclear vms
18237 To ensure that a clean exception is signalled for stack
18238 overflow, set the environment variable
18239 @env{GNAT_STACK_LIMIT} to indicate the maximum
18240 stack area that can be used, as in:
18241 @cindex GNAT_STACK_LIMIT
18243 @smallexample
18244 SET GNAT_STACK_LIMIT 1600
18245 @end smallexample
18247 @noindent
18248 The limit is given in kilobytes, so the above declaration would
18249 set the stack limit of the environment task to 1.6 megabytes.
18250 Note that the only purpose of this usage is to limit the amount
18251 of stack used by the environment task. If it is necessary to
18252 increase the amount of stack for the environment task, then this
18253 is an operating systems issue, and must be addressed with the
18254 appropriate operating systems commands.
18255 @end ifclear
18256 @ifset vms
18257 To have a fixed size stack in the environment task, the stack must be put
18258 in the P0 address space and its size specified.  Use these switches to
18259 create a p0 image:
18261 @smallexample
18262 gnatmake my_progs -largs "-Wl,--opt=STACK=4000,/p0image"
18263 @end smallexample
18265 @noindent
18266 The quotes are required to keep case.  The number after @samp{STACK=} is the
18267 size of the environmental task stack in pagelets (512 bytes).  In this example
18268 the stack size is about 2 megabytes.
18270 @noindent
18271 A consequence of the @option{/p0image} qualifier is also to makes RMS buffers
18272 be placed in P0 space.  Refer to @cite{HP OpenVMS Linker Utility Manual} for
18273 more details about the @option{/p0image} qualifier and the @option{stack}
18274 option.
18276 @noindent
18277 On Itanium platforms, you can instead assign the @samp{GNAT_STACK_SIZE} and
18278 @samp{GNAT_RBS_SIZE} logicals to the size of the primary and register
18279 stack in kilobytes.  For example:
18281 @smallexample
18282 $ define GNAT_RBS_SIZE 1024 ! Limit the RBS size to 1MB.
18283 @end smallexample
18284 @end ifset
18286 @node Static Stack Usage Analysis
18287 @section Static Stack Usage Analysis
18288 @cindex Static Stack Usage Analysis
18289 @cindex -fstack-usage
18291 @noindent
18292 A unit compiled with @option{-fstack-usage} will generate an extra file
18293 that specifies
18294 the maximum amount of stack used, on a per-function basis.
18295 The file has the same
18296 basename as the target object file with a @file{.su} extension.
18297 Each line of this file is made up of three fields:
18299 @itemize
18300 @item
18301 The name of the function.
18302 @item
18303 A number of bytes.
18304 @item
18305 One or more qualifiers: @code{static}, @code{dynamic}, @code{bounded}.
18306 @end itemize
18308 The second field corresponds to the size of the known part of the function
18309 frame.
18311 The qualifier @code{static} means that the function frame size
18312 is purely static.
18313 It usually means that all local variables have a static size.
18314 In this case, the second field is a reliable measure of the function stack
18315 utilization.
18317 The qualifier @code{dynamic} means that the function frame size is not static.
18318 It happens mainly when some local variables have a dynamic size. When this
18319 qualifier appears alone, the second field is not a reliable measure
18320 of the function stack analysis. When it is qualified with  @code{bounded}, it
18321 means that the second field is a reliable maximum of the function stack
18322 utilization.
18324 A unit compiled with @option{-Wstack-usage} will issue a warning for each
18325 subprogram whose stack usage might be larger than the specified amount of
18326 bytes.  The wording is in keeping with the qualifier documented above.
18328 @node Dynamic Stack Usage Analysis
18329 @section Dynamic Stack Usage Analysis
18331 @noindent
18332 It is possible to measure the maximum amount of stack used by a task, by
18333 adding a switch to @command{gnatbind}, as:
18335 @smallexample
18336 $ gnatbind -u0 file
18337 @end smallexample
18339 @noindent
18340 With this option, at each task termination, its stack usage is  output on
18341 @file{stderr}.
18342 It is not always convenient to output the stack usage when the program
18343 is still running. Hence, it is possible to delay this output until program
18344 termination. for a given number of tasks specified as the argument of the
18345 @option{-u} option. For instance:
18347 @smallexample
18348 $ gnatbind -u100 file
18349 @end smallexample
18351 @noindent
18352 will buffer the stack usage information of the first 100 tasks to terminate and
18353 output this info at program termination. Results are displayed in four
18354 columns:
18356 @noindent
18357 Index | Task Name | Stack Size | Stack Usage
18359 @noindent
18360 where:
18362 @table @emph
18363 @item Index
18364 is a number associated with each task.
18366 @item Task Name
18367 is the name of the task analyzed.
18369 @item Stack Size
18370 is the maximum size for the stack.
18372 @item Stack Usage
18373 is the measure done by the stack analyzer. In order to prevent overflow, the stack
18374 is not entirely analyzed, and it's not possible to know exactly how
18375 much has actually been used.
18377 @end table
18379 @noindent
18380 The environment task stack, e.g., the stack that contains the main unit, is
18381 only processed when the environment variable GNAT_STACK_LIMIT is set.
18383 @noindent
18384 The package @code{GNAT.Task_Stack_Usage} provides facilities to get
18385 stack usage reports at run-time. See its body for the details.
18387 @c *********************************
18388 @c *            GNATCHECK          *
18389 @c *********************************
18390 @node Verifying Properties with gnatcheck
18391 @chapter Verifying Properties with @command{gnatcheck}
18392 @findex gnatcheck
18393 @cindex @command{gnatcheck}
18395 @noindent
18396 The @command{gnatcheck} tool is an ASIS-based utility that checks properties
18397 of Ada source files according to a given set of semantic rules.
18398 @cindex ASIS
18400 In order to check compliance with a given rule, @command{gnatcheck} has to
18401 semantically analyze the Ada sources.
18402 Therefore, checks can only be performed on
18403 legal Ada units. Moreover, when a unit depends semantically upon units located
18404 outside the current directory, the source search path has to be provided when
18405 calling @command{gnatcheck}, either through a specified project file or
18406 through @command{gnatcheck} switches.
18408 For full details, refer to @cite{GNATcheck Reference Manual} document.
18411 @c *********************************
18412 @node Creating Sample Bodies with gnatstub
18413 @chapter Creating Sample Bodies with @command{gnatstub}
18414 @findex gnatstub
18416 @noindent
18417 @command{gnatstub} creates body stubs, that is, empty but compilable bodies
18418 for library unit declarations.
18420 Note: to invoke @code{gnatstub} with a project file, use the @code{gnat}
18421 driver (see @ref{The GNAT Driver and Project Files}).
18423 To create a body stub, @command{gnatstub} has to compile the library
18424 unit declaration. Therefore, bodies can be created only for legal
18425 library units. Moreover, if a library unit depends semantically upon
18426 units located outside the current directory, you have to provide
18427 the source search path when calling @command{gnatstub}, see the description
18428 of @command{gnatstub} switches below.
18430 By default, all the program unit body stubs generated by @code{gnatstub}
18431 raise the predefined @code{Program_Error} exception, which will catch
18432 accidental calls of generated stubs. This behavior can be changed with
18433 option @option{^--no-exception^/NO_EXCEPTION^} (see below).
18435 @menu
18436 * Running gnatstub::
18437 * Switches for gnatstub::
18438 @end menu
18440 @node Running gnatstub
18441 @section Running @command{gnatstub}
18443 @noindent
18444 @command{gnatstub} has a command-line interface of the form:
18446 @smallexample
18447 @c $ gnatstub @ovar{switches} @var{filename} @ovar{directory}
18448 @c Expanding @ovar macro inline (explanation in macro def comments)
18449 $ gnatstub @r{[}@var{switches}@r{]} @var{filename} @r{[}@var{directory}@r{]} @r{[}-cargs @var{gcc_switches}@r{]}
18450 @end smallexample
18452 @noindent
18453 where
18454 @table @var
18455 @item filename
18456 is the name of the source file that contains a library unit declaration
18457 for which a body must be created. The file name may contain the path
18458 information.
18459 The file name does not have to follow the GNAT file name conventions. If the
18460 name
18461 does not follow GNAT file naming conventions, the name of the body file must
18462 be provided
18463 explicitly as the value of the @option{^-o^/BODY=^@var{body-name}} option.
18464 If the file name follows the GNAT file naming
18465 conventions and the name of the body file is not provided,
18466 @command{gnatstub}
18467 creates the name
18468 of the body file from the argument file name by replacing the @file{.ads}
18469 suffix
18470 with the @file{.adb} suffix.
18472 @item directory
18473 indicates the directory in which the body stub is to be placed (the default
18474 is the
18475 current directory)
18477 @item @samp{@var{gcc_switches}} is a list of switches for
18478 @command{gcc}. They will be passed on to all compiler invocations made by
18479 @command{gnatstub} to generate the ASIS trees. Here you can provide
18480 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
18481 use the @option{-gnatec} switch to set the configuration file,
18482 use the @option{-gnat05} switch if sources should be compiled in
18483 Ada 2005 mode etc.
18485 @item switches
18486 is an optional sequence of switches as described in the next section
18487 @end table
18489 @node Switches for gnatstub
18490 @section Switches for @command{gnatstub}
18492 @table @option
18493 @c !sort!
18495 @item --version
18496 @cindex @option{--version} @command{gnatstub}
18497 Display Copyright and version, then exit disregarding all other options.
18499 @item --help
18500 @cindex @option{--help} @command{gnatstub}
18501 Display usage, then exit disregarding all other options.
18503 @item ^-f^/FULL^
18504 @cindex @option{^-f^/FULL^} (@command{gnatstub})
18505 If the destination directory already contains a file with the name of the
18506 body file
18507 for the argument spec file, replace it with the generated body stub.
18509 @item ^-hs^/HEADER=SPEC^
18510 @cindex @option{^-hs^/HEADER=SPEC^} (@command{gnatstub})
18511 Put the comment header (i.e., all the comments preceding the
18512 compilation unit) from the source of the library unit declaration
18513 into the body stub.
18515 @item ^-hg^/HEADER=GENERAL^
18516 @cindex @option{^-hg^/HEADER=GENERAL^} (@command{gnatstub})
18517 Put a sample comment header into the body stub.
18519 @item ^--header-file=@var{filename}^/FROM_HEADER_FILE=@var{filename}^
18520 @cindex @option{^--header-file^/FROM_HEADER_FILE=^} (@command{gnatstub})
18521 Use the content of the file as the comment header for a generated body stub.
18523 @ifclear vms
18524 @item -IDIR
18525 @cindex @option{-IDIR} (@command{gnatstub})
18526 @itemx -I-
18527 @cindex @option{-I-} (@command{gnatstub})
18528 @end ifclear
18529 @ifset vms
18530 @item /NOCURRENT_DIRECTORY
18531 @cindex @option{/NOCURRENT_DIRECTORY} (@command{gnatstub})
18532 @end ifset
18533 ^These switches have ^This switch has^ the same meaning as in calls to
18534 @command{gcc}.
18535 ^They define ^It defines ^ the source search path in the call to
18536 @command{gcc} issued
18537 by @command{gnatstub} to compile an argument source file.
18539 @item ^-gnatec^/CONFIGURATION_PRAGMAS_FILE=^@var{PATH}
18540 @cindex @option{^-gnatec^/CONFIGURATION_PRAGMAS_FILE^} (@command{gnatstub})
18541 This switch has the same meaning as in calls to @command{gcc}.
18542 It defines the additional configuration file to be passed to the call to
18543 @command{gcc} issued
18544 by @command{gnatstub} to compile an argument source file.
18546 @item ^-gnatyM^/MAX_LINE_LENGTH=^@var{n}
18547 @cindex @option{^-gnatyM^/MAX_LINE_LENGTH^} (@command{gnatstub})
18548 (@var{n} is a non-negative integer). Set the maximum line length in the
18549 body stub to @var{n}; the default is 79. The maximum value that can be
18550 specified is 32767. Note that in the special case of configuration
18551 pragma files, the maximum is always 32767 regardless of whether or
18552 not this switch appears.
18554 @item ^-gnaty^/STYLE_CHECKS=^@var{n}
18555 @cindex @option{^-gnaty^/STYLE_CHECKS=^} (@command{gnatstub})
18556 (@var{n} is a non-negative integer from 1 to 9). Set the indentation level in
18557 the generated body sample to @var{n}.
18558 The default indentation is 3.
18560 @item ^-gnatyo^/ORDERED_SUBPROGRAMS^
18561 @cindex @option{^-gnatyo^/ORDERED_SUBPROGRAMS^} (@command{gnatstub})
18562 Order local bodies alphabetically. (By default local bodies are ordered
18563 in the same way as the corresponding local specs in the argument spec file.)
18565 @item ^-i^/INDENTATION=^@var{n}
18566 @cindex @option{^-i^/INDENTATION^} (@command{gnatstub})
18567 Same as @option{^-gnaty^/STYLE_CHECKS=^@var{n}}
18569 @item ^-k^/TREE_FILE=SAVE^
18570 @cindex @option{^-k^/TREE_FILE=SAVE^} (@command{gnatstub})
18571 Do not remove the tree file (i.e., the snapshot of the compiler internal
18572 structures used by @command{gnatstub}) after creating the body stub.
18574 @item ^-l^/LINE_LENGTH=^@var{n}
18575 @cindex @option{^-l^/LINE_LENGTH^} (@command{gnatstub})
18576 Same as @option{^-gnatyM^/MAX_LINE_LENGTH=^@var{n}}
18578 @item ^--no-exception^/NO_EXCEPTION^
18579 @cindex @option{^--no-exception^/NO_EXCEPTION^} (@command{gnatstub})
18580 Avoid raising PROGRAM_ERROR in the generated bodies of program unit stubs.
18581 This is not always possible for function stubs.
18583 @item ^--no-local-header^/NO_LOCAL_HEADER^
18584 @cindex @option{^--no-local-header^/NO_LOCAL_HEADER^} (@command{gnatstub})
18585 Do not place local comment header with unit name before body stub for a
18586 unit.
18588 @item ^-o ^/BODY=^@var{body-name}
18589 @cindex @option{^-o^/BODY^} (@command{gnatstub})
18590 Body file name.  This should be set if the argument file name does not
18591 follow
18592 the GNAT file naming
18593 conventions. If this switch is omitted the default name for the body will be
18594 obtained
18595 from the argument file name according to the GNAT file naming conventions.
18597 @item ^-q^/QUIET^
18598 @cindex @option{^-q^/QUIET^} (@command{gnatstub})
18599 Quiet mode: do not generate a confirmation when a body is
18600 successfully created, and do not generate a message when a body is not
18601 required for an
18602 argument unit.
18604 @item ^-r^/TREE_FILE=REUSE^
18605 @cindex @option{^-r^/TREE_FILE=REUSE^} (@command{gnatstub})
18606 Reuse the tree file (if it exists) instead of creating it.  Instead of
18607 creating the tree file for the library unit declaration, @command{gnatstub}
18608 tries to find it in the current directory and use it for creating
18609 a body. If the tree file is not found, no body is created. This option
18610 also implies @option{^-k^/SAVE^}, whether or not
18611 the latter is set explicitly.
18613 @item ^-t^/TREE_FILE=OVERWRITE^
18614 @cindex @option{^-t^/TREE_FILE=OVERWRITE^} (@command{gnatstub})
18615 Overwrite the existing tree file.  If the current directory already
18616 contains the file which, according to the GNAT file naming rules should
18617 be considered as a tree file for the argument source file,
18618 @command{gnatstub}
18619 will refuse to create the tree file needed to create a sample body
18620 unless this option is set.
18622 @item ^-v^/VERBOSE^
18623 @cindex @option{^-v^/VERBOSE^} (@command{gnatstub})
18624 Verbose mode: generate version information.
18626 @end table
18628 @c *********************************
18629 @node Creating Unit Tests with gnattest
18630 @chapter Creating Unit Tests with @command{gnattest}
18631 @findex gnattest
18633 @noindent
18634 @command{gnattest} is an ASIS-based utility that creates unit-test skeletons
18635 as well as a test driver infrastructure (harness). @command{gnattest} creates
18636 a skeleton for each visible subprogram in the packages under consideration when
18637 they do not exist already.
18639 In order to process source files from a project, @command{gnattest} has to
18640 semantically analyze the sources. Therefore, test skeletons can only be
18641 generated for legal Ada units. If a unit is dependent on other units,
18642 those units should be among the source files of the project or of other projects
18643 imported by this one.
18645 Generated skeletons and harnesses are based on the AUnit testing framework.
18646 AUnit is an Ada adaptation of the xxxUnit testing frameworks, similar to JUnit
18647 for Java or CppUnit for C++. While it is advised that gnattest users read
18648 the AUnit manual, deep knowledge of AUnit is not necessary for using gnattest.
18649 For correct operation of @command{gnattest}, AUnit should be installed and
18650 aunit.gpr must be on the project path. This happens automatically when Aunit
18651 is installed at its default location.
18652 @menu
18653 * Running gnattest::
18654 * Switches for gnattest::
18655 * Project Attributes for gnattest::
18656 * Simple Example::
18657 * Setting Up and Tearing Down the Testing Environment::
18658 * Regenerating Tests::
18659 * Default Test Behavior::
18660 * Testing Primitive Operations of Tagged Types::
18661 * Testing Inheritance::
18662 * Tagged Types Substitutability Testing::
18663 * Testing with Contracts::
18664 * Additional Tests::
18665 @ifclear vms
18666 * Support for other platforms/run-times::
18667 @end ifclear
18668 * Current Limitations::
18669 @end menu
18671 @node Running gnattest
18672 @section Running @command{gnattest}
18674 @noindent
18675 @command{gnattest} has a command-line interface of the form
18677 @smallexample
18678 @c $ gnattest @var{-Pprojname} @ovar{switches} @ovar{filename} @ovar{directory}
18679 @c Expanding @ovar macro inline (explanation in macro def comments)
18680 $ gnattest @var{-Pprojname} @r{[}@var{--harness-dir=dirname}@r{]} @r{[}@var{switches}@r{]} @r{[}@var{filename}@r{]} @r{[}-cargs @var{gcc_switches}@r{]}
18681 @end smallexample
18683 @noindent
18684 where
18685 @table @var
18687 @item -Pprojname
18688 specifies the project defining the location of source files. When no
18689 file names are provided on the command line, all sources in the project
18690 are used as input. This switch is required.
18692 @item filename
18693 is the name of the source file containing the library unit package declaration
18694 for which a test package will be created. The file name may be given with a
18695 path.
18697 @item @samp{@var{gcc_switches}}
18698 is a list of switches for
18699 @command{gcc}. These switches will be passed on to all compiler invocations
18700 made by @command{gnattest} to generate a set of ASIS trees. Here you can provide
18701 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
18702 use the @option{-gnatec} switch to set the configuration file,
18703 use the @option{-gnat05} switch if sources should be compiled in
18704 Ada 2005 mode, etc.
18706 @item switches
18707 is an optional sequence of switches as described in the next section.
18709 @end table
18711 @command{gnattest} results can be found in two different places.
18713 @itemize @bullet
18714 @item automatic harness:
18715 the harness code, which is located by default in "gnattest/harness" directory
18716 that is created in the object directory of corresponding project file. All of
18717 this code is generated completely automatically and can be destroyed and
18718 regenerated at will. It is not recommended to modify this code manually, since
18719 it could easily be overridden by mistake. The entry point in the harness code is
18720 the project file named @command{test_driver.gpr}. Tests can be compiled and run
18721 using a command such as:
18723 @smallexample
18724 gnatmake -P<harness-dir>/test_driver
18725 test_runner
18726 @end smallexample
18728 Note that you might need to specify the necessary values of scenario variables
18729 when you are not using the AUnit defaults.
18731 @item actual unit test skeletons:
18732 a test skeleton for each visible subprogram is created in a separate file, if it
18733 doesn't exist already. By default, those separate test files are located in a
18734 "gnattest/tests" directory that is created in the object directory of
18735 corresponding project file. For example, if a source file my_unit.ads in
18736 directory src contains a visible subprogram Proc, then the corresponding unit
18737 test will be found in file src/tests/my_unit-test_data-tests-proc_<code>.adb.
18738 <code> is a signature encoding used to differentiate test names in case of
18739 overloading.
18741 Note that if the project already has both my_unit.ads and my_unit-test_data.ads,
18742 this will cause a name conflict with the generated test package.
18743 @end itemize
18745 @node Switches for gnattest
18746 @section Switches for @command{gnattest}
18748 @table @option
18749 @c !sort!
18751 @item --harness-only
18752 @cindex @option{--harness-only} (@command{gnattest})
18753 When this option is given, @command{gnattest} creates a harness for all
18754 sources, treating them as test packages.
18756 @item --additional-tests=@var{projname}
18757 @cindex @option{--additional-tests} (@command{gnattest})
18758 Sources described in @var{projname} are considered potential additional
18759 manual tests to be added to the test suite.
18761 @item -r
18762 @cindex @option{-r} (@command{gnattest})
18763 Recursively consider all sources from all projects.
18765 @item -X@var{name=value}
18766 @cindex @option{-X} (@command{gnattest})
18767 Indicate that external variable @var{name} has the value @var{value}.
18769 @item -q
18770 @cindex @option{-q} (@command{gnattest})
18771 Suppresses noncritical output messages.
18773 @item -v
18774 @cindex @option{-v} (@command{gnattest})
18775 Verbose mode: generates version information.
18777 @item --validate-type-extensions
18778 @cindex @option{--validate-type-extensions} (@command{gnattest})
18779 Enables substitution check: run all tests from all parents in order
18780 to check substitutability.
18782 @item --skeleton-default=@var{val}
18783 @cindex @option{--skeleton-default} (@command{gnattest})
18784 Specifies the default behavior of generated skeletons. @var{val} can be either
18785 "fail" or "pass", "fail" being the default.
18787 @item --tests-root=@var{dirname}
18788 @cindex @option{--tests-root} (@command{gnattest})
18789 The directory hierarchy of tested sources is recreated in the @var{dirname}
18790 directory, and test packages are placed in corresponding directories.
18791 If the @var{dirname} is a relative path, it is considered relative to the object
18792 directory of the project file. When all sources from all projects are taken
18793 recursively from all projects, directory hierarchies of tested sources are
18794 recreated for each project in their object directories and test packages are
18795 placed accordingly.
18797 @item --subdir=@var{dirname}
18798 @cindex @option{--subdir} (@command{gnattest})
18799 Test packages are placed in subdirectories.
18801 @item --tests-dir=@var{dirname}
18802 @cindex @option{--tests-dir} (@command{gnattest})
18803 All test packages are placed in the @var{dirname} directory.
18804 If the @var{dirname} is a relative path, it is considered relative to the object
18805 directory of the project file. When all sources from all projects are taken
18806 recursively from all projects, @var{dirname} directories are created for each
18807 project in their object directories and test packages are placed accordingly.
18809 @item --harness-dir=@var{dirname}
18810 @cindex @option{--harness-dir} (@command{gnattest})
18811 specifies the directory that will hold the harness packages and project file
18812 for the test driver. If the @var{dirname} is a relative path, it is considered
18813 relative to the object directory of the project file.
18815 @item --separates
18816 @cindex @option{--separates} (@command{gnattest})
18817 Bodies of all test routines are generated as separates. Note that this mode is
18818 kept for compatibility reasons only and it is not advised to use it due to
18819 possible problems with hash in names of test skeletons when using an
18820 inconsistent casing. Separate test skeletons can be incorporated to monolith
18821 test package with improved hash being used by using @option{--transition}
18822 switch.
18825 @item --transition
18826 @cindex @option{--transition} (@command{gnattest})
18827 This allows transition from separate test routines to monolith test packages.
18828 All matching test routines are overwritten with contents of corresponding
18829 separates. Note that if separate test routines had any manually added with
18830 clauses they will be moved to the test package body as is and have to be moved
18831 by hand.
18833 @end table
18835 @option{--tests_root}, @option{--subdir} and @option{--tests-dir} switches are
18836 mutually exclusive.
18838 @node Project Attributes for gnattest
18839 @section Project Attributes for @command{gnattest}
18841 @noindent
18843 Most of the command-line options can also be passed to the tool by adding
18844 special attributes to the project file. Those attributes should be put in
18845 package gnattest. Here is the list of attributes:
18847 @itemize @bullet
18849 @item Tests_Root
18850 is used to select the same output mode as with the --tests-root option.
18851 This attribute cannot be used together with Subdir or Tests_Dir.
18853 @item Subdir
18854 is used to select the same output mode as with the --subdir option.
18855 This attribute cannot be used together with Tests_Root or Tests_Dir.
18857 @item Tests_Dir
18858 is used to select the same output mode as with the --tests-dir option.
18859 This attribute cannot be used together with Subdir or Tests_Root.
18861 @item Harness_Dir
18862 is used to specify the directory in which to place harness packages and project
18863 file for the test driver, otherwise specified by --harness-dir.
18865 @item Additional_Tests
18866 is used to specify the project file, otherwise given by
18867 --additional-tests switch.
18869 @item Skeletons_Default
18870 is used to specify the default behaviour of test skeletons, otherwise
18871 specified by --skeleton-default option. The value of this attribute
18872 should be either "pass" or "fail".
18874 @end itemize
18876 Each of those attributes can be overridden from the command line if needed.
18877 Other @command{gnattest} switches can also be passed via the project
18878 file as an attribute list called GNATtest_Switches.
18880 @node Simple Example
18881 @section Simple Example
18883 @noindent
18885 Let's take a very simple example using the first @command{gnattest} example
18886 located in:
18888 @smallexample
18889 <install_prefix>/share/examples/gnattest/simple
18890 @end smallexample
18892 This project contains a simple package containing one subprogram. By running gnattest:
18894 @smallexample
18895 $ gnattest --harness-dir=driver -Psimple.gpr
18896 @end smallexample
18898 a test driver is created in directory "driver". It can be compiled and run:
18900 @smallexample
18901 $ cd obj/driver
18902 $ gnatmake -Ptest_driver
18903 $ test_runner
18904 @end smallexample
18906 One failed test with diagnosis "test not implemented" is reported.
18907 Since no special output option was specified, the test package Simple.Tests
18908 is located in:
18910 @smallexample
18911 <install_prefix>/share/examples/gnattest/simple/obj/gnattest/tests
18912 @end smallexample
18914 For each package containing visible subprograms, a child test package is
18915 generated. It contains one test routine per tested subprogram. Each
18916 declaration of a test subprogram has a comment specifying which tested
18917 subprogram it corresponds to. Bodies of test routines are placed in test package
18918 bodies and are surrounded by special comment sections. Those comment sections
18919 should not be removed or modified in order for gnattest to be able to regenerate
18920 test packages and keep already written tests in place.
18921 The test routine Test_Inc_5eaee3 located at simple-test_data-tests.adb contains
18922 a single statement: a call to procedure Assert. It has two arguments:
18923 the Boolean expression we want to check and the diagnosis message to display if
18924 the condition is false.
18926 That is where actual testing code should be written after a proper setup.
18927 An actual check can be performed by replacing the Assert call with:
18929 @smallexample @c ada
18930 Assert (Inc (1) = 2, "wrong incrementation");
18931 @end smallexample
18933 After recompiling and running the test driver, one successfully passed test
18934 is reported.
18936 @node Setting Up and Tearing Down the Testing Environment
18937 @section Setting Up and Tearing Down the Testing Environment
18939 @noindent
18941 Besides test routines themselves, each test package has a parent package
18942 Test_Data that has two procedures: Set_Up and Tear_Down. This package is never
18943 overwritten by the tool. Set_Up is called before each test routine of the
18944 package and Tear_Down is called after each test routine. Those two procedures
18945 can be used to perform necessary initialization and finalization,
18946 memory allocation, etc. Test type declared in Test_Data package is parent type
18947 for the test type of test package and can have user-defined components whose
18948 values can be set by Set_Up routine and used in test routines afterwards.
18950 @node Regenerating Tests
18951 @section Regenerating Tests
18953 @noindent
18955 Bodies of test routines and test_data packages are never overridden after they
18956 have been created once. As long as the name of the subprogram, full expanded Ada
18957 names, and the order of its parameters is the same, and comment sections are
18958 intact the old test routine will fit in its place and no test skeleton will be
18959 generated for the subprogram.
18961 This can be demonstrated with the previous example. By uncommenting declaration
18962 and body of function Dec in simple.ads and simple.adb, running
18963 @command{gnattest} on the project, and then running the test driver:
18965 @smallexample
18966 gnattest --harness-dir=driver -Psimple.gpr
18967 cd obj/driver
18968 gnatmake -Ptest_driver
18969 test_runner
18970 @end smallexample
18972 the old test is not replaced with a stub, nor is it lost, but a new test
18973 skeleton is created for function Dec.
18975 The only way of regenerating tests skeletons is to remove the previously created
18976 tests together with corresponding comment sections.
18978 @node Default Test Behavior
18979 @section Default Test Behavior
18981 @noindent
18983 The generated test driver can treat unimplemented tests in two ways:
18984 either count them all as failed (this is useful to see which tests are still
18985 left to implement) or as passed (to sort out unimplemented ones from those
18986 actually failing).
18988 The test driver accepts a switch to specify this behavior:
18989 --skeleton-default=val, where val is either "pass" or "fail" (exactly as for
18990 @command{gnattest}).
18992 The default behavior of the test driver is set with the same switch
18993 as passed to gnattest when generating the test driver.
18995 Passing it to the driver generated on the first example:
18997 @smallexample
18998 test_runner --skeleton-default=pass
18999 @end smallexample
19001 makes both tests pass, even the unimplemented one.
19003 @node Testing Primitive Operations of Tagged Types
19004 @section Testing Primitive Operations of Tagged Types
19006 @noindent
19008 Creation of test skeletons for primitive operations of tagged types entails
19009 a number of features. Test routines for all primitives of a given tagged type
19010 are placed in a separate child package named according to the tagged type. For
19011 example, if you have tagged type T in package P, all tests for primitives
19012 of T will be in P.T_Test_Data.T_Tests.
19014 Consider running gnattest on the second example (note: actual tests for this
19015 example already exist, so there's no need to worry if the tool reports that
19016 no new stubs were generated):
19018 @smallexample
19019 cd <install_prefix>/share/examples/gnattest/tagged_rec
19020 gnattest --harness-dir=driver -Ptagged_rec.gpr
19021 @end smallexample
19023 Taking a closer look at the test type declared in the test package
19024 Speed1.Controller_Test_Data is necessary. It is declared in:
19026 @smallexample
19027 <install_prefix>/share/examples/gnattest/tagged_rec/obj/gnattest/tests
19028 @end smallexample
19030 Test types are direct or indirect descendants of
19031 AUnit.Test_Fixtures.Test_Fixture type. In the case of nonprimitive tested
19032 subprograms, the user doesn't need to be concerned with them. However,
19033 when generating test packages for primitive operations, there are some things
19034 the user needs to know.
19036 Type Test_Controller has components that allow assignment of various
19037 derivations of type Controller. And if you look at the specification of
19038 package Speed2.Auto_Controller, you will see that Test_Auto_Controller
19039 actually derives from Test_Controller rather than AUnit type Test_Fixture.
19040 Thus, test types mirror the hierarchy of tested types.
19042 The Set_Up procedure of Test_Data package corresponding to a test package
19043 of primitive operations of type T assigns to Fixture a reference to an
19044 object of that exact type T. Notice, however, that if the tagged type has
19045 discriminants, the Set_Up only has a commented template for setting
19046 up the fixture, since filling the discriminant with actual value is up
19047 to the user.
19049 The knowledge of the structure of test types allows additional testing
19050 without additional effort. Those possibilities are described below.
19052 @node Testing Inheritance
19053 @section Testing Inheritance
19055 @noindent
19057 Since the test type hierarchy mimics the hierarchy of tested types, the
19058 inheritance of tests takes place. An example of such inheritance can be
19059 seen by running the test driver generated for the second example. As previously
19060 mentioned, actual tests are already written for this example.
19062 @smallexample
19063 cd obj/driver
19064 gnatmake -Ptest_driver
19065 test_runner
19066 @end smallexample
19068 There are 6 passed tests while there are only 5 testable subprograms. The test
19069 routine for function Speed has been inherited and run against objects of the
19070 derived type.
19072 @node Tagged Types Substitutability Testing
19073 @section Tagged Types Substitutability Testing
19075 @noindent
19077 Tagged Types Substitutability Testing is a way of verifying the global type
19078 consistency by testing. Global type consistency is a principle stating that if
19079 S is a subtype of T (in Ada, S is a derived type of tagged type T),
19080 then objects of type T may be replaced with objects of type S (that is,
19081 objects of type S may be substituted for objects of type T), without
19082 altering any of the desirable properties of the program. When the properties
19083 of the program are expressed in the form of subprogram preconditions and
19084 postconditions (let's call them pre and post), the principle is formulated as
19085 relations between the pre and post of primitive operations and the pre and post
19086 of their derived operations. The pre of a derived operation should not be
19087 stronger than the original pre, and the post of the derived operation should
19088 not be weaker than the original post. Those relations ensure that verifying if
19089 a dispatching call is safe can be done just by using the pre and post of the
19090 root operation.
19092 Verifying global type consistency by testing consists of running all the unit
19093 tests associated with the primitives of a given tagged type with objects of its
19094 derived types.
19096 In the example used in the previous section, there was clearly a violation of
19097 type consistency. The overriding primitive Adjust_Speed in package Speed2
19098 removes the functionality of the overridden primitive and thus doesn't respect
19099 the consistency principle.
19100 Gnattest has a special option to run overridden parent tests against objects
19101 of the type which have overriding primitives:
19103 @smallexample
19104 gnattest --harness-dir=driver --validate-type-extensions -Ptagged_rec.gpr
19105 cd obj/driver
19106 gnatmake -Ptest_driver
19107 test_runner
19108 @end smallexample
19110 While all the tests pass by themselves, the parent test for Adjust_Speed fails
19111 against objects of the derived type.
19113 Non-overridden tests are already inherited for derived test types, so the
19114 --validate-type-extensions enables the application of overriden tests to objects
19115 of derived types.
19117 @node Testing with Contracts
19118 @section Testing with Contracts
19120 @noindent
19122 @command{gnattest} supports pragmas Precondition, Postcondition, and Test_Case,
19123 as well as corresponding aspects.
19124 Test routines are generated, one per each Test_Case associated with a tested
19125 subprogram. Those test routines have special wrappers for tested functions
19126 that have composition of pre- and postcondition of the subprogram with
19127 "requires" and "ensures" of the Test_Case (depending on the mode, pre and post
19128 either count for Nominal mode or do not count for Robustness mode).
19130 The third example demonstrates how this works:
19132 @smallexample
19133 cd <install_prefix>/share/examples/gnattest/contracts
19134 gnattest --harness-dir=driver -Pcontracts.gpr
19135 @end smallexample
19137 Putting actual checks within the range of the contract does not cause any
19138 error reports. For example, for the test routine which corresponds to
19139 test case 1:
19141 @smallexample @c ada
19142 Assert (Sqrt (9.0) = 3.0, "wrong sqrt");
19143 @end smallexample
19145 and for the test routine corresponding to test case 2:
19147 @smallexample @c ada
19148 Assert (Sqrt (-5.0) = -1.0, "wrong error indication");
19149 @end smallexample
19151 are acceptable:
19153 @smallexample
19154 cd obj/driver
19155 gnatmake -Ptest_driver
19156 test_runner
19157 @end smallexample
19159 However, by changing 9.0 to 25.0 and 3.0 to 5.0, for example, you can get
19160 a precondition violation for test case one. Also, by using any otherwise
19161 correct but positive pair of numbers in the second test routine, you can also
19162 get a precondition violation. Postconditions are checked and reported
19163 the same way.
19165 @node Additional Tests
19166 @section Additional Tests
19168 @noindent
19169 @command{gnattest} can add user-written tests to the main suite of the test
19170 driver. @command{gnattest} traverses the given packages and searches for test
19171 routines. All procedures with a single in out parameter of a type which is
19172 derived from AUnit.Test_Fixtures.Test_Fixture and that are declared in package
19173 specifications are added to the suites and are then executed by the test driver.
19174 (Set_Up and Tear_Down are filtered out.)
19176 An example illustrates two ways of creating test harnesses for user-written
19177 tests. Directory additional_tests contains an AUnit-based test driver written
19178 by hand.
19180 @smallexample
19181 <install_prefix>/share/examples/gnattest/additional_tests/
19182 @end smallexample
19184 To create a test driver for already-written tests, use the --harness-only
19185 option:
19187 @smallexample
19188 gnattest -Padditional/harness/harness.gpr --harness-dir=harness_only \
19189   --harness-only
19190 gnatmake -Pharness_only/test_driver.gpr
19191 harness_only/test_runner
19192 @end smallexample
19194 Additional tests can also be executed together with generated tests:
19196 @smallexample
19197 gnattest -Psimple.gpr --additional-tests=additional/harness/harness.gpr \
19198   --harness-dir=mixing
19199 gnatmake -Pmixing/test_driver.gpr
19200 mixing/test_runner
19201 @end smallexample
19203 @ifclear vms
19204 @node Support for other platforms/run-times
19205 @section Support for other platforms/run-times
19207 @noindent
19208 @command{gnattest} can be used to generate the test harness for platforms
19209 and run-time libraries others than the default native target with the
19210 default full run-time. For example, when using a limited run-time library
19211 such as Zero FootPrint (ZFP), a simplified harness is generated.
19213 Two variables are used to tell the underlying AUnit framework how to generate
19214 the test harness: @code{PLATFORM}, which identifies the target, and
19215 @code{RUNTIME}, used to determine the run-time library for which the harness
19216 is generated. Corresponding prefix should also be used when calling
19217 @command{gnattest} for non-native targets. For example, the following options
19218 are used to generate the AUnit test harness for a PowerPC ELF target using
19219 the ZFP run-time library:
19221 @smallexample
19222 powerpc-elf-gnattest -Psimple.gpr -XPLATFORM=powerpc-elf -XRUNTIME=zfp
19223 @end smallexample
19224 @end ifclear
19226 @node Current Limitations
19227 @section Current Limitations
19229 @noindent
19231 The tool currently does not support following features:
19233 @itemize @bullet
19234 @item generic tests for generic packages and package instantiations
19235 @item tests for protected subprograms and entries
19237 @end itemize
19239 @c *********************************
19240 @node Performing Dimensionality Analysis in GNAT
19241 @chapter Performing Dimensionality Analysis in GNAT
19242 @noindent
19243 The GNAT compiler now supports dimensionality checking. The user can
19244 specify physical units for objects, and the compiler will verify that uses
19245 of these objects are compatible with their dimensions, in a fashion that is
19246 familiar to engineering practice. The dimensions of algebraic expressions
19247 (including powers with static exponents) are computed from their consistuents.
19249 This feature depends on Ada 2012 aspect specifications, and is available from
19250 version 7.0.1 of GNAT onwards. The GNAT-specific aspect Dimension_System allows
19251 you to define a system of units; the aspect Dimension then allows the user
19252 to declare dimensioned quantities within a given system.
19254 The major advantage of this model is that it does not require the declaration of
19255 multiple operators for all possible combinations of types: it is only necessary
19256 to use the proper subtypes in object declarations.
19258 The simplest way to impose dimensionality checking on a computation is to make
19259 use of the package System.Dim.Mks, which is part of the GNAT library. This
19260 package defines a floating-point type MKS_Type, for which a sequence of
19261 dimension names are specified, together with their conventional abbreviations.
19262 The following should be read together with the full specification of the
19263 package, in file s-dimmks.ads.
19265 @smallexample @c ada
19266    type Mks_Type is new Long_Long_Float
19267      with
19268       Dimension_System => (
19269         (Unit_Name => Meter,    Unit_Symbol => 'm',   Dim_Symbol => 'L'),
19270         (Unit_Name => Kilogram, Unit_Symbol => "kg",  Dim_Symbol => 'M'),
19271         (Unit_Name => Second,   Unit_Symbol => 's',   Dim_Symbol => 'T'),
19272         (Unit_Name => Ampere,   Unit_Symbol => 'A',   Dim_Symbol => 'I'),
19273         (Unit_Name => Kelvin,   Unit_Symbol => 'K',   Dim_Symbol => "Theta"),
19274         (Unit_Name => Mole,     Unit_Symbol => "mol", Dim_Symbol => 'N'),
19275         (Unit_Name => Candela,  Unit_Symbol => "cd",  Dim_Symbol => 'J'));
19276 @end smallexample
19278 @noindent
19279 The package then defines a series of subtypes that correspond to these
19280 conventional units. For example:
19281 @smallexample @c ada
19282    subtype Length is Mks_Type
19283      with
19284       Dimension => (Symbol => 'm', Meter  => 1, others => 0);
19285 @end smallexample
19286 @noindent
19287 and similarly for Mass, Time, Electric_Current, Thermodynamic_Temperature,
19288 Amount_Of_Substance, and Luminous_Intensity (the standard set of units of
19289 the SI system).
19291 The package also defines conventional names for values of each unit, for
19292 example:
19294 @smallexample @c ada
19295    m   : constant Length           := 1.0;
19296    kg  : constant Mass             := 1.0;
19297    s   : constant Time             := 1.0;
19298    A   : constant Electric_Current := 1.0;
19299 @end smallexample
19301 @noindent
19302 as well as useful multiples of these units:
19304 @smallexample @c ada
19305    cm  : constant Length := 1.0E-02;
19306    g   : constant Mass   := 1.0E-03;
19307    min : constant Time   := 60.0;
19308    day : constant TIme   := 60.0 * 24.0 * min;
19309   ...
19310 @end smallexample
19312 @noindent
19313 Using this package, you can then define a derived unit by
19314 providing the aspect that
19315 specifies its dimensions within the MKS system, as well as the string to
19316 be used for output of a value of that unit:
19318 @smallexample @c ada
19319   subtype Acceleration is Mks_Type
19320     with Dimension => ("m/sec^^^2",
19321                        Meter => 1,
19322                        Second => -2,
19323                        others => 0);
19324 @end smallexample
19326 @noindent
19327 Here is a complete example of use:
19329 @smallexample @c ada
19330 with System.Dim.MKS; use System.Dim.Mks;
19331 with System.Dim.Mks_IO; use System.Dim.Mks_IO;
19332 with Text_IO; use Text_IO;
19333 procedure Free_Fall is
19334   subtype Acceleration is Mks_Type
19335     with Dimension => ("m/sec^^^2", 1, 0, -2, others => 0);
19336   G : constant acceleration := 9.81 * m / (s ** 2);
19337   T : Time := 10.0*s;
19338   Distance : Length;
19339 begin
19340   Put ("Gravitational constant: ");
19341   Put (G, Aft => 2, Exp => 0); Put_Line ("");
19342   Distance := 0.5 * G * T ** 2;
19343   Put ("distance travelled in 10 seconds of free fall ");
19344   Put (Distance, Aft => 2, Exp => 0);
19345   Put_Line ("");
19346 end Free_Fall;
19347 @end smallexample
19349 @noindent
19350 Execution of this program yields:
19351 @smallexample
19352 Gravitational constant:  9.81 m/sec^^^2
19353 distance travelled in 10 seconds of free fall 490.50 m
19354 @end smallexample
19356 @noindent
19357 However, incorrect assignments such as:
19359 @smallexample @c ada
19360    Distance := 5.0;
19361    Distance := 5.0 * kg:
19362 @end smallexample
19364 @noindent
19365 are rejected with the following diagnoses:
19367 @smallexample
19368    Distance := 5.0;
19369       >>> dimensions mismatch in assignment
19370       >>> left-hand side has dimension [L]
19371       >>> right-hand side is dimensionless
19373    Distance := 5.0 * kg:
19374       >>> dimensions mismatch in assignment
19375       >>> left-hand side has dimension [L]
19376       >>> right-hand side has dimension [M]
19377 @end smallexample
19379 @noindent
19380 The dimensions of an expression are properly displayed, even if there is
19381 no explicit subtype for it. If we add to the program:
19383 @smallexample @c ada
19384       Put ("Final velocity: ");
19385       Put (G * T, Aft =>2, Exp =>0);
19386       Put_Line ("");
19387 @end smallexample
19389 @noindent
19390 then the output includes:
19391 @smallexample
19392      Final velocity: 98.10 m.s**(-1)
19393 @end smallexample
19395 @c *********************************
19396 @node Generating Ada Bindings for C and C++ headers
19397 @chapter Generating Ada Bindings for C and C++ headers
19398 @findex binding
19400 @noindent
19401 GNAT now comes with a binding generator for C and C++ headers which is
19402 intended to do 95% of the tedious work of generating Ada specs from C
19403 or C++ header files.
19405 Note that this capability is not intended to generate 100% correct Ada specs,
19406 and will is some cases require manual adjustments, although it can often
19407 be used out of the box in practice.
19409 Some of the known limitations include:
19411 @itemize @bullet
19412 @item only very simple character constant macros are translated into Ada
19413 constants. Function macros (macros with arguments) are partially translated
19414 as comments, to be completed manually if needed.
19415 @item some extensions (e.g. vector types) are not supported
19416 @item pointers to pointers or complex structures are mapped to System.Address
19417 @item identifiers with identical name (except casing) will generate compilation
19418       errors (e.g. @code{shm_get} vs @code{SHM_GET}).
19419 @end itemize
19421 The code generated is using the Ada 2005 syntax, which makes it
19422 easier to interface with other languages than previous versions of Ada.
19424 @menu
19425 * Running the binding generator::
19426 * Generating bindings for C++ headers::
19427 * Switches::
19428 @end menu
19430 @node Running the binding generator
19431 @section Running the binding generator
19433 @noindent
19434 The binding generator is part of the @command{gcc} compiler and can be
19435 invoked via the @option{-fdump-ada-spec} switch, which will generate Ada
19436 spec files for the header files specified on the command line, and all
19437 header files needed by these files transitively. For example:
19439 @smallexample
19440 $ g++ -c -fdump-ada-spec -C /usr/include/time.h
19441 $ gcc -c -gnat05 *.ads
19442 @end smallexample
19444 will generate, under GNU/Linux, the following files: @file{time_h.ads},
19445 @file{bits_time_h.ads}, @file{stddef_h.ads}, @file{bits_types_h.ads} which
19446 correspond to the files @file{/usr/include/time.h},
19447 @file{/usr/include/bits/time.h}, etc@dots{}, and will then compile in Ada 2005
19448 mode these Ada specs.
19450 The @code{-C} switch tells @command{gcc} to extract comments from headers,
19451 and will attempt to generate corresponding Ada comments.
19453 If you want to generate a single Ada file and not the transitive closure, you
19454 can use instead the @option{-fdump-ada-spec-slim} switch.
19456 You can optionally specify a parent unit, of which all generated units will
19457 be children, using @code{-fada-spec-parent=}@var{unit}.
19459 Note that we recommend when possible to use the @command{g++} driver to
19460 generate bindings, even for most C headers, since this will in general
19461 generate better Ada specs. For generating bindings for C++ headers, it is
19462 mandatory to use the @command{g++} command, or @command{gcc -x c++} which
19463 is equivalent in this case. If @command{g++} cannot work on your C headers
19464 because of incompatibilities between C and C++, then you can fallback to
19465 @command{gcc} instead.
19467 For an example of better bindings generated from the C++ front-end,
19468 the name of the parameters (when available) are actually ignored by the C
19469 front-end. Consider the following C header:
19471 @smallexample
19472 extern void foo (int variable);
19473 @end smallexample
19475 with the C front-end, @code{variable} is ignored, and the above is handled as:
19477 @smallexample
19478 extern void foo (int);
19479 @end smallexample
19481 generating a generic:
19483 @smallexample
19484 procedure foo (param1 : int);
19485 @end smallexample
19487 with the C++ front-end, the name is available, and we generate:
19489 @smallexample
19490 procedure foo (variable : int);
19491 @end smallexample
19493 In some cases, the generated bindings will be more complete or more meaningful
19494 when defining some macros, which you can do via the @option{-D} switch. This
19495 is for example the case with @file{Xlib.h} under GNU/Linux:
19497 @smallexample
19498 g++ -c -fdump-ada-spec -DXLIB_ILLEGAL_ACCESS -C /usr/include/X11/Xlib.h
19499 @end smallexample
19501 The above will generate more complete bindings than a straight call without
19502 the @option{-DXLIB_ILLEGAL_ACCESS} switch.
19504 In other cases, it is not possible to parse a header file in a stand-alone
19505 manner, because other include files need to be included first. In this
19506 case, the solution is to create a small header file including the needed
19507 @code{#include} and possible @code{#define} directives. For example, to
19508 generate Ada bindings for @file{readline/readline.h}, you need to first
19509 include @file{stdio.h}, so you can create a file with the following two
19510 lines in e.g. @file{readline1.h}:
19512 @smallexample
19513 #include <stdio.h>
19514 #include <readline/readline.h>
19515 @end smallexample
19517 and then generate Ada bindings from this file:
19519 @smallexample
19520 $ g++ -c -fdump-ada-spec readline1.h
19521 @end smallexample
19523 @node Generating bindings for C++ headers
19524 @section Generating bindings for C++ headers
19526 @noindent
19527 Generating bindings for C++ headers is done using the same options, always
19528 with the @command{g++} compiler.
19530 In this mode, C++ classes will be mapped to Ada tagged types, constructors
19531 will be mapped using the @code{CPP_Constructor} pragma, and when possible,
19532 multiple inheritance of abstract classes will be mapped to Ada interfaces
19533 (@xref{Interfacing to C++,,,gnat_rm, GNAT Reference Manual}, for additional
19534 information on interfacing to C++).
19536 For example, given the following C++ header file:
19538 @smallexample
19539 @group
19540 @cartouche
19541 class Carnivore @{
19542 public:
19543    virtual int Number_Of_Teeth () = 0;
19546 class Domestic @{
19547 public:
19548    virtual void Set_Owner (char* Name) = 0;
19551 class Animal @{
19552 public:
19553   int Age_Count;
19554   virtual void Set_Age (int New_Age);
19557 class Dog : Animal, Carnivore, Domestic @{
19558  public:
19559   int  Tooth_Count;
19560   char *Owner;
19562   virtual int  Number_Of_Teeth ();
19563   virtual void Set_Owner (char* Name);
19565   Dog();
19567 @end cartouche
19568 @end group
19569 @end smallexample
19571 The corresponding Ada code is generated:
19573 @smallexample @c ada
19574 @group
19575 @cartouche
19576   package Class_Carnivore is
19577     type Carnivore is limited interface;
19578     pragma Import (CPP, Carnivore);
19580     function Number_Of_Teeth (this : access Carnivore) return int is abstract;
19581   end;
19582   use Class_Carnivore;
19584   package Class_Domestic is
19585     type Domestic is limited interface;
19586     pragma Import (CPP, Domestic);
19588     procedure Set_Owner
19589       (this : access Domestic;
19590        Name : Interfaces.C.Strings.chars_ptr) is abstract;
19591   end;
19592   use Class_Domestic;
19594   package Class_Animal is
19595     type Animal is tagged limited record
19596       Age_Count : aliased int;
19597     end record;
19598     pragma Import (CPP, Animal);
19600     procedure Set_Age (this : access Animal; New_Age : int);
19601     pragma Import (CPP, Set_Age, "_ZN6Animal7Set_AgeEi");
19602   end;
19603   use Class_Animal;
19605   package Class_Dog is
19606     type Dog is new Animal and Carnivore and Domestic with record
19607       Tooth_Count : aliased int;
19608       Owner : Interfaces.C.Strings.chars_ptr;
19609     end record;
19610     pragma Import (CPP, Dog);
19612     function Number_Of_Teeth (this : access Dog) return int;
19613     pragma Import (CPP, Number_Of_Teeth, "_ZN3Dog15Number_Of_TeethEv");
19615     procedure Set_Owner
19616       (this : access Dog; Name : Interfaces.C.Strings.chars_ptr);
19617     pragma Import (CPP, Set_Owner, "_ZN3Dog9Set_OwnerEPc");
19619     function New_Dog return Dog;
19620     pragma CPP_Constructor (New_Dog);
19621     pragma Import (CPP, New_Dog, "_ZN3DogC1Ev");
19622   end;
19623   use Class_Dog;
19624 @end cartouche
19625 @end group
19626 @end smallexample
19628 @node Switches
19629 @section Switches
19631 @table @option
19632 @item -fdump-ada-spec
19633 @cindex @option{-fdump-ada-spec} (@command{gcc})
19634 Generate Ada spec files for the given header files transitively (including
19635 all header files that these headers depend upon).
19637 @item -fdump-ada-spec-slim
19638 @cindex @option{-fdump-ada-spec-slim} (@command{gcc})
19639 Generate Ada spec files for the header files specified on the command line
19640 only.
19642 @item -fada-spec-parent=@var{unit}
19643 @cindex -fada-spec-parent (@command{gcc})
19644 Specifies that all files generated by @option{-fdump-ada-spec*} are
19645 to be child units of the specified parent unit.
19647 @item -C
19648 @cindex @option{-C} (@command{gcc})
19649 Extract comments from headers and generate Ada comments in the Ada spec files.
19650 @end table
19652 @node Other Utility Programs
19653 @chapter Other Utility Programs
19655 @noindent
19656 This chapter discusses some other utility programs available in the Ada
19657 environment.
19659 @menu
19660 * Using Other Utility Programs with GNAT::
19661 * The External Symbol Naming Scheme of GNAT::
19662 * Converting Ada Files to html with gnathtml::
19663 * Installing gnathtml::
19664 @ifset vms
19665 * LSE::
19666 * Profiling::
19667 @end ifset
19668 @end menu
19670 @node Using Other Utility Programs with GNAT
19671 @section Using Other Utility Programs with GNAT
19673 @noindent
19674 The object files generated by GNAT are in standard system format and in
19675 particular the debugging information uses this format. This means
19676 programs generated by GNAT can be used with existing utilities that
19677 depend on these formats.
19679 @ifclear vms
19680 In general, any utility program that works with C will also often work with
19681 Ada programs generated by GNAT. This includes software utilities such as
19682 gprof (a profiling program), @code{gdb} (the FSF debugger), and utilities such
19683 as Purify.
19684 @end ifclear
19686 @node The External Symbol Naming Scheme of GNAT
19687 @section The External Symbol Naming Scheme of GNAT
19689 @noindent
19690 In order to interpret the output from GNAT, when using tools that are
19691 originally intended for use with other languages, it is useful to
19692 understand the conventions used to generate link names from the Ada
19693 entity names.
19695 All link names are in all lowercase letters. With the exception of library
19696 procedure names, the mechanism used is simply to use the full expanded
19697 Ada name with dots replaced by double underscores. For example, suppose
19698 we have the following package spec:
19700 @smallexample @c ada
19701 @group
19702 @cartouche
19703 package QRS is
19704    MN : Integer;
19705 end QRS;
19706 @end cartouche
19707 @end group
19708 @end smallexample
19710 @noindent
19711 The variable @code{MN} has a full expanded Ada name of @code{QRS.MN}, so
19712 the corresponding link name is @code{qrs__mn}.
19713 @findex Export
19714 Of course if a @code{pragma Export} is used this may be overridden:
19716 @smallexample @c ada
19717 @group
19718 @cartouche
19719 package Exports is
19720    Var1 : Integer;
19721    pragma Export (Var1, C, External_Name => "var1_name");
19722    Var2 : Integer;
19723    pragma Export (Var2, C, Link_Name => "var2_link_name");
19724 end Exports;
19725 @end cartouche
19726 @end group
19727 @end smallexample
19729 @noindent
19730 In this case, the link name for @var{Var1} is whatever link name the
19731 C compiler would assign for the C function @var{var1_name}. This typically
19732 would be either @var{var1_name} or @var{_var1_name}, depending on operating
19733 system conventions, but other possibilities exist. The link name for
19734 @var{Var2} is @var{var2_link_name}, and this is not operating system
19735 dependent.
19737 @findex _main
19738 One exception occurs for library level procedures. A potential ambiguity
19739 arises between the required name @code{_main} for the C main program,
19740 and the name we would otherwise assign to an Ada library level procedure
19741 called @code{Main} (which might well not be the main program).
19743 To avoid this ambiguity, we attach the prefix @code{_ada_} to such
19744 names. So if we have a library level procedure such as
19746 @smallexample @c ada
19747 @group
19748 @cartouche
19749 procedure Hello (S : String);
19750 @end cartouche
19751 @end group
19752 @end smallexample
19754 @noindent
19755 the external name of this procedure will be @var{_ada_hello}.
19758 @node Converting Ada Files to html with gnathtml
19759 @section Converting Ada Files to HTML with @code{gnathtml}
19761 @noindent
19762 This @code{Perl} script allows Ada source files to be browsed using
19763 standard Web browsers. For installation procedure, see the section
19764 @xref{Installing gnathtml}.
19766 Ada reserved keywords are highlighted in a bold font and Ada comments in
19767 a blue font. Unless your program was compiled with the gcc @option{-gnatx}
19768 switch to suppress the generation of cross-referencing information, user
19769 defined variables and types will appear in a different color; you will
19770 be able to click on any identifier and go to its declaration.
19772 The command line is as follow:
19773 @smallexample
19774 @c $ perl gnathtml.pl @ovar{^switches^options^} @var{ada-files}
19775 @c Expanding @ovar macro inline (explanation in macro def comments)
19776 $ perl gnathtml.pl @r{[}@var{^switches^options^}@r{]} @var{ada-files}
19777 @end smallexample
19779 @noindent
19780 You can pass it as many Ada files as you want. @code{gnathtml} will generate
19781 an html file for every ada file, and a global file called @file{index.htm}.
19782 This file is an index of every identifier defined in the files.
19784 The available ^switches^options^ are the following ones:
19786 @table @option
19787 @item -83
19788 @cindex @option{-83} (@code{gnathtml})
19789 Only the Ada 83 subset of keywords will be highlighted.
19791 @item -cc @var{color}
19792 @cindex @option{-cc} (@code{gnathtml})
19793 This option allows you to change the color used for comments. The default
19794 value is green. The color argument can be any name accepted by html.
19796 @item -d
19797 @cindex @option{-d} (@code{gnathtml})
19798 If the Ada files depend on some other files (for instance through
19799 @code{with} clauses, the latter files will also be converted to html.
19800 Only the files in the user project will be converted to html, not the files
19801 in the run-time library itself.
19803 @item -D
19804 @cindex @option{-D} (@code{gnathtml})
19805 This command is the same as @option{-d} above, but @command{gnathtml} will
19806 also look for files in the run-time library, and generate html files for them.
19808 @item -ext @var{extension}
19809 @cindex @option{-ext} (@code{gnathtml})
19810 This option allows you to change the extension of the generated HTML files.
19811 If you do not specify an extension, it will default to @file{htm}.
19813 @item -f
19814 @cindex @option{-f} (@code{gnathtml})
19815 By default, gnathtml will generate html links only for global entities
19816 ('with'ed units, global variables and types,@dots{}).  If you specify
19817 @option{-f} on the command line, then links will be generated for local
19818 entities too.
19820 @item -l @var{number}
19821 @cindex @option{-l} (@code{gnathtml})
19822 If this ^switch^option^ is provided and @var{number} is not 0, then
19823 @code{gnathtml} will number the html files every @var{number} line.
19825 @item -I @var{dir}
19826 @cindex @option{-I} (@code{gnathtml})
19827 Specify a directory to search for library files (@file{.ALI} files) and
19828 source files. You can provide several -I switches on the command line,
19829 and the directories will be parsed in the order of the command line.
19831 @item -o @var{dir}
19832 @cindex @option{-o} (@code{gnathtml})
19833 Specify the output directory for html files. By default, gnathtml will
19834 saved the generated html files in a subdirectory named @file{html/}.
19836 @item -p @var{file}
19837 @cindex @option{-p} (@code{gnathtml})
19838 If you are using Emacs and the most recent Emacs Ada mode, which provides
19839 a full Integrated Development Environment for compiling, checking,
19840 running and debugging applications, you may use @file{.gpr} files
19841 to give the directories where Emacs can find sources and object files.
19843 Using this ^switch^option^, you can tell gnathtml to use these files.
19844 This allows you to get an html version of your application, even if it
19845 is spread over multiple directories.
19847 @item -sc @var{color}
19848 @cindex @option{-sc} (@code{gnathtml})
19849 This ^switch^option^ allows you to change the color used for symbol
19850 definitions.
19851 The default value is red. The color argument can be any name accepted by html.
19853 @item -t @var{file}
19854 @cindex @option{-t} (@code{gnathtml})
19855 This ^switch^option^ provides the name of a file. This file contains a list of
19856 file names to be converted, and the effect is exactly as though they had
19857 appeared explicitly on the command line. This
19858 is the recommended way to work around the command line length limit on some
19859 systems.
19861 @end table
19863 @node Installing gnathtml
19864 @section Installing @code{gnathtml}
19866 @noindent
19867 @code{Perl} needs to be installed on your machine to run this script.
19868 @code{Perl} is freely available for almost every architecture and
19869 Operating System via the Internet.
19871 On Unix systems, you  may want to modify  the  first line of  the script
19872 @code{gnathtml},  to explicitly  tell  the Operating  system  where Perl
19873 is. The syntax of this line is:
19874 @smallexample
19875 #!full_path_name_to_perl
19876 @end smallexample
19878 @noindent
19879 Alternatively, you may run the script using the following command line:
19881 @smallexample
19882 @c $ perl gnathtml.pl @ovar{switches} @var{files}
19883 @c Expanding @ovar macro inline (explanation in macro def comments)
19884 $ perl gnathtml.pl @r{[}@var{switches}@r{]} @var{files}
19885 @end smallexample
19887 @ifset vms
19888 @node LSE
19889 @section LSE
19890 @findex LSE
19892 @noindent
19893 The GNAT distribution provides an Ada 95 template for the HP Language
19894 Sensitive Editor (LSE), a component of DECset. In order to
19895 access it, invoke LSE with the qualifier /ENVIRONMENT=GNU:[LIB]ADA95.ENV.
19897 @node Profiling
19898 @section Profiling
19899 @findex PCA
19901 @noindent
19902 GNAT supports The HP Performance Coverage Analyzer (PCA), a component
19903 of DECset. To use it proceed as outlined under ``HELP PCA'', except for running
19904 the collection phase with the /DEBUG qualifier.
19906 @smallexample
19907 $ GNAT MAKE /DEBUG <PROGRAM_NAME>
19908 $ DEFINE LIB$DEBUG PCA$COLLECTOR
19909 $ RUN/DEBUG <PROGRAM_NAME>
19910 @end smallexample
19911 @noindent
19912 @end ifset
19914 @ifclear vms
19915 @c ******************************
19916 @node Code Coverage and Profiling
19917 @chapter Code Coverage and Profiling
19918 @cindex Code Coverage
19919 @cindex Profiling
19921 @noindent
19922 This chapter describes how to use @code{gcov} - coverage testing tool - and
19923 @code{gprof} - profiler tool - on your Ada programs.
19925 @menu
19926 * Code Coverage of Ada Programs with gcov::
19927 * Profiling an Ada Program with gprof::
19928 @end menu
19930 @node Code Coverage of Ada Programs with gcov
19931 @section Code Coverage of Ada Programs with gcov
19932 @cindex gcov
19933 @cindex -fprofile-arcs
19934 @cindex -ftest-coverage
19935 @cindex -coverage
19936 @cindex Code Coverage
19938 @noindent
19939 @code{gcov} is a test coverage program: it analyzes the execution of a given
19940 program on selected tests, to help you determine the portions of the program
19941 that are still untested.
19943 @code{gcov} is part of the GCC suite, and is described in detail in the GCC
19944 User's Guide. You can refer to this documentation for a more complete
19945 description.
19947 This chapter provides a quick startup guide, and
19948 details some Gnat-specific features.
19950 @menu
19951 * Quick startup guide::
19952 * Gnat specifics::
19953 @end menu
19955 @node Quick startup guide
19956 @subsection Quick startup guide
19958 In order to perform coverage analysis of a program using @code{gcov}, 3
19959 steps are needed:
19961 @itemize @bullet
19962 @item
19963 Code instrumentation during the compilation process
19964 @item
19965 Execution of the instrumented program
19966 @item
19967 Execution of the @code{gcov} tool to generate the result.
19968 @end itemize
19970 The code instrumentation needed by gcov is created at the object level:
19971 The source code is not modified in any way, because the instrumentation code is
19972 inserted by gcc during the compilation process. To compile your code with code
19973 coverage activated, you need to recompile your whole project using the
19974 switches
19975 @code{-fprofile-arcs} and @code{-ftest-coverage}, and link it using
19976 @code{-fprofile-arcs}.
19978 @smallexample
19979 $ gnatmake -P my_project.gpr -f -cargs -fprofile-arcs -ftest-coverage \
19980    -largs -fprofile-arcs
19981 @end smallexample
19983 This compilation process will create @file{.gcno} files together with
19984 the usual object files.
19986 Once the program is compiled with coverage instrumentation, you can
19987 run it as many times as needed - on portions of a test suite for
19988 example. The first execution will produce @file{.gcda} files at the
19989 same location as the @file{.gcno} files.  The following executions
19990 will update those files, so that a cumulative result of the covered
19991 portions of the program is generated.
19993 Finally, you need to call the @code{gcov} tool. The different options of
19994 @code{gcov} are available in the GCC User's Guide, section 'Invoking gcov'.
19996 This will create annotated source files with a @file{.gcov} extension:
19997 @file{my_main.adb} file will be analysed in @file{my_main.adb.gcov}.
19999 @node Gnat specifics
20000 @subsection Gnat specifics
20002 Because Ada semantics, portions of the source code may be shared among
20003 several object files. This is the case for example when generics are
20004 involved, when inlining is active  or when declarations generate  initialisation
20005 calls. In order to take
20006 into account this shared code, you need to call @code{gcov} on all
20007 source files of the tested program at once.
20009 The list of source files might exceed the system's maximum command line
20010 length. In order to bypass this limitation, a new mechanism has been
20011 implemented in @code{gcov}: you can now list all your project's files into a
20012 text file, and provide this file to gcov as a parameter,  preceded by a @@
20013 (e.g. @samp{gcov @@mysrclist.txt}).
20015 Note that on AIX compiling a static library with @code{-fprofile-arcs} is
20016 not supported as there can be unresolved symbols during the final link.
20018 @node Profiling an Ada Program with gprof
20019 @section Profiling an Ada Program with gprof
20020 @cindex gprof
20021 @cindex -pg
20022 @cindex Profiling
20024 @noindent
20025 This section is not meant to be an exhaustive documentation of @code{gprof}.
20026 Full documentation for it can be found in the GNU Profiler User's Guide
20027 documentation that is part of this GNAT distribution.
20029 Profiling a program helps determine the parts of a program that are executed
20030 most often, and are therefore the most time-consuming.
20032 @code{gprof} is the standard GNU profiling tool; it has been enhanced to
20033 better handle Ada programs and multitasking.
20034 It is currently supported on the following platforms
20035 @itemize @bullet
20036 @item
20037 linux x86/x86_64
20038 @item
20039 solaris sparc/sparc64/x86
20040 @item
20041 windows x86
20042 @end itemize
20044 @noindent
20045 In order to profile a program using @code{gprof}, 3 steps are needed:
20047 @itemize @bullet
20048 @item
20049 Code instrumentation, requiring a full recompilation of the project with the
20050 proper switches.
20051 @item
20052 Execution of the program under the analysis conditions, i.e. with the desired
20053 input.
20054 @item
20055 Analysis of the results using the @code{gprof} tool.
20056 @end itemize
20058 @noindent
20059 The following sections detail the different steps, and indicate how
20060 to interpret the results:
20061 @menu
20062 * Compilation for profiling::
20063 * Program execution::
20064 * Running gprof::
20065 * Interpretation of profiling results::
20066 @end menu
20068 @node Compilation for profiling
20069 @subsection Compilation for profiling
20070 @cindex -pg
20071 @cindex Profiling
20073 In order to profile a program the first step is to tell the compiler
20074 to generate the necessary profiling information. The compiler switch to be used
20075 is @code{-pg}, which must be added to other compilation switches. This
20076 switch needs to be specified both during compilation and link stages, and can
20077 be specified once when using gnatmake:
20079 @smallexample
20080 gnatmake -f -pg -P my_project
20081 @end smallexample
20083 @noindent
20084 Note that only the objects that were compiled with the @samp{-pg} switch will
20085 be profiled; if you need to profile your whole project, use the @samp{-f}
20086 gnatmake switch to force full recompilation.
20088 @node Program execution
20089 @subsection Program execution
20091 @noindent
20092 Once the program has been compiled for profiling, you can run it as usual.
20094 The only constraint imposed by profiling is that the program must terminate
20095 normally. An interrupted program (via a Ctrl-C, kill, etc.) will not be
20096 properly analyzed.
20098 Once the program completes execution, a data file called @file{gmon.out} is
20099 generated in the directory where the program was launched from. If this file
20100 already exists, it will be overwritten.
20102 @node Running gprof
20103 @subsection Running gprof
20105 @noindent
20106 The @code{gprof} tool is called as follow:
20108 @smallexample
20109 gprof my_prog gmon.out
20110 @end smallexample
20112 @noindent
20113 or simpler:
20115 @smallexample
20116 gprof my_prog
20117 @end smallexample
20119 @noindent
20120 The complete form of the gprof command line is the following:
20122 @smallexample
20123 gprof [^switches^options^] [executable [data-file]]
20124 @end smallexample
20126 @noindent
20127 @code{gprof} supports numerous ^switch^options^. The order of these
20128 ^switch^options^ does not matter. The full list of options can be found in
20129 the GNU Profiler User's Guide documentation that comes with this documentation.
20131 The following is the subset of those switches that is most relevant:
20133 @table @option
20135 @item --demangle[=@var{style}]
20136 @itemx --no-demangle
20137 @cindex @option{--demangle} (@code{gprof})
20138 These options control whether symbol names should be demangled when
20139 printing output.  The default is to demangle C++ symbols.  The
20140 @code{--no-demangle} option may be used to turn off demangling. Different
20141 compilers have different mangling styles.  The optional demangling style
20142 argument can be used to choose an appropriate demangling style for your
20143 compiler, in particular Ada symbols generated by GNAT can be demangled using
20144 @code{--demangle=gnat}.
20146 @item -e @var{function_name}
20147 @cindex @option{-e} (@code{gprof})
20148 The @samp{-e @var{function}} option tells @code{gprof} not to print
20149 information about the function @var{function_name} (and its
20150 children@dots{}) in the call graph.  The function will still be listed
20151 as a child of any functions that call it, but its index number will be
20152 shown as @samp{[not printed]}.  More than one @samp{-e} option may be
20153 given; only one @var{function_name} may be indicated with each @samp{-e}
20154 option.
20156 @item -E @var{function_name}
20157 @cindex @option{-E} (@code{gprof})
20158 The @code{-E @var{function}} option works like the @code{-e} option, but
20159 execution time spent in the function (and children who were not called from
20160 anywhere else), will not be used to compute the percentages-of-time for
20161 the call graph.  More than one @samp{-E} option may be given; only one
20162 @var{function_name} may be indicated with each @samp{-E} option.
20164 @item -f @var{function_name}
20165 @cindex @option{-f} (@code{gprof})
20166 The @samp{-f @var{function}} option causes @code{gprof} to limit the
20167 call graph to the function @var{function_name} and its children (and
20168 their children@dots{}).  More than one @samp{-f} option may be given;
20169 only one @var{function_name} may be indicated with each @samp{-f}
20170 option.
20172 @item -F @var{function_name}
20173 @cindex @option{-F} (@code{gprof})
20174 The @samp{-F @var{function}} option works like the @code{-f} option, but
20175 only time spent in the function and its children (and their
20176 children@dots{}) will be used to determine total-time and
20177 percentages-of-time for the call graph.  More than one @samp{-F} option
20178 may be given; only one @var{function_name} may be indicated with each
20179 @samp{-F} option.  The @samp{-F} option overrides the @samp{-E} option.
20181 @end table
20183 @node Interpretation of profiling results
20184 @subsection Interpretation of profiling results
20186 @noindent
20188 The results of the profiling analysis are represented by two arrays: the
20189 'flat profile' and the 'call graph'. Full documentation of those outputs
20190 can be found in the GNU Profiler User's Guide.
20192 The flat profile shows the time spent in each function of the program, and how
20193 many time it has been called. This allows you to locate easily the most
20194 time-consuming functions.
20196 The call graph shows, for each subprogram, the subprograms that call it,
20197 and the subprograms that it calls. It also provides an estimate of the time
20198 spent in each of those callers/called subprograms.
20199 @end ifclear
20201 @c ******************************
20202 @node Running and Debugging Ada Programs
20203 @chapter Running and Debugging Ada Programs
20204 @cindex Debugging
20206 @noindent
20207 This chapter discusses how to debug Ada programs.
20208 @ifset vms
20209 It applies to GNAT on the Alpha OpenVMS platform;
20210 for I64 OpenVMS please refer to the @cite{OpenVMS Debugger Manual},
20211 since HP has implemented Ada support in the OpenVMS debugger on I64.
20212 @end ifset
20214 An incorrect Ada program may be handled in three ways by the GNAT compiler:
20216 @enumerate
20217 @item
20218 The illegality may be a violation of the static semantics of Ada. In
20219 that case GNAT diagnoses the constructs in the program that are illegal.
20220 It is then a straightforward matter for the user to modify those parts of
20221 the program.
20223 @item
20224 The illegality may be a violation of the dynamic semantics of Ada. In
20225 that case the program compiles and executes, but may generate incorrect
20226 results, or may terminate abnormally with some exception.
20228 @item
20229 When presented with a program that contains convoluted errors, GNAT
20230 itself may terminate abnormally without providing full diagnostics on
20231 the incorrect user program.
20232 @end enumerate
20234 @menu
20235 * The GNAT Debugger GDB::
20236 * Running GDB::
20237 * Introduction to GDB Commands::
20238 * Using Ada Expressions::
20239 * Calling User-Defined Subprograms::
20240 * Using the Next Command in a Function::
20241 * Ada Exceptions::
20242 * Ada Tasks::
20243 * Debugging Generic Units::
20244 * Remote Debugging with gdbserver::
20245 * GNAT Abnormal Termination or Failure to Terminate::
20246 * Naming Conventions for GNAT Source Files::
20247 * Getting Internal Debugging Information::
20248 * Stack Traceback::
20249 @end menu
20251 @cindex Debugger
20252 @findex gdb
20254 @node The GNAT Debugger GDB
20255 @section The GNAT Debugger GDB
20257 @noindent
20258 @code{GDB} is a general purpose, platform-independent debugger that
20259 can be used to debug mixed-language programs compiled with @command{gcc},
20260 and in particular is capable of debugging Ada programs compiled with
20261 GNAT. The latest versions of @code{GDB} are Ada-aware and can handle
20262 complex Ada data structures.
20264 @xref{Top,, Debugging with GDB, gdb, Debugging with GDB},
20265 @ifset vms
20266 located in the GNU:[DOCS] directory,
20267 @end ifset
20268 for full details on the usage of @code{GDB}, including a section on
20269 its usage on programs. This manual should be consulted for full
20270 details. The section that follows is a brief introduction to the
20271 philosophy and use of @code{GDB}.
20273 When GNAT programs are compiled, the compiler optionally writes debugging
20274 information into the generated object file, including information on
20275 line numbers, and on declared types and variables. This information is
20276 separate from the generated code. It makes the object files considerably
20277 larger, but it does not add to the size of the actual executable that
20278 will be loaded into memory, and has no impact on run-time performance. The
20279 generation of debug information is triggered by the use of the
20280 ^-g^/DEBUG^ switch in the @command{gcc} or @command{gnatmake} command
20281 used to carry out the compilations. It is important to emphasize that
20282 the use of these options does not change the generated code.
20284 The debugging information is written in standard system formats that
20285 are used by many tools, including debuggers and profilers. The format
20286 of the information is typically designed to describe C types and
20287 semantics, but GNAT implements a translation scheme which allows full
20288 details about Ada types and variables to be encoded into these
20289 standard C formats. Details of this encoding scheme may be found in
20290 the file exp_dbug.ads in the GNAT source distribution. However, the
20291 details of this encoding are, in general, of no interest to a user,
20292 since @code{GDB} automatically performs the necessary decoding.
20294 When a program is bound and linked, the debugging information is
20295 collected from the object files, and stored in the executable image of
20296 the program. Again, this process significantly increases the size of
20297 the generated executable file, but it does not increase the size of
20298 the executable program itself. Furthermore, if this program is run in
20299 the normal manner, it runs exactly as if the debug information were
20300 not present, and takes no more actual memory.
20302 However, if the program is run under control of @code{GDB}, the
20303 debugger is activated.  The image of the program is loaded, at which
20304 point it is ready to run.  If a run command is given, then the program
20305 will run exactly as it would have if @code{GDB} were not present. This
20306 is a crucial part of the @code{GDB} design philosophy.  @code{GDB} is
20307 entirely non-intrusive until a breakpoint is encountered.  If no
20308 breakpoint is ever hit, the program will run exactly as it would if no
20309 debugger were present. When a breakpoint is hit, @code{GDB} accesses
20310 the debugging information and can respond to user commands to inspect
20311 variables, and more generally to report on the state of execution.
20313 @c **************
20314 @node Running GDB
20315 @section Running GDB
20317 @noindent
20318 This section describes how to initiate the debugger.
20319 @c The above sentence is really just filler, but it was otherwise
20320 @c clumsy to get the first paragraph nonindented given the conditional
20321 @c nature of the description
20323 @ifclear vms
20324 The debugger can be launched from a @code{GPS} menu or
20325 directly from the command line. The description below covers the latter use.
20326 All the commands shown can be used in the @code{GPS} debug console window,
20327 but there are usually more GUI-based ways to achieve the same effect.
20328 @end ifclear
20330 The command to run @code{GDB} is
20332 @smallexample
20333 $ ^gdb program^GDB PROGRAM^
20334 @end smallexample
20336 @noindent
20337 where @code{^program^PROGRAM^} is the name of the executable file. This
20338 activates the debugger and results in a prompt for debugger commands.
20339 The simplest command is simply @code{run}, which causes the program to run
20340 exactly as if the debugger were not present. The following section
20341 describes some of the additional commands that can be given to @code{GDB}.
20343 @c *******************************
20344 @node Introduction to GDB Commands
20345 @section Introduction to GDB Commands
20347 @noindent
20348 @code{GDB} contains a large repertoire of commands.  @xref{Top,,
20349 Debugging with GDB, gdb, Debugging with GDB},
20350 @ifset vms
20351 located in the GNU:[DOCS] directory,
20352 @end ifset
20353 for extensive documentation on the use
20354 of these commands, together with examples of their use. Furthermore,
20355 the command @command{help} invoked from within GDB activates a simple help
20356 facility which summarizes the available commands and their options.
20357 In this section we summarize a few of the most commonly
20358 used commands to give an idea of what @code{GDB} is about. You should create
20359 a simple program with debugging information and experiment with the use of
20360 these @code{GDB} commands on the program as you read through the
20361 following section.
20363 @table @code
20364 @item set args @var{arguments}
20365 The @var{arguments} list above is a list of arguments to be passed to
20366 the program on a subsequent run command, just as though the arguments
20367 had been entered on a normal invocation of the program. The @code{set args}
20368 command is not needed if the program does not require arguments.
20370 @item run
20371 The @code{run} command causes execution of the program to start from
20372 the beginning. If the program is already running, that is to say if
20373 you are currently positioned at a breakpoint, then a prompt will ask
20374 for confirmation that you want to abandon the current execution and
20375 restart.
20377 @item breakpoint @var{location}
20378 The breakpoint command sets a breakpoint, that is to say a point at which
20379 execution will halt and @code{GDB} will await further
20380 commands. @var{location} is
20381 either a line number within a file, given in the format @code{file:linenumber},
20382 or it is the name of a subprogram. If you request that a breakpoint be set on
20383 a subprogram that is overloaded, a prompt will ask you to specify on which of
20384 those subprograms you want to breakpoint. You can also
20385 specify that all of them should be breakpointed. If the program is run
20386 and execution encounters the breakpoint, then the program
20387 stops and @code{GDB} signals that the breakpoint was encountered by
20388 printing the line of code before which the program is halted.
20390 @item catch exception @var{name}
20391 This command causes the program execution to stop whenever exception
20392 @var{name} is raised.  If @var{name} is omitted, then the execution is
20393 suspended when any exception is raised.
20395 @item print @var{expression}
20396 This will print the value of the given expression. Most simple
20397 Ada expression formats are properly handled by @code{GDB}, so the expression
20398 can contain function calls, variables, operators, and attribute references.
20400 @item continue
20401 Continues execution following a breakpoint, until the next breakpoint or the
20402 termination of the program.
20404 @item step
20405 Executes a single line after a breakpoint. If the next statement
20406 is a subprogram call, execution continues into (the first statement of)
20407 the called subprogram.
20409 @item next
20410 Executes a single line. If this line is a subprogram call, executes and
20411 returns from the call.
20413 @item list
20414 Lists a few lines around the current source location. In practice, it
20415 is usually more convenient to have a separate edit window open with the
20416 relevant source file displayed. Successive applications of this command
20417 print subsequent lines. The command can be given an argument which is a
20418 line number, in which case it displays a few lines around the specified one.
20420 @item backtrace
20421 Displays a backtrace of the call chain. This command is typically
20422 used after a breakpoint has occurred, to examine the sequence of calls that
20423 leads to the current breakpoint. The display includes one line for each
20424 activation record (frame) corresponding to an active subprogram.
20426 @item up
20427 At a breakpoint, @code{GDB} can display the values of variables local
20428 to the current frame. The command @code{up} can be used to
20429 examine the contents of other active frames, by moving the focus up
20430 the stack, that is to say from callee to caller, one frame at a time.
20432 @item down
20433 Moves the focus of @code{GDB} down from the frame currently being
20434 examined to the frame of its callee (the reverse of the previous command),
20436 @item frame @var{n}
20437 Inspect the frame with the given number. The value 0 denotes the frame
20438 of the current breakpoint, that is to say the top of the call stack.
20440 @end table
20442 @noindent
20443 The above list is a very short introduction to the commands that
20444 @code{GDB} provides. Important additional capabilities, including conditional
20445 breakpoints, the ability to execute command sequences on a breakpoint,
20446 the ability to debug at the machine instruction level and many other
20447 features are described in detail in @ref{Top,, Debugging with GDB, gdb,
20448 Debugging with GDB}.  Note that most commands can be abbreviated
20449 (for example, c for continue, bt for backtrace).
20451 @node Using Ada Expressions
20452 @section Using Ada Expressions
20453 @cindex Ada expressions
20455 @noindent
20456 @code{GDB} supports a fairly large subset of Ada expression syntax, with some
20457 extensions. The philosophy behind the design of this subset is
20459 @itemize @bullet
20460 @item
20461 That @code{GDB} should provide basic literals and access to operations for
20462 arithmetic, dereferencing, field selection, indexing, and subprogram calls,
20463 leaving more sophisticated computations to subprograms written into the
20464 program (which therefore may be called from @code{GDB}).
20466 @item
20467 That type safety and strict adherence to Ada language restrictions
20468 are not particularly important to the @code{GDB} user.
20470 @item
20471 That brevity is important to the @code{GDB} user.
20472 @end itemize
20474 @noindent
20475 Thus, for brevity, the debugger acts as if there were
20476 implicit @code{with} and @code{use} clauses in effect for all user-written
20477 packages, thus making it unnecessary to fully qualify most names with
20478 their packages, regardless of context. Where this causes ambiguity,
20479 @code{GDB} asks the user's intent.
20481 For details on the supported Ada syntax, see @ref{Top,, Debugging with
20482 GDB, gdb, Debugging with GDB}.
20484 @node Calling User-Defined Subprograms
20485 @section Calling User-Defined Subprograms
20487 @noindent
20488 An important capability of @code{GDB} is the ability to call user-defined
20489 subprograms while debugging. This is achieved simply by entering
20490 a subprogram call statement in the form:
20492 @smallexample
20493 call subprogram-name (parameters)
20494 @end smallexample
20496 @noindent
20497 The keyword @code{call} can be omitted in the normal case where the
20498 @code{subprogram-name} does not coincide with any of the predefined
20499 @code{GDB} commands.
20501 The effect is to invoke the given subprogram, passing it the
20502 list of parameters that is supplied. The parameters can be expressions and
20503 can include variables from the program being debugged. The
20504 subprogram must be defined
20505 at the library level within your program, and @code{GDB} will call the
20506 subprogram within the environment of your program execution (which
20507 means that the subprogram is free to access or even modify variables
20508 within your program).
20510 The most important use of this facility is in allowing the inclusion of
20511 debugging routines that are tailored to particular data structures
20512 in your program. Such debugging routines can be written to provide a suitably
20513 high-level description of an abstract type, rather than a low-level dump
20514 of its physical layout. After all, the standard
20515 @code{GDB print} command only knows the physical layout of your
20516 types, not their abstract meaning. Debugging routines can provide information
20517 at the desired semantic level and are thus enormously useful.
20519 For example, when debugging GNAT itself, it is crucial to have access to
20520 the contents of the tree nodes used to represent the program internally.
20521 But tree nodes are represented simply by an integer value (which in turn
20522 is an index into a table of nodes).
20523 Using the @code{print} command on a tree node would simply print this integer
20524 value, which is not very useful. But the PN routine (defined in file
20525 treepr.adb in the GNAT sources) takes a tree node as input, and displays
20526 a useful high level representation of the tree node, which includes the
20527 syntactic category of the node, its position in the source, the integers
20528 that denote descendant nodes and parent node, as well as varied
20529 semantic information. To study this example in more detail, you might want to
20530 look at the body of the PN procedure in the stated file.
20532 @node Using the Next Command in a Function
20533 @section Using the Next Command in a Function
20535 @noindent
20536 When you use the @code{next} command in a function, the current source
20537 location will advance to the next statement as usual. A special case
20538 arises in the case of a @code{return} statement.
20540 Part of the code for a return statement is the ``epilog'' of the function.
20541 This is the code that returns to the caller. There is only one copy of
20542 this epilog code, and it is typically associated with the last return
20543 statement in the function if there is more than one return. In some
20544 implementations, this epilog is associated with the first statement
20545 of the function.
20547 The result is that if you use the @code{next} command from a return
20548 statement that is not the last return statement of the function you
20549 may see a strange apparent jump to the last return statement or to
20550 the start of the function. You should simply ignore this odd jump.
20551 The value returned is always that from the first return statement
20552 that was stepped through.
20554 @node Ada Exceptions
20555 @section Stopping when Ada Exceptions are Raised
20556 @cindex Exceptions
20558 @noindent
20559 You can set catchpoints that stop the program execution when your program
20560 raises selected exceptions.
20562 @table @code
20563 @item catch exception
20564 Set a catchpoint that stops execution whenever (any task in the) program
20565 raises any exception.
20567 @item catch exception @var{name}
20568 Set a catchpoint that stops execution whenever (any task in the) program
20569 raises the exception @var{name}.
20571 @item catch exception unhandled
20572 Set a catchpoint that stops executing whenever (any task in the) program
20573 raises an exception for which there is no handler.
20575 @item info exceptions
20576 @itemx info exceptions @var{regexp}
20577 The @code{info exceptions} command permits the user to examine all defined
20578 exceptions within Ada programs. With a regular expression, @var{regexp}, as
20579 argument, prints out only those exceptions whose name matches @var{regexp}.
20580 @end table
20582 @node Ada Tasks
20583 @section Ada Tasks
20584 @cindex Tasks
20586 @noindent
20587 @code{GDB} allows the following task-related commands:
20589 @table @code
20590 @item info tasks
20591 This command shows a list of current Ada tasks, as in the following example:
20593 @smallexample
20594 @iftex
20595 @leftskip=0cm
20596 @end iftex
20597 (gdb) info tasks
20598   ID       TID P-ID   Thread Pri State                 Name
20599    1   8088000   0   807e000  15 Child Activation Wait main_task
20600    2   80a4000   1   80ae000  15 Accept/Select Wait    b
20601    3   809a800   1   80a4800  15 Child Activation Wait a
20602 *  4   80ae800   3   80b8000  15 Running               c
20603 @end smallexample
20605 @noindent
20606 In this listing, the asterisk before the first task indicates it to be the
20607 currently running task. The first column lists the task ID that is used
20608 to refer to tasks in the following commands.
20610 @item break @var{linespec} task @var{taskid}
20611 @itemx break @var{linespec} task @var{taskid} if @dots{}
20612 @cindex Breakpoints and tasks
20613 These commands are like the @code{break @dots{} thread @dots{}}.
20614 @var{linespec} specifies source lines.
20616 Use the qualifier @samp{task @var{taskid}} with a breakpoint command
20617 to specify that you only want @code{GDB} to stop the program when a
20618 particular Ada task reaches this breakpoint. @var{taskid} is one of the
20619 numeric task identifiers assigned by @code{GDB}, shown in the first
20620 column of the @samp{info tasks} display.
20622 If you do not specify @samp{task @var{taskid}} when you set a
20623 breakpoint, the breakpoint applies to @emph{all} tasks of your
20624 program.
20626 You can use the @code{task} qualifier on conditional breakpoints as
20627 well; in this case, place @samp{task @var{taskid}} before the
20628 breakpoint condition (before the @code{if}).
20630 @item task @var{taskno}
20631 @cindex Task switching
20633 This command allows to switch to the task referred by @var{taskno}. In
20634 particular, This allows to browse the backtrace of the specified
20635 task. It is advised to switch back to the original task before
20636 continuing execution otherwise the scheduling of the program may be
20637 perturbed.
20638 @end table
20640 @noindent
20641 For more detailed information on the tasking support,
20642 see @ref{Top,, Debugging with GDB, gdb, Debugging with GDB}.
20644 @node Debugging Generic Units
20645 @section Debugging Generic Units
20646 @cindex Debugging Generic Units
20647 @cindex Generics
20649 @noindent
20650 GNAT always uses code expansion for generic instantiation. This means that
20651 each time an instantiation occurs, a complete copy of the original code is
20652 made, with appropriate substitutions of formals by actuals.
20654 It is not possible to refer to the original generic entities in
20655 @code{GDB}, but it is always possible to debug a particular instance of
20656 a generic, by using the appropriate expanded names. For example, if we have
20658 @smallexample @c ada
20659 @group
20660 @cartouche
20661 procedure g is
20663    generic package k is
20664       procedure kp (v1 : in out integer);
20665    end k;
20667    package body k is
20668       procedure kp (v1 : in out integer) is
20669       begin
20670          v1 := v1 + 1;
20671       end kp;
20672    end k;
20674    package k1 is new k;
20675    package k2 is new k;
20677    var : integer := 1;
20679 begin
20680    k1.kp (var);
20681    k2.kp (var);
20682    k1.kp (var);
20683    k2.kp (var);
20684 end;
20685 @end cartouche
20686 @end group
20687 @end smallexample
20689 @noindent
20690 Then to break on a call to procedure kp in the k2 instance, simply
20691 use the command:
20693 @smallexample
20694 (gdb) break g.k2.kp
20695 @end smallexample
20697 @noindent
20698 When the breakpoint occurs, you can step through the code of the
20699 instance in the normal manner and examine the values of local variables, as for
20700 other units.
20702 @node Remote Debugging with gdbserver
20703 @section Remote Debugging with gdbserver
20704 @cindex Remote Debugging with gdbserver
20706 @noindent
20707 On platforms where gdbserver is supported, it is possible to use this tool
20708 to debug your application remotely.  This can be useful in situations
20709 where the program needs to be run on a target host that is different
20710 from the host used for development, particularly when the target has
20711 a limited amount of resources (either CPU and/or memory).
20713 To do so, start your program using gdbserver on the target machine.
20714 gdbserver then automatically suspends the execution of your program
20715 at its entry point, waiting for a debugger to connect to it.  The
20716 following commands starts an application and tells gdbserver to
20717 wait for a connection with the debugger on localhost port 4444.
20719 @smallexample
20720 $ gdbserver localhost:4444 program
20721 Process program created; pid = 5685
20722 Listening on port 4444
20723 @end smallexample
20725 Once gdbserver has started listening, we can tell the debugger to establish
20726 a connection with this gdbserver, and then start the same debugging session
20727 as if the program was being debugged on the same host, directly under
20728 the control of GDB.
20730 @smallexample
20731 $ gdb program
20732 (gdb) target remote targethost:4444
20733 Remote debugging using targethost:4444
20734 0x00007f29936d0af0 in ?? () from /lib64/ld-linux-x86-64.so.
20735 (gdb) b foo.adb:3
20736 Breakpoint 1 at 0x401f0c: file foo.adb, line 3.
20737 (gdb) continue
20738 Continuing.
20740 Breakpoint 1, foo () at foo.adb:4
20741 4       end foo;
20742 @end smallexample
20744 It is also possible to use gdbserver to attach to an already running
20745 program, in which case the execution of that program is simply suspended
20746 until the connection between the debugger and gdbserver is established.
20748 For more information on how to use gdbserver, @ref{Top, Server, Using
20749 the gdbserver Program, gdb, Debugging with GDB}.  @value{EDITION} provides support
20750 for gdbserver on x86-linux, x86-windows and x86_64-linux.
20752 @node GNAT Abnormal Termination or Failure to Terminate
20753 @section GNAT Abnormal Termination or Failure to Terminate
20754 @cindex GNAT Abnormal Termination or Failure to Terminate
20756 @noindent
20757 When presented with programs that contain serious errors in syntax
20758 or semantics,
20759 GNAT may on rare occasions  experience problems in operation, such
20760 as aborting with a
20761 segmentation fault or illegal memory access, raising an internal
20762 exception, terminating abnormally, or failing to terminate at all.
20763 In such cases, you can activate
20764 various features of GNAT that can help you pinpoint the construct in your
20765 program that is the likely source of the problem.
20767 The following strategies are presented in increasing order of
20768 difficulty, corresponding to your experience in using GNAT and your
20769 familiarity with compiler internals.
20771 @enumerate
20772 @item
20773 Run @command{gcc} with the @option{-gnatf}. This first
20774 switch causes all errors on a given line to be reported. In its absence,
20775 only the first error on a line is displayed.
20777 The @option{-gnatdO} switch causes errors to be displayed as soon as they
20778 are encountered, rather than after compilation is terminated. If GNAT
20779 terminates prematurely or goes into an infinite loop, the last error
20780 message displayed may help to pinpoint the culprit.
20782 @item
20783 Run @command{gcc} with the @option{^-v (verbose)^/VERBOSE^} switch. In this
20784 mode, @command{gcc} produces ongoing information about the progress of the
20785 compilation and provides the name of each procedure as code is
20786 generated. This switch allows you to find which Ada procedure was being
20787 compiled when it encountered a code generation problem.
20789 @item
20790 @cindex @option{-gnatdc} switch
20791 Run @command{gcc} with the @option{-gnatdc} switch. This is a GNAT specific
20792 switch that does for the front-end what @option{^-v^VERBOSE^} does
20793 for the back end. The system prints the name of each unit,
20794 either a compilation unit or nested unit, as it is being analyzed.
20795 @item
20796 Finally, you can start
20797 @code{gdb} directly on the @code{gnat1} executable. @code{gnat1} is the
20798 front-end of GNAT, and can be run independently (normally it is just
20799 called from @command{gcc}). You can use @code{gdb} on @code{gnat1} as you
20800 would on a C program (but @pxref{The GNAT Debugger GDB} for caveats). The
20801 @code{where} command is the first line of attack; the variable
20802 @code{lineno} (seen by @code{print lineno}), used by the second phase of
20803 @code{gnat1} and by the @command{gcc} backend, indicates the source line at
20804 which the execution stopped, and @code{input_file name} indicates the name of
20805 the source file.
20806 @end enumerate
20808 @node Naming Conventions for GNAT Source Files
20809 @section Naming Conventions for GNAT Source Files
20811 @noindent
20812 In order to examine the workings of the GNAT system, the following
20813 brief description of its organization may be helpful:
20815 @itemize @bullet
20816 @item
20817 Files with prefix @file{^sc^SC^} contain the lexical scanner.
20819 @item
20820 All files prefixed with @file{^par^PAR^} are components of the parser. The
20821 numbers correspond to chapters of the Ada Reference Manual. For example,
20822 parsing of select statements can be found in @file{par-ch9.adb}.
20824 @item
20825 All files prefixed with @file{^sem^SEM^} perform semantic analysis. The
20826 numbers correspond to chapters of the Ada standard. For example, all
20827 issues involving context clauses can be found in @file{sem_ch10.adb}. In
20828 addition, some features of the language require sufficient special processing
20829 to justify their own semantic files: sem_aggr for aggregates, sem_disp for
20830 dynamic dispatching, etc.
20832 @item
20833 All files prefixed with @file{^exp^EXP^} perform normalization and
20834 expansion of the intermediate representation (abstract syntax tree, or AST).
20835 these files use the same numbering scheme as the parser and semantics files.
20836 For example, the construction of record initialization procedures is done in
20837 @file{exp_ch3.adb}.
20839 @item
20840 The files prefixed with @file{^bind^BIND^} implement the binder, which
20841 verifies the consistency of the compilation, determines an order of
20842 elaboration, and generates the bind file.
20844 @item
20845 The files @file{atree.ads} and @file{atree.adb} detail the low-level
20846 data structures used by the front-end.
20848 @item
20849 The files @file{sinfo.ads} and @file{sinfo.adb} detail the structure of
20850 the abstract syntax tree as produced by the parser.
20852 @item
20853 The files @file{einfo.ads} and @file{einfo.adb} detail the attributes of
20854 all entities, computed during semantic analysis.
20856 @item
20857 Library management issues are dealt with in files with prefix
20858 @file{^lib^LIB^}.
20860 @item
20861 @findex Ada
20862 @cindex Annex A
20863 Ada files with the prefix @file{^a-^A-^} are children of @code{Ada}, as
20864 defined in Annex A.
20866 @item
20867 @findex Interfaces
20868 @cindex Annex B
20869 Files with prefix @file{^i-^I-^} are children of @code{Interfaces}, as
20870 defined in Annex B.
20872 @item
20873 @findex System
20874 Files with prefix @file{^s-^S-^} are children of @code{System}. This includes
20875 both language-defined children and GNAT run-time routines.
20877 @item
20878 @findex GNAT
20879 Files with prefix @file{^g-^G-^} are children of @code{GNAT}. These are useful
20880 general-purpose packages, fully documented in their specs. All
20881 the other @file{.c} files are modifications of common @command{gcc} files.
20882 @end itemize
20884 @node Getting Internal Debugging Information
20885 @section Getting Internal Debugging Information
20887 @noindent
20888 Most compilers have internal debugging switches and modes. GNAT
20889 does also, except GNAT internal debugging switches and modes are not
20890 secret. A summary and full description of all the compiler and binder
20891 debug flags are in the file @file{debug.adb}. You must obtain the
20892 sources of the compiler to see the full detailed effects of these flags.
20894 The switches that print the source of the program (reconstructed from
20895 the internal tree) are of general interest for user programs, as are the
20896 options to print
20897 the full internal tree, and the entity table (the symbol table
20898 information). The reconstructed source provides a readable version of the
20899 program after the front-end has completed analysis and  expansion,
20900 and is useful when studying the performance of specific constructs.
20901 For example, constraint checks are indicated, complex aggregates
20902 are replaced with loops and assignments, and tasking primitives
20903 are replaced with run-time calls.
20905 @node Stack Traceback
20906 @section Stack Traceback
20907 @cindex traceback
20908 @cindex stack traceback
20909 @cindex stack unwinding
20911 @noindent
20912 Traceback is a mechanism to display the sequence of subprogram calls that
20913 leads to a specified execution point in a program. Often (but not always)
20914 the execution point is an instruction at which an exception has been raised.
20915 This mechanism is also known as @i{stack unwinding} because it obtains
20916 its information by scanning the run-time stack and recovering the activation
20917 records of all active subprograms. Stack unwinding is one of the most
20918 important tools for program debugging.
20920 The first entry stored in traceback corresponds to the deepest calling level,
20921 that is to say the subprogram currently executing the instruction
20922 from which we want to obtain the traceback.
20924 Note that there is no runtime performance penalty when stack traceback
20925 is enabled, and no exception is raised during program execution.
20927 @menu
20928 * Non-Symbolic Traceback::
20929 * Symbolic Traceback::
20930 @end menu
20932 @node Non-Symbolic Traceback
20933 @subsection Non-Symbolic Traceback
20934 @cindex traceback, non-symbolic
20936 @noindent
20937 Note: this feature is not supported on all platforms. See
20938 @file{GNAT.Traceback spec in g-traceb.ads} for a complete list of supported
20939 platforms.
20941 @menu
20942 * Tracebacks From an Unhandled Exception::
20943 * Tracebacks From Exception Occurrences (non-symbolic)::
20944 * Tracebacks From Anywhere in a Program (non-symbolic)::
20945 @end menu
20947 @node Tracebacks From an Unhandled Exception
20948 @subsubsection Tracebacks From an Unhandled Exception
20950 @noindent
20951 A runtime non-symbolic traceback is a list of addresses of call instructions.
20952 To enable this feature you must use the @option{-E}
20953 @code{gnatbind}'s option. With this option a stack traceback is stored as part
20954 of exception information. You can retrieve this information using the
20955 @code{addr2line} tool.
20957 Here is a simple example:
20959 @smallexample @c ada
20960 @cartouche
20961 procedure STB is
20963    procedure P1 is
20964    begin
20965       raise Constraint_Error;
20966    end P1;
20968    procedure P2 is
20969    begin
20970       P1;
20971    end P2;
20973 begin
20974    P2;
20975 end STB;
20976 @end cartouche
20977 @end smallexample
20979 @smallexample
20980 $ gnatmake stb -bargs -E
20981 $ stb
20983 Execution terminated by unhandled exception
20984 Exception name: CONSTRAINT_ERROR
20985 Message: stb.adb:5
20986 Call stack traceback locations:
20987 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
20988 @end smallexample
20990 @noindent
20991 As we see the traceback lists a sequence of addresses for the unhandled
20992 exception @code{CONSTRAINT_ERROR} raised in procedure P1. It is easy to
20993 guess that this exception come from procedure P1. To translate these
20994 addresses into the source lines where the calls appear, the
20995 @code{addr2line} tool, described below, is invaluable. The use of this tool
20996 requires the program to be compiled with debug information.
20998 @smallexample
20999 $ gnatmake -g stb -bargs -E
21000 $ stb
21002 Execution terminated by unhandled exception
21003 Exception name: CONSTRAINT_ERROR
21004 Message: stb.adb:5
21005 Call stack traceback locations:
21006 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
21008 $ addr2line --exe=stb 0x401373 0x40138b 0x40139c 0x401335 0x4011c4
21009    0x4011f1 0x77e892a4
21011 00401373 at d:/stb/stb.adb:5
21012 0040138B at d:/stb/stb.adb:10
21013 0040139C at d:/stb/stb.adb:14
21014 00401335 at d:/stb/b~stb.adb:104
21015 004011C4 at /build/@dots{}/crt1.c:200
21016 004011F1 at /build/@dots{}/crt1.c:222
21017 77E892A4 in ?? at ??:0
21018 @end smallexample
21020 @noindent
21021 The @code{addr2line} tool has several other useful options:
21023 @table @code
21024 @item --functions
21025 to get the function name corresponding to any location
21027 @item --demangle=gnat
21028 to use the gnat decoding mode for the function names. Note that
21029 for binutils version 2.9.x the option is simply @option{--demangle}.
21030 @end table
21032 @smallexample
21033 $ addr2line --exe=stb --functions --demangle=gnat 0x401373 0x40138b
21034    0x40139c 0x401335 0x4011c4 0x4011f1
21036 00401373 in stb.p1 at d:/stb/stb.adb:5
21037 0040138B in stb.p2 at d:/stb/stb.adb:10
21038 0040139C in stb at d:/stb/stb.adb:14
21039 00401335 in main at d:/stb/b~stb.adb:104
21040 004011C4 in <__mingw_CRTStartup> at /build/@dots{}/crt1.c:200
21041 004011F1 in <mainCRTStartup> at /build/@dots{}/crt1.c:222
21042 @end smallexample
21044 @noindent
21045 From this traceback we can see that the exception was raised in
21046 @file{stb.adb} at line 5, which was reached from a procedure call in
21047 @file{stb.adb} at line 10, and so on. The @file{b~std.adb} is the binder file,
21048 which contains the call to the main program.
21049 @xref{Running gnatbind}. The remaining entries are assorted runtime routines,
21050 and the output will vary from platform to platform.
21052 It is also possible to use @code{GDB} with these traceback addresses to debug
21053 the program. For example, we can break at a given code location, as reported
21054 in the stack traceback:
21056 @smallexample
21057 $ gdb -nw stb
21058 @ifclear vms
21059 @noindent
21060 Furthermore, this feature is not implemented inside Windows DLL. Only
21061 the non-symbolic traceback is reported in this case.
21062 @end ifclear
21064 (gdb) break *0x401373
21065 Breakpoint 1 at 0x401373: file stb.adb, line 5.
21066 @end smallexample
21068 @noindent
21069 It is important to note that the stack traceback addresses
21070 do not change when debug information is included. This is particularly useful
21071 because it makes it possible to release software without debug information (to
21072 minimize object size), get a field report that includes a stack traceback
21073 whenever an internal bug occurs, and then be able to retrieve the sequence
21074 of calls with the same program compiled with debug information.
21076 @node Tracebacks From Exception Occurrences (non-symbolic)
21077 @subsubsection Tracebacks From Exception Occurrences
21079 @noindent
21080 Non-symbolic tracebacks are obtained by using the @option{-E} binder argument.
21081 The stack traceback is attached to the exception information string, and can
21082 be retrieved in an exception handler within the Ada program, by means of the
21083 Ada facilities defined in @code{Ada.Exceptions}. Here is a simple example:
21085 @smallexample @c ada
21086 with Ada.Text_IO;
21087 with Ada.Exceptions;
21089 procedure STB is
21091    use Ada;
21092    use Ada.Exceptions;
21094    procedure P1 is
21095       K : Positive := 1;
21096    begin
21097       K := K - 1;
21098    exception
21099       when E : others =>
21100          Text_IO.Put_Line (Exception_Information (E));
21101    end P1;
21103    procedure P2 is
21104    begin
21105       P1;
21106    end P2;
21108 begin
21109    P2;
21110 end STB;
21111 @end smallexample
21113 @noindent
21114 This program will output:
21116 @smallexample
21117 $ stb
21119 Exception name: CONSTRAINT_ERROR
21120 Message: stb.adb:12
21121 Call stack traceback locations:
21122 0x4015e4 0x401633 0x401644 0x401461 0x4011c4 0x4011f1 0x77e892a4
21123 @end smallexample
21125 @node Tracebacks From Anywhere in a Program (non-symbolic)
21126 @subsubsection Tracebacks From Anywhere in a Program
21128 @noindent
21129 It is also possible to retrieve a stack traceback from anywhere in a
21130 program. For this you need to
21131 use the @code{GNAT.Traceback} API. This package includes a procedure called
21132 @code{Call_Chain} that computes a complete stack traceback, as well as useful
21133 display procedures described below. It is not necessary to use the
21134 @option{-E gnatbind} option in this case, because the stack traceback mechanism
21135 is invoked explicitly.
21137 @noindent
21138 In the following example we compute a traceback at a specific location in
21139 the program, and we display it using @code{GNAT.Debug_Utilities.Image} to
21140 convert addresses to strings:
21142 @smallexample @c ada
21143 with Ada.Text_IO;
21144 with GNAT.Traceback;
21145 with GNAT.Debug_Utilities;
21147 procedure STB is
21149    use Ada;
21150    use GNAT;
21151    use GNAT.Traceback;
21153    procedure P1 is
21154       TB  : Tracebacks_Array (1 .. 10);
21155       --  We are asking for a maximum of 10 stack frames.
21156       Len : Natural;
21157       --  Len will receive the actual number of stack frames returned.
21158    begin
21159       Call_Chain (TB, Len);
21161       Text_IO.Put ("In STB.P1 : ");
21163       for K in 1 .. Len loop
21164          Text_IO.Put (Debug_Utilities.Image (TB (K)));
21165          Text_IO.Put (' ');
21166       end loop;
21168       Text_IO.New_Line;
21169    end P1;
21171    procedure P2 is
21172    begin
21173       P1;
21174    end P2;
21176 begin
21177    P2;
21178 end STB;
21179 @end smallexample
21181 @smallexample
21182 $ gnatmake -g stb
21183 $ stb
21185 In STB.P1 : 16#0040_F1E4# 16#0040_14F2# 16#0040_170B# 16#0040_171C#
21186 16#0040_1461# 16#0040_11C4# 16#0040_11F1# 16#77E8_92A4#
21187 @end smallexample
21189 @noindent
21190 You can then get further information by invoking the @code{addr2line}
21191 tool as described earlier (note that the hexadecimal addresses
21192 need to be specified in C format, with a leading ``0x'').
21194 @node Symbolic Traceback
21195 @subsection Symbolic Traceback
21196 @cindex traceback, symbolic
21198 @noindent
21199 A symbolic traceback is a stack traceback in which procedure names are
21200 associated with each code location.
21202 @noindent
21203 Note that this feature is not supported on all platforms. See
21204 @file{GNAT.Traceback.Symbolic spec in g-trasym.ads} for a complete
21205 list of currently supported platforms.
21207 @noindent
21208 Note that the symbolic traceback requires that the program be compiled
21209 with debug information. If it is not compiled with debug information
21210 only the non-symbolic information will be valid.
21212 @menu
21213 * Tracebacks From Exception Occurrences (symbolic)::
21214 * Tracebacks From Anywhere in a Program (symbolic)::
21215 @end menu
21217 @node Tracebacks From Exception Occurrences (symbolic)
21218 @subsubsection Tracebacks From Exception Occurrences
21220 @smallexample @c ada
21221 with Ada.Text_IO;
21222 with GNAT.Traceback.Symbolic;
21224 procedure STB is
21226    procedure P1 is
21227    begin
21228       raise Constraint_Error;
21229    end P1;
21231    procedure P2 is
21232    begin
21233       P1;
21234    end P2;
21236    procedure P3 is
21237    begin
21238       P2;
21239    end P3;
21241 begin
21242    P3;
21243 exception
21244    when E : others =>
21245       Ada.Text_IO.Put_Line (GNAT.Traceback.Symbolic.Symbolic_Traceback (E));
21246 end STB;
21247 @end smallexample
21249 @smallexample
21250 $ gnatmake -g .\stb -bargs -E -largs -lgnat -laddr2line -lintl
21251 $ stb
21253 0040149F in stb.p1 at stb.adb:8
21254 004014B7 in stb.p2 at stb.adb:13
21255 004014CF in stb.p3 at stb.adb:18
21256 004015DD in ada.stb at stb.adb:22
21257 00401461 in main at b~stb.adb:168
21258 004011C4 in __mingw_CRTStartup at crt1.c:200
21259 004011F1 in mainCRTStartup at crt1.c:222
21260 77E892A4 in ?? at ??:0
21261 @end smallexample
21263 @noindent
21264 In the above example the ``.\'' syntax in the @command{gnatmake} command
21265 is currently required by @command{addr2line} for files that are in
21266 the current working directory.
21267 Moreover, the exact sequence of linker options may vary from platform
21268 to platform.
21269 The above @option{-largs} section is for Windows platforms. By contrast,
21270 under Unix there is no need for the @option{-largs} section.
21271 Differences across platforms are due to details of linker implementation.
21273 @node Tracebacks From Anywhere in a Program (symbolic)
21274 @subsubsection Tracebacks From Anywhere in a Program
21276 @noindent
21277 It is possible to get a symbolic stack traceback
21278 from anywhere in a program, just as for non-symbolic tracebacks.
21279 The first step is to obtain a non-symbolic
21280 traceback, and then call @code{Symbolic_Traceback} to compute the symbolic
21281 information. Here is an example:
21283 @smallexample @c ada
21284 with Ada.Text_IO;
21285 with GNAT.Traceback;
21286 with GNAT.Traceback.Symbolic;
21288 procedure STB is
21290    use Ada;
21291    use GNAT.Traceback;
21292    use GNAT.Traceback.Symbolic;
21294    procedure P1 is
21295       TB  : Tracebacks_Array (1 .. 10);
21296       --  We are asking for a maximum of 10 stack frames.
21297       Len : Natural;
21298       --  Len will receive the actual number of stack frames returned.
21299    begin
21300       Call_Chain (TB, Len);
21301       Text_IO.Put_Line (Symbolic_Traceback (TB (1 .. Len)));
21302    end P1;
21304    procedure P2 is
21305    begin
21306       P1;
21307    end P2;
21309 begin
21310    P2;
21311 end STB;
21312 @end smallexample
21314 @c ******************************
21315 @ifset vms
21316 @node Compatibility with HP Ada
21317 @chapter Compatibility with HP Ada
21318 @cindex Compatibility
21320 @noindent
21321 @cindex DEC Ada
21322 @cindex HP Ada
21323 @cindex Compatibility between GNAT and HP Ada
21324 This chapter compares HP Ada (formerly known as ``DEC Ada'')
21325 for OpenVMS Alpha and GNAT for OpenVMS for Alpha and for I64.
21326 GNAT is highly compatible
21327 with HP Ada, and it should generally be straightforward to port code
21328 from the HP Ada environment to GNAT. However, there are a few language
21329 and implementation differences of which the user must be aware. These
21330 differences are discussed in this chapter. In
21331 addition, the operating environment and command structure for the
21332 compiler are different, and these differences are also discussed.
21334 For further details on these and other compatibility issues,
21335 see Appendix E of the HP publication
21336 @cite{HP Ada, Technical Overview and Comparison on HP Platforms}.
21338 Except where otherwise indicated, the description of GNAT for OpenVMS
21339 applies to both the Alpha and I64 platforms.
21341 For information on porting Ada code from GNAT on Alpha OpenVMS to GNAT on
21342 I64 OpenVMS, see @ref{Transitioning to 64-Bit GNAT for OpenVMS}.
21344 The discussion in this chapter addresses specifically the implementation
21345 of Ada 83 for HP OpenVMS Alpha Systems. In cases where the implementation
21346 of HP Ada differs between OpenVMS Alpha Systems and OpenVMS VAX Systems,
21347 GNAT always follows the Alpha implementation.
21349 For GNAT running on other than VMS systems, all the HP Ada 83 pragmas and
21350 attributes are recognized, although only a subset of them can sensibly
21351 be implemented.  The description of pragmas in
21352 @xref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference Manual},
21353 indicates whether or not they are applicable to non-VMS systems.
21355 @menu
21356 * Ada Language Compatibility::
21357 * Differences in the Definition of Package System::
21358 * Language-Related Features::
21359 * The Package STANDARD::
21360 * The Package SYSTEM::
21361 * Tasking and Task-Related Features::
21362 * Pragmas and Pragma-Related Features::
21363 * Library of Predefined Units::
21364 * Bindings::
21365 * Main Program Definition::
21366 * Implementation-Defined Attributes::
21367 * Compiler and Run-Time Interfacing::
21368 * Program Compilation and Library Management::
21369 * Input-Output::
21370 * Implementation Limits::
21371 * Tools and Utilities::
21372 @end menu
21374 @node Ada Language Compatibility
21375 @section Ada Language Compatibility
21377 @noindent
21378 GNAT handles Ada 95 and Ada 2005 as well as Ada 83, whereas HP Ada is only
21379 for Ada 83. Ada 95 and Ada 2005 are almost completely upwards compatible
21380 with Ada 83, and therefore Ada 83 programs will compile
21381 and run under GNAT with
21382 no changes or only minor changes. The @cite{Annotated Ada Reference Manual}
21383 provides details on specific incompatibilities.
21385 GNAT provides the switch @option{/83} on the @command{GNAT COMPILE} command,
21386 as well as the pragma @code{ADA_83}, to force the compiler to
21387 operate in Ada 83 mode. This mode does not guarantee complete
21388 conformance to Ada 83, but in practice is sufficient to
21389 eliminate most sources of incompatibilities.
21390 In particular, it eliminates the recognition of the
21391 additional Ada 95 and Ada 2005 keywords, so that their use as identifiers
21392 in Ada 83 programs is legal, and handles the cases of packages
21393 with optional bodies, and generics that instantiate unconstrained
21394 types without the use of @code{(<>)}.
21396 @node Differences in the Definition of Package System
21397 @section Differences in the Definition of Package @code{System}
21399 @noindent
21400 An Ada compiler is allowed to add
21401 implementation-dependent declarations to package @code{System}.
21402 In normal mode,
21403 GNAT does not take advantage of this permission, and the version of
21404 @code{System} provided by GNAT exactly matches that defined in the Ada
21405 Reference Manual.
21407 However, HP Ada adds an extensive set of declarations to package
21408 @code{System},
21409 as fully documented in the HP Ada manuals. To minimize changes required
21410 for programs that make use of these extensions, GNAT provides the pragma
21411 @code{Extend_System} for extending the definition of package System. By using:
21412 @cindex pragma @code{Extend_System}
21413 @cindex @code{Extend_System} pragma
21415 @smallexample @c ada
21416 @group
21417 @cartouche
21418 pragma Extend_System (Aux_DEC);
21419 @end cartouche
21420 @end group
21421 @end smallexample
21423 @noindent
21424 the set of definitions in @code{System} is extended to include those in
21425 package @code{System.Aux_DEC}.
21426 @cindex @code{System.Aux_DEC} package
21427 @cindex @code{Aux_DEC} package (child of @code{System})
21428 These definitions are incorporated directly into package @code{System},
21429 as though they had been declared there. For a
21430 list of the declarations added, see the spec of this package,
21431 which can be found in the file @file{s-auxdec.ads} in the GNAT library.
21432 @cindex @file{s-auxdec.ads} file
21433 The pragma @code{Extend_System} is a configuration pragma, which means that
21434 it can be placed in the file @file{gnat.adc}, so that it will automatically
21435 apply to all subsequent compilations. See @ref{Configuration Pragmas},
21436 for further details.
21438 An alternative approach that avoids the use of the non-standard
21439 @code{Extend_System} pragma is to add a context clause to the unit that
21440 references these facilities:
21442 @smallexample @c ada
21443 @cartouche
21444 with System.Aux_DEC;
21445 use  System.Aux_DEC;
21446 @end cartouche
21447 @end smallexample
21449 @noindent
21450 The effect is not quite semantically identical to incorporating
21451 the declarations directly into package @code{System},
21452 but most programs will not notice a difference
21453 unless they use prefix notation (e.g.@: @code{System.Integer_8})
21454 to reference the entities directly in package @code{System}.
21455 For units containing such references,
21456 the prefixes must either be removed, or the pragma @code{Extend_System}
21457 must be used.
21459 @node Language-Related Features
21460 @section Language-Related Features
21462 @noindent
21463 The following sections highlight differences in types,
21464 representations of types, operations, alignment, and
21465 related topics.
21467 @menu
21468 * Integer Types and Representations::
21469 * Floating-Point Types and Representations::
21470 * Pragmas Float_Representation and Long_Float::
21471 * Fixed-Point Types and Representations::
21472 * Record and Array Component Alignment::
21473 * Address Clauses::
21474 * Other Representation Clauses::
21475 @end menu
21477 @node Integer Types and Representations
21478 @subsection Integer Types and Representations
21480 @noindent
21481 The set of predefined integer types is identical in HP Ada and GNAT.
21482 Furthermore the representation of these integer types is also identical,
21483 including the capability of size clauses forcing biased representation.
21485 In addition,
21486 HP Ada for OpenVMS Alpha systems has defined the
21487 following additional integer types in package @code{System}:
21489 @itemize @bullet
21491 @item
21492 @code{INTEGER_8}
21494 @item
21495 @code{INTEGER_16}
21497 @item
21498 @code{INTEGER_32}
21500 @item
21501 @code{INTEGER_64}
21503 @item
21504 @code{LARGEST_INTEGER}
21505 @end itemize
21507 @noindent
21508 In GNAT, the first four of these types may be obtained from the
21509 standard Ada package @code{Interfaces}.
21510 Alternatively, by use of the pragma @code{Extend_System}, identical
21511 declarations can be referenced directly in package @code{System}.
21512 On both GNAT and HP Ada, the maximum integer size is 64 bits.
21514 @node Floating-Point Types and Representations
21515 @subsection Floating-Point Types and Representations
21516 @cindex Floating-Point types
21518 @noindent
21519 The set of predefined floating-point types is identical in HP Ada and GNAT.
21520 Furthermore the representation of these floating-point
21521 types is also identical. One important difference is that the default
21522 representation for HP Ada is @code{VAX_Float}, but the default representation
21523 for GNAT is IEEE.
21525 Specific types may be declared to be @code{VAX_Float} or IEEE, using the
21526 pragma @code{Float_Representation} as described in the HP Ada
21527 documentation.
21528 For example, the declarations:
21530 @smallexample @c ada
21531 @cartouche
21532 type F_Float is digits 6;
21533 pragma Float_Representation (VAX_Float, F_Float);
21534 @end cartouche
21535 @end smallexample
21537 @noindent
21538 declares a type @code{F_Float} that will be represented in @code{VAX_Float}
21539 format.
21540 This set of declarations actually appears in @code{System.Aux_DEC},
21541 which contains
21542 the full set of additional floating-point declarations provided in
21543 the HP Ada version of package @code{System}.
21544 This and similar declarations may be accessed in a user program
21545 by using pragma @code{Extend_System}. The use of this
21546 pragma, and the related pragma @code{Long_Float} is described in further
21547 detail in the following section.
21549 @node Pragmas Float_Representation and Long_Float
21550 @subsection Pragmas @code{Float_Representation} and @code{Long_Float}
21552 @noindent
21553 HP Ada provides the pragma @code{Float_Representation}, which
21554 acts as a program library switch to allow control over
21555 the internal representation chosen for the predefined
21556 floating-point types declared in the package @code{Standard}.
21557 The format of this pragma is as follows:
21559 @smallexample @c ada
21560 @cartouche
21561 pragma Float_Representation(VAX_Float | IEEE_Float);
21562 @end cartouche
21563 @end smallexample
21565 @noindent
21566 This pragma controls the representation of floating-point
21567 types as follows:
21569 @itemize @bullet
21570 @item
21571 @code{VAX_Float} specifies that floating-point
21572 types are represented by default with the VAX system hardware types
21573 @code{F-floating}, @code{D-floating}, @code{G-floating}.
21574 Note that the @code{H-floating}
21575 type was available only on VAX systems, and is not available
21576 in either HP Ada or GNAT.
21578 @item
21579 @code{IEEE_Float} specifies that floating-point
21580 types are represented by default with the IEEE single and
21581 double floating-point types.
21582 @end itemize
21584 @noindent
21585 GNAT provides an identical implementation of the pragma
21586 @code{Float_Representation}, except that it functions as a
21587 configuration pragma. Note that the
21588 notion of configuration pragma corresponds closely to the
21589 HP Ada notion of a program library switch.
21591 When no pragma is used in GNAT, the default is @code{IEEE_Float},
21592 which is different
21593 from HP Ada 83, where the default is @code{VAX_Float}. In addition, the
21594 predefined libraries in GNAT are built using @code{IEEE_Float}, so it is not
21595 advisable to change the format of numbers passed to standard library
21596 routines, and if necessary explicit type conversions may be needed.
21598 The use of @code{IEEE_Float} is recommended in GNAT since it is more
21599 efficient, and (given that it conforms to an international standard)
21600 potentially more portable.
21601 The situation in which @code{VAX_Float} may be useful is in interfacing
21602 to existing code and data that expect the use of @code{VAX_Float}.
21603 In such a situation use the predefined @code{VAX_Float}
21604 types in package @code{System}, as extended by
21605 @code{Extend_System}. For example, use @code{System.F_Float}
21606 to specify the 32-bit @code{F-Float} format.
21608 @noindent
21609 On OpenVMS systems, HP Ada provides the pragma @code{Long_Float}
21610 to allow control over the internal representation chosen
21611 for the predefined type @code{Long_Float} and for floating-point
21612 type declarations with digits specified in the range 7 .. 15.
21613 The format of this pragma is as follows:
21615 @smallexample @c ada
21616 @cartouche
21617 pragma Long_Float (D_FLOAT | G_FLOAT);
21618 @end cartouche
21619 @end smallexample
21621 @node Fixed-Point Types and Representations
21622 @subsection Fixed-Point Types and Representations
21624 @noindent
21625 On HP Ada for OpenVMS Alpha systems, rounding is
21626 away from zero for both positive and negative numbers.
21627 Therefore, @code{+0.5} rounds to @code{1},
21628 and @code{-0.5} rounds to @code{-1}.
21630 On GNAT the results of operations
21631 on fixed-point types are in accordance with the Ada
21632 rules. In particular, results of operations on decimal
21633 fixed-point types are truncated.
21635 @node Record and Array Component Alignment
21636 @subsection Record and Array Component Alignment
21638 @noindent
21639 On HP Ada for OpenVMS Alpha, all non-composite components
21640 are aligned on natural boundaries. For example, 1-byte
21641 components are aligned on byte boundaries, 2-byte
21642 components on 2-byte boundaries, 4-byte components on 4-byte
21643 byte boundaries, and so on. The OpenVMS Alpha hardware
21644 runs more efficiently with naturally aligned data.
21646 On GNAT, alignment rules are compatible
21647 with HP Ada for OpenVMS Alpha.
21649 @node Address Clauses
21650 @subsection Address Clauses
21652 @noindent
21653 In HP Ada and GNAT, address clauses are supported for
21654 objects and imported subprograms.
21655 The predefined type @code{System.Address} is a private type
21656 in both compilers on Alpha OpenVMS, with the same representation
21657 (it is simply a machine pointer). Addition, subtraction, and comparison
21658 operations are available in the standard Ada package
21659 @code{System.Storage_Elements}, or in package @code{System}
21660 if it is extended to include @code{System.Aux_DEC} using a
21661 pragma @code{Extend_System} as previously described.
21663 Note that code that @code{with}'s both this extended package @code{System}
21664 and the package @code{System.Storage_Elements} should not @code{use}
21665 both packages, or ambiguities will result. In general it is better
21666 not to mix these two sets of facilities. The Ada package was
21667 designed specifically to provide the kind of features that HP Ada
21668 adds directly to package @code{System}.
21670 The type @code{System.Address} is a 64-bit integer type in GNAT for
21671 I64 OpenVMS.  For more information,
21672 see @ref{Transitioning to 64-Bit GNAT for OpenVMS}.
21674 GNAT is compatible with HP Ada in its handling of address
21675 clauses, except for some limitations in
21676 the form of address clauses for composite objects with
21677 initialization. Such address clauses are easily replaced
21678 by the use of an explicitly-defined constant as described
21679 in the Ada Reference Manual (13.1(22)). For example, the sequence
21680 of declarations:
21682 @smallexample @c ada
21683 @cartouche
21684 X, Y : Integer := Init_Func;
21685 Q : String (X .. Y) := "abc";
21686 @dots{}
21687 for Q'Address use Compute_Address;
21688 @end cartouche
21689 @end smallexample
21691 @noindent
21692 will be rejected by GNAT, since the address cannot be computed at the time
21693 that @code{Q} is declared. To achieve the intended effect, write instead:
21695 @smallexample @c ada
21696 @group
21697 @cartouche
21698 X, Y : Integer := Init_Func;
21699 Q_Address : constant Address := Compute_Address;
21700 Q : String (X .. Y) := "abc";
21701 @dots{}
21702 for Q'Address use Q_Address;
21703 @end cartouche
21704 @end group
21705 @end smallexample
21707 @noindent
21708 which will be accepted by GNAT (and other Ada compilers), and is also
21709 compatible with Ada 83. A fuller description of the restrictions
21710 on address specifications is found in @ref{Top, GNAT Reference Manual,
21711 About This Guide, gnat_rm, GNAT Reference Manual}.
21713 @node Other Representation Clauses
21714 @subsection Other Representation Clauses
21716 @noindent
21717 GNAT implements in a compatible manner all the representation
21718 clauses supported by HP Ada. In addition, GNAT
21719 implements the representation clause forms that were introduced in Ada 95,
21720 including @code{COMPONENT_SIZE} and @code{SIZE} clauses for objects.
21722 @node The Package STANDARD
21723 @section The Package @code{STANDARD}
21725 @noindent
21726 The package @code{STANDARD}, as implemented by HP Ada, is fully
21727 described in the @cite{Ada Reference Manual} and in the
21728 @cite{HP Ada Language Reference Manual}. As implemented by GNAT, the
21729 package @code{STANDARD} is described in the @cite{Ada Reference Manual}.
21731 In addition, HP Ada supports the Latin-1 character set in
21732 the type @code{CHARACTER}. GNAT supports the Latin-1 character set
21733 in the type @code{CHARACTER} and also Unicode (ISO 10646 BMP) in
21734 the type @code{WIDE_CHARACTER}.
21736 The floating-point types supported by GNAT are those
21737 supported by HP Ada, but the defaults are different, and are controlled by
21738 pragmas. See @ref{Floating-Point Types and Representations}, for details.
21740 @node The Package SYSTEM
21741 @section The Package @code{SYSTEM}
21743 @noindent
21744 HP Ada provides a specific version of the package
21745 @code{SYSTEM} for each platform on which the language is implemented.
21746 For the complete spec of the package @code{SYSTEM}, see
21747 Appendix F of the @cite{HP Ada Language Reference Manual}.
21749 On HP Ada, the package @code{SYSTEM} includes the following conversion
21750 functions:
21751 @itemize @bullet
21752 @item @code{TO_ADDRESS(INTEGER)}
21754 @item @code{TO_ADDRESS(UNSIGNED_LONGWORD)}
21756 @item @code{TO_ADDRESS(}@i{universal_integer}@code{)}
21758 @item @code{TO_INTEGER(ADDRESS)}
21760 @item @code{TO_UNSIGNED_LONGWORD(ADDRESS)}
21762 @item Function @code{IMPORT_VALUE return UNSIGNED_LONGWORD} and the
21763 functions @code{IMPORT_ADDRESS} and @code{IMPORT_LARGEST_VALUE}
21764 @end itemize
21766 @noindent
21767 By default, GNAT supplies a version of @code{SYSTEM} that matches
21768 the definition given in the @cite{Ada Reference Manual}.
21769 This
21770 is a subset of the HP system definitions, which is as
21771 close as possible to the original definitions. The only difference
21772 is that the definition of @code{SYSTEM_NAME} is different:
21774 @smallexample @c ada
21775 @cartouche
21776 type Name is (SYSTEM_NAME_GNAT);
21777 System_Name : constant Name := SYSTEM_NAME_GNAT;
21778 @end cartouche
21779 @end smallexample
21781 @noindent
21782 Also, GNAT adds the Ada declarations for
21783 @code{BIT_ORDER} and @code{DEFAULT_BIT_ORDER}.
21785 However, the use of the following pragma causes GNAT
21786 to extend the definition of package @code{SYSTEM} so that it
21787 encompasses the full set of HP-specific extensions,
21788 including the functions listed above:
21790 @smallexample @c ada
21791 @cartouche
21792 pragma Extend_System (Aux_DEC);
21793 @end cartouche
21794 @end smallexample
21796 @noindent
21797 The pragma @code{Extend_System} is a configuration pragma that
21798 is most conveniently placed in the @file{gnat.adc} file. @xref{Pragma
21799 Extend_System,,, gnat_rm, GNAT Reference Manual}, for further details.
21801 HP Ada does not allow the recompilation of the package
21802 @code{SYSTEM}. Instead HP Ada provides several pragmas
21803 (@code{SYSTEM_NAME}, @code{STORAGE_UNIT}, and @code{MEMORY_SIZE})
21804 to modify values in the package @code{SYSTEM}.
21805 On OpenVMS Alpha systems, the pragma
21806 @code{SYSTEM_NAME} takes the enumeration literal @code{OPENVMS_AXP} as
21807 its single argument.
21809 GNAT does permit the recompilation of package @code{SYSTEM} using
21810 the special switch @option{-gnatg}, and this switch can be used if
21811 it is necessary to modify the definitions in @code{SYSTEM}. GNAT does
21812 not permit the specification of @code{SYSTEM_NAME}, @code{STORAGE_UNIT}
21813 or @code{MEMORY_SIZE} by any other means.
21815 On GNAT systems, the pragma @code{SYSTEM_NAME} takes the
21816 enumeration literal @code{SYSTEM_NAME_GNAT}.
21818 The definitions provided by the use of
21820 @smallexample @c ada
21821 pragma Extend_System (AUX_Dec);
21822 @end smallexample
21824 @noindent
21825 are virtually identical to those provided by the HP Ada 83 package
21826 @code{SYSTEM}. One important difference is that the name of the
21827 @code{TO_ADDRESS}
21828 function for type @code{UNSIGNED_LONGWORD} is changed to
21829 @code{TO_ADDRESS_LONG}.
21830 @xref{Address Clauses,,, gnat_rm, GNAT Reference Manual}, for a
21831 discussion of why this change was necessary.
21833 @noindent
21834 The version of @code{TO_ADDRESS} taking a @i{universal_integer} argument
21835 is in fact
21836 an extension to Ada 83 not strictly compatible with the reference manual.
21837 GNAT, in order to be exactly compatible with the standard,
21838 does not provide this capability. In HP Ada 83, the
21839 point of this definition is to deal with a call like:
21841 @smallexample @c ada
21842 TO_ADDRESS (16#12777#);
21843 @end smallexample
21845 @noindent
21846 Normally, according to Ada 83 semantics, one would expect this to be
21847 ambiguous, since it matches both the @code{INTEGER} and
21848 @code{UNSIGNED_LONGWORD} forms of @code{TO_ADDRESS}.
21849 However, in HP Ada 83, there is no ambiguity, since the
21850 definition using @i{universal_integer} takes precedence.
21852 In GNAT, since the version with @i{universal_integer} cannot be supplied,
21853 it is
21854 not possible to be 100% compatible. Since there are many programs using
21855 numeric constants for the argument to @code{TO_ADDRESS}, the decision in
21856 GNAT was
21857 to change the name of the function in the @code{UNSIGNED_LONGWORD} case,
21858 so the declarations provided in the GNAT version of @code{AUX_Dec} are:
21860 @smallexample @c ada
21861 function To_Address (X : Integer) return Address;
21862 pragma Pure_Function (To_Address);
21864 function To_Address_Long (X : Unsigned_Longword) return Address;
21865 pragma Pure_Function (To_Address_Long);
21866 @end smallexample
21868 @noindent
21869 This means that programs using @code{TO_ADDRESS} for
21870 @code{UNSIGNED_LONGWORD} must change the name to @code{TO_ADDRESS_LONG}.
21872 @node Tasking and Task-Related Features
21873 @section Tasking and Task-Related Features
21875 @noindent
21876 This section compares the treatment of tasking in GNAT
21877 and in HP Ada for OpenVMS Alpha.
21878 The GNAT description applies to both Alpha and I64 OpenVMS.
21879 For detailed information on tasking in
21880 HP Ada, see the @cite{HP Ada Language Reference Manual} and the
21881 relevant run-time reference manual.
21883 @menu
21884 * Implementation of Tasks in HP Ada for OpenVMS Alpha Systems::
21885 * Assigning Task IDs::
21886 * Task IDs and Delays::
21887 * Task-Related Pragmas::
21888 * Scheduling and Task Priority::
21889 * The Task Stack::
21890 * External Interrupts::
21891 @end menu
21893 @node Implementation of Tasks in HP Ada for OpenVMS Alpha Systems
21894 @subsection Implementation of Tasks in HP Ada for OpenVMS Alpha Systems
21896 @noindent
21897 On OpenVMS Alpha systems, each Ada task (except a passive
21898 task) is implemented as a single stream of execution
21899 that is created and managed by the kernel. On these
21900 systems, HP Ada tasking support is based on DECthreads,
21901 an implementation of the POSIX standard for threads.
21903 Also, on OpenVMS Alpha systems, HP Ada tasks and foreign
21904 code that calls DECthreads routines can be used together.
21905 The interaction between Ada tasks and DECthreads routines
21906 can have some benefits. For example when on OpenVMS Alpha,
21907 HP Ada can call C code that is already threaded.
21909 GNAT uses the facilities of DECthreads,
21910 and Ada tasks are mapped to threads.
21912 @node Assigning Task IDs
21913 @subsection Assigning Task IDs
21915 @noindent
21916 The HP Ada Run-Time Library always assigns @code{%TASK 1} to
21917 the environment task that executes the main program. On
21918 OpenVMS Alpha systems, @code{%TASK 0} is often used for tasks
21919 that have been created but are not yet activated.
21921 On OpenVMS Alpha systems, task IDs are assigned at
21922 activation. On GNAT systems, task IDs are also assigned at
21923 task creation but do not have the same form or values as
21924 task ID values in HP Ada. There is no null task, and the
21925 environment task does not have a specific task ID value.
21927 @node Task IDs and Delays
21928 @subsection Task IDs and Delays
21930 @noindent
21931 On OpenVMS Alpha systems, tasking delays are implemented
21932 using Timer System Services. The Task ID is used for the
21933 identification of the timer request (the @code{REQIDT} parameter).
21934 If Timers are used in the application take care not to use
21935 @code{0} for the identification, because cancelling such a timer
21936 will cancel all timers and may lead to unpredictable results.
21938 @node Task-Related Pragmas
21939 @subsection Task-Related Pragmas
21941 @noindent
21942 Ada supplies the pragma @code{TASK_STORAGE}, which allows
21943 specification of the size of the guard area for a task
21944 stack. (The guard area forms an area of memory that has no
21945 read or write access and thus helps in the detection of
21946 stack overflow.) On OpenVMS Alpha systems, if the pragma
21947 @code{TASK_STORAGE} specifies a value of zero, a minimal guard
21948 area is created. In the absence of a pragma @code{TASK_STORAGE},
21949 a default guard area is created.
21951 GNAT supplies the following task-related pragmas:
21953 @itemize @bullet
21954 @item  @code{TASK_INFO}
21956 This pragma appears within a task definition and
21957 applies to the task in which it appears. The argument
21958 must be of type @code{SYSTEM.TASK_INFO.TASK_INFO_TYPE}.
21960 @item  @code{TASK_STORAGE}
21962 GNAT implements pragma @code{TASK_STORAGE} in the same way as HP Ada.
21963 Both HP Ada and GNAT supply the pragmas @code{PASSIVE},
21964 @code{SUPPRESS}, and @code{VOLATILE}.
21965 @end itemize
21966 @node Scheduling and Task Priority
21967 @subsection Scheduling and Task Priority
21969 @noindent
21970 HP Ada implements the Ada language requirement that
21971 when two tasks are eligible for execution and they have
21972 different priorities, the lower priority task does not
21973 execute while the higher priority task is waiting. The HP
21974 Ada Run-Time Library keeps a task running until either the
21975 task is suspended or a higher priority task becomes ready.
21977 On OpenVMS Alpha systems, the default strategy is round-
21978 robin with preemption. Tasks of equal priority take turns
21979 at the processor. A task is run for a certain period of
21980 time and then placed at the tail of the ready queue for
21981 its priority level.
21983 HP Ada provides the implementation-defined pragma @code{TIME_SLICE},
21984 which can be used to enable or disable round-robin
21985 scheduling of tasks with the same priority.
21986 See the relevant HP Ada run-time reference manual for
21987 information on using the pragmas to control HP Ada task
21988 scheduling.
21990 GNAT follows the scheduling rules of Annex D (Real-Time
21991 Annex) of the @cite{Ada Reference Manual}. In general, this
21992 scheduling strategy is fully compatible with HP Ada
21993 although it provides some additional constraints (as
21994 fully documented in Annex D).
21995 GNAT implements time slicing control in a manner compatible with
21996 HP Ada 83, by means of the pragma @code{Time_Slice}, whose semantics
21997 are identical to the HP Ada 83 pragma of the same name.
21998 Note that it is not possible to mix GNAT tasking and
21999 HP Ada 83 tasking in the same program, since the two run-time
22000 libraries are not compatible.
22002 @node The Task Stack
22003 @subsection The Task Stack
22005 @noindent
22006 In HP Ada, a task stack is allocated each time a
22007 non-passive task is activated. As soon as the task is
22008 terminated, the storage for the task stack is deallocated.
22009 If you specify a size of zero (bytes) with @code{T'STORAGE_SIZE},
22010 a default stack size is used. Also, regardless of the size
22011 specified, some additional space is allocated for task
22012 management purposes. On OpenVMS Alpha systems, at least
22013 one page is allocated.
22015 GNAT handles task stacks in a similar manner. In accordance with
22016 the Ada rules, it provides the pragma @code{STORAGE_SIZE} as
22017 an alternative method for controlling the task stack size.
22018 The specification of the attribute @code{T'STORAGE_SIZE} is also
22019 supported in a manner compatible with HP Ada.
22021 @node External Interrupts
22022 @subsection External Interrupts
22024 @noindent
22025 On HP Ada, external interrupts can be associated with task entries.
22026 GNAT is compatible with HP Ada in its handling of external interrupts.
22028 @node Pragmas and Pragma-Related Features
22029 @section Pragmas and Pragma-Related Features
22031 @noindent
22032 Both HP Ada and GNAT supply all language-defined pragmas
22033 as specified by the Ada 83 standard. GNAT also supplies all
22034 language-defined pragmas introduced by Ada 95 and Ada 2005.
22035 In addition, GNAT implements the implementation-defined pragmas
22036 from HP Ada 83.
22038 @itemize @bullet
22039 @item  @code{AST_ENTRY}
22041 @item  @code{COMMON_OBJECT}
22043 @item  @code{COMPONENT_ALIGNMENT}
22045 @item  @code{EXPORT_EXCEPTION}
22047 @item  @code{EXPORT_FUNCTION}
22049 @item  @code{EXPORT_OBJECT}
22051 @item  @code{EXPORT_PROCEDURE}
22053 @item  @code{EXPORT_VALUED_PROCEDURE}
22055 @item  @code{FLOAT_REPRESENTATION}
22057 @item  @code{IDENT}
22059 @item  @code{IMPORT_EXCEPTION}
22061 @item  @code{IMPORT_FUNCTION}
22063 @item  @code{IMPORT_OBJECT}
22065 @item  @code{IMPORT_PROCEDURE}
22067 @item  @code{IMPORT_VALUED_PROCEDURE}
22069 @item  @code{INLINE_GENERIC}
22071 @item  @code{INTERFACE_NAME}
22073 @item  @code{LONG_FLOAT}
22075 @item  @code{MAIN_STORAGE}
22077 @item  @code{PASSIVE}
22079 @item  @code{PSECT_OBJECT}
22081 @item  @code{SHARE_GENERIC}
22083 @item  @code{SUPPRESS_ALL}
22085 @item  @code{TASK_STORAGE}
22087 @item  @code{TIME_SLICE}
22089 @item  @code{TITLE}
22090 @end itemize
22092 @noindent
22093 These pragmas are all fully implemented, with the exception of @code{TITLE},
22094 @code{PASSIVE}, and @code{SHARE_GENERIC}, which are
22095 recognized, but which have no
22096 effect in GNAT. The effect of @code{PASSIVE} may be obtained by the
22097 use of Ada protected objects. In GNAT, all generics are inlined.
22099 Unlike HP Ada, the GNAT ``@code{EXPORT_}@i{subprogram}'' pragmas require
22100 a separate subprogram specification which must appear before the
22101 subprogram body.
22103 GNAT also supplies a number of implementation-defined pragmas including the
22104 following:
22106 @itemize @bullet
22107 @item  @code{ABORT_DEFER}
22109 @item  @code{ADA_83}
22111 @item  @code{ADA_95}
22113 @item  @code{ADA_05}
22115 @item  @code{Ada_2005}
22117 @item  @code{Ada_12}
22119 @item  @code{Ada_2012}
22121 @item  @code{ANNOTATE}
22123 @item  @code{ASSERT}
22125 @item  @code{C_PASS_BY_COPY}
22127 @item  @code{CPP_CLASS}
22129 @item  @code{CPP_CONSTRUCTOR}
22131 @item  @code{CPP_DESTRUCTOR}
22133 @item  @code{DEBUG}
22135 @item  @code{EXTEND_SYSTEM}
22137 @item  @code{LINKER_ALIAS}
22139 @item  @code{LINKER_SECTION}
22141 @item  @code{MACHINE_ATTRIBUTE}
22143 @item  @code{NO_RETURN}
22145 @item  @code{PURE_FUNCTION}
22147 @item  @code{SOURCE_FILE_NAME}
22149 @item  @code{SOURCE_REFERENCE}
22151 @item  @code{TASK_INFO}
22153 @item  @code{UNCHECKED_UNION}
22155 @item  @code{UNIMPLEMENTED_UNIT}
22157 @item  @code{UNIVERSAL_DATA}
22159 @item  @code{UNSUPPRESS}
22161 @item  @code{WARNINGS}
22163 @item  @code{WEAK_EXTERNAL}
22164 @end itemize
22166 @noindent
22167 For full details on these and other GNAT implementation-defined pragmas,
22168 see @ref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference
22169 Manual}.
22171 @menu
22172 * Restrictions on the Pragma INLINE::
22173 * Restrictions on the Pragma INTERFACE::
22174 * Restrictions on the Pragma SYSTEM_NAME::
22175 @end menu
22177 @node Restrictions on the Pragma INLINE
22178 @subsection Restrictions on Pragma @code{INLINE}
22180 @noindent
22181 HP Ada enforces the following restrictions on the pragma @code{INLINE}:
22182 @itemize @bullet
22183 @item  Parameters cannot have a task type.
22185 @item  Function results cannot be task types, unconstrained
22186 array types, or unconstrained types with discriminants.
22188 @item  Bodies cannot declare the following:
22189 @itemize @bullet
22190 @item  Subprogram body or stub (imported subprogram is allowed)
22192 @item  Tasks
22194 @item  Generic declarations
22196 @item  Instantiations
22198 @item  Exceptions
22200 @item  Access types (types derived from access types allowed)
22202 @item  Array or record types
22204 @item  Dependent tasks
22206 @item  Direct recursive calls of subprogram or containing
22207 subprogram, directly or via a renaming
22209 @end itemize
22210 @end itemize
22212 @noindent
22213 In GNAT, the only restriction on pragma @code{INLINE} is that the
22214 body must occur before the call if both are in the same
22215 unit, and the size must be appropriately small. There are
22216 no other specific restrictions which cause subprograms to
22217 be incapable of being inlined.
22219 @node  Restrictions on the Pragma INTERFACE
22220 @subsection  Restrictions on Pragma @code{INTERFACE}
22222 @noindent
22223 The following restrictions on pragma @code{INTERFACE}
22224 are enforced by both HP Ada and GNAT:
22225 @itemize @bullet
22226 @item  Languages accepted: Ada, Bliss, C, Fortran, Default.
22227 Default is the default on OpenVMS Alpha systems.
22229 @item  Parameter passing: Language specifies default
22230 mechanisms but can be overridden with an @code{EXPORT} pragma.
22232 @itemize @bullet
22233 @item  Ada: Use internal Ada rules.
22235 @item  Bliss, C: Parameters must be mode @code{in}; cannot be
22236 record or task type. Result cannot be a string, an
22237 array, or a record.
22239 @item  Fortran: Parameters cannot have a task type. Result cannot
22240 be a string, an array, or a record.
22241 @end itemize
22242 @end itemize
22244 @noindent
22245 GNAT is entirely upwards compatible with HP Ada, and in addition allows
22246 record parameters for all languages.
22248 @node  Restrictions on the Pragma SYSTEM_NAME
22249 @subsection  Restrictions on Pragma @code{SYSTEM_NAME}
22251 @noindent
22252 For HP Ada for OpenVMS Alpha, the enumeration literal
22253 for the type @code{NAME} is @code{OPENVMS_AXP}.
22254 In GNAT, the enumeration
22255 literal for the type @code{NAME} is @code{SYSTEM_NAME_GNAT}.
22257 @node  Library of Predefined Units
22258 @section  Library of Predefined Units
22260 @noindent
22261 A library of predefined units is provided as part of the
22262 HP Ada and GNAT implementations. HP Ada does not provide
22263 the package @code{MACHINE_CODE} but instead recommends importing
22264 assembler code.
22266 The GNAT versions of the HP Ada Run-Time Library (@code{ADA$PREDEFINED:})
22267 units are taken from the OpenVMS Alpha version, not the OpenVMS VAX
22268 version.
22269 The HP Ada Predefined Library units are modified to remove post-Ada 83
22270 incompatibilities and to make them interoperable with GNAT
22271 (@pxref{Changes to DECLIB}, for details).
22272 The units are located in the @file{DECLIB} directory.
22274 The GNAT RTL is contained in
22275 the @file{ADALIB} directory, and
22276 the default search path is set up to find @code{DECLIB} units in preference
22277 to @code{ADALIB} units with the same name (@code{TEXT_IO},
22278 @code{SEQUENTIAL_IO}, and @code{DIRECT_IO}, for example).
22280 @menu
22281 * Changes to DECLIB::
22282 @end menu
22284 @node Changes to DECLIB
22285 @subsection Changes to @code{DECLIB}
22287 @noindent
22288 The changes made to the HP Ada predefined library for GNAT and post-Ada 83
22289 compatibility are minor and include the following:
22291 @itemize @bullet
22292 @item  Adjusting the location of pragmas and record representation
22293 clauses to obey Ada 95 (and thus Ada 2005) rules
22295 @item  Adding the proper notation to generic formal parameters
22296 that take unconstrained types in instantiation
22298 @item  Adding pragma @code{ELABORATE_BODY} to package specs
22299 that have package bodies not otherwise allowed
22301 @item  Replacing occurrences of the identifier ``@code{PROTECTED}'' by
22302 ``@code{PROTECTD}''.
22303 Currently these are found only in the @code{STARLET} package spec.
22305 @item Changing @code{SYSTEM.ADDRESS} to @code{SYSTEM.SHORT_ADDRESS}
22306 where the address size is constrained to 32 bits.
22307 @end itemize
22309 @noindent
22310 None of the above changes is visible to users.
22312 @node Bindings
22313 @section Bindings
22315 @noindent
22316 On OpenVMS Alpha, HP Ada provides the following strongly-typed bindings:
22317 @itemize @bullet
22319 @item  Command Language Interpreter (CLI interface)
22321 @item  DECtalk Run-Time Library (DTK interface)
22323 @item  Librarian utility routines (LBR interface)
22325 @item  General Purpose Run-Time Library (LIB interface)
22327 @item  Math Run-Time Library (MTH interface)
22329 @item  National Character Set Run-Time Library (NCS interface)
22331 @item  Compiled Code Support Run-Time Library (OTS interface)
22333 @item  Parallel Processing Run-Time Library (PPL interface)
22335 @item  Screen Management Run-Time Library (SMG interface)
22337 @item  Sort Run-Time Library (SOR interface)
22339 @item  String Run-Time Library (STR interface)
22341 @item STARLET System Library
22342 @findex Starlet
22344 @item  X Window System Version 11R4 and 11R5 (X, XLIB interface)
22346 @item  X Windows Toolkit (XT interface)
22348 @item  X/Motif Version 1.1.3 and 1.2 (XM interface)
22349 @end itemize
22351 @noindent
22352 GNAT provides implementations of these HP bindings in the @code{DECLIB}
22353 directory, on both the Alpha and I64 OpenVMS platforms.
22355 The X components of DECLIB compatibility package are located in a separate
22356 library, called XDECGNAT, which is not linked with by default; this library
22357 must be explicitly linked with any application that makes use of any X facilities,
22358 with a command similar to
22360 @code{GNAT MAKE USE_X /LINK /LIBRARY=XDECGNAT}
22362 The X/Motif bindings used to build @code{DECLIB} are whatever versions are
22363 in the
22364 HP Ada @file{ADA$PREDEFINED} directory with extension @file{.ADC}.
22365 A pragma @code{Linker_Options} has been added to packages @code{Xm},
22366 @code{Xt}, and @code{X_Lib}
22367 causing the default X/Motif sharable image libraries to be linked in. This
22368 is done via options files named @file{xm.opt}, @file{xt.opt}, and
22369 @file{x_lib.opt} (also located in the @file{DECLIB} directory).
22371 It may be necessary to edit these options files to update or correct the
22372 library names if, for example, the newer X/Motif bindings from
22373 @file{ADA$EXAMPLES}
22374 had been (previous to installing GNAT) copied and renamed to supersede the
22375 default @file{ADA$PREDEFINED} versions.
22377 @menu
22378 * Shared Libraries and Options Files::
22379 * Interfaces to C::
22380 @end menu
22382 @node Shared Libraries and Options Files
22383 @subsection Shared Libraries and Options Files
22385 @noindent
22386 When using the HP Ada
22387 predefined X and Motif bindings, the linking with their sharable images is
22388 done automatically by @command{GNAT LINK}.
22389 When using other X and Motif bindings, you need
22390 to add the corresponding sharable images to the command line for
22391 @code{GNAT LINK}. When linking with shared libraries, or with
22392 @file{.OPT} files, you must
22393 also add them to the command line for @command{GNAT LINK}.
22395 A shared library to be used with GNAT is built in the same way as other
22396 libraries under VMS. The VMS Link command can be used in standard fashion.
22398 @node Interfaces to C
22399 @subsection Interfaces to C
22401 @noindent
22402 HP Ada
22403 provides the following Ada types and operations:
22405 @itemize @bullet
22406 @item C types package (@code{C_TYPES})
22408 @item C strings (@code{C_TYPES.NULL_TERMINATED})
22410 @item Other_types (@code{SHORT_INT})
22411 @end itemize
22413 @noindent
22414 Interfacing to C with GNAT, you can use the above approach
22415 described for HP Ada or the facilities of Annex B of
22416 the @cite{Ada Reference Manual} (packages @code{INTERFACES.C},
22417 @code{INTERFACES.C.STRINGS} and @code{INTERFACES.C.POINTERS}). For more
22418 information, see @ref{Interfacing to C,,, gnat_rm, GNAT Reference Manual}.
22420 The @option{-gnatF} qualifier forces default and explicit
22421 @code{External_Name} parameters in pragmas @code{Import} and @code{Export}
22422 to be uppercased for compatibility with the default behavior
22423 of HP C. The qualifier has no effect on @code{Link_Name} parameters.
22425 @node Main Program Definition
22426 @section Main Program Definition
22428 @noindent
22429 The following section discusses differences in the
22430 definition of main programs on HP Ada and GNAT.
22431 On HP Ada, main programs are defined to meet the
22432 following conditions:
22433 @itemize @bullet
22434 @item  Procedure with no formal parameters (returns @code{0} upon
22435 normal completion)
22437 @item  Procedure with no formal parameters (returns @code{42} when
22438 an unhandled exception is raised)
22440 @item  Function with no formal parameters whose returned value
22441 is of a discrete type
22443 @item  Procedure with one @code{out} formal of a discrete type for
22444 which a specification of pragma @code{EXPORT_VALUED_PROCEDURE} is given.
22446 @end itemize
22448 @noindent
22449 When declared with the pragma @code{EXPORT_VALUED_PROCEDURE},
22450 a main function or main procedure returns a discrete
22451 value whose size is less than 64 bits (32 on VAX systems),
22452 the value is zero- or sign-extended as appropriate.
22453 On GNAT, main programs are defined as follows:
22454 @itemize @bullet
22455 @item  Must be a non-generic, parameterless subprogram that
22456 is either a procedure or function returning an Ada
22457 @code{STANDARD.INTEGER} (the predefined type)
22459 @item  Cannot be a generic subprogram or an instantiation of a
22460 generic subprogram
22461 @end itemize
22463 @node Implementation-Defined Attributes
22464 @section Implementation-Defined Attributes
22466 @noindent
22467 GNAT provides all HP Ada implementation-defined
22468 attributes.
22470 @node Compiler and Run-Time Interfacing
22471 @section Compiler and Run-Time Interfacing
22473 @noindent
22474 HP Ada provides the following qualifiers to pass options to the linker
22475 (ACS LINK):
22476 @itemize @bullet
22477 @item  @option{/WAIT} and @option{/SUBMIT}
22479 @item  @option{/COMMAND}
22481 @item  @option{/@r{[}NO@r{]}MAP}
22483 @item  @option{/OUTPUT=@var{file-spec}}
22485 @item  @option{/@r{[}NO@r{]}DEBUG} and @option{/@r{[}NO@r{]}TRACEBACK}
22486 @end itemize
22488 @noindent
22489 To pass options to the linker, GNAT provides the following
22490 switches:
22492 @itemize @bullet
22493 @item   @option{/EXECUTABLE=@var{exec-name}}
22495 @item   @option{/VERBOSE}
22497 @item   @option{/@r{[}NO@r{]}DEBUG} and @option{/@r{[}NO@r{]}TRACEBACK}
22498 @end itemize
22500 @noindent
22501 For more information on these switches, see
22502 @ref{Switches for gnatlink}.
22503 In HP Ada, the command-line switch @option{/OPTIMIZE} is available
22504 to control optimization. HP Ada also supplies the
22505 following pragmas:
22506 @itemize @bullet
22507 @item  @code{OPTIMIZE}
22509 @item  @code{INLINE}
22511 @item  @code{INLINE_GENERIC}
22513 @item  @code{SUPPRESS_ALL}
22515 @item  @code{PASSIVE}
22516 @end itemize
22518 @noindent
22519 In GNAT, optimization is controlled strictly by command
22520 line parameters, as described in the corresponding section of this guide.
22521 The HP pragmas for control of optimization are
22522 recognized but ignored.
22524 Note that in GNAT, the default is optimization off, whereas in HP Ada
22525 the default is that optimization is turned on.
22527 @node Program Compilation and Library Management
22528 @section Program Compilation and Library Management
22530 @noindent
22531 HP Ada and GNAT provide a comparable set of commands to
22532 build programs. HP Ada also provides a program library,
22533 which is a concept that does not exist on GNAT. Instead,
22534 GNAT provides directories of sources that are compiled as
22535 needed.
22537 The following table summarizes
22538 the HP Ada commands and provides
22539 equivalent GNAT commands. In this table, some GNAT
22540 equivalents reflect the fact that GNAT does not use the
22541 concept of a program library. Instead, it uses a model
22542 in which collections of source and object files are used
22543 in a manner consistent with other languages like C and
22544 Fortran. Therefore, standard system file commands are used
22545 to manipulate these elements. Those GNAT commands are marked with
22546 an asterisk.
22547 Note that, unlike HP Ada, none of the GNAT commands accepts wild cards.
22549 @need 1500
22550 @multitable @columnfractions .35 .65
22552 @item @emph{HP Ada Command}
22553 @tab @emph{GNAT Equivalent / Description}
22555 @item @command{ADA}
22556 @tab @command{GNAT COMPILE}@*
22557 Invokes the compiler to compile one or more Ada source files.
22559 @item @command{ACS ATTACH}@*
22560 @tab [No equivalent]@*
22561 Switches control of terminal from current process running the program
22562 library manager.
22564 @item @command{ACS CHECK}
22565 @tab @command{GNAT MAKE /DEPENDENCY_LIST}@*
22566 Forms the execution closure of one
22567 or more compiled units and checks completeness and currency.
22569 @item @command{ACS COMPILE}
22570 @tab @command{GNAT MAKE /ACTIONS=COMPILE}@*
22571 Forms the execution closure of one or
22572 more specified units, checks completeness and currency,
22573 identifies units that have revised source files, compiles same,
22574 and recompiles units that are or will become obsolete.
22575 Also completes incomplete generic instantiations.
22577 @item @command{ACS COPY FOREIGN}
22578 @tab Copy (*)@*
22579 Copies a foreign object file into the program library as a
22580 library unit body.
22582 @item @command{ACS COPY UNIT}
22583 @tab Copy (*)@*
22584 Copies a compiled unit from one program library to another.
22586 @item @command{ACS CREATE LIBRARY}
22587 @tab Create /directory (*)@*
22588 Creates a program library.
22590 @item @command{ACS CREATE SUBLIBRARY}
22591 @tab Create /directory (*)@*
22592 Creates a program sublibrary.
22594 @item @command{ACS DELETE LIBRARY}
22595 @tab @*
22596 Deletes a program library and its contents.
22598 @item @command{ACS DELETE SUBLIBRARY}
22599 @tab @*
22600 Deletes a program sublibrary and its contents.
22602 @item @command{ACS DELETE UNIT}
22603 @tab Delete file (*)@*
22604 On OpenVMS systems, deletes one or more compiled units from
22605 the current program library.
22607 @item @command{ACS DIRECTORY}
22608 @tab Directory (*)@*
22609 On OpenVMS systems, lists units contained in the current
22610 program library.
22612 @item @command{ACS ENTER FOREIGN}
22613 @tab Copy (*)@*
22614 Allows the import of a foreign body as an Ada library
22615 spec and enters a reference to a pointer.
22617 @item @command{ACS ENTER UNIT}
22618 @tab Copy (*)@*
22619 Enters a reference (pointer) from the current program library to
22620 a unit compiled into another program library.
22622 @item @command{ACS EXIT}
22623 @tab [No equivalent]@*
22624 Exits from the program library manager.
22626 @item @command{ACS EXPORT}
22627 @tab Copy (*)@*
22628 Creates an object file that contains system-specific object code
22629 for one or more units. With GNAT, object files can simply be copied
22630 into the desired directory.
22632 @item @command{ACS EXTRACT SOURCE}
22633 @tab Copy (*)@*
22634 Allows access to the copied source file for each Ada compilation unit
22636 @item @command{ACS HELP}
22637 @tab @command{HELP GNAT}@*
22638 Provides online help.
22640 @item @command{ACS LINK}
22641 @tab @command{GNAT LINK}@*
22642 Links an object file containing Ada units into an executable file.
22644 @item @command{ACS LOAD}
22645 @tab Copy (*)@*
22646 Loads (partially compiles) Ada units into the program library.
22647 Allows loading a program from a collection of files into a library
22648 without knowing the relationship among units.
22650 @item @command{ACS MERGE}
22651 @tab Copy (*)@*
22652 Merges into the current program library, one or more units from
22653 another library where they were modified.
22655 @item @command{ACS RECOMPILE}
22656 @tab @command{GNAT MAKE /ACTIONS=COMPILE}@*
22657 Recompiles from   external or copied source files any obsolete
22658 unit in the closure. Also, completes any incomplete generic
22659 instantiations.
22661 @item @command{ACS REENTER}
22662 @tab @command{GNAT MAKE}@*
22663 Reenters current references to units compiled after last entered
22664 with the @command{ACS ENTER UNIT} command.
22666 @item @command{ACS SET LIBRARY}
22667 @tab Set default (*)@*
22668 Defines a program library to be the compilation context as well
22669 as the target library for compiler output and commands in general.
22671 @item @command{ACS SET PRAGMA}
22672 @tab Edit @file{gnat.adc} (*)@*
22673 Redefines specified  values of the library characteristics
22674 @code{LONG_ FLOAT}, @code{MEMORY_SIZE}, @code{SYSTEM_NAME},
22675 and @code{Float_Representation}.
22677 @item @command{ACS SET SOURCE}
22678 @tab Define @code{ADA_INCLUDE_PATH} path (*)@*
22679 Defines the source file search list for the @command{ACS COMPILE} command.
22681 @item @command{ACS SHOW LIBRARY}
22682 @tab Directory (*)@*
22683 Lists information about one or more program libraries.
22685 @item @command{ACS SHOW PROGRAM}
22686 @tab [No equivalent]@*
22687 Lists information about the execution closure of one or
22688 more units in the program library.
22690 @item @command{ACS SHOW SOURCE}
22691 @tab Show logical @code{ADA_INCLUDE_PATH}@*
22692 Shows the source file search used when compiling units.
22694 @item @command{ACS SHOW VERSION}
22695 @tab Compile with @option{VERBOSE} option
22696 Displays the version number of the compiler and program library
22697 manager used.
22699 @item @command{ACS SPAWN}
22700 @tab [No equivalent]@*
22701 Creates a subprocess of the current process (same as @command{DCL SPAWN}
22702 command).
22704 @item @command{ACS VERIFY}
22705 @tab [No equivalent]@*
22706 Performs a series of consistency checks on a program library to
22707 determine whether the library structure and library files are in
22708 valid form.
22709 @end multitable
22711 @noindent
22713 @node Input-Output
22714 @section Input-Output
22716 @noindent
22717 On OpenVMS Alpha systems, HP Ada uses OpenVMS Record
22718 Management Services (RMS) to perform operations on
22719 external files.
22721 @noindent
22722 HP Ada and GNAT predefine an identical set of input-
22723 output packages. To make the use of the
22724 generic @code{TEXT_IO} operations more convenient, HP Ada
22725 provides predefined library packages that instantiate the
22726 integer and floating-point operations for the predefined
22727 integer and floating-point types as shown in the following table.
22729 @multitable @columnfractions .45 .55
22730 @item @emph{Package Name} @tab Instantiation
22732 @item @code{INTEGER_TEXT_IO}
22733 @tab @code{INTEGER_IO(INTEGER)}
22735 @item @code{SHORT_INTEGER_TEXT_IO}
22736 @tab @code{INTEGER_IO(SHORT_INTEGER)}
22738 @item @code{SHORT_SHORT_INTEGER_TEXT_IO}
22739 @tab @code{INTEGER_IO(SHORT_SHORT_INTEGER)}
22741 @item @code{FLOAT_TEXT_IO}
22742 @tab @code{FLOAT_IO(FLOAT)}
22744 @item @code{LONG_FLOAT_TEXT_IO}
22745 @tab @code{FLOAT_IO(LONG_FLOAT)}
22746 @end multitable
22748 @noindent
22749 The HP Ada predefined packages and their operations
22750 are implemented using OpenVMS Alpha files and input-output
22751 facilities. HP Ada supports asynchronous input-output on OpenVMS Alpha.
22752 Familiarity with the following is recommended:
22753 @itemize @bullet
22754 @item  RMS file organizations and access methods
22756 @item  OpenVMS file specifications and directories
22758 @item  OpenVMS File Definition Language (FDL)
22759 @end itemize
22761 @noindent
22762 GNAT provides I/O facilities that are completely
22763 compatible with HP Ada. The distribution includes the
22764 standard HP Ada versions of all I/O packages, operating
22765 in a manner compatible with HP Ada. In particular, the
22766 following packages are by default the HP Ada (Ada 83)
22767 versions of these packages rather than the renamings
22768 suggested in Annex J of the Ada Reference Manual:
22769 @itemize @bullet
22770 @item  @code{TEXT_IO}
22772 @item  @code{SEQUENTIAL_IO}
22774 @item  @code{DIRECT_IO}
22775 @end itemize
22777 @noindent
22778 The use of the standard child package syntax (for
22779 example, @code{ADA.TEXT_IO}) retrieves the post-Ada 83 versions of these
22780 packages.
22781 GNAT provides HP-compatible predefined instantiations
22782 of the @code{TEXT_IO} packages, and also
22783 provides the standard predefined instantiations required
22784 by the @cite{Ada Reference Manual}.
22786 For further information on how GNAT interfaces to the file
22787 system or how I/O is implemented in programs written in
22788 mixed languages, see @ref{Implementation of the Standard I/O,,,
22789 gnat_rm, GNAT Reference Manual}.
22790 This chapter covers the following:
22791 @itemize @bullet
22792 @item  Standard I/O packages
22794 @item  @code{FORM} strings
22796 @item  @code{ADA.DIRECT_IO}
22798 @item  @code{ADA.SEQUENTIAL_IO}
22800 @item  @code{ADA.TEXT_IO}
22802 @item  Stream pointer positioning
22804 @item  Reading and writing non-regular files
22806 @item  @code{GET_IMMEDIATE}
22808 @item  Treating @code{TEXT_IO} files as streams
22810 @item  Shared files
22812 @item  Open modes
22813 @end itemize
22815 @node Implementation Limits
22816 @section Implementation Limits
22818 @noindent
22819 The following table lists implementation limits for HP Ada
22820 and GNAT systems.
22821 @multitable @columnfractions .60 .20 .20
22822 @sp 1
22823 @item  @emph{Compilation Parameter}
22824 @tab   @emph{HP Ada}
22825 @tab   @emph{GNAT}
22826 @sp 1
22828 @item  In a subprogram or entry  declaration, maximum number of
22829 formal parameters that are of an unconstrained record type
22830 @tab   32
22831 @tab   No set limit
22832 @sp 1
22834 @item  Maximum identifier length (number of characters)
22835 @tab   255
22836 @tab   32766
22837 @sp 1
22839 @item  Maximum number of characters in a source line
22840 @tab   255
22841 @tab   32766
22842 @sp 1
22844 @item  Maximum collection size   (number of bytes)
22845 @tab   2**31-1
22846 @tab   2**31-1
22847 @sp 1
22849 @item  Maximum number of discriminants for a record type
22850 @tab   245
22851 @tab   No set limit
22852 @sp 1
22854 @item  Maximum number of formal parameters in an entry or
22855 subprogram declaration
22856 @tab   246
22857 @tab    No set limit
22858 @sp 1
22860 @item  Maximum number of dimensions in an array type
22861 @tab   255
22862 @tab   No set limit
22863 @sp 1
22865 @item  Maximum number of library  units and subunits in a compilation.
22866 @tab   4095
22867 @tab   No set limit
22868 @sp 1
22870 @item  Maximum number of library units and subunits in an execution.
22871 @tab   16383
22872 @tab   No set limit
22873 @sp 1
22875 @item  Maximum number of objects declared with the pragma @code{COMMON_OBJECT}
22876 or @code{PSECT_OBJECT}
22877 @tab   32757
22878 @tab   No set limit
22879 @sp 1
22881 @item  Maximum number of enumeration literals in an enumeration type
22882 definition
22883 @tab   65535
22884 @tab   No set limit
22885 @sp 1
22887 @item  Maximum number of lines in a source file
22888 @tab   65534
22889 @tab   No set limit
22890 @sp 1
22892 @item  Maximum number of bits in any object
22893 @tab   2**31-1
22894 @tab   2**31-1
22895 @sp 1
22897 @item  Maximum size of the static portion of a stack frame (approximate)
22898 @tab   2**31-1
22899 @tab   2**31-1
22900 @end multitable
22902 @node Tools and Utilities
22903 @section Tools and Utilities
22905 @noindent
22906 The following table lists some of the OpenVMS development tools
22907 available for HP Ada, and the corresponding tools for
22908 use with @value{EDITION} on Alpha and I64 platforms.
22909 Aside from the debugger, all the OpenVMS tools identified are part
22910 of the DECset package.
22912 @iftex
22913 @c Specify table in TeX since Texinfo does a poor job
22914 @tex
22915 \smallskip
22916 \smallskip
22917 \settabs\+Language-Sensitive Editor\quad
22918    &Product with HP Ada\quad
22919    &\cr
22920 \+\it Tool
22921    &\it Product with HP Ada
22922    & \it Product with @value{EDITION}\cr
22923 \smallskip
22924 \+Code Management System
22925    &HP CMS
22926    & HP CMS\cr
22927 \smallskip
22928 \+Language-Sensitive Editor
22929    &HP LSE
22930    & emacs or HP LSE (Alpha)\cr
22932    &
22933    & HP LSE (I64)\cr
22934 \smallskip
22935 \+Debugger
22936    &OpenVMS Debug
22937    & gdb (Alpha),\cr
22939    &
22940    & OpenVMS Debug (I64)\cr
22941 \smallskip
22942 \+Source Code Analyzer /
22943    &HP SCA
22944    & GNAT XREF\cr
22945 \+Cross Referencer
22946    &
22947    &\cr
22948 \smallskip
22949 \+Test Manager
22950    &HP Digital Test
22951    & HP DTM\cr
22953    &Manager (DTM)
22954    &\cr
22955 \smallskip
22956 \+Performance and
22957    & HP PCA
22958    & HP PCA\cr
22959 \+Coverage Analyzer
22960    &
22961    &\cr
22962 \smallskip
22963 \+Module Management
22964    & HP MMS
22965    & Not applicable\cr
22966 \+ System
22967    &
22968    &\cr
22969 \smallskip
22970 \smallskip
22971 @end tex
22972 @end iftex
22974 @ifnottex
22975 @c This is the Texinfo version of the table.  It renders poorly in pdf, hence
22976 @c the TeX version above for the printed version
22977 @flushleft
22978 @c @multitable @columnfractions .3 .4 .4
22979 @multitable {Source Code Analyzer /}{Tool with HP Ada}{Tool with @value{EDITION}}
22980 @item @i{Tool}
22981 @tab @i{Tool with HP Ada}
22982 @tab @i{Tool with @value{EDITION}}
22983 @item Code Management@*System
22984 @tab HP CMS
22985 @tab HP CMS
22986 @item Language-Sensitive@*Editor
22987 @tab HP LSE
22988 @tab emacs or HP LSE (Alpha)
22989 @item
22990 @tab
22991 @tab HP LSE (I64)
22992 @item Debugger
22993 @tab OpenVMS Debug
22994 @tab gdb (Alpha),
22995 @item
22996 @tab
22997 @tab OpenVMS Debug (I64)
22998 @item Source Code Analyzer /@*Cross Referencer
22999 @tab HP SCA
23000 @tab GNAT XREF
23001 @item Test Manager
23002 @tab HP Digital Test@*Manager (DTM)
23003 @tab HP DTM
23004 @item Performance and@*Coverage Analyzer
23005 @tab HP PCA
23006 @tab HP PCA
23007 @item Module Management@*System
23008 @tab HP MMS
23009 @tab Not applicable
23010 @end multitable
23011 @end flushleft
23012 @end ifnottex
23014 @end ifset
23016 @c **************************************
23017 @node Platform-Specific Information for the Run-Time Libraries
23018 @appendix Platform-Specific Information for the Run-Time Libraries
23019 @cindex Tasking and threads libraries
23020 @cindex Threads libraries and tasking
23021 @cindex Run-time libraries (platform-specific information)
23023 @noindent
23024 The GNAT run-time implementation may vary with respect to both the
23025 underlying threads library and the exception handling scheme.
23026 For threads support, one or more of the following are supplied:
23027 @itemize @bullet
23028 @item @b{native threads library}, a binding to the thread package from
23029 the underlying operating system
23031 @item @b{pthreads library} (Sparc Solaris only), a binding to the Solaris
23032 POSIX thread package
23033 @end itemize
23035 @noindent
23036 For exception handling, either or both of two models are supplied:
23037 @itemize @bullet
23038 @item @b{Zero-Cost Exceptions} (``ZCX''),@footnote{
23039 Most programs should experience a substantial speed improvement by
23040 being compiled with a ZCX run-time.
23041 This is especially true for
23042 tasking applications or applications with many exception handlers.}
23043 @cindex Zero-Cost Exceptions
23044 @cindex ZCX (Zero-Cost Exceptions)
23045 which uses binder-generated tables that
23046 are interrogated at run time to locate a handler
23048 @item @b{setjmp / longjmp} (``SJLJ''),
23049 @cindex setjmp/longjmp Exception Model
23050 @cindex SJLJ (setjmp/longjmp Exception Model)
23051 which uses dynamically-set data to establish
23052 the set of handlers
23053 @end itemize
23055 @noindent
23056 This appendix summarizes which combinations of threads and exception support
23057 are supplied on various GNAT platforms.
23058 It then shows how to select a particular library either
23059 permanently or temporarily,
23060 explains the properties of (and tradeoffs among) the various threads
23061 libraries, and provides some additional
23062 information about several specific platforms.
23064 @menu
23065 * Summary of Run-Time Configurations::
23066 * Specifying a Run-Time Library::
23067 * Choosing the Scheduling Policy::
23068 * Solaris-Specific Considerations::
23069 * Linux-Specific Considerations::
23070 * AIX-Specific Considerations::
23071 * RTX-Specific Considerations::
23072 * HP-UX-Specific Considerations::
23073 @end menu
23075 @node Summary of Run-Time Configurations
23076 @section Summary of Run-Time Configurations
23078 @multitable @columnfractions .30 .70
23079 @item @b{alpha-openvms}
23080 @item @code{@ @ }@i{rts-native (default)}
23081 @item @code{@ @ @ @ }Tasking    @tab native VMS threads
23082 @item @code{@ @ @ @ }Exceptions @tab ZCX
23084 @item @code{@ @ }@i{rts-sjlj}
23085 @item @code{@ @ @ @ }Tasking    @tab native TRU64 threads
23086 @item @code{@ @ @ @ }Exceptions @tab SJLJ
23088 @item @b{ia64-hp_linux}
23089 @item @code{@ @ }@i{rts-native (default)}
23090 @item @code{@ @ @ @ }Tasking    @tab pthread library
23091 @item @code{@ @ @ @ }Exceptions @tab ZCX
23093 @item @b{ia64-hpux}
23094 @item @code{@ @ }@i{rts-native (default)}
23095 @item @code{@ @ @ @ }Tasking    @tab native HP-UX threads
23096 @item @code{@ @ @ @ }Exceptions @tab SJLJ
23098 @item @b{ia64-openvms}
23099 @item @code{@ @ }@i{rts-native (default)}
23100 @item @code{@ @ @ @ }Tasking    @tab native VMS threads
23101 @item @code{@ @ @ @ }Exceptions @tab ZCX
23103 @item @b{ia64-sgi_linux}
23104 @item @code{@ @ }@i{rts-native (default)}
23105 @item @code{@ @ @ @ }Tasking    @tab pthread library
23106 @item @code{@ @ @ @ }Exceptions @tab ZCX
23108 @item @b{pa-hpux}
23109 @item @code{@ @ }@i{rts-native (default)}
23110 @item @code{@ @ @ @ }Tasking    @tab native HP-UX threads
23111 @item @code{@ @ @ @ }Exceptions @tab ZCX
23113 @item @code{@ @ }@i{rts-sjlj}
23114 @item @code{@ @ @ @ }Tasking    @tab native HP-UX threads
23115 @item @code{@ @ @ @ }Exceptions @tab SJLJ
23117 @item @b{ppc-aix}
23118 @item @code{@ @ }@i{rts-native (default)}
23119 @item @code{@ @ @ @ }Tasking    @tab native AIX threads
23120 @item @code{@ @ @ @ }Exceptions @tab ZCX
23122 @item @code{@ @ }@i{rts-sjlj}
23123 @item @code{@ @ @ @ }Tasking    @tab native AIX threads
23124 @item @code{@ @ @ @ }Exceptions @tab SJLJ
23126 @item @b{ppc-darwin}
23127 @item @code{@ @ }@i{rts-native (default)}
23128 @item @code{@ @ @ @ }Tasking    @tab native MacOS threads
23129 @item @code{@ @ @ @ }Exceptions @tab ZCX
23131 @item @b{sparc-solaris}  @tab
23132 @item @code{@ @ }@i{rts-native (default)}
23133 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads library
23134 @item @code{@ @ @ @ }Exceptions @tab ZCX
23136 @item @code{@ @ }@i{rts-pthread}
23137 @item @code{@ @ @ @ }Tasking    @tab pthread library
23138 @item @code{@ @ @ @ }Exceptions @tab ZCX
23140 @item @code{@ @ }@i{rts-sjlj}
23141 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads library
23142 @item @code{@ @ @ @ }Exceptions @tab SJLJ
23144 @item @b{sparc64-solaris}  @tab
23145 @item @code{@ @ }@i{rts-native (default)}
23146 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads library
23147 @item @code{@ @ @ @ }Exceptions @tab ZCX
23149 @item @b{x86-linux}
23150 @item @code{@ @ }@i{rts-native (default)}
23151 @item @code{@ @ @ @ }Tasking    @tab pthread library
23152 @item @code{@ @ @ @ }Exceptions @tab ZCX
23154 @item @code{@ @ }@i{rts-sjlj}
23155 @item @code{@ @ @ @ }Tasking    @tab pthread library
23156 @item @code{@ @ @ @ }Exceptions @tab SJLJ
23158 @item @b{x86-lynx}
23159 @item @code{@ @ }@i{rts-native (default)}
23160 @item @code{@ @ @ @ }Tasking    @tab native LynxOS threads
23161 @item @code{@ @ @ @ }Exceptions @tab SJLJ
23163 @item @b{x86-solaris}
23164 @item @code{@ @ }@i{rts-native (default)}
23165 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads
23166 @item @code{@ @ @ @ }Exceptions @tab ZCX
23168 @item @code{@ @ }@i{rts-sjlj}
23169 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads library
23170 @item @code{@ @ @ @ }Exceptions @tab SJLJ
23172 @item @b{x86-windows}
23173 @item @code{@ @ }@i{rts-native (default)}
23174 @item @code{@ @ @ @ }Tasking    @tab native Win32 threads
23175 @item @code{@ @ @ @ }Exceptions @tab ZCX
23177 @item @code{@ @ }@i{rts-sjlj}
23178 @item @code{@ @ @ @ }Tasking    @tab native Win32 threads
23179 @item @code{@ @ @ @ }Exceptions @tab SJLJ
23181 @item @b{x86-windows-rtx}
23182 @item @code{@ @ }@i{rts-rtx-rtss (default)}
23183 @item @code{@ @ @ @ }Tasking    @tab RTX real-time subsystem RTSS threads (kernel mode)
23184 @item @code{@ @ @ @ }Exceptions @tab SJLJ
23186 @item @code{@ @ }@i{rts-rtx-w32}
23187 @item @code{@ @ @ @ }Tasking    @tab RTX Win32 threads (user mode)
23188 @item @code{@ @ @ @ }Exceptions @tab ZCX
23190 @item @b{x86_64-linux}
23191 @item @code{@ @ }@i{rts-native (default)}
23192 @item @code{@ @ @ @ }Tasking    @tab pthread library
23193 @item @code{@ @ @ @ }Exceptions @tab ZCX
23195 @item @code{@ @ }@i{rts-sjlj}
23196 @item @code{@ @ @ @ }Tasking    @tab pthread library
23197 @item @code{@ @ @ @ }Exceptions @tab SJLJ
23199 @end multitable
23201 @node Specifying a Run-Time Library
23202 @section Specifying a Run-Time Library
23204 @noindent
23205 The @file{adainclude} subdirectory containing the sources of the GNAT
23206 run-time library, and the @file{adalib} subdirectory containing the
23207 @file{ALI} files and the static and/or shared GNAT library, are located
23208 in the gcc target-dependent area:
23210 @smallexample
23211 target=$prefix/lib/gcc/gcc-@i{dumpmachine}/gcc-@i{dumpversion}/
23212 @end smallexample
23214 @noindent
23215 As indicated above, on some platforms several run-time libraries are supplied.
23216 These libraries are installed in the target dependent area and
23217 contain a complete source and binary subdirectory. The detailed description
23218 below explains the differences between the different libraries in terms of
23219 their thread support.
23221 The default run-time library (when GNAT is installed) is @emph{rts-native}.
23222 This default run time is selected by the means of soft links.
23223 For example on x86-linux:
23225 @smallexample
23226 @group
23227  $(target-dir)
23228      |
23229      +--- adainclude----------+
23230      |                        |
23231      +--- adalib-----------+  |
23232      |                     |  |
23233      +--- rts-native       |  |
23234      |    |                |  |
23235      |    +--- adainclude <---+
23236      |    |                |
23237      |    +--- adalib <----+
23238      |
23239      +--- rts-sjlj
23240           |
23241           +--- adainclude
23242           |
23243           +--- adalib
23244 @end group
23245 @end smallexample
23247 @noindent
23248 If the @i{rts-sjlj} library is to be selected on a permanent basis,
23249 these soft links can be modified with the following commands:
23251 @smallexample
23252 $ cd $target
23253 $ rm -f adainclude adalib
23254 $ ln -s rts-sjlj/adainclude adainclude
23255 $ ln -s rts-sjlj/adalib adalib
23256 @end smallexample
23258 @noindent
23259 Alternatively, you can specify @file{rts-sjlj/adainclude} in the file
23260 @file{$target/ada_source_path} and @file{rts-sjlj/adalib} in
23261 @file{$target/ada_object_path}.
23263 Selecting another run-time library temporarily can be
23264 achieved by using the @option{--RTS} switch, e.g., @option{--RTS=sjlj}
23265 @cindex @option{--RTS} option
23267 @node Choosing the Scheduling Policy
23268 @section Choosing the Scheduling Policy
23270 @noindent
23271 When using a POSIX threads implementation, you have a choice of several
23272 scheduling policies: @code{SCHED_FIFO},
23273 @cindex @code{SCHED_FIFO} scheduling policy
23274 @code{SCHED_RR}
23275 @cindex @code{SCHED_RR} scheduling policy
23276 and @code{SCHED_OTHER}.
23277 @cindex @code{SCHED_OTHER} scheduling policy
23278 Typically, the default is @code{SCHED_OTHER}, while using @code{SCHED_FIFO}
23279 or @code{SCHED_RR} requires special (e.g., root) privileges.
23281 By default, GNAT uses the @code{SCHED_OTHER} policy. To specify
23282 @code{SCHED_FIFO},
23283 @cindex @code{SCHED_FIFO} scheduling policy
23284 you can use one of the following:
23286 @itemize @bullet
23287 @item
23288 @code{pragma Time_Slice (0.0)}
23289 @cindex pragma Time_Slice
23290 @item
23291 the corresponding binder option @option{-T0}
23292 @cindex @option{-T0} option
23293 @item
23294 @code{pragma Task_Dispatching_Policy (FIFO_Within_Priorities)}
23295 @cindex pragma Task_Dispatching_Policy
23296 @end itemize
23298 @noindent
23299 To specify @code{SCHED_RR},
23300 @cindex @code{SCHED_RR} scheduling policy
23301 you should use @code{pragma Time_Slice} with a
23302 value greater than @code{0.0}, or else use the corresponding @option{-T}
23303 binder option.
23305 @node Solaris-Specific Considerations
23306 @section Solaris-Specific Considerations
23307 @cindex Solaris Sparc threads libraries
23309 @noindent
23310 This section addresses some topics related to the various threads libraries
23311 on Sparc Solaris.
23313 @menu
23314 * Solaris Threads Issues::
23315 @end menu
23317 @node Solaris Threads Issues
23318 @subsection Solaris Threads Issues
23320 @noindent
23321 GNAT under Solaris/Sparc 32 bits comes with an alternate tasking run-time
23322 library based on POSIX threads --- @emph{rts-pthread}.
23323 @cindex rts-pthread threads library
23324 This run-time library has the advantage of being mostly shared across all
23325 POSIX-compliant thread implementations, and it also provides under
23326 @w{Solaris 8} the @code{PTHREAD_PRIO_INHERIT}
23327 @cindex @code{PTHREAD_PRIO_INHERIT} policy (under rts-pthread)
23328 and @code{PTHREAD_PRIO_PROTECT}
23329 @cindex @code{PTHREAD_PRIO_PROTECT} policy (under rts-pthread)
23330 semantics that can be selected using the predefined pragma
23331 @code{Locking_Policy}
23332 @cindex pragma Locking_Policy (under rts-pthread)
23333 with respectively
23334 @code{Inheritance_Locking} and @code{Ceiling_Locking} as the policy.
23335 @cindex @code{Inheritance_Locking} (under rts-pthread)
23336 @cindex @code{Ceiling_Locking} (under rts-pthread)
23338 As explained above, the native run-time library is based on the Solaris thread
23339 library (@code{libthread}) and is the default library.
23341 When the Solaris threads library is used (this is the default), programs
23342 compiled with GNAT can automatically take advantage of
23343 and can thus execute on multiple processors.
23344 The user can alternatively specify a processor on which the program should run
23345 to emulate a single-processor system. The multiprocessor / uniprocessor choice
23346 is made by
23347 setting the environment variable @env{GNAT_PROCESSOR}
23348 @cindex @env{GNAT_PROCESSOR} environment variable (on Sparc Solaris)
23349 to one of the following:
23351 @table @code
23352 @item -2
23353 Use the default configuration (run the program on all
23354 available processors) - this is the same as having @code{GNAT_PROCESSOR}
23355 unset
23357 @item -1
23358 Let the run-time implementation choose one processor and run the program on
23359 that processor
23361 @item 0 .. Last_Proc
23362 Run the program on the specified processor.
23363 @code{Last_Proc} is equal to @code{_SC_NPROCESSORS_CONF - 1}
23364 (where @code{_SC_NPROCESSORS_CONF} is a system variable).
23365 @end table
23367 @node Linux-Specific Considerations
23368 @section Linux-Specific Considerations
23369 @cindex Linux threads libraries
23371 @noindent
23372 On GNU/Linux without NPTL support (usually system with GNU C Library
23373 older than 2.3), the signal model is not POSIX compliant, which means
23374 that to send a signal to the process, you need to send the signal to all
23375 threads, e.g.@: by using @code{killpg()}.
23377 @node AIX-Specific Considerations
23378 @section AIX-Specific Considerations
23379 @cindex AIX resolver library
23381 @noindent
23382 On AIX, the resolver library initializes some internal structure on
23383 the first call to @code{get*by*} functions, which are used to implement
23384 @code{GNAT.Sockets.Get_Host_By_Name} and
23385 @code{GNAT.Sockets.Get_Host_By_Address}.
23386 If such initialization occurs within an Ada task, and the stack size for
23387 the task is the default size, a stack overflow may occur.
23389 To avoid this overflow, the user should either ensure that the first call
23390 to @code{GNAT.Sockets.Get_Host_By_Name} or
23391 @code{GNAT.Sockets.Get_Host_By_Addrss}
23392 occurs in the environment task, or use @code{pragma Storage_Size} to
23393 specify a sufficiently large size for the stack of the task that contains
23394 this call.
23396 @node RTX-Specific Considerations
23397 @section RTX-Specific Considerations
23398 @cindex RTX libraries
23400 @noindent
23401 The Real-time Extension (RTX) to Windows is based on the Windows Win32
23402 API. Applications can be built to work in two different modes:
23404 @itemize @bullet
23405 @item
23406 Windows executables that run in Ring 3 to utilize memory protection
23407 (@emph{rts-rtx-w32}).
23409 @item
23410 Real-time subsystem (RTSS) executables that run in Ring 0, where
23411 performance can be optimized with RTSS applications taking precedent
23412 over all Windows applications (@emph{rts-rtx-rtss}). This mode requires
23413 the Microsoft linker to handle RTSS libraries.
23415 @end itemize
23417 @node HP-UX-Specific Considerations
23418 @section HP-UX-Specific Considerations
23419 @cindex HP-UX Scheduling
23421 @noindent
23422 On HP-UX, appropriate privileges are required to change the scheduling
23423 parameters of a task. The calling process must have appropriate
23424 privileges or be a member of a group having @code{PRIV_RTSCHED} access to
23425 successfully change the scheduling parameters.
23427 By default, GNAT uses the @code{SCHED_HPUX} policy. To have access to the
23428 priority range 0-31 either the @code{FIFO_Within_Priorities} or the
23429 @code{Round_Robin_Within_Priorities} scheduling policies need to be set.
23431 To specify the @code{FIFO_Within_Priorities} scheduling policy you can use
23432 one of the following:
23434 @itemize @bullet
23435 @item
23436 @code{pragma Time_Slice (0.0)}
23437 @cindex pragma Time_Slice
23438 @item
23439 the corresponding binder option @option{-T0}
23440 @cindex @option{-T0} option
23441 @item
23442 @code{pragma Task_Dispatching_Policy (FIFO_Within_Priorities)}
23443 @cindex pragma Task_Dispatching_Policy
23444 @end itemize
23446 @noindent
23447 To specify the @code{Round_Robin_Within_Priorities}, scheduling policy
23448 you should use @code{pragma Time_Slice} with a
23449 value greater than @code{0.0}, or use the corresponding @option{-T}
23450 binder option, or set the @code{pragma Task_Dispatching_Policy
23451 (Round_Robin_Within_Priorities)}.
23453 @c *******************************
23454 @node Example of Binder Output File
23455 @appendix Example of Binder Output File
23457 @noindent
23458 This Appendix displays the source code for @command{gnatbind}'s output
23459 file generated for a simple ``Hello World'' program.
23460 Comments have been added for clarification purposes.
23462 @smallexample @c adanocomment
23463 @iftex
23464 @leftskip=0cm
23465 @end iftex
23466 --  The package is called Ada_Main unless this name is actually used
23467 --  as a unit name in the partition, in which case some other unique
23468 --  name is used.
23470 with System;
23471 package ada_main is
23473    Elab_Final_Code : Integer;
23474    pragma Import (C, Elab_Final_Code, "__gnat_inside_elab_final_code");
23476    --  The main program saves the parameters (argument count,
23477    --  argument values, environment pointer) in global variables
23478    --  for later access by other units including
23479    --  Ada.Command_Line.
23481    gnat_argc : Integer;
23482    gnat_argv : System.Address;
23483    gnat_envp : System.Address;
23485    --  The actual variables are stored in a library routine. This
23486    --  is useful for some shared library situations, where there
23487    --  are problems if variables are not in the library.
23489    pragma Import (C, gnat_argc);
23490    pragma Import (C, gnat_argv);
23491    pragma Import (C, gnat_envp);
23493    --  The exit status is similarly an external location
23495    gnat_exit_status : Integer;
23496    pragma Import (C, gnat_exit_status);
23498    GNAT_Version : constant String :=
23499                     "GNAT Version: 6.0.0w (20061115)";
23500    pragma Export (C, GNAT_Version, "__gnat_version");
23502    --  This is the generated adafinal routine that performs
23503    --  finalization at the end of execution. In the case where
23504    --  Ada is the main program, this main program makes a call
23505    --  to adafinal at program termination.
23507    procedure adafinal;
23508    pragma Export (C, adafinal, "adafinal");
23510    --  This is the generated adainit routine that performs
23511    --  initialization at the start of execution. In the case
23512    --  where Ada is the main program, this main program makes
23513    --  a call to adainit at program startup.
23515    procedure adainit;
23516    pragma Export (C, adainit, "adainit");
23518    --  This routine is called at the start of execution. It is
23519    --  a dummy routine that is used by the debugger to breakpoint
23520    --  at the start of execution.
23522    procedure Break_Start;
23523    pragma Import (C, Break_Start, "__gnat_break_start");
23525    --  This is the actual generated main program (it would be
23526    --  suppressed if the no main program switch were used). As
23527    --  required by standard system conventions, this program has
23528    --  the external name main.
23530    function main
23531      (argc : Integer;
23532       argv : System.Address;
23533       envp : System.Address)
23534       return Integer;
23535    pragma Export (C, main, "main");
23537    --  The following set of constants give the version
23538    --  identification values for every unit in the bound
23539    --  partition. This identification is computed from all
23540    --  dependent semantic units, and corresponds to the
23541    --  string that would be returned by use of the
23542    --  Body_Version or Version attributes.
23544    type Version_32 is mod 2 ** 32;
23545    u00001 : constant Version_32 := 16#7880BEB3#;
23546    u00002 : constant Version_32 := 16#0D24CBD0#;
23547    u00003 : constant Version_32 := 16#3283DBEB#;
23548    u00004 : constant Version_32 := 16#2359F9ED#;
23549    u00005 : constant Version_32 := 16#664FB847#;
23550    u00006 : constant Version_32 := 16#68E803DF#;
23551    u00007 : constant Version_32 := 16#5572E604#;
23552    u00008 : constant Version_32 := 16#46B173D8#;
23553    u00009 : constant Version_32 := 16#156A40CF#;
23554    u00010 : constant Version_32 := 16#033DABE0#;
23555    u00011 : constant Version_32 := 16#6AB38FEA#;
23556    u00012 : constant Version_32 := 16#22B6217D#;
23557    u00013 : constant Version_32 := 16#68A22947#;
23558    u00014 : constant Version_32 := 16#18CC4A56#;
23559    u00015 : constant Version_32 := 16#08258E1B#;
23560    u00016 : constant Version_32 := 16#367D5222#;
23561    u00017 : constant Version_32 := 16#20C9ECA4#;
23562    u00018 : constant Version_32 := 16#50D32CB6#;
23563    u00019 : constant Version_32 := 16#39A8BB77#;
23564    u00020 : constant Version_32 := 16#5CF8FA2B#;
23565    u00021 : constant Version_32 := 16#2F1EB794#;
23566    u00022 : constant Version_32 := 16#31AB6444#;
23567    u00023 : constant Version_32 := 16#1574B6E9#;
23568    u00024 : constant Version_32 := 16#5109C189#;
23569    u00025 : constant Version_32 := 16#56D770CD#;
23570    u00026 : constant Version_32 := 16#02F9DE3D#;
23571    u00027 : constant Version_32 := 16#08AB6B2C#;
23572    u00028 : constant Version_32 := 16#3FA37670#;
23573    u00029 : constant Version_32 := 16#476457A0#;
23574    u00030 : constant Version_32 := 16#731E1B6E#;
23575    u00031 : constant Version_32 := 16#23C2E789#;
23576    u00032 : constant Version_32 := 16#0F1BD6A1#;
23577    u00033 : constant Version_32 := 16#7C25DE96#;
23578    u00034 : constant Version_32 := 16#39ADFFA2#;
23579    u00035 : constant Version_32 := 16#571DE3E7#;
23580    u00036 : constant Version_32 := 16#5EB646AB#;
23581    u00037 : constant Version_32 := 16#4249379B#;
23582    u00038 : constant Version_32 := 16#0357E00A#;
23583    u00039 : constant Version_32 := 16#3784FB72#;
23584    u00040 : constant Version_32 := 16#2E723019#;
23585    u00041 : constant Version_32 := 16#623358EA#;
23586    u00042 : constant Version_32 := 16#107F9465#;
23587    u00043 : constant Version_32 := 16#6843F68A#;
23588    u00044 : constant Version_32 := 16#63305874#;
23589    u00045 : constant Version_32 := 16#31E56CE1#;
23590    u00046 : constant Version_32 := 16#02917970#;
23591    u00047 : constant Version_32 := 16#6CCBA70E#;
23592    u00048 : constant Version_32 := 16#41CD4204#;
23593    u00049 : constant Version_32 := 16#572E3F58#;
23594    u00050 : constant Version_32 := 16#20729FF5#;
23595    u00051 : constant Version_32 := 16#1D4F93E8#;
23596    u00052 : constant Version_32 := 16#30B2EC3D#;
23597    u00053 : constant Version_32 := 16#34054F96#;
23598    u00054 : constant Version_32 := 16#5A199860#;
23599    u00055 : constant Version_32 := 16#0E7F912B#;
23600    u00056 : constant Version_32 := 16#5760634A#;
23601    u00057 : constant Version_32 := 16#5D851835#;
23603    --  The following Export pragmas export the version numbers
23604    --  with symbolic names ending in B (for body) or S
23605    --  (for spec) so that they can be located in a link. The
23606    --  information provided here is sufficient to track down
23607    --  the exact versions of units used in a given build.
23609    pragma Export (C, u00001, "helloB");
23610    pragma Export (C, u00002, "system__standard_libraryB");
23611    pragma Export (C, u00003, "system__standard_libraryS");
23612    pragma Export (C, u00004, "adaS");
23613    pragma Export (C, u00005, "ada__text_ioB");
23614    pragma Export (C, u00006, "ada__text_ioS");
23615    pragma Export (C, u00007, "ada__exceptionsB");
23616    pragma Export (C, u00008, "ada__exceptionsS");
23617    pragma Export (C, u00009, "gnatS");
23618    pragma Export (C, u00010, "gnat__heap_sort_aB");
23619    pragma Export (C, u00011, "gnat__heap_sort_aS");
23620    pragma Export (C, u00012, "systemS");
23621    pragma Export (C, u00013, "system__exception_tableB");
23622    pragma Export (C, u00014, "system__exception_tableS");
23623    pragma Export (C, u00015, "gnat__htableB");
23624    pragma Export (C, u00016, "gnat__htableS");
23625    pragma Export (C, u00017, "system__exceptionsS");
23626    pragma Export (C, u00018, "system__machine_state_operationsB");
23627    pragma Export (C, u00019, "system__machine_state_operationsS");
23628    pragma Export (C, u00020, "system__machine_codeS");
23629    pragma Export (C, u00021, "system__storage_elementsB");
23630    pragma Export (C, u00022, "system__storage_elementsS");
23631    pragma Export (C, u00023, "system__secondary_stackB");
23632    pragma Export (C, u00024, "system__secondary_stackS");
23633    pragma Export (C, u00025, "system__parametersB");
23634    pragma Export (C, u00026, "system__parametersS");
23635    pragma Export (C, u00027, "system__soft_linksB");
23636    pragma Export (C, u00028, "system__soft_linksS");
23637    pragma Export (C, u00029, "system__stack_checkingB");
23638    pragma Export (C, u00030, "system__stack_checkingS");
23639    pragma Export (C, u00031, "system__tracebackB");
23640    pragma Export (C, u00032, "system__tracebackS");
23641    pragma Export (C, u00033, "ada__streamsS");
23642    pragma Export (C, u00034, "ada__tagsB");
23643    pragma Export (C, u00035, "ada__tagsS");
23644    pragma Export (C, u00036, "system__string_opsB");
23645    pragma Export (C, u00037, "system__string_opsS");
23646    pragma Export (C, u00038, "interfacesS");
23647    pragma Export (C, u00039, "interfaces__c_streamsB");
23648    pragma Export (C, u00040, "interfaces__c_streamsS");
23649    pragma Export (C, u00041, "system__file_ioB");
23650    pragma Export (C, u00042, "system__file_ioS");
23651    pragma Export (C, u00043, "ada__finalizationB");
23652    pragma Export (C, u00044, "ada__finalizationS");
23653    pragma Export (C, u00045, "system__finalization_rootB");
23654    pragma Export (C, u00046, "system__finalization_rootS");
23655    pragma Export (C, u00047, "system__finalization_implementationB");
23656    pragma Export (C, u00048, "system__finalization_implementationS");
23657    pragma Export (C, u00049, "system__string_ops_concat_3B");
23658    pragma Export (C, u00050, "system__string_ops_concat_3S");
23659    pragma Export (C, u00051, "system__stream_attributesB");
23660    pragma Export (C, u00052, "system__stream_attributesS");
23661    pragma Export (C, u00053, "ada__io_exceptionsS");
23662    pragma Export (C, u00054, "system__unsigned_typesS");
23663    pragma Export (C, u00055, "system__file_control_blockS");
23664    pragma Export (C, u00056, "ada__finalization__list_controllerB");
23665    pragma Export (C, u00057, "ada__finalization__list_controllerS");
23667    -- BEGIN ELABORATION ORDER
23668    -- ada (spec)
23669    -- gnat (spec)
23670    -- gnat.heap_sort_a (spec)
23671    -- gnat.heap_sort_a (body)
23672    -- gnat.htable (spec)
23673    -- gnat.htable (body)
23674    -- interfaces (spec)
23675    -- system (spec)
23676    -- system.machine_code (spec)
23677    -- system.parameters (spec)
23678    -- system.parameters (body)
23679    -- interfaces.c_streams (spec)
23680    -- interfaces.c_streams (body)
23681    -- system.standard_library (spec)
23682    -- ada.exceptions (spec)
23683    -- system.exception_table (spec)
23684    -- system.exception_table (body)
23685    -- ada.io_exceptions (spec)
23686    -- system.exceptions (spec)
23687    -- system.storage_elements (spec)
23688    -- system.storage_elements (body)
23689    -- system.machine_state_operations (spec)
23690    -- system.machine_state_operations (body)
23691    -- system.secondary_stack (spec)
23692    -- system.stack_checking (spec)
23693    -- system.soft_links (spec)
23694    -- system.soft_links (body)
23695    -- system.stack_checking (body)
23696    -- system.secondary_stack (body)
23697    -- system.standard_library (body)
23698    -- system.string_ops (spec)
23699    -- system.string_ops (body)
23700    -- ada.tags (spec)
23701    -- ada.tags (body)
23702    -- ada.streams (spec)
23703    -- system.finalization_root (spec)
23704    -- system.finalization_root (body)
23705    -- system.string_ops_concat_3 (spec)
23706    -- system.string_ops_concat_3 (body)
23707    -- system.traceback (spec)
23708    -- system.traceback (body)
23709    -- ada.exceptions (body)
23710    -- system.unsigned_types (spec)
23711    -- system.stream_attributes (spec)
23712    -- system.stream_attributes (body)
23713    -- system.finalization_implementation (spec)
23714    -- system.finalization_implementation (body)
23715    -- ada.finalization (spec)
23716    -- ada.finalization (body)
23717    -- ada.finalization.list_controller (spec)
23718    -- ada.finalization.list_controller (body)
23719    -- system.file_control_block (spec)
23720    -- system.file_io (spec)
23721    -- system.file_io (body)
23722    -- ada.text_io (spec)
23723    -- ada.text_io (body)
23724    -- hello (body)
23725    -- END ELABORATION ORDER
23727 end ada_main;
23729 --  The following source file name pragmas allow the generated file
23730 --  names to be unique for different main programs. They are needed
23731 --  since the package name will always be Ada_Main.
23733 pragma Source_File_Name (ada_main, Spec_File_Name => "b~hello.ads");
23734 pragma Source_File_Name (ada_main, Body_File_Name => "b~hello.adb");
23736 --  Generated package body for Ada_Main starts here
23738 package body ada_main is
23740    --  The actual finalization is performed by calling the
23741    --  library routine in System.Standard_Library.Adafinal
23743    procedure Do_Finalize;
23744    pragma Import (C, Do_Finalize, "system__standard_library__adafinal");
23746    -------------
23747    -- adainit --
23748    -------------
23750 @findex adainit
23751    procedure adainit is
23753       --  These booleans are set to True once the associated unit has
23754       --  been elaborated. It is also used to avoid elaborating the
23755       --  same unit twice.
23757       E040 : Boolean;
23758       pragma Import (Ada, E040, "interfaces__c_streams_E");
23760       E008 : Boolean;
23761       pragma Import (Ada, E008, "ada__exceptions_E");
23763       E014 : Boolean;
23764       pragma Import (Ada, E014, "system__exception_table_E");
23766       E053 : Boolean;
23767       pragma Import (Ada, E053, "ada__io_exceptions_E");
23769       E017 : Boolean;
23770       pragma Import (Ada, E017, "system__exceptions_E");
23772       E024 : Boolean;
23773       pragma Import (Ada, E024, "system__secondary_stack_E");
23775       E030 : Boolean;
23776       pragma Import (Ada, E030, "system__stack_checking_E");
23778       E028 : Boolean;
23779       pragma Import (Ada, E028, "system__soft_links_E");
23781       E035 : Boolean;
23782       pragma Import (Ada, E035, "ada__tags_E");
23784       E033 : Boolean;
23785       pragma Import (Ada, E033, "ada__streams_E");
23787       E046 : Boolean;
23788       pragma Import (Ada, E046, "system__finalization_root_E");
23790       E048 : Boolean;
23791       pragma Import (Ada, E048, "system__finalization_implementation_E");
23793       E044 : Boolean;
23794       pragma Import (Ada, E044, "ada__finalization_E");
23796       E057 : Boolean;
23797       pragma Import (Ada, E057, "ada__finalization__list_controller_E");
23799       E055 : Boolean;
23800       pragma Import (Ada, E055, "system__file_control_block_E");
23802       E042 : Boolean;
23803       pragma Import (Ada, E042, "system__file_io_E");
23805       E006 : Boolean;
23806       pragma Import (Ada, E006, "ada__text_io_E");
23808       --  Set_Globals is a library routine that stores away the
23809       --  value of the indicated set of global values in global
23810       --  variables within the library.
23812       procedure Set_Globals
23813         (Main_Priority            : Integer;
23814          Time_Slice_Value         : Integer;
23815          WC_Encoding              : Character;
23816          Locking_Policy           : Character;
23817          Queuing_Policy           : Character;
23818          Task_Dispatching_Policy  : Character;
23819          Adafinal                 : System.Address;
23820          Unreserve_All_Interrupts : Integer;
23821          Exception_Tracebacks     : Integer);
23822 @findex __gnat_set_globals
23823       pragma Import (C, Set_Globals, "__gnat_set_globals");
23825       --  SDP_Table_Build is a library routine used to build the
23826       --  exception tables. See unit Ada.Exceptions in files
23827       --  a-except.ads/adb for full details of how zero cost
23828       --  exception handling works. This procedure, the call to
23829       --  it, and the two following tables are all omitted if the
23830       --  build is in longjmp/setjmp exception mode.
23832 @findex SDP_Table_Build
23833 @findex Zero Cost Exceptions
23834       procedure SDP_Table_Build
23835         (SDP_Addresses   : System.Address;
23836          SDP_Count       : Natural;
23837          Elab_Addresses  : System.Address;
23838          Elab_Addr_Count : Natural);
23839       pragma Import (C, SDP_Table_Build, "__gnat_SDP_Table_Build");
23841       --  Table of Unit_Exception_Table addresses. Used for zero
23842       --  cost exception handling to build the top level table.
23844       ST : aliased constant array (1 .. 23) of System.Address := (
23845         Hello'UET_Address,
23846         Ada.Text_Io'UET_Address,
23847         Ada.Exceptions'UET_Address,
23848         Gnat.Heap_Sort_A'UET_Address,
23849         System.Exception_Table'UET_Address,
23850         System.Machine_State_Operations'UET_Address,
23851         System.Secondary_Stack'UET_Address,
23852         System.Parameters'UET_Address,
23853         System.Soft_Links'UET_Address,
23854         System.Stack_Checking'UET_Address,
23855         System.Traceback'UET_Address,
23856         Ada.Streams'UET_Address,
23857         Ada.Tags'UET_Address,
23858         System.String_Ops'UET_Address,
23859         Interfaces.C_Streams'UET_Address,
23860         System.File_Io'UET_Address,
23861         Ada.Finalization'UET_Address,
23862         System.Finalization_Root'UET_Address,
23863         System.Finalization_Implementation'UET_Address,
23864         System.String_Ops_Concat_3'UET_Address,
23865         System.Stream_Attributes'UET_Address,
23866         System.File_Control_Block'UET_Address,
23867         Ada.Finalization.List_Controller'UET_Address);
23869       --  Table of addresses of elaboration routines. Used for
23870       --  zero cost exception handling to make sure these
23871       --  addresses are included in the top level procedure
23872       --  address table.
23874       EA : aliased constant array (1 .. 23) of System.Address := (
23875         adainit'Code_Address,
23876         Do_Finalize'Code_Address,
23877         Ada.Exceptions'Elab_Spec'Address,
23878         System.Exceptions'Elab_Spec'Address,
23879         Interfaces.C_Streams'Elab_Spec'Address,
23880         System.Exception_Table'Elab_Body'Address,
23881         Ada.Io_Exceptions'Elab_Spec'Address,
23882         System.Stack_Checking'Elab_Spec'Address,
23883         System.Soft_Links'Elab_Body'Address,
23884         System.Secondary_Stack'Elab_Body'Address,
23885         Ada.Tags'Elab_Spec'Address,
23886         Ada.Tags'Elab_Body'Address,
23887         Ada.Streams'Elab_Spec'Address,
23888         System.Finalization_Root'Elab_Spec'Address,
23889         Ada.Exceptions'Elab_Body'Address,
23890         System.Finalization_Implementation'Elab_Spec'Address,
23891         System.Finalization_Implementation'Elab_Body'Address,
23892         Ada.Finalization'Elab_Spec'Address,
23893         Ada.Finalization.List_Controller'Elab_Spec'Address,
23894         System.File_Control_Block'Elab_Spec'Address,
23895         System.File_Io'Elab_Body'Address,
23896         Ada.Text_Io'Elab_Spec'Address,
23897         Ada.Text_Io'Elab_Body'Address);
23899    --  Start of processing for adainit
23901    begin
23903       --  Call SDP_Table_Build to build the top level procedure
23904       --  table for zero cost exception handling (omitted in
23905       --  longjmp/setjmp mode).
23907       SDP_Table_Build (ST'Address, 23, EA'Address, 23);
23909       --  Call Set_Globals to record various information for
23910       --  this partition.  The values are derived by the binder
23911       --  from information stored in the ali files by the compiler.
23913 @findex __gnat_set_globals
23914       Set_Globals
23915         (Main_Priority            => -1,
23916          --  Priority of main program, -1 if no pragma Priority used
23918          Time_Slice_Value         => -1,
23919          --  Time slice from Time_Slice pragma, -1 if none used
23921          WC_Encoding              => 'b',
23922          --  Wide_Character encoding used, default is brackets
23924          Locking_Policy           => ' ',
23925          --  Locking_Policy used, default of space means not
23926          --  specified, otherwise it is the first character of
23927          --  the policy name.
23929          Queuing_Policy           => ' ',
23930          --  Queuing_Policy used, default of space means not
23931          --  specified, otherwise it is the first character of
23932          --  the policy name.
23934          Task_Dispatching_Policy  => ' ',
23935          --  Task_Dispatching_Policy used, default of space means
23936          --  not specified, otherwise first character of the
23937          --  policy name.
23939          Adafinal                 => System.Null_Address,
23940          --  Address of Adafinal routine, not used anymore
23942          Unreserve_All_Interrupts => 0,
23943          --  Set true if pragma Unreserve_All_Interrupts was used
23945          Exception_Tracebacks     => 0);
23946          --  Indicates if exception tracebacks are enabled
23948       Elab_Final_Code := 1;
23950       --  Now we have the elaboration calls for all units in the partition.
23951       --  The Elab_Spec and Elab_Body attributes generate references to the
23952       --  implicit elaboration procedures generated by the compiler for
23953       --  each unit that requires elaboration.
23955       if not E040 then
23956          Interfaces.C_Streams'Elab_Spec;
23957       end if;
23958       E040 := True;
23959       if not E008 then
23960          Ada.Exceptions'Elab_Spec;
23961       end if;
23962       if not E014 then
23963          System.Exception_Table'Elab_Body;
23964          E014 := True;
23965       end if;
23966       if not E053 then
23967          Ada.Io_Exceptions'Elab_Spec;
23968          E053 := True;
23969       end if;
23970       if not E017 then
23971          System.Exceptions'Elab_Spec;
23972          E017 := True;
23973       end if;
23974       if not E030 then
23975          System.Stack_Checking'Elab_Spec;
23976       end if;
23977       if not E028 then
23978          System.Soft_Links'Elab_Body;
23979          E028 := True;
23980       end if;
23981       E030 := True;
23982       if not E024 then
23983          System.Secondary_Stack'Elab_Body;
23984          E024 := True;
23985       end if;
23986       if not E035 then
23987          Ada.Tags'Elab_Spec;
23988       end if;
23989       if not E035 then
23990          Ada.Tags'Elab_Body;
23991          E035 := True;
23992       end if;
23993       if not E033 then
23994          Ada.Streams'Elab_Spec;
23995          E033 := True;
23996       end if;
23997       if not E046 then
23998          System.Finalization_Root'Elab_Spec;
23999       end if;
24000       E046 := True;
24001       if not E008 then
24002          Ada.Exceptions'Elab_Body;
24003          E008 := True;
24004       end if;
24005       if not E048 then
24006          System.Finalization_Implementation'Elab_Spec;
24007       end if;
24008       if not E048 then
24009          System.Finalization_Implementation'Elab_Body;
24010          E048 := True;
24011       end if;
24012       if not E044 then
24013          Ada.Finalization'Elab_Spec;
24014       end if;
24015       E044 := True;
24016       if not E057 then
24017          Ada.Finalization.List_Controller'Elab_Spec;
24018       end if;
24019       E057 := True;
24020       if not E055 then
24021          System.File_Control_Block'Elab_Spec;
24022          E055 := True;
24023       end if;
24024       if not E042 then
24025          System.File_Io'Elab_Body;
24026          E042 := True;
24027       end if;
24028       if not E006 then
24029          Ada.Text_Io'Elab_Spec;
24030       end if;
24031       if not E006 then
24032          Ada.Text_Io'Elab_Body;
24033          E006 := True;
24034       end if;
24036       Elab_Final_Code := 0;
24037    end adainit;
24039    --------------
24040    -- adafinal --
24041    --------------
24043 @findex adafinal
24044    procedure adafinal is
24045    begin
24046       Do_Finalize;
24047    end adafinal;
24049    ----------
24050    -- main --
24051    ----------
24053    --  main is actually a function, as in the ANSI C standard,
24054    --  defined to return the exit status. The three parameters
24055    --  are the argument count, argument values and environment
24056    --  pointer.
24058 @findex Main Program
24059    function main
24060      (argc : Integer;
24061       argv : System.Address;
24062       envp : System.Address)
24063       return Integer
24064    is
24065       --  The initialize routine performs low level system
24066       --  initialization using a standard library routine which
24067       --  sets up signal handling and performs any other
24068       --  required setup. The routine can be found in file
24069       --  a-init.c.
24071 @findex __gnat_initialize
24072       procedure initialize;
24073       pragma Import (C, initialize, "__gnat_initialize");
24075       --  The finalize routine performs low level system
24076       --  finalization using a standard library routine. The
24077       --  routine is found in file a-final.c and in the standard
24078       --  distribution is a dummy routine that does nothing, so
24079       --  really this is a hook for special user finalization.
24081 @findex __gnat_finalize
24082       procedure finalize;
24083       pragma Import (C, finalize, "__gnat_finalize");
24085       --  We get to the main program of the partition by using
24086       --  pragma Import because if we try to with the unit and
24087       --  call it Ada style, then not only do we waste time
24088       --  recompiling it, but also, we don't really know the right
24089       --  switches (e.g.@: identifier character set) to be used
24090       --  to compile it.
24092       procedure Ada_Main_Program;
24093       pragma Import (Ada, Ada_Main_Program, "_ada_hello");
24095    --  Start of processing for main
24097    begin
24098       --  Save global variables
24100       gnat_argc := argc;
24101       gnat_argv := argv;
24102       gnat_envp := envp;
24104       --  Call low level system initialization
24106       Initialize;
24108       --  Call our generated Ada initialization routine
24110       adainit;
24112       --  This is the point at which we want the debugger to get
24113       --  control
24115       Break_Start;
24117       --  Now we call the main program of the partition
24119       Ada_Main_Program;
24121       --  Perform Ada finalization
24123       adafinal;
24125       --  Perform low level system finalization
24127       Finalize;
24129       --  Return the proper exit status
24130       return (gnat_exit_status);
24131    end;
24133 --  This section is entirely comments, so it has no effect on the
24134 --  compilation of the Ada_Main package. It provides the list of
24135 --  object files and linker options, as well as some standard
24136 --  libraries needed for the link. The gnatlink utility parses
24137 --  this b~hello.adb file to read these comment lines to generate
24138 --  the appropriate command line arguments for the call to the
24139 --  system linker. The BEGIN/END lines are used for sentinels for
24140 --  this parsing operation.
24142 --  The exact file names will of course depend on the environment,
24143 --  host/target and location of files on the host system.
24145 @findex Object file list
24146 -- BEGIN Object file/option list
24147    --   ./hello.o
24148    --   -L./
24149    --   -L/usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/
24150    --   /usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/libgnat.a
24151 -- END Object file/option list
24153 end ada_main;
24154 @end smallexample
24156 @noindent
24157 The Ada code in the above example is exactly what is generated by the
24158 binder. We have added comments to more clearly indicate the function
24159 of each part of the generated @code{Ada_Main} package.
24161 The code is standard Ada in all respects, and can be processed by any
24162 tools that handle Ada. In particular, it is possible to use the debugger
24163 in Ada mode to debug the generated @code{Ada_Main} package. For example,
24164 suppose that for reasons that you do not understand, your program is crashing
24165 during elaboration of the body of @code{Ada.Text_IO}. To locate this bug,
24166 you can place a breakpoint on the call:
24168 @smallexample @c ada
24169 Ada.Text_Io'Elab_Body;
24170 @end smallexample
24172 @noindent
24173 and trace the elaboration routine for this package to find out where
24174 the problem might be (more usually of course you would be debugging
24175 elaboration code in your own application).
24177 @node Elaboration Order Handling in GNAT
24178 @appendix Elaboration Order Handling in GNAT
24179 @cindex Order of elaboration
24180 @cindex Elaboration control
24182 @menu
24183 * Elaboration Code::
24184 * Checking the Elaboration Order::
24185 * Controlling the Elaboration Order::
24186 * Controlling Elaboration in GNAT - Internal Calls::
24187 * Controlling Elaboration in GNAT - External Calls::
24188 * Default Behavior in GNAT - Ensuring Safety::
24189 * Treatment of Pragma Elaborate::
24190 * Elaboration Issues for Library Tasks::
24191 * Mixing Elaboration Models::
24192 * What to Do If the Default Elaboration Behavior Fails::
24193 * Elaboration for Dispatching Calls::
24194 * Summary of Procedures for Elaboration Control::
24195 * Other Elaboration Order Considerations::
24196 @end menu
24198 @noindent
24199 This chapter describes the handling of elaboration code in Ada and
24200 in GNAT, and discusses how the order of elaboration of program units can
24201 be controlled in GNAT, either automatically or with explicit programming
24202 features.
24204 @node Elaboration Code
24205 @section Elaboration Code
24207 @noindent
24208 Ada provides rather general mechanisms for executing code at elaboration
24209 time, that is to say before the main program starts executing. Such code arises
24210 in three contexts:
24212 @table @asis
24213 @item Initializers for variables.
24214 Variables declared at the library level, in package specs or bodies, can
24215 require initialization that is performed at elaboration time, as in:
24216 @smallexample @c ada
24217 @cartouche
24218 Sqrt_Half : Float := Sqrt (0.5);
24219 @end cartouche
24220 @end smallexample
24222 @item Package initialization code
24223 Code in a @code{BEGIN-END} section at the outer level of a package body is
24224 executed as part of the package body elaboration code.
24226 @item Library level task allocators
24227 Tasks that are declared using task allocators at the library level
24228 start executing immediately and hence can execute at elaboration time.
24229 @end table
24231 @noindent
24232 Subprogram calls are possible in any of these contexts, which means that
24233 any arbitrary part of the program may be executed as part of the elaboration
24234 code. It is even possible to write a program which does all its work at
24235 elaboration time, with a null main program, although stylistically this
24236 would usually be considered an inappropriate way to structure
24237 a program.
24239 An important concern arises in the context of elaboration code:
24240 we have to be sure that it is executed in an appropriate order. What we
24241 have is a series of elaboration code sections, potentially one section
24242 for each unit in the program. It is important that these execute
24243 in the correct order. Correctness here means that, taking the above
24244 example of the declaration of @code{Sqrt_Half},
24245 if some other piece of
24246 elaboration code references @code{Sqrt_Half},
24247 then it must run after the
24248 section of elaboration code that contains the declaration of
24249 @code{Sqrt_Half}.
24251 There would never be any order of elaboration problem if we made a rule
24252 that whenever you @code{with} a unit, you must elaborate both the spec and body
24253 of that unit before elaborating the unit doing the @code{with}'ing:
24255 @smallexample @c ada
24256 @group
24257 @cartouche
24258 with Unit_1;
24259 package Unit_2 is @dots{}
24260 @end cartouche
24261 @end group
24262 @end smallexample
24264 @noindent
24265 would require that both the body and spec of @code{Unit_1} be elaborated
24266 before the spec of @code{Unit_2}. However, a rule like that would be far too
24267 restrictive. In particular, it would make it impossible to have routines
24268 in separate packages that were mutually recursive.
24270 You might think that a clever enough compiler could look at the actual
24271 elaboration code and determine an appropriate correct order of elaboration,
24272 but in the general case, this is not possible. Consider the following
24273 example.
24275 In the body of @code{Unit_1}, we have a procedure @code{Func_1}
24276 that references
24277 the variable @code{Sqrt_1}, which is declared in the elaboration code
24278 of the body of @code{Unit_1}:
24280 @smallexample @c ada
24281 @cartouche
24282 Sqrt_1 : Float := Sqrt (0.1);
24283 @end cartouche
24284 @end smallexample
24286 @noindent
24287 The elaboration code of the body of @code{Unit_1} also contains:
24289 @smallexample @c ada
24290 @group
24291 @cartouche
24292 if expression_1 = 1 then
24293    Q := Unit_2.Func_2;
24294 end if;
24295 @end cartouche
24296 @end group
24297 @end smallexample
24299 @noindent
24300 @code{Unit_2} is exactly parallel,
24301 it has a procedure @code{Func_2} that references
24302 the variable @code{Sqrt_2}, which is declared in the elaboration code of
24303 the body @code{Unit_2}:
24305 @smallexample @c ada
24306 @cartouche
24307 Sqrt_2 : Float := Sqrt (0.1);
24308 @end cartouche
24309 @end smallexample
24311 @noindent
24312 The elaboration code of the body of @code{Unit_2} also contains:
24314 @smallexample @c ada
24315 @group
24316 @cartouche
24317 if expression_2 = 2 then
24318    Q := Unit_1.Func_1;
24319 end if;
24320 @end cartouche
24321 @end group
24322 @end smallexample
24324 @noindent
24325 Now the question is, which of the following orders of elaboration is
24326 acceptable:
24328 @smallexample
24329 @group
24330 Spec of Unit_1
24331 Spec of Unit_2
24332 Body of Unit_1
24333 Body of Unit_2
24334 @end group
24335 @end smallexample
24337 @noindent
24340 @smallexample
24341 @group
24342 Spec of Unit_2
24343 Spec of Unit_1
24344 Body of Unit_2
24345 Body of Unit_1
24346 @end group
24347 @end smallexample
24349 @noindent
24350 If you carefully analyze the flow here, you will see that you cannot tell
24351 at compile time the answer to this question.
24352 If @code{expression_1} is not equal to 1,
24353 and @code{expression_2} is not equal to 2,
24354 then either order is acceptable, because neither of the function calls is
24355 executed. If both tests evaluate to true, then neither order is acceptable
24356 and in fact there is no correct order.
24358 If one of the two expressions is true, and the other is false, then one
24359 of the above orders is correct, and the other is incorrect. For example,
24360 if @code{expression_1} /= 1 and @code{expression_2} = 2,
24361 then the call to @code{Func_1}
24362 will occur, but not the call to @code{Func_2.}
24363 This means that it is essential
24364 to elaborate the body of @code{Unit_1} before
24365 the body of @code{Unit_2}, so the first
24366 order of elaboration is correct and the second is wrong.
24368 By making @code{expression_1} and @code{expression_2}
24369 depend on input data, or perhaps
24370 the time of day, we can make it impossible for the compiler or binder
24371 to figure out which of these expressions will be true, and hence it
24372 is impossible to guarantee a safe order of elaboration at run time.
24374 @node Checking the Elaboration Order
24375 @section Checking the Elaboration Order
24377 @noindent
24378 In some languages that involve the same kind of elaboration problems,
24379 e.g.@: Java and C++, the programmer is expected to worry about these
24380 ordering problems himself, and it is common to
24381 write a program in which an incorrect elaboration order  gives
24382 surprising results, because it references variables before they
24383 are initialized.
24384 Ada is designed to be a safe language, and a programmer-beware approach is
24385 clearly not sufficient. Consequently, the language provides three lines
24386 of defense:
24388 @table @asis
24389 @item Standard rules
24390 Some standard rules restrict the possible choice of elaboration
24391 order. In particular, if you @code{with} a unit, then its spec is always
24392 elaborated before the unit doing the @code{with}. Similarly, a parent
24393 spec is always elaborated before the child spec, and finally
24394 a spec is always elaborated before its corresponding body.
24396 @item Dynamic elaboration checks
24397 @cindex Elaboration checks
24398 @cindex Checks, elaboration
24399 Dynamic checks are made at run time, so that if some entity is accessed
24400 before it is elaborated (typically  by means of a subprogram call)
24401 then the exception (@code{Program_Error}) is raised.
24403 @item Elaboration control
24404 Facilities are provided for the programmer to specify the desired order
24405 of elaboration.
24406 @end table
24408 Let's look at these facilities in more detail. First, the rules for
24409 dynamic checking. One possible rule would be simply to say that the
24410 exception is raised if you access a variable which has not yet been
24411 elaborated. The trouble with this approach is that it could require
24412 expensive checks on every variable reference. Instead Ada has two
24413 rules which are a little more restrictive, but easier to check, and
24414 easier to state:
24416 @table @asis
24417 @item Restrictions on calls
24418 A subprogram can only be called at elaboration time if its body
24419 has been elaborated. The rules for elaboration given above guarantee
24420 that the spec of the subprogram has been elaborated before the
24421 call, but not the body. If this rule is violated, then the
24422 exception @code{Program_Error} is raised.
24424 @item Restrictions on instantiations
24425 A generic unit can only be instantiated if the body of the generic
24426 unit has been elaborated. Again, the rules for elaboration given above
24427 guarantee that the spec of the generic unit has been elaborated
24428 before the instantiation, but not the body. If this rule is
24429 violated, then the exception @code{Program_Error} is raised.
24430 @end table
24432 @noindent
24433 The idea is that if the body has been elaborated, then any variables
24434 it references must have been elaborated; by checking for the body being
24435 elaborated we guarantee that none of its references causes any
24436 trouble. As we noted above, this is a little too restrictive, because a
24437 subprogram that has no non-local references in its body may in fact be safe
24438 to call. However, it really would be unsafe to rely on this, because
24439 it would mean that the caller was aware of details of the implementation
24440 in the body. This goes against the basic tenets of Ada.
24442 A plausible implementation can be described as follows.
24443 A Boolean variable is associated with each subprogram
24444 and each generic unit. This variable is initialized to False, and is set to
24445 True at the point body is elaborated. Every call or instantiation checks the
24446 variable, and raises @code{Program_Error} if the variable is False.
24448 Note that one might think that it would be good enough to have one Boolean
24449 variable for each package, but that would not deal with cases of trying
24450 to call a body in the same package as the call
24451 that has not been elaborated yet.
24452 Of course a compiler may be able to do enough analysis to optimize away
24453 some of the Boolean variables as unnecessary, and @code{GNAT} indeed
24454 does such optimizations, but still the easiest conceptual model is to
24455 think of there being one variable per subprogram.
24457 @node Controlling the Elaboration Order
24458 @section Controlling the Elaboration Order
24460 @noindent
24461 In the previous section we discussed the rules in Ada which ensure
24462 that @code{Program_Error} is raised if an incorrect elaboration order is
24463 chosen. This prevents erroneous executions, but we need mechanisms to
24464 specify a correct execution and avoid the exception altogether.
24465 To achieve this, Ada provides a number of features for controlling
24466 the order of elaboration. We discuss these features in this section.
24468 First, there are several ways of indicating to the compiler that a given
24469 unit has no elaboration problems:
24471 @table @asis
24472 @item packages that do not require a body
24473 A library package that does not require a body does not permit
24474 a body (this rule was introduced in Ada 95).
24475 Thus if we have a such a package, as in:
24477 @smallexample @c ada
24478 @group
24479 @cartouche
24480 package Definitions is
24481    generic
24482       type m is new integer;
24483    package Subp is
24484       type a is array (1 .. 10) of m;
24485       type b is array (1 .. 20) of m;
24486    end Subp;
24487 end Definitions;
24488 @end cartouche
24489 @end group
24490 @end smallexample
24492 @noindent
24493 A package that @code{with}'s @code{Definitions} may safely instantiate
24494 @code{Definitions.Subp} because the compiler can determine that there
24495 definitely is no package body to worry about in this case
24497 @item pragma Pure
24498 @cindex pragma Pure
24499 @findex Pure
24500 Places sufficient restrictions on a unit to guarantee that
24501 no call to any subprogram in the unit can result in an
24502 elaboration problem. This means that the compiler does not need
24503 to worry about the point of elaboration of such units, and in
24504 particular, does not need to check any calls to any subprograms
24505 in this unit.
24507 @item pragma Preelaborate
24508 @findex Preelaborate
24509 @cindex pragma Preelaborate
24510 This pragma places slightly less stringent restrictions on a unit than
24511 does pragma Pure,
24512 but these restrictions are still sufficient to ensure that there
24513 are no elaboration problems with any calls to the unit.
24515 @item pragma Elaborate_Body
24516 @findex Elaborate_Body
24517 @cindex pragma Elaborate_Body
24518 This pragma requires that the body of a unit be elaborated immediately
24519 after its spec. Suppose a unit @code{A} has such a pragma,
24520 and unit @code{B} does
24521 a @code{with} of unit @code{A}. Recall that the standard rules require
24522 the spec of unit @code{A}
24523 to be elaborated before the @code{with}'ing unit; given the pragma in
24524 @code{A}, we also know that the body of @code{A}
24525 will be elaborated before @code{B}, so
24526 that calls to @code{A} are safe and do not need a check.
24527 @end table
24529 @noindent
24530 Note that,
24531 unlike pragma @code{Pure} and pragma @code{Preelaborate},
24532 the use of
24533 @code{Elaborate_Body} does not guarantee that the program is
24534 free of elaboration problems, because it may not be possible
24535 to satisfy the requested elaboration order.
24536 Let's go back to the example with @code{Unit_1} and @code{Unit_2}.
24537 If a programmer
24538 marks @code{Unit_1} as @code{Elaborate_Body},
24539 and not @code{Unit_2,} then the order of
24540 elaboration will be:
24542 @smallexample
24543 @group
24544 Spec of Unit_2
24545 Spec of Unit_1
24546 Body of Unit_1
24547 Body of Unit_2
24548 @end group
24549 @end smallexample
24551 @noindent
24552 Now that means that the call to @code{Func_1} in @code{Unit_2}
24553 need not be checked,
24554 it must be safe. But the call to @code{Func_2} in
24555 @code{Unit_1} may still fail if
24556 @code{Expression_1} is equal to 1,
24557 and the programmer must still take
24558 responsibility for this not being the case.
24560 If all units carry a pragma @code{Elaborate_Body}, then all problems are
24561 eliminated, except for calls entirely within a body, which are
24562 in any case fully under programmer control. However, using the pragma
24563 everywhere is not always possible.
24564 In particular, for our @code{Unit_1}/@code{Unit_2} example, if
24565 we marked both of them as having pragma @code{Elaborate_Body}, then
24566 clearly there would be no possible elaboration order.
24568 The above pragmas allow a server to guarantee safe use by clients, and
24569 clearly this is the preferable approach. Consequently a good rule
24570 is to mark units as @code{Pure} or @code{Preelaborate} if possible,
24571 and if this is not possible,
24572 mark them as @code{Elaborate_Body} if possible.
24573 As we have seen, there are situations where neither of these
24574 three pragmas can be used.
24575 So we also provide methods for clients to control the
24576 order of elaboration of the servers on which they depend:
24578 @table @asis
24579 @item pragma Elaborate (unit)
24580 @findex Elaborate
24581 @cindex pragma Elaborate
24582 This pragma is placed in the context clause, after a @code{with} clause,
24583 and it requires that the body of the named unit be elaborated before
24584 the unit in which the pragma occurs. The idea is to use this pragma
24585 if the current unit calls at elaboration time, directly or indirectly,
24586 some subprogram in the named unit.
24588 @item pragma Elaborate_All (unit)
24589 @findex Elaborate_All
24590 @cindex pragma Elaborate_All
24591 This is a stronger version of the Elaborate pragma. Consider the
24592 following example:
24594 @smallexample
24595 Unit A @code{with}'s unit B and calls B.Func in elab code
24596 Unit B @code{with}'s unit C, and B.Func calls C.Func
24597 @end smallexample
24599 @noindent
24600 Now if we put a pragma @code{Elaborate (B)}
24601 in unit @code{A}, this ensures that the
24602 body of @code{B} is elaborated before the call, but not the
24603 body of @code{C}, so
24604 the call to @code{C.Func} could still cause @code{Program_Error} to
24605 be raised.
24607 The effect of a pragma @code{Elaborate_All} is stronger, it requires
24608 not only that the body of the named unit be elaborated before the
24609 unit doing the @code{with}, but also the bodies of all units that the
24610 named unit uses, following @code{with} links transitively. For example,
24611 if we put a pragma @code{Elaborate_All (B)} in unit @code{A},
24612 then it requires
24613 not only that the body of @code{B} be elaborated before @code{A},
24614 but also the
24615 body of @code{C}, because @code{B} @code{with}'s @code{C}.
24616 @end table
24618 @noindent
24619 We are now in a position to give a usage rule in Ada for avoiding
24620 elaboration problems, at least if dynamic dispatching and access to
24621 subprogram values are not used. We will handle these cases separately
24622 later.
24624 The rule is simple. If a unit has elaboration code that can directly or
24625 indirectly make a call to a subprogram in a @code{with}'ed unit, or instantiate
24626 a generic package in a @code{with}'ed unit,
24627 then if the @code{with}'ed unit does not have
24628 pragma @code{Pure} or @code{Preelaborate}, then the client should have
24629 a pragma @code{Elaborate_All}
24630 for the @code{with}'ed unit. By following this rule a client is
24631 assured that calls can be made without risk of an exception.
24633 For generic subprogram instantiations, the rule can be relaxed to
24634 require only a pragma @code{Elaborate} since elaborating the body
24635 of a subprogram cannot cause any transitive elaboration (we are
24636 not calling the subprogram in this case, just elaborating its
24637 declaration).
24639 If this rule is not followed, then a program may be in one of four
24640 states:
24642 @table @asis
24643 @item No order exists
24644 No order of elaboration exists which follows the rules, taking into
24645 account any @code{Elaborate}, @code{Elaborate_All},
24646 or @code{Elaborate_Body} pragmas. In
24647 this case, an Ada compiler must diagnose the situation at bind
24648 time, and refuse to build an executable program.
24650 @item One or more orders exist, all incorrect
24651 One or more acceptable elaboration orders exist, and all of them
24652 generate an elaboration order problem. In this case, the binder
24653 can build an executable program, but @code{Program_Error} will be raised
24654 when the program is run.
24656 @item Several orders exist, some right, some incorrect
24657 One or more acceptable elaboration orders exists, and some of them
24658 work, and some do not. The programmer has not controlled
24659 the order of elaboration, so the binder may or may not pick one of
24660 the correct orders, and the program may or may not raise an
24661 exception when it is run. This is the worst case, because it means
24662 that the program may fail when moved to another compiler, or even
24663 another version of the same compiler.
24665 @item One or more orders exists, all correct
24666 One ore more acceptable elaboration orders exist, and all of them
24667 work. In this case the program runs successfully. This state of
24668 affairs can be guaranteed by following the rule we gave above, but
24669 may be true even if the rule is not followed.
24670 @end table
24672 @noindent
24673 Note that one additional advantage of following our rules on the use
24674 of @code{Elaborate} and @code{Elaborate_All}
24675 is that the program continues to stay in the ideal (all orders OK) state
24676 even if maintenance
24677 changes some bodies of some units. Conversely, if a program that does
24678 not follow this rule happens to be safe at some point, this state of affairs
24679 may deteriorate silently as a result of maintenance changes.
24681 You may have noticed that the above discussion did not mention
24682 the use of @code{Elaborate_Body}. This was a deliberate omission. If you
24683 @code{with} an @code{Elaborate_Body} unit, it still may be the case that
24684 code in the body makes calls to some other unit, so it is still necessary
24685 to use @code{Elaborate_All} on such units.
24687 @node Controlling Elaboration in GNAT - Internal Calls
24688 @section Controlling Elaboration in GNAT - Internal Calls
24690 @noindent
24691 In the case of internal calls, i.e., calls within a single package, the
24692 programmer has full control over the order of elaboration, and it is up
24693 to the programmer to elaborate declarations in an appropriate order. For
24694 example writing:
24696 @smallexample @c ada
24697 @group
24698 @cartouche
24699 function One return Float;
24701 Q : Float := One;
24703 function One return Float is
24704 begin
24705      return 1.0;
24706 end One;
24707 @end cartouche
24708 @end group
24709 @end smallexample
24711 @noindent
24712 will obviously raise @code{Program_Error} at run time, because function
24713 One will be called before its body is elaborated. In this case GNAT will
24714 generate a warning that the call will raise @code{Program_Error}:
24716 @smallexample
24717 @group
24718 @cartouche
24719  1. procedure y is
24720  2.    function One return Float;
24721  3.
24722  4.    Q : Float := One;
24723                     |
24724     >>> warning: cannot call "One" before body is elaborated
24725     >>> warning: Program_Error will be raised at run time
24727  5.
24728  6.    function One return Float is
24729  7.    begin
24730  8.         return 1.0;
24731  9.    end One;
24733 11. begin
24734 12.    null;
24735 13. end;
24736 @end cartouche
24737 @end group
24738 @end smallexample
24740 @noindent
24741 Note that in this particular case, it is likely that the call is safe, because
24742 the function @code{One} does not access any global variables.
24743 Nevertheless in Ada, we do not want the validity of the check to depend on
24744 the contents of the body (think about the separate compilation case), so this
24745 is still wrong, as we discussed in the previous sections.
24747 The error is easily corrected by rearranging the declarations so that the
24748 body of @code{One} appears before the declaration containing the call
24749 (note that in Ada 95 and Ada 2005,
24750 declarations can appear in any order, so there is no restriction that
24751 would prevent this reordering, and if we write:
24753 @smallexample @c ada
24754 @group
24755 @cartouche
24756 function One return Float;
24758 function One return Float is
24759 begin
24760      return 1.0;
24761 end One;
24763 Q : Float := One;
24764 @end cartouche
24765 @end group
24766 @end smallexample
24768 @noindent
24769 then all is well, no warning is generated, and no
24770 @code{Program_Error} exception
24771 will be raised.
24772 Things are more complicated when a chain of subprograms is executed:
24774 @smallexample @c ada
24775 @group
24776 @cartouche
24777 function A return Integer;
24778 function B return Integer;
24779 function C return Integer;
24781 function B return Integer is begin return A; end;
24782 function C return Integer is begin return B; end;
24784 X : Integer := C;
24786 function A return Integer is begin return 1; end;
24787 @end cartouche
24788 @end group
24789 @end smallexample
24791 @noindent
24792 Now the call to @code{C}
24793 at elaboration time in the declaration of @code{X} is correct, because
24794 the body of @code{C} is already elaborated,
24795 and the call to @code{B} within the body of
24796 @code{C} is correct, but the call
24797 to @code{A} within the body of @code{B} is incorrect, because the body
24798 of @code{A} has not been elaborated, so @code{Program_Error}
24799 will be raised on the call to @code{A}.
24800 In this case GNAT will generate a
24801 warning that @code{Program_Error} may be
24802 raised at the point of the call. Let's look at the warning:
24804 @smallexample
24805 @group
24806 @cartouche
24807  1. procedure x is
24808  2.    function A return Integer;
24809  3.    function B return Integer;
24810  4.    function C return Integer;
24811  5.
24812  6.    function B return Integer is begin return A; end;
24813                                                     |
24814     >>> warning: call to "A" before body is elaborated may
24815                  raise Program_Error
24816     >>> warning: "B" called at line 7
24817     >>> warning: "C" called at line 9
24819  7.    function C return Integer is begin return B; end;
24820  8.
24821  9.    X : Integer := C;
24823 11.    function A return Integer is begin return 1; end;
24825 13. begin
24826 14.    null;
24827 15. end;
24828 @end cartouche
24829 @end group
24830 @end smallexample
24832 @noindent
24833 Note that the message here says ``may raise'', instead of the direct case,
24834 where the message says ``will be raised''. That's because whether
24835 @code{A} is
24836 actually called depends in general on run-time flow of control.
24837 For example, if the body of @code{B} said
24839 @smallexample @c ada
24840 @group
24841 @cartouche
24842 function B return Integer is
24843 begin
24844    if some-condition-depending-on-input-data then
24845       return A;
24846    else
24847       return 1;
24848    end if;
24849 end B;
24850 @end cartouche
24851 @end group
24852 @end smallexample
24854 @noindent
24855 then we could not know until run time whether the incorrect call to A would
24856 actually occur, so @code{Program_Error} might
24857 or might not be raised. It is possible for a compiler to
24858 do a better job of analyzing bodies, to
24859 determine whether or not @code{Program_Error}
24860 might be raised, but it certainly
24861 couldn't do a perfect job (that would require solving the halting problem
24862 and is provably impossible), and because this is a warning anyway, it does
24863 not seem worth the effort to do the analysis. Cases in which it
24864 would be relevant are rare.
24866 In practice, warnings of either of the forms given
24867 above will usually correspond to
24868 real errors, and should be examined carefully and eliminated.
24869 In the rare case where a warning is bogus, it can be suppressed by any of
24870 the following methods:
24872 @itemize @bullet
24873 @item
24874 Compile with the @option{-gnatws} switch set
24876 @item
24877 Suppress @code{Elaboration_Check} for the called subprogram
24879 @item
24880 Use pragma @code{Warnings_Off} to turn warnings off for the call
24881 @end itemize
24883 @noindent
24884 For the internal elaboration check case,
24885 GNAT by default generates the
24886 necessary run-time checks to ensure
24887 that @code{Program_Error} is raised if any
24888 call fails an elaboration check. Of course this can only happen if a
24889 warning has been issued as described above. The use of pragma
24890 @code{Suppress (Elaboration_Check)} may (but is not guaranteed to) suppress
24891 some of these checks, meaning that it may be possible (but is not
24892 guaranteed) for a program to be able to call a subprogram whose body
24893 is not yet elaborated, without raising a @code{Program_Error} exception.
24895 @node Controlling Elaboration in GNAT - External Calls
24896 @section Controlling Elaboration in GNAT - External Calls
24898 @noindent
24899 The previous section discussed the case in which the execution of a
24900 particular thread of elaboration code occurred entirely within a
24901 single unit. This is the easy case to handle, because a programmer
24902 has direct and total control over the order of elaboration, and
24903 furthermore, checks need only be generated in cases which are rare
24904 and which the compiler can easily detect.
24905 The situation is more complex when separate compilation is taken into account.
24906 Consider the following:
24908 @smallexample @c ada
24909 @cartouche
24910 @group
24911 package Math is
24912    function Sqrt (Arg : Float) return Float;
24913 end Math;
24915 package body Math is
24916    function Sqrt (Arg : Float) return Float is
24917    begin
24918          @dots{}
24919    end Sqrt;
24920 end Math;
24921 @end group
24922 @group
24923 with Math;
24924 package Stuff is
24925    X : Float := Math.Sqrt (0.5);
24926 end Stuff;
24928 with Stuff;
24929 procedure Main is
24930 begin
24931    @dots{}
24932 end Main;
24933 @end group
24934 @end cartouche
24935 @end smallexample
24937 @noindent
24938 where @code{Main} is the main program. When this program is executed, the
24939 elaboration code must first be executed, and one of the jobs of the
24940 binder is to determine the order in which the units of a program are
24941 to be elaborated. In this case we have four units: the spec and body
24942 of @code{Math},
24943 the spec of @code{Stuff} and the body of @code{Main}).
24944 In what order should the four separate sections of elaboration code
24945 be executed?
24947 There are some restrictions in the order of elaboration that the binder
24948 can choose. In particular, if unit U has a @code{with}
24949 for a package @code{X}, then you
24950 are assured that the spec of @code{X}
24951 is elaborated before U , but you are
24952 not assured that the body of @code{X}
24953 is elaborated before U.
24954 This means that in the above case, the binder is allowed to choose the
24955 order:
24957 @smallexample
24958 spec of Math
24959 spec of Stuff
24960 body of Math
24961 body of Main
24962 @end smallexample
24964 @noindent
24965 but that's not good, because now the call to @code{Math.Sqrt}
24966 that happens during
24967 the elaboration of the @code{Stuff}
24968 spec happens before the body of @code{Math.Sqrt} is
24969 elaborated, and hence causes @code{Program_Error} exception to be raised.
24970 At first glance, one might say that the binder is misbehaving, because
24971 obviously you want to elaborate the body of something you @code{with}
24972 first, but
24973 that is not a general rule that can be followed in all cases. Consider
24975 @smallexample @c ada
24976 @group
24977 @cartouche
24978 package X is @dots{}
24980 package Y is @dots{}
24982 with X;
24983 package body Y is @dots{}
24985 with Y;
24986 package body X is @dots{}
24987 @end cartouche
24988 @end group
24989 @end smallexample
24991 @noindent
24992 This is a common arrangement, and, apart from the order of elaboration
24993 problems that might arise in connection with elaboration code, this works fine.
24994 A rule that says that you must first elaborate the body of anything you
24995 @code{with} cannot work in this case:
24996 the body of @code{X} @code{with}'s @code{Y},
24997 which means you would have to
24998 elaborate the body of @code{Y} first, but that @code{with}'s @code{X},
24999 which means
25000 you have to elaborate the body of @code{X} first, but @dots{} and we have a
25001 loop that cannot be broken.
25003 It is true that the binder can in many cases guess an order of elaboration
25004 that is unlikely to cause a @code{Program_Error}
25005 exception to be raised, and it tries to do so (in the
25006 above example of @code{Math/Stuff/Spec}, the GNAT binder will
25007 by default
25008 elaborate the body of @code{Math} right after its spec, so all will be well).
25010 However, a program that blindly relies on the binder to be helpful can
25011 get into trouble, as we discussed in the previous sections, so
25012 GNAT
25013 provides a number of facilities for assisting the programmer in
25014 developing programs that are robust with respect to elaboration order.
25016 @node Default Behavior in GNAT - Ensuring Safety
25017 @section Default Behavior in GNAT - Ensuring Safety
25019 @noindent
25020 The default behavior in GNAT ensures elaboration safety. In its
25021 default mode GNAT implements the
25022 rule we previously described as the right approach. Let's restate it:
25024 @itemize
25025 @item
25026 @emph{If a unit has elaboration code that can directly or indirectly make a
25027 call to a subprogram in a @code{with}'ed unit, or instantiate a generic
25028 package in a @code{with}'ed unit, then if the @code{with}'ed unit
25029 does not have pragma @code{Pure} or
25030 @code{Preelaborate}, then the client should have an
25031 @code{Elaborate_All} pragma for the @code{with}'ed unit.}
25033 @emph{In the case of instantiating a generic subprogram, it is always
25034 sufficient to have only an @code{Elaborate} pragma for the
25035 @code{with}'ed unit.}
25036 @end itemize
25038 @noindent
25039 By following this rule a client is assured that calls and instantiations
25040 can be made without risk of an exception.
25042 In this mode GNAT traces all calls that are potentially made from
25043 elaboration code, and puts in any missing implicit @code{Elaborate}
25044 and @code{Elaborate_All} pragmas.
25045 The advantage of this approach is that no elaboration problems
25046 are possible if the binder can find an elaboration order that is
25047 consistent with these implicit @code{Elaborate} and
25048 @code{Elaborate_All} pragmas. The
25049 disadvantage of this approach is that no such order may exist.
25051 If the binder does not generate any diagnostics, then it means that it has
25052 found an elaboration order that is guaranteed to be safe. However, the binder
25053 may still be relying on implicitly generated @code{Elaborate} and
25054 @code{Elaborate_All} pragmas so portability to other compilers than GNAT is not
25055 guaranteed.
25057 If it is important to guarantee portability, then the compilations should
25058 use the
25059 @option{-gnatwl}
25060 (warn on elaboration problems) switch. This will cause warning messages
25061 to be generated indicating the missing @code{Elaborate} and
25062 @code{Elaborate_All} pragmas.
25063 Consider the following source program:
25065 @smallexample @c ada
25066 @group
25067 @cartouche
25068 with k;
25069 package j is
25070   m : integer := k.r;
25071 end;
25072 @end cartouche
25073 @end group
25074 @end smallexample
25076 @noindent
25077 where it is clear that there
25078 should be a pragma @code{Elaborate_All}
25079 for unit @code{k}. An implicit pragma will be generated, and it is
25080 likely that the binder will be able to honor it. However, if you want
25081 to port this program to some other Ada compiler than GNAT.
25082 it is safer to include the pragma explicitly in the source. If this
25083 unit is compiled with the
25084 @option{-gnatwl}
25085 switch, then the compiler outputs a warning:
25087 @smallexample
25088 @group
25089 @cartouche
25090 1. with k;
25091 2. package j is
25092 3.   m : integer := k.r;
25093                      |
25094    >>> warning: call to "r" may raise Program_Error
25095    >>> warning: missing pragma Elaborate_All for "k"
25097 4. end;
25098 @end cartouche
25099 @end group
25100 @end smallexample
25102 @noindent
25103 and these warnings can be used as a guide for supplying manually
25104 the missing pragmas. It is usually a bad idea to use this warning
25105 option during development. That's because it will warn you when
25106 you need to put in a pragma, but cannot warn you when it is time
25107 to take it out. So the use of pragma @code{Elaborate_All} may lead to
25108 unnecessary dependencies and even false circularities.
25110 This default mode is more restrictive than the Ada Reference
25111 Manual, and it is possible to construct programs which will compile
25112 using the dynamic model described there, but will run into a
25113 circularity using the safer static model we have described.
25115 Of course any Ada compiler must be able to operate in a mode
25116 consistent with the requirements of the Ada Reference Manual,
25117 and in particular must have the capability of implementing the
25118 standard dynamic model of elaboration with run-time checks.
25120 In GNAT, this standard mode can be achieved either by the use of
25121 the @option{-gnatE} switch on the compiler (@command{gcc} or
25122 @command{gnatmake}) command, or by the use of the configuration pragma:
25124 @smallexample @c ada
25125 pragma Elaboration_Checks (DYNAMIC);
25126 @end smallexample
25128 @noindent
25129 Either approach will cause the unit affected to be compiled using the
25130 standard dynamic run-time elaboration checks described in the Ada
25131 Reference Manual. The static model is generally preferable, since it
25132 is clearly safer to rely on compile and link time checks rather than
25133 run-time checks. However, in the case of legacy code, it may be
25134 difficult to meet the requirements of the static model. This
25135 issue is further discussed in
25136 @ref{What to Do If the Default Elaboration Behavior Fails}.
25138 Note that the static model provides a strict subset of the allowed
25139 behavior and programs of the Ada Reference Manual, so if you do
25140 adhere to the static model and no circularities exist,
25141 then you are assured that your program will
25142 work using the dynamic model, providing that you remove any
25143 pragma Elaborate statements from the source.
25145 @node Treatment of Pragma Elaborate
25146 @section Treatment of Pragma Elaborate
25147 @cindex Pragma Elaborate
25149 @noindent
25150 The use of @code{pragma Elaborate}
25151 should generally be avoided in Ada 95 and Ada 2005 programs,
25152 since there is no guarantee that transitive calls
25153 will be properly handled. Indeed at one point, this pragma was placed
25154 in Annex J (Obsolescent Features), on the grounds that it is never useful.
25156 Now that's a bit restrictive. In practice, the case in which
25157 @code{pragma Elaborate} is useful is when the caller knows that there
25158 are no transitive calls, or that the called unit contains all necessary
25159 transitive @code{pragma Elaborate} statements, and legacy code often
25160 contains such uses.
25162 Strictly speaking the static mode in GNAT should ignore such pragmas,
25163 since there is no assurance at compile time that the necessary safety
25164 conditions are met. In practice, this would cause GNAT to be incompatible
25165 with correctly written Ada 83 code that had all necessary
25166 @code{pragma Elaborate} statements in place. Consequently, we made the
25167 decision that GNAT in its default mode will believe that if it encounters
25168 a @code{pragma Elaborate} then the programmer knows what they are doing,
25169 and it will trust that no elaboration errors can occur.
25171 The result of this decision is two-fold. First to be safe using the
25172 static mode, you should remove all @code{pragma Elaborate} statements.
25173 Second, when fixing circularities in existing code, you can selectively
25174 use @code{pragma Elaborate} statements to convince the static mode of
25175 GNAT that it need not generate an implicit @code{pragma Elaborate_All}
25176 statement.
25178 When using the static mode with @option{-gnatwl}, any use of
25179 @code{pragma Elaborate} will generate a warning about possible
25180 problems.
25182 @node Elaboration Issues for Library Tasks
25183 @section Elaboration Issues for Library Tasks
25184 @cindex Library tasks, elaboration issues
25185 @cindex Elaboration of library tasks
25187 @noindent
25188 In this section we examine special elaboration issues that arise for
25189 programs that declare library level tasks.
25191 Generally the model of execution of an Ada program is that all units are
25192 elaborated, and then execution of the program starts. However, the
25193 declaration of library tasks definitely does not fit this model. The
25194 reason for this is that library tasks start as soon as they are declared
25195 (more precisely, as soon as the statement part of the enclosing package
25196 body is reached), that is to say before elaboration
25197 of the program is complete. This means that if such a task calls a
25198 subprogram, or an entry in another task, the callee may or may not be
25199 elaborated yet, and in the standard
25200 Reference Manual model of dynamic elaboration checks, you can even
25201 get timing dependent Program_Error exceptions, since there can be
25202 a race between the elaboration code and the task code.
25204 The static model of elaboration in GNAT seeks to avoid all such
25205 dynamic behavior, by being conservative, and the conservative
25206 approach in this particular case is to assume that all the code
25207 in a task body is potentially executed at elaboration time if
25208 a task is declared at the library level.
25210 This can definitely result in unexpected circularities. Consider
25211 the following example
25213 @smallexample @c ada
25214 package Decls is
25215   task Lib_Task is
25216      entry Start;
25217   end Lib_Task;
25219   type My_Int is new Integer;
25221   function Ident (M : My_Int) return My_Int;
25222 end Decls;
25224 with Utils;
25225 package body Decls is
25226   task body Lib_Task is
25227   begin
25228      accept Start;
25229      Utils.Put_Val (2);
25230   end Lib_Task;
25232   function Ident (M : My_Int) return My_Int is
25233   begin
25234      return M;
25235   end Ident;
25236 end Decls;
25238 with Decls;
25239 package Utils is
25240   procedure Put_Val (Arg : Decls.My_Int);
25241 end Utils;
25243 with Text_IO;
25244 package body Utils is
25245   procedure Put_Val (Arg : Decls.My_Int) is
25246   begin
25247      Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
25248   end Put_Val;
25249 end Utils;
25251 with Decls;
25252 procedure Main is
25253 begin
25254    Decls.Lib_Task.Start;
25255 end;
25256 @end smallexample
25258 @noindent
25259 If the above example is compiled in the default static elaboration
25260 mode, then a circularity occurs. The circularity comes from the call
25261 @code{Utils.Put_Val} in the task body of @code{Decls.Lib_Task}. Since
25262 this call occurs in elaboration code, we need an implicit pragma
25263 @code{Elaborate_All} for @code{Utils}. This means that not only must
25264 the spec and body of @code{Utils} be elaborated before the body
25265 of @code{Decls}, but also the spec and body of any unit that is
25266 @code{with'ed} by the body of @code{Utils} must also be elaborated before
25267 the body of @code{Decls}. This is the transitive implication of
25268 pragma @code{Elaborate_All} and it makes sense, because in general
25269 the body of @code{Put_Val} might have a call to something in a
25270 @code{with'ed} unit.
25272 In this case, the body of Utils (actually its spec) @code{with's}
25273 @code{Decls}. Unfortunately this means that the body of @code{Decls}
25274 must be elaborated before itself, in case there is a call from the
25275 body of @code{Utils}.
25277 Here is the exact chain of events we are worrying about:
25279 @enumerate
25280 @item
25281 In the body of @code{Decls} a call is made from within the body of a library
25282 task to a subprogram in the package @code{Utils}. Since this call may
25283 occur at elaboration time (given that the task is activated at elaboration
25284 time), we have to assume the worst, i.e., that the
25285 call does happen at elaboration time.
25287 @item
25288 This means that the body and spec of @code{Util} must be elaborated before
25289 the body of @code{Decls} so that this call does not cause an access before
25290 elaboration.
25292 @item
25293 Within the body of @code{Util}, specifically within the body of
25294 @code{Util.Put_Val} there may be calls to any unit @code{with}'ed
25295 by this package.
25297 @item
25298 One such @code{with}'ed package is package @code{Decls}, so there
25299 might be a call to a subprogram in @code{Decls} in @code{Put_Val}.
25300 In fact there is such a call in this example, but we would have to
25301 assume that there was such a call even if it were not there, since
25302 we are not supposed to write the body of @code{Decls} knowing what
25303 is in the body of @code{Utils}; certainly in the case of the
25304 static elaboration model, the compiler does not know what is in
25305 other bodies and must assume the worst.
25307 @item
25308 This means that the spec and body of @code{Decls} must also be
25309 elaborated before we elaborate the unit containing the call, but
25310 that unit is @code{Decls}! This means that the body of @code{Decls}
25311 must be elaborated before itself, and that's a circularity.
25312 @end enumerate
25314 @noindent
25315 Indeed, if you add an explicit pragma @code{Elaborate_All} for @code{Utils} in
25316 the body of @code{Decls} you will get a true Ada Reference Manual
25317 circularity that makes the program illegal.
25319 In practice, we have found that problems with the static model of
25320 elaboration in existing code often arise from library tasks, so
25321 we must address this particular situation.
25323 Note that if we compile and run the program above, using the dynamic model of
25324 elaboration (that is to say use the @option{-gnatE} switch),
25325 then it compiles, binds,
25326 links, and runs, printing the expected result of 2. Therefore in some sense
25327 the circularity here is only apparent, and we need to capture
25328 the properties of this program that  distinguish it from other library-level
25329 tasks that have real elaboration problems.
25331 We have four possible answers to this question:
25333 @itemize @bullet
25335 @item
25336 Use the dynamic model of elaboration.
25338 If we use the @option{-gnatE} switch, then as noted above, the program works.
25339 Why is this? If we examine the task body, it is apparent that the task cannot
25340 proceed past the
25341 @code{accept} statement until after elaboration has been completed, because
25342 the corresponding entry call comes from the main program, not earlier.
25343 This is why the dynamic model works here. But that's really giving
25344 up on a precise analysis, and we prefer to take this approach only if we cannot
25345 solve the
25346 problem in any other manner. So let us examine two ways to reorganize
25347 the program to avoid the potential elaboration problem.
25349 @item
25350 Split library tasks into separate packages.
25352 Write separate packages, so that library tasks are isolated from
25353 other declarations as much as possible. Let us look at a variation on
25354 the above program.
25356 @smallexample @c ada
25357 package Decls1 is
25358   task Lib_Task is
25359      entry Start;
25360   end Lib_Task;
25361 end Decls1;
25363 with Utils;
25364 package body Decls1 is
25365   task body Lib_Task is
25366   begin
25367      accept Start;
25368      Utils.Put_Val (2);
25369   end Lib_Task;
25370 end Decls1;
25372 package Decls2 is
25373   type My_Int is new Integer;
25374   function Ident (M : My_Int) return My_Int;
25375 end Decls2;
25377 with Utils;
25378 package body Decls2 is
25379   function Ident (M : My_Int) return My_Int is
25380   begin
25381      return M;
25382   end Ident;
25383 end Decls2;
25385 with Decls2;
25386 package Utils is
25387   procedure Put_Val (Arg : Decls2.My_Int);
25388 end Utils;
25390 with Text_IO;
25391 package body Utils is
25392   procedure Put_Val (Arg : Decls2.My_Int) is
25393   begin
25394      Text_IO.Put_Line (Decls2.My_Int'Image (Decls2.Ident (Arg)));
25395   end Put_Val;
25396 end Utils;
25398 with Decls1;
25399 procedure Main is
25400 begin
25401    Decls1.Lib_Task.Start;
25402 end;
25403 @end smallexample
25405 @noindent
25406 All we have done is to split @code{Decls} into two packages, one
25407 containing the library task, and one containing everything else. Now
25408 there is no cycle, and the program compiles, binds, links and executes
25409 using the default static model of elaboration.
25411 @item
25412 Declare separate task types.
25414 A significant part of the problem arises because of the use of the
25415 single task declaration form. This means that the elaboration of
25416 the task type, and the elaboration of the task itself (i.e.@: the
25417 creation of the task) happen at the same time. A good rule
25418 of style in Ada is to always create explicit task types. By
25419 following the additional step of placing task objects in separate
25420 packages from the task type declaration, many elaboration problems
25421 are avoided. Here is another modified example of the example program:
25423 @smallexample @c ada
25424 package Decls is
25425   task type Lib_Task_Type is
25426      entry Start;
25427   end Lib_Task_Type;
25429   type My_Int is new Integer;
25431   function Ident (M : My_Int) return My_Int;
25432 end Decls;
25434 with Utils;
25435 package body Decls is
25436   task body Lib_Task_Type is
25437   begin
25438      accept Start;
25439      Utils.Put_Val (2);
25440   end Lib_Task_Type;
25442   function Ident (M : My_Int) return My_Int is
25443   begin
25444      return M;
25445   end Ident;
25446 end Decls;
25448 with Decls;
25449 package Utils is
25450   procedure Put_Val (Arg : Decls.My_Int);
25451 end Utils;
25453 with Text_IO;
25454 package body Utils is
25455   procedure Put_Val (Arg : Decls.My_Int) is
25456   begin
25457      Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
25458   end Put_Val;
25459 end Utils;
25461 with Decls;
25462 package Declst is
25463    Lib_Task : Decls.Lib_Task_Type;
25464 end Declst;
25466 with Declst;
25467 procedure Main is
25468 begin
25469    Declst.Lib_Task.Start;
25470 end;
25471 @end smallexample
25473 @noindent
25474 What we have done here is to replace the @code{task} declaration in
25475 package @code{Decls} with a @code{task type} declaration. Then we
25476 introduce a separate package @code{Declst} to contain the actual
25477 task object. This separates the elaboration issues for
25478 the @code{task type}
25479 declaration, which causes no trouble, from the elaboration issues
25480 of the task object, which is also unproblematic, since it is now independent
25481 of the elaboration of  @code{Utils}.
25482 This separation of concerns also corresponds to
25483 a generally sound engineering principle of separating declarations
25484 from instances. This version of the program also compiles, binds, links,
25485 and executes, generating the expected output.
25487 @item
25488 Use No_Entry_Calls_In_Elaboration_Code restriction.
25489 @cindex No_Entry_Calls_In_Elaboration_Code
25491 The previous two approaches described how a program can be restructured
25492 to avoid the special problems caused by library task bodies. in practice,
25493 however, such restructuring may be difficult to apply to existing legacy code,
25494 so we must consider solutions that do not require massive rewriting.
25496 Let us consider more carefully why our original sample program works
25497 under the dynamic model of elaboration. The reason is that the code
25498 in the task body blocks immediately on the @code{accept}
25499 statement. Now of course there is nothing to prohibit elaboration
25500 code from making entry calls (for example from another library level task),
25501 so we cannot tell in isolation that
25502 the task will not execute the accept statement  during elaboration.
25504 However, in practice it is very unusual to see elaboration code
25505 make any entry calls, and the pattern of tasks starting
25506 at elaboration time and then immediately blocking on @code{accept} or
25507 @code{select} statements is very common. What this means is that
25508 the compiler is being too pessimistic when it analyzes the
25509 whole package body as though it might be executed at elaboration
25510 time.
25512 If we know that the elaboration code contains no entry calls, (a very safe
25513 assumption most of the time, that could almost be made the default
25514 behavior), then we can compile all units of the program under control
25515 of the following configuration pragma:
25517 @smallexample
25518 pragma Restrictions (No_Entry_Calls_In_Elaboration_Code);
25519 @end smallexample
25521 @noindent
25522 This pragma can be placed in the @file{gnat.adc} file in the usual
25523 manner. If we take our original unmodified program and compile it
25524 in the presence of a @file{gnat.adc} containing the above pragma,
25525 then once again, we can compile, bind, link, and execute, obtaining
25526 the expected result. In the presence of this pragma, the compiler does
25527 not trace calls in a task body, that appear after the first @code{accept}
25528 or @code{select} statement, and therefore does not report a potential
25529 circularity in the original program.
25531 The compiler will check to the extent it can that the above
25532 restriction is not violated, but it is not always possible to do a
25533 complete check at compile time, so it is important to use this
25534 pragma only if the stated restriction is in fact met, that is to say
25535 no task receives an entry call before elaboration of all units is completed.
25537 @end itemize
25539 @node Mixing Elaboration Models
25540 @section Mixing Elaboration Models
25541 @noindent
25542 So far, we have assumed that the entire program is either compiled
25543 using the dynamic model or static model, ensuring consistency. It
25544 is possible to mix the two models, but rules have to be followed
25545 if this mixing is done to ensure that elaboration checks are not
25546 omitted.
25548 The basic rule is that @emph{a unit compiled with the static model cannot
25549 be @code{with'ed} by a unit compiled with the dynamic model}. The
25550 reason for this is that in the static model, a unit assumes that
25551 its clients guarantee to use (the equivalent of) pragma
25552 @code{Elaborate_All} so that no elaboration checks are required
25553 in inner subprograms, and this assumption is violated if the
25554 client is compiled with dynamic checks.
25556 The precise rule is as follows. A unit that is compiled with dynamic
25557 checks can only @code{with} a unit that meets at least one of the
25558 following criteria:
25560 @itemize @bullet
25562 @item
25563 The @code{with'ed} unit is itself compiled with dynamic elaboration
25564 checks (that is with the @option{-gnatE} switch.
25566 @item
25567 The @code{with'ed} unit is an internal GNAT implementation unit from
25568 the System, Interfaces, Ada, or GNAT hierarchies.
25570 @item
25571 The @code{with'ed} unit has pragma Preelaborate or pragma Pure.
25573 @item
25574 The @code{with'ing} unit (that is the client) has an explicit pragma
25575 @code{Elaborate_All} for the @code{with'ed} unit.
25577 @end itemize
25579 @noindent
25580 If this rule is violated, that is if a unit with dynamic elaboration
25581 checks @code{with's} a unit that does not meet one of the above four
25582 criteria, then the binder (@code{gnatbind}) will issue a warning
25583 similar to that in the following example:
25585 @smallexample
25586 warning: "x.ads" has dynamic elaboration checks and with's
25587 warning:   "y.ads" which has static elaboration checks
25588 @end smallexample
25590 @noindent
25591 These warnings indicate that the rule has been violated, and that as a result
25592 elaboration checks may be missed in the resulting executable file.
25593 This warning may be suppressed using the @option{-ws} binder switch
25594 in the usual manner.
25596 One useful application of this mixing rule is in the case of a subsystem
25597 which does not itself @code{with} units from the remainder of the
25598 application. In this case, the entire subsystem can be compiled with
25599 dynamic checks to resolve a circularity in the subsystem, while
25600 allowing the main application that uses this subsystem to be compiled
25601 using the more reliable default static model.
25603 @node What to Do If the Default Elaboration Behavior Fails
25604 @section What to Do If the Default Elaboration Behavior Fails
25606 @noindent
25607 If the binder cannot find an acceptable order, it outputs detailed
25608 diagnostics. For example:
25609 @smallexample
25610 @group
25611 @iftex
25612 @leftskip=0cm
25613 @end iftex
25614 error: elaboration circularity detected
25615 info:   "proc (body)" must be elaborated before "pack (body)"
25616 info:     reason: Elaborate_All probably needed in unit "pack (body)"
25617 info:     recompile "pack (body)" with -gnatwl
25618 info:                             for full details
25619 info:       "proc (body)"
25620 info:         is needed by its spec:
25621 info:       "proc (spec)"
25622 info:         which is withed by:
25623 info:       "pack (body)"
25624 info:  "pack (body)" must be elaborated before "proc (body)"
25625 info:     reason: pragma Elaborate in unit "proc (body)"
25626 @end group
25628 @end smallexample
25630 @noindent
25631 In this case we have a cycle that the binder cannot break. On the one
25632 hand, there is an explicit pragma Elaborate in @code{proc} for
25633 @code{pack}. This means that the body of @code{pack} must be elaborated
25634 before the body of @code{proc}. On the other hand, there is elaboration
25635 code in @code{pack} that calls a subprogram in @code{proc}. This means
25636 that for maximum safety, there should really be a pragma
25637 Elaborate_All in @code{pack} for @code{proc} which would require that
25638 the body of @code{proc} be elaborated before the body of
25639 @code{pack}. Clearly both requirements cannot be satisfied.
25640 Faced with a circularity of this kind, you have three different options.
25642 @table @asis
25643 @item Fix the program
25644 The most desirable option from the point of view of long-term maintenance
25645 is to rearrange the program so that the elaboration problems are avoided.
25646 One useful technique is to place the elaboration code into separate
25647 child packages. Another is to move some of the initialization code to
25648 explicitly called subprograms, where the program controls the order
25649 of initialization explicitly. Although this is the most desirable option,
25650 it may be impractical and involve too much modification, especially in
25651 the case of complex legacy code.
25653 @item Perform dynamic checks
25654 If the compilations are done using the
25655 @option{-gnatE}
25656 (dynamic elaboration check) switch, then GNAT behaves in a quite different
25657 manner. Dynamic checks are generated for all calls that could possibly result
25658 in raising an exception. With this switch, the compiler does not generate
25659 implicit @code{Elaborate} or @code{Elaborate_All} pragmas. The behavior then is
25660 exactly as specified in the @cite{Ada Reference Manual}.
25661 The binder will generate
25662 an executable program that may or may not raise @code{Program_Error}, and then
25663 it is the programmer's job to ensure that it does not raise an exception. Note
25664 that it is important to compile all units with the switch, it cannot be used
25665 selectively.
25667 @item Suppress checks
25668 The drawback of dynamic checks is that they generate a
25669 significant overhead at run time, both in space and time. If you
25670 are absolutely sure that your program cannot raise any elaboration
25671 exceptions, and you still want to use the dynamic elaboration model,
25672 then you can use the configuration pragma
25673 @code{Suppress (Elaboration_Check)} to suppress all such checks. For
25674 example this pragma could be placed in the @file{gnat.adc} file.
25676 @item Suppress checks selectively
25677 When you know that certain calls or instantiations in elaboration code cannot
25678 possibly lead to an elaboration error, and the binder nevertheless complains
25679 about implicit @code{Elaborate} and @code{Elaborate_All} pragmas that lead to
25680 elaboration circularities, it is possible to remove those warnings locally and
25681 obtain a program that will bind. Clearly this can be unsafe, and it is the
25682 responsibility of the programmer to make sure that the resulting program has no
25683 elaboration anomalies. The pragma @code{Suppress (Elaboration_Check)} can be
25684 used with different granularity to suppress warnings and break elaboration
25685 circularities:
25687 @itemize @bullet
25688 @item
25689 Place the pragma that names the called subprogram in the declarative part
25690 that contains the call.
25692 @item
25693 Place the pragma in the declarative part, without naming an entity. This
25694 disables warnings on all calls in the corresponding  declarative region.
25696 @item
25697 Place the pragma in the package spec that declares the called subprogram,
25698 and name the subprogram. This disables warnings on all elaboration calls to
25699 that subprogram.
25701 @item
25702 Place the pragma in the package spec that declares the called subprogram,
25703 without naming any entity. This disables warnings on all elaboration calls to
25704 all subprograms declared in this spec.
25706 @item Use Pragma Elaborate
25707 As previously described in section @xref{Treatment of Pragma Elaborate},
25708 GNAT in static mode assumes that a @code{pragma} Elaborate indicates correctly
25709 that no elaboration checks are required on calls to the designated unit.
25710 There may be cases in which the caller knows that no transitive calls
25711 can occur, so that a @code{pragma Elaborate} will be sufficient in a
25712 case where @code{pragma Elaborate_All} would cause a circularity.
25713 @end itemize
25715 @noindent
25716 These five cases are listed in order of decreasing safety, and therefore
25717 require increasing programmer care in their application. Consider the
25718 following program:
25720 @smallexample @c adanocomment
25721 package Pack1 is
25722   function F1 return Integer;
25723   X1 : Integer;
25724 end Pack1;
25726 package Pack2 is
25727   function F2 return Integer;
25728   function Pure (x : integer) return integer;
25729   --  pragma Suppress (Elaboration_Check, On => Pure);  -- (3)
25730   --  pragma Suppress (Elaboration_Check);              -- (4)
25731 end Pack2;
25733 with Pack2;
25734 package body Pack1 is
25735   function F1 return Integer is
25736   begin
25737     return 100;
25738   end F1;
25739   Val : integer := Pack2.Pure (11);    --  Elab. call (1)
25740 begin
25741   declare
25742     --  pragma Suppress(Elaboration_Check, Pack2.F2);   -- (1)
25743     --  pragma Suppress(Elaboration_Check);             -- (2)
25744   begin
25745     X1 := Pack2.F2 + 1;                --  Elab. call (2)
25746   end;
25747 end Pack1;
25749 with Pack1;
25750 package body Pack2 is
25751   function F2 return Integer is
25752   begin
25753      return Pack1.F1;
25754   end F2;
25755   function Pure (x : integer) return integer is
25756   begin
25757      return x ** 3 - 3 * x;
25758   end;
25759 end Pack2;
25761 with Pack1, Ada.Text_IO;
25762 procedure Proc3 is
25763 begin
25764   Ada.Text_IO.Put_Line(Pack1.X1'Img); -- 101
25765 end Proc3;
25766 @end smallexample
25767 In the absence of any pragmas, an attempt to bind this program produces
25768 the following diagnostics:
25769 @smallexample
25770 @group
25771 @iftex
25772 @leftskip=.5cm
25773 @end iftex
25774 error: elaboration circularity detected
25775 info:    "pack1 (body)" must be elaborated before "pack1 (body)"
25776 info:       reason: Elaborate_All probably needed in unit "pack1 (body)"
25777 info:       recompile "pack1 (body)" with -gnatwl for full details
25778 info:          "pack1 (body)"
25779 info:             must be elaborated along with its spec:
25780 info:          "pack1 (spec)"
25781 info:             which is withed by:
25782 info:          "pack2 (body)"
25783 info:             which must be elaborated along with its spec:
25784 info:          "pack2 (spec)"
25785 info:             which is withed by:
25786 info:          "pack1 (body)"
25787 @end group
25788 @end smallexample
25789 The sources of the circularity are the two calls to @code{Pack2.Pure} and
25790 @code{Pack2.F2} in the body of @code{Pack1}. We can see that the call to
25791 F2 is safe, even though F2 calls F1, because the call appears after the
25792 elaboration of the body of F1. Therefore the pragma (1) is safe, and will
25793 remove the warning on the call. It is also possible to use pragma (2)
25794 because there are no other potentially unsafe calls in the block.
25796 @noindent
25797 The call to @code{Pure} is safe because this function does not depend on the
25798 state of @code{Pack2}. Therefore any call to this function is safe, and it
25799 is correct to place pragma (3) in the corresponding package spec.
25801 @noindent
25802 Finally, we could place pragma (4) in the spec of @code{Pack2} to disable
25803 warnings on all calls to functions declared therein. Note that this is not
25804 necessarily safe, and requires more detailed examination of the subprogram
25805 bodies involved. In particular, a call to @code{F2} requires that @code{F1}
25806 be already elaborated.
25807 @end table
25809 @noindent
25810 It is hard to generalize on which of these four approaches should be
25811 taken. Obviously if it is possible to fix the program so that the default
25812 treatment works, this is preferable, but this may not always be practical.
25813 It is certainly simple enough to use
25814 @option{-gnatE}
25815 but the danger in this case is that, even if the GNAT binder
25816 finds a correct elaboration order, it may not always do so,
25817 and certainly a binder from another Ada compiler might not. A
25818 combination of testing and analysis (for which the warnings generated
25819 with the
25820 @option{-gnatwl}
25821 switch can be useful) must be used to ensure that the program is free
25822 of errors. One switch that is useful in this testing is the
25823 @option{^-p (pessimistic elaboration order)^/PESSIMISTIC_ELABORATION_ORDER^}
25824 switch for
25825 @code{gnatbind}.
25826 Normally the binder tries to find an order that has the best chance
25827 of avoiding elaboration problems. However, if this switch is used, the binder
25828 plays a devil's advocate role, and tries to choose the order that
25829 has the best chance of failing. If your program works even with this
25830 switch, then it has a better chance of being error free, but this is still
25831 not a guarantee.
25833 For an example of this approach in action, consider the C-tests (executable
25834 tests) from the ACVC suite. If these are compiled and run with the default
25835 treatment, then all but one of them succeed without generating any error
25836 diagnostics from the binder. However, there is one test that fails, and
25837 this is not surprising, because the whole point of this test is to ensure
25838 that the compiler can handle cases where it is impossible to determine
25839 a correct order statically, and it checks that an exception is indeed
25840 raised at run time.
25842 This one test must be compiled and run using the
25843 @option{-gnatE}
25844 switch, and then it passes. Alternatively, the entire suite can
25845 be run using this switch. It is never wrong to run with the dynamic
25846 elaboration switch if your code is correct, and we assume that the
25847 C-tests are indeed correct (it is less efficient, but efficiency is
25848 not a factor in running the ACVC tests.)
25850 @node Elaboration for Dispatching Calls
25851 @section Elaboration for Dispatching Calls
25852 @cindex Dispatching calls
25854 @noindent
25855 In rare cases, the static elaboration model fails to prevent
25856 dispatching calls to not-yet-elaborated subprograms. In such cases, we
25857 fall back to run-time checks; premature calls to any primitive
25858 operation of a tagged type before the body of the operation has been
25859 elaborated will raise @code{Program_Error}.
25861 Access-to-subprogram types, however, are handled conservatively, and
25862 do not require run-time checks. This was not true in earlier versions
25863 of the compiler; you can use the @option{-gnatd.U} debug switch to
25864 revert to the old behavior if the new conservative behavior causes
25865 elaboration cycles.
25867 @node Summary of Procedures for Elaboration Control
25868 @section Summary of Procedures for Elaboration Control
25869 @cindex Elaboration control
25871 @noindent
25872 First, compile your program with the default options, using none of
25873 the special elaboration control switches. If the binder successfully
25874 binds your program, then you can be confident that, apart from issues
25875 raised by the use of access-to-subprogram types and dynamic dispatching,
25876 the program is free of elaboration errors. If it is important that the
25877 program be portable, then use the
25878 @option{-gnatwl}
25879 switch to generate warnings about missing @code{Elaborate} or
25880 @code{Elaborate_All} pragmas, and supply the missing pragmas.
25882 If the program fails to bind using the default static elaboration
25883 handling, then you can fix the program to eliminate the binder
25884 message, or recompile the entire program with the
25885 @option{-gnatE} switch to generate dynamic elaboration checks,
25886 and, if you are sure there really are no elaboration problems,
25887 use a global pragma @code{Suppress (Elaboration_Check)}.
25889 @node Other Elaboration Order Considerations
25890 @section Other Elaboration Order Considerations
25891 @noindent
25892 This section has been entirely concerned with the issue of finding a valid
25893 elaboration order, as defined by the Ada Reference Manual. In a case
25894 where several elaboration orders are valid, the task is to find one
25895 of the possible valid elaboration orders (and the static model in GNAT
25896 will ensure that this is achieved).
25898 The purpose of the elaboration rules in the Ada Reference Manual is to
25899 make sure that no entity is accessed before it has been elaborated. For
25900 a subprogram, this means that the spec and body must have been elaborated
25901 before the subprogram is called. For an object, this means that the object
25902 must have been elaborated before its value is read or written. A violation
25903 of either of these two requirements is an access before elaboration order,
25904 and this section has been all about avoiding such errors.
25906 In the case where more than one order of elaboration is possible, in the
25907 sense that access before elaboration errors are avoided, then any one of
25908 the orders is ``correct'' in the sense that it meets the requirements of
25909 the Ada Reference Manual, and no such error occurs.
25911 However, it may be the case for a given program, that there are
25912 constraints on the order of elaboration that come not from consideration
25913 of avoiding elaboration errors, but rather from extra-lingual logic
25914 requirements. Consider this example:
25916 @smallexample @c ada
25917 with Init_Constants;
25918 package Constants is
25919    X : Integer := 0;
25920    Y : Integer := 0;
25921 end Constants;
25923 package Init_Constants is
25924    procedure P; -- require a body
25925 end Init_Constants;
25927 with Constants;
25928 package body Init_Constants is
25929    procedure P is begin null; end;
25930 begin
25931    Constants.X := 3;
25932    Constants.Y := 4;
25933 end Init_Constants;
25935 with Constants;
25936 package Calc is
25937    Z : Integer := Constants.X + Constants.Y;
25938 end Calc;
25940 with Calc;
25941 with Text_IO; use Text_IO;
25942 procedure Main is
25943 begin
25944    Put_Line (Calc.Z'Img);
25945 end Main;
25946 @end smallexample
25948 @noindent
25949 In this example, there is more than one valid order of elaboration. For
25950 example both the following are correct orders:
25952 @smallexample
25953 Init_Constants spec
25954 Constants spec
25955 Calc spec
25956 Init_Constants body
25957 Main body
25959   and
25961 Init_Constants spec
25962 Init_Constants body
25963 Constants spec
25964 Calc spec
25965 Main body
25966 @end smallexample
25968 @noindent
25969 There is no language rule to prefer one or the other, both are correct
25970 from an order of elaboration point of view. But the programmatic effects
25971 of the two orders are very different. In the first, the elaboration routine
25972 of @code{Calc} initializes @code{Z} to zero, and then the main program
25973 runs with this value of zero. But in the second order, the elaboration
25974 routine of @code{Calc} runs after the body of Init_Constants has set
25975 @code{X} and @code{Y} and thus @code{Z} is set to 7 before @code{Main}
25976 runs.
25978 One could perhaps by applying pretty clever non-artificial intelligence
25979 to the situation guess that it is more likely that the second order of
25980 elaboration is the one desired, but there is no formal linguistic reason
25981 to prefer one over the other. In fact in this particular case, GNAT will
25982 prefer the second order, because of the rule that bodies are elaborated
25983 as soon as possible, but it's just luck that this is what was wanted
25984 (if indeed the second order was preferred).
25986 If the program cares about the order of elaboration routines in a case like
25987 this, it is important to specify the order required. In this particular
25988 case, that could have been achieved by adding to the spec of Calc:
25990 @smallexample @c ada
25991 pragma Elaborate_All (Constants);
25992 @end smallexample
25994 @noindent
25995 which requires that the body (if any) and spec of @code{Constants},
25996 as well as the body and spec of any unit @code{with}'ed by
25997 @code{Constants} be elaborated before @code{Calc} is elaborated.
25999 Clearly no automatic method can always guess which alternative you require,
26000 and if you are working with legacy code that had constraints of this kind
26001 which were not properly specified by adding @code{Elaborate} or
26002 @code{Elaborate_All} pragmas, then indeed it is possible that two different
26003 compilers can choose different orders.
26005 However, GNAT does attempt to diagnose the common situation where there
26006 are uninitialized variables in the visible part of a package spec, and the
26007 corresponding package body has an elaboration block that directly or
26008 indirectly initialized one or more of these variables. This is the situation
26009 in which a pragma Elaborate_Body is usually desirable, and GNAT will generate
26010 a warning that suggests this addition if it detects this situation.
26012 The @code{gnatbind}
26013 @option{^-p^/PESSIMISTIC_ELABORATION^} switch may be useful in smoking
26014 out problems. This switch causes bodies to be elaborated as late as possible
26015 instead of as early as possible. In the example above, it would have forced
26016 the choice of the first elaboration order. If you get different results
26017 when using this switch, and particularly if one set of results is right,
26018 and one is wrong as far as you are concerned, it shows that you have some
26019 missing @code{Elaborate} pragmas. For the example above, we have the
26020 following output:
26022 @smallexample
26023 gnatmake -f -q main
26024 main
26026 gnatmake -f -q main -bargs -p
26027 main
26029 @end smallexample
26031 @noindent
26032 It is of course quite unlikely that both these results are correct, so
26033 it is up to you in a case like this to investigate the source of the
26034 difference, by looking at the two elaboration orders that are chosen,
26035 and figuring out which is correct, and then adding the necessary
26036 @code{Elaborate} or @code{Elaborate_All} pragmas to ensure the desired order.
26039 @c **********************************
26040 @node Overflow Check Handling in GNAT
26041 @appendix Overflow Check Handling in GNAT
26042 @cindex Overflow checks
26043 @cindex Checks (overflow)
26044 @c **********************************
26046 @menu
26047 * Background::
26048 * Overflow Checking Modes in GNAT::
26049 * Specifying the Desired Mode::
26050 * Default Settings::
26051 * Implementation Notes::
26052 @end menu
26055 @node Background
26056 @section Background
26058 @noindent
26059 Overflow checks are checks that the compiler may make to ensure
26060 that intermediate results are not out of range. For example:
26062 @smallexample @c ada
26063    A : Integer;
26064    ...
26065    A := A + 1;
26066 @end smallexample
26068 @noindent
26069 if @code{A} has the value @code{Integer'Last}, then the addition may cause
26070 overflow since the result is out of range of the type @code{Integer}.
26071 In this case @code{Constraint_Error} will be raised if checks are
26072 enabled.
26074 A trickier situation arises in examples like the following:
26076 @smallexample @c ada
26077   A, C : Integer;
26078   ...
26079   A := (A + 1) + C;
26080 @end smallexample
26082 @noindent
26083 where @code{A} is @code{Integer'Last} and @code{C} is @code{-1}.
26084 Now the final result of the expression on the right hand side is
26085 @code{Integer'Last} which is in range, but the question arises whether the
26086 intermediate addition of @code{(A + 1)} raises an overflow error.
26088 The (perhaps surprising) answer is that the Ada language
26089 definition does not answer this question. Instead it leaves
26090 it up to the implementation to do one of two things if overflow
26091 checks are enabled.
26093 @itemize @bullet
26094 @item
26095 raise an exception (@code{Constraint_Error}), or
26097 @item
26098 yield the correct mathematical result which is then used in
26099 subsequent operations.
26100 @end itemize
26102 @noindent
26103 If the compiler chooses the first approach, then the assignment of this
26104 example will indeed raise @code{Constraint_Error} if overflow checking is
26105 enabled, or result in erroneous execution if overflow checks are suppressed.
26107 But if the compiler
26108 chooses the second approach, then it can perform both additions yielding
26109 the correct mathematical result, which is in range, so no exception
26110 will be raised, and the right result is obtained, regardless of whether
26111 overflow checks are suppressed.
26113 Note that in the first example an
26114 exception will be raised in either case, since if the compiler
26115 gives the correct mathematical result for the addition, it will
26116 be out of range of the target type of the assignment, and thus
26117 fails the range check.
26119 This lack of specified behavior in the handling of overflow for
26120 intermediate results is a source of non-portability, and can thus
26121 be problematic when programs are ported. Most typically this arises
26122 in a situation where the original compiler did not raise an exception,
26123 and then the application is moved to a compiler where the check is
26124 performed on the intermediate result and an unexpected exception is
26125 raised.
26127 Furthermore, when using Ada 2012's preconditions and other
26128 assertion forms, another issue arises. Consider:
26130 @smallexample @c ada
26131      procedure P (A, B : Integer) with
26132        Pre => A + B <= Integer'Last;
26133 @end smallexample
26135 @noindent
26136 One often wants to regard arithmetic in a context like this from
26137 a mathematical point of view. So for example, if the two actual parameters
26138 for a call to @code{P} are both @code{Integer'Last}, then
26139 the precondition should be regarded as False. If we are executing
26140 in a mode with run-time checks enabled for preconditions, then we would
26141 like this precondition to fail, rather than raising an exception
26142 because of the intermediate overflow.
26144 However, the language definition leaves the specification of
26145 whether the above condition fails (raising @code{Assert_Error}) or
26146 causes an intermediate overflow (raising @code{Constraint_Error})
26147 up to the implementation.
26149 The situation is worse in a case such as the following:
26151 @smallexample @c ada
26152      procedure Q (A, B, C : Integer) with
26153        Pre => A + B + C <= Integer'Last;
26154 @end smallexample
26156 @noindent
26157 Consider the call
26159 @smallexample @c ada
26160      Q (A => Integer'Last, B => 1, C => -1);
26161 @end smallexample
26163 @noindent
26164 From a mathematical point of view the precondition
26165 is True, but at run time we may (but are not guaranteed to) get an
26166 exception raised because of the intermediate overflow (and we really
26167 would prefer this precondition to be considered True at run time).
26169 @node Overflow Checking Modes in GNAT
26170 @section Overflow Checking Modes in GNAT
26172 @noindent
26173 To deal with the portability issue, and with the problem of
26174 mathematical versus run-time interpretation of the expressions in
26175 assertions, GNAT provides comprehensive control over the handling
26176 of intermediate overflow. GNAT can operate in three modes, and
26177 furthemore, permits separate selection of operating modes for
26178 the expressions within assertions (here the term ``assertions''
26179 is used in the technical sense, which includes preconditions and so forth)
26180 and for expressions appearing outside assertions.
26182 The three modes are:
26184 @itemize @bullet
26185 @item   @i{Use base type for intermediate operations} (@code{STRICT})
26187      In this mode, all intermediate results for predefined arithmetic
26188      operators are computed using the base type, and the result must
26189      be in range of the base type. If this is not the
26190      case then either an exception is raised (if overflow checks are
26191      enabled) or the execution is erroneous (if overflow checks are suppressed).
26192      This is the normal default mode.
26194 @item   @i{Most intermediate overflows avoided} (@code{MINIMIZED})
26196      In this mode, the compiler attempts to avoid intermediate overflows by
26197      using a larger integer type, typically @code{Long_Long_Integer},
26198      as the type in which arithmetic is
26199      performed for predefined arithmetic operators. This may be slightly more
26200      expensive at
26201      run time (compared to suppressing intermediate overflow checks), though
26202      the cost is negligible on modern 64-bit machines. For the examples given
26203      earlier, no intermediate overflows would have resulted in exceptions,
26204      since the intermediate results are all in the range of
26205      @code{Long_Long_Integer} (typically 64-bits on nearly all implementations
26206      of GNAT). In addition, if checks are enabled, this reduces the number of
26207      checks that must be made, so this choice may actually result in an
26208      improvement in space and time behavior.
26210      However, there are cases where @code{Long_Long_Integer} is not large
26211      enough, consider the following example:
26213 @smallexample @c ada
26214        procedure R (A, B, C, D : Integer) with
26215          Pre => (A**2 * B**2) / (C**2 * D**2) <= 10;
26216 @end smallexample
26218      where @code{A} = @code{B} = @code{C} = @code{D} = @code{Integer'Last}.
26219      Now the intermediate results are
26220      out of the range of @code{Long_Long_Integer} even though the final result
26221      is in range and the precondition is True (from a mathematical point
26222      of view). In such a case, operating in this mode, an overflow occurs
26223      for the intermediate computation (which is why this mode
26224      says @i{most} intermediate overflows are avoided). In this case,
26225      an exception is raised if overflow checks are enabled, and the
26226      execution is erroneous if overflow checks are suppressed.
26228 @item   @i{All intermediate overflows avoided} (@code{ELIMINATED})
26230      In this mode, the compiler  avoids all intermediate overflows
26231      by using arbitrary precision arithmetic as required. In this
26232      mode, the above example with @code{A**2 * B**2} would
26233      not cause intermediate overflow, because the intermediate result
26234      would be evaluated using sufficient precision, and the result
26235      of evaluating the precondition would be True.
26237      This mode has the advantage of avoiding any intermediate
26238      overflows, but at the expense of significant run-time overhead,
26239      including the use of a library (included automatically in this
26240      mode) for multiple-precision arithmetic.
26242      This mode provides cleaner semantics for assertions, since now
26243      the run-time behavior emulates true arithmetic behavior for the
26244      predefined arithmetic operators, meaning that there is never a
26245      conflict between the mathematical view of the assertion, and its
26246      run-time behavior.
26248      Note that in this mode, the behavior is unaffected by whether or
26249      not overflow checks are suppressed, since overflow does not occur.
26250      It is possible for gigantic intermediate expressions to raise
26251      @code{Storage_Error} as a result of attempting to compute the
26252      results of such expressions (e.g. @code{Integer'Last ** Integer'Last})
26253      but overflow is impossible.
26256 @end itemize
26258 @noindent
26259   Note that these modes apply only to the evaluation of predefined
26260   arithmetic, membership, and comparison operators for signed integer
26261   aritmetic.
26263   For fixed-point arithmetic, checks can be suppressed. But if checks
26264   are enabled
26265   then fixed-point values are always checked for overflow against the
26266   base type for intermediate expressions (that is such checks always
26267   operate in the equivalent of @code{STRICT} mode).
26269   For floating-point, on nearly all architectures, @code{Machine_Overflows}
26270   is False, and IEEE infinities are generated, so overflow exceptions
26271   are never raised. If you want to avoid infinities, and check that
26272   final results of expressions are in range, then you can declare a
26273   constrained floating-point type, and range checks will be carried
26274   out in the normal manner (with infinite values always failing all
26275   range checks).
26278 @c -------------------------
26279 @node Specifying the Desired Mode
26280 @section Specifying the Desired Mode
26282 @noindent
26283 The desired mode of for handling intermediate overflow can be specified using
26284 either the @code{Overflow_Mode} pragma or an equivalent compiler switch.
26285 The pragma has the form
26286 @cindex pragma @code{Overflow_Mode}
26288 @smallexample @c ada
26289     pragma Overflow_Mode ([General =>] MODE [, [Assertions =>] MODE]);
26290 @end smallexample
26292 @noindent
26293 where @code{MODE} is one of
26295 @itemize @bullet
26296 @item   @code{STRICT}:  intermediate overflows checked (using base type)
26297 @item   @code{MINIMIZED}: minimize intermediate overflows
26298 @item   @code{ELIMINATED}: eliminate intermediate overflows
26299 @end itemize
26301 @noindent
26302 The case is ignored, so @code{MINIMIZED}, @code{Minimized} and
26303 @code{minimized} all have the same effect.
26305 If only the @code{General} parameter is present, then the given @code{MODE}
26306 applies
26307 to expressions both within and outside assertions. If both arguments
26308 are present, then @code{General} applies to expressions outside assertions,
26309 and @code{Assertions} applies to expressions within assertions. For example:
26311 @smallexample @c ada
26312    pragma Overflow_Mode
26313      (General => Minimized, Assertions => Eliminated);
26314 @end smallexample
26316 @noindent
26317 specifies that general expressions outside assertions be evaluated
26318 in ``minimize intermediate overflows'' mode, and expressions within
26319 assertions be evaluated in ``eliminate intermediate overflows'' mode.
26320 This is often a reasonable choice, avoiding excessive overhead
26321 outside assertions, but assuring a high degree of portability
26322 when importing code from another compiler, while incurring
26323 the extra overhead for assertion expressions to ensure that
26324 the behavior at run time matches the expected mathematical
26325 behavior.
26327 The @code{Overflow_Mode} pragma has the same scoping and placement
26328 rules as pragma @code{Suppress}, so it can occur either as a
26329 configuration pragma, specifying a default for the whole
26330 program, or in a declarative scope, where it applies to the
26331 remaining declarations and statements in that scope.
26333 Note that pragma @code{Overflow_Mode} does not affect whether
26334 overflow checks are enabled or suppressed. It only controls the
26335 method used to compute intermediate values. To control whether
26336 overflow checking is enabled or suppressed, use pragma @code{Suppress}
26337 or @code{Unsuppress} in the usual manner
26339 Additionally, a compiler switch @option{-gnato?} or @option{-gnato??}
26340 can be used to control the checking mode default (which can be subsequently
26341 overridden using pragmas).
26342 @cindex @option{-gnato?} (gcc)
26343 @cindex @option{-gnato??} (gcc)
26345 Here `@code{?}' is one of the digits `@code{1}' through `@code{3}':
26347 @itemize @bullet
26348 @item   @code{1}:
26349 use base type for intermediate operations (@code{STRICT})
26350 @item   @code{2}:
26351 minimize intermediate overflows (@code{MINIMIZED})
26352 @item   @code{3}:
26353 eliminate intermediate overflows (@code{ELIMINATED})
26354 @end itemize
26356 @noindent
26357 As with the pragma, if only one digit appears then it applies to all
26358 cases; if two digits are given, then the first applies outside
26359 assertions, and the second within assertions. Thus the equivalent
26360 of the example pragma above would be
26361 @option{^-gnato23^/OVERFLOW_CHECKS=23^}.
26363 If no digits follow the @option{-gnato}, then it is equivalent to
26364 @option{^-gnato11^/OVERFLOW_CHECKS=11^},
26365 causing all intermediate operations to be computed using the base
26366 type (@code{STRICT} mode).
26368 In addition to setting the mode used for computation of intermediate
26369 results, the @code{-gnato} switch also enables overflow checking (which
26370 is suppressed by default). It thus combines the effect of using
26371 a pragma @code{Overflow_Mode} and pragma @code{Unsuppress}.
26374 @c -------------------------
26375 @node Default Settings
26376 @section Default Settings
26378 The default mode for overflow checks is
26380 @smallexample
26381    General => Strict
26382 @end smallexample
26384 @noindent
26385 which causes all computations both inside and outside assertions to use
26386 the base type. In addition overflow checks are suppressed.
26388 This retains compatibility with previous versions of
26389 GNAT which suppressed overflow checks by default and always
26390 used the base type for computation of intermediate results.
26392 The switch @option{-gnato} (with no digits following) is equivalent to
26393 @cindex @option{-gnato} (gcc)
26395 @smallexample
26396    General => Strict
26397 @end smallexample
26399 @noindent
26400 which causes overflow checking of all intermediate overflows
26401 both inside and outside assertions against the base type.
26402 This provides compatibility
26403 with this switch as implemented in previous versions of GNAT.
26405 The pragma @code{Suppress (Overflow_Check)} disables overflow
26406 checking, but it has no effect on the method used for computing
26407 intermediate results.
26409 The pragma @code{Unsuppress (Overflow_Check)} enables overflow
26410 checking, but it has no effect on the method used for computing
26411 intermediate results.
26413 @c -------------------------
26414 @node Implementation Notes
26415 @section Implementation Notes
26417 In practice on typical 64-bit machines, the @code{MINIMIZED} mode is
26418 reasonably efficient, and can be generally used. It also helps
26419 to ensure compatibility with code imported from some other
26420 compiler to GNAT.
26422 Setting all intermediate overflows checking (@code{CHECKED} mode)
26423 makes sense if you want to
26424 make sure that your code is compatible with any other possible
26425 Ada implementation. This may be useful in ensuring portability
26426 for code that is to be exported to some other compiler than GNAT.
26429 The Ada standard allows the reassociation of expressions at
26430 the same precedence level if no parentheses are present. For
26431 example, @w{@code{A+B+C}} parses as though it were @w{@code{(A+B)+C}}, but
26432 the compiler can reintepret this as @w{@code{A+(B+C)}}, possibly
26433 introducing or eliminating an overflow exception. The GNAT
26434 compiler never takes advantage of this freedom, and the
26435 expression @w{@code{A+B+C}} will be evaluated as @w{@code{(A+B)+C}}.
26436 If you need the other order, you can write the parentheses
26437 explicitly @w{@code{A+(B+C)}} and GNAT will respect this order.
26439 The use of @code{ELIMINATED} mode will cause the compiler to
26440 automatically include an appropriate arbitrary precision
26441 integer arithmetic package. The compiler will make calls
26442 to this package, though only in cases where it cannot be
26443 sure that @code{Long_Long_Integer} is sufficient to guard against
26444 intermediate overflows. This package does not use dynamic
26445 alllocation, but it does use the secondary stack, so an
26446 appropriate secondary stack package must be present (this
26447 is always true for standard full Ada, but may require
26448 specific steps for restricted run times such as ZFP).
26450 Although @code{ELIMINATED} mode causes expressions to use arbitrary
26451 precision arithmetic, avoiding overflow, the final result
26452 must be in an appropriate range. This is true even if the
26453 final result is of type @code{[Long_[Long_]]Integer'Base}, which
26454 still has the same bounds as its associated constrained
26455 type at run-time.
26457 Currently, the @code{ELIMINATED} mode is only available on target
26458 platforms for which @code{Long_Long_Integer} is 64-bits (nearly all GNAT
26459 platforms).
26461 @c *******************************
26462 @node Conditional Compilation
26463 @appendix Conditional Compilation
26464 @c *******************************
26465 @cindex Conditional compilation
26467 @noindent
26468 It is often necessary to arrange for a single source program
26469 to serve multiple purposes, where it is compiled in different
26470 ways to achieve these different goals. Some examples of the
26471 need for this feature are
26473 @itemize @bullet
26474 @item  Adapting a program to a different hardware environment
26475 @item  Adapting a program to a different target architecture
26476 @item  Turning debugging features on and off
26477 @item  Arranging for a program to compile with different compilers
26478 @end itemize
26480 @noindent
26481 In C, or C++, the typical approach would be to use the preprocessor
26482 that is defined as part of the language. The Ada language does not
26483 contain such a feature. This is not an oversight, but rather a very
26484 deliberate design decision, based on the experience that overuse of
26485 the preprocessing features in C and C++ can result in programs that
26486 are extremely difficult to maintain. For example, if we have ten
26487 switches that can be on or off, this means that there are a thousand
26488 separate programs, any one of which might not even be syntactically
26489 correct, and even if syntactically correct, the resulting program
26490 might not work correctly. Testing all combinations can quickly become
26491 impossible.
26493 Nevertheless, the need to tailor programs certainly exists, and in
26494 this Appendix we will discuss how this can
26495 be achieved using Ada in general, and GNAT in particular.
26497 @menu
26498 * Use of Boolean Constants::
26499 * Debugging - A Special Case::
26500 * Conditionalizing Declarations::
26501 * Use of Alternative Implementations::
26502 * Preprocessing::
26503 @end menu
26505 @node Use of Boolean Constants
26506 @section Use of Boolean Constants
26508 @noindent
26509 In the case where the difference is simply which code
26510 sequence is executed, the cleanest solution is to use Boolean
26511 constants to control which code is executed.
26513 @smallexample @c ada
26514 @group
26515 FP_Initialize_Required : constant Boolean := True;
26516 @dots{}
26517 if FP_Initialize_Required then
26518 @dots{}
26519 end if;
26520 @end group
26521 @end smallexample
26523 @noindent
26524 Not only will the code inside the @code{if} statement not be executed if
26525 the constant Boolean is @code{False}, but it will also be completely
26526 deleted from the program.
26527 However, the code is only deleted after the @code{if} statement
26528 has been checked for syntactic and semantic correctness.
26529 (In contrast, with preprocessors the code is deleted before the
26530 compiler ever gets to see it, so it is not checked until the switch
26531 is turned on.)
26532 @cindex Preprocessors (contrasted with conditional compilation)
26534 Typically the Boolean constants will be in a separate package,
26535 something like:
26537 @smallexample @c ada
26538 @group
26539 package Config is
26540    FP_Initialize_Required : constant Boolean := True;
26541    Reset_Available        : constant Boolean := False;
26542    @dots{}
26543 end Config;
26544 @end group
26545 @end smallexample
26547 @noindent
26548 The @code{Config} package exists in multiple forms for the various targets,
26549 with an appropriate script selecting the version of @code{Config} needed.
26550 Then any other unit requiring conditional compilation can do a @code{with}
26551 of @code{Config} to make the constants visible.
26554 @node Debugging - A Special Case
26555 @section Debugging - A Special Case
26557 @noindent
26558 A common use of conditional code is to execute statements (for example
26559 dynamic checks, or output of intermediate results) under control of a
26560 debug switch, so that the debugging behavior can be turned on and off.
26561 This can be done using a Boolean constant to control whether the code
26562 is active:
26564 @smallexample @c ada
26565 @group
26566 if Debugging then
26567    Put_Line ("got to the first stage!");
26568 end if;
26569 @end group
26570 @end smallexample
26572 @noindent
26575 @smallexample @c ada
26576 @group
26577 if Debugging and then Temperature > 999.0 then
26578    raise Temperature_Crazy;
26579 end if;
26580 @end group
26581 @end smallexample
26583 @noindent
26584 Since this is a common case, there are special features to deal with
26585 this in a convenient manner. For the case of tests, Ada 2005 has added
26586 a pragma @code{Assert} that can be used for such tests. This pragma is modeled
26587 @cindex pragma @code{Assert}
26588 on the @code{Assert} pragma that has always been available in GNAT, so this
26589 feature may be used with GNAT even if you are not using Ada 2005 features.
26590 The use of pragma @code{Assert} is described in
26591 @ref{Pragma Assert,,, gnat_rm, GNAT Reference Manual}, but as an
26592 example, the last test could be written:
26594 @smallexample @c ada
26595 pragma Assert (Temperature <= 999.0, "Temperature Crazy");
26596 @end smallexample
26598 @noindent
26599 or simply
26601 @smallexample @c ada
26602 pragma Assert (Temperature <= 999.0);
26603 @end smallexample
26605 @noindent
26606 In both cases, if assertions are active and the temperature is excessive,
26607 the exception @code{Assert_Failure} will be raised, with the given string in
26608 the first case or a string indicating the location of the pragma in the second
26609 case used as the exception message.
26611 You can turn assertions on and off by using the @code{Assertion_Policy}
26612 pragma.
26613 @cindex pragma @code{Assertion_Policy}
26614 This is an Ada 2005 pragma which is implemented in all modes by
26615 GNAT, but only in the latest versions of GNAT which include Ada 2005
26616 capability. Alternatively, you can use the @option{-gnata} switch
26617 @cindex @option{-gnata} switch
26618 to enable assertions from the command line (this is recognized by all versions
26619 of GNAT).
26621 For the example above with the @code{Put_Line}, the GNAT-specific pragma
26622 @code{Debug} can be used:
26623 @cindex pragma @code{Debug}
26625 @smallexample @c ada
26626 pragma Debug (Put_Line ("got to the first stage!"));
26627 @end smallexample
26629 @noindent
26630 If debug pragmas are enabled, the argument, which must be of the form of
26631 a procedure call, is executed (in this case, @code{Put_Line} will be called).
26632 Only one call can be present, but of course a special debugging procedure
26633 containing any code you like can be included in the program and then
26634 called in a pragma @code{Debug} argument as needed.
26636 One advantage of pragma @code{Debug} over the @code{if Debugging then}
26637 construct is that pragma @code{Debug} can appear in declarative contexts,
26638 such as at the very beginning of a procedure, before local declarations have
26639 been elaborated.
26641 Debug pragmas are enabled using either the @option{-gnata} switch that also
26642 controls assertions, or with a separate Debug_Policy pragma.
26643 @cindex pragma @code{Debug_Policy}
26644 The latter pragma is new in the Ada 2005 versions of GNAT (but it can be used
26645 in Ada 95 and Ada 83 programs as well), and is analogous to
26646 pragma @code{Assertion_Policy} to control assertions.
26648 @code{Assertion_Policy} and @code{Debug_Policy} are configuration pragmas,
26649 and thus they can appear in @file{gnat.adc} if you are not using a
26650 project file, or in the file designated to contain configuration pragmas
26651 in a project file.
26652 They then apply to all subsequent compilations. In practice the use of
26653 the @option{-gnata} switch is often the most convenient method of controlling
26654 the status of these pragmas.
26656 Note that a pragma is not a statement, so in contexts where a statement
26657 sequence is required, you can't just write a pragma on its own. You have
26658 to add a @code{null} statement.
26660 @smallexample @c ada
26661 @group
26662 if @dots{} then
26663    @dots{} -- some statements
26664 else
26665    pragma Assert (Num_Cases < 10);
26666    null;
26667 end if;
26668 @end group
26669 @end smallexample
26672 @node Conditionalizing Declarations
26673 @section Conditionalizing Declarations
26675 @noindent
26676 In some cases, it may be necessary to conditionalize declarations to meet
26677 different requirements. For example we might want a bit string whose length
26678 is set to meet some hardware message requirement.
26680 In some cases, it may be possible to do this using declare blocks controlled
26681 by conditional constants:
26683 @smallexample @c ada
26684 @group
26685 if Small_Machine then
26686    declare
26687       X : Bit_String (1 .. 10);
26688    begin
26689       @dots{}
26690    end;
26691 else
26692    declare
26693       X : Large_Bit_String (1 .. 1000);
26694    begin
26695       @dots{}
26696    end;
26697 end if;
26698 @end group
26699 @end smallexample
26701 @noindent
26702 Note that in this approach, both declarations are analyzed by the
26703 compiler so this can only be used where both declarations are legal,
26704 even though one of them will not be used.
26706 Another approach is to define integer constants, e.g.@: @code{Bits_Per_Word},
26707 or Boolean constants, e.g.@: @code{Little_Endian}, and then write declarations
26708 that are parameterized by these constants. For example
26710 @smallexample @c ada
26711 @group
26712 for Rec use
26713   Field1 at 0 range Boolean'Pos (Little_Endian) * 10 .. Bits_Per_Word;
26714 end record;
26715 @end group
26716 @end smallexample
26718 @noindent
26719 If @code{Bits_Per_Word} is set to 32, this generates either
26721 @smallexample @c ada
26722 @group
26723 for Rec use
26724   Field1 at 0 range 0 .. 32;
26725 end record;
26726 @end group
26727 @end smallexample
26729 @noindent
26730 for the big endian case, or
26732 @smallexample @c ada
26733 @group
26734 for Rec use record
26735   Field1 at 0 range 10 .. 32;
26736 end record;
26737 @end group
26738 @end smallexample
26740 @noindent
26741 for the little endian case. Since a powerful subset of Ada expression
26742 notation is usable for creating static constants, clever use of this
26743 feature can often solve quite difficult problems in conditionalizing
26744 compilation (note incidentally that in Ada 95, the little endian
26745 constant was introduced as @code{System.Default_Bit_Order}, so you do not
26746 need to define this one yourself).
26749 @node Use of Alternative Implementations
26750 @section Use of Alternative Implementations
26752 @noindent
26753 In some cases, none of the approaches described above are adequate. This
26754 can occur for example if the set of declarations required is radically
26755 different for two different configurations.
26757 In this situation, the official Ada way of dealing with conditionalizing
26758 such code is to write separate units for the different cases. As long as
26759 this does not result in excessive duplication of code, this can be done
26760 without creating maintenance problems. The approach is to share common
26761 code as far as possible, and then isolate the code and declarations
26762 that are different. Subunits are often a convenient method for breaking
26763 out a piece of a unit that is to be conditionalized, with separate files
26764 for different versions of the subunit for different targets, where the
26765 build script selects the right one to give to the compiler.
26766 @cindex Subunits (and conditional compilation)
26768 As an example, consider a situation where a new feature in Ada 2005
26769 allows something to be done in a really nice way. But your code must be able
26770 to compile with an Ada 95 compiler. Conceptually you want to say:
26772 @smallexample @c ada
26773 @group
26774 if Ada_2005 then
26775    @dots{} neat Ada 2005 code
26776 else
26777    @dots{} not quite as neat Ada 95 code
26778 end if;
26779 @end group
26780 @end smallexample
26782 @noindent
26783 where @code{Ada_2005} is a Boolean constant.
26785 But this won't work when @code{Ada_2005} is set to @code{False},
26786 since the @code{then} clause will be illegal for an Ada 95 compiler.
26787 (Recall that although such unreachable code would eventually be deleted
26788 by the compiler, it still needs to be legal.  If it uses features
26789 introduced in Ada 2005, it will be illegal in Ada 95.)
26791 So instead we write
26793 @smallexample @c ada
26794 procedure Insert is separate;
26795 @end smallexample
26797 @noindent
26798 Then we have two files for the subunit @code{Insert}, with the two sets of
26799 code.
26800 If the package containing this is called @code{File_Queries}, then we might
26801 have two files
26803 @itemize @bullet
26804 @item    @file{file_queries-insert-2005.adb}
26805 @item    @file{file_queries-insert-95.adb}
26806 @end itemize
26808 @noindent
26809 and the build script renames the appropriate file to
26811 @smallexample
26812 file_queries-insert.adb
26813 @end smallexample
26815 @noindent
26816 and then carries out the compilation.
26818 This can also be done with project files' naming schemes. For example:
26820 @smallexample @c project
26821 For Body ("File_Queries.Insert") use "file_queries-insert-2005.ada";
26822 @end smallexample
26824 @noindent
26825 Note also that with project files it is desirable to use a different extension
26826 than @file{ads} / @file{adb} for alternative versions. Otherwise a naming
26827 conflict may arise through another commonly used feature: to declare as part
26828 of the project a set of directories containing all the sources obeying the
26829 default naming scheme.
26831 The use of alternative units is certainly feasible in all situations,
26832 and for example the Ada part of the GNAT run-time is conditionalized
26833 based on the target architecture using this approach. As a specific example,
26834 consider the implementation of the AST feature in VMS. There is one
26835 spec:
26837 @smallexample
26838 s-asthan.ads
26839 @end smallexample
26841 @noindent
26842 which is the same for all architectures, and three bodies:
26844 @table @file
26845 @item    s-asthan.adb
26846 used for all non-VMS operating systems
26847 @item    s-asthan-vms-alpha.adb
26848 used for VMS on the Alpha
26849 @item    s-asthan-vms-ia64.adb
26850 used for VMS on the ia64
26851 @end table
26853 @noindent
26854 The dummy version @file{s-asthan.adb} simply raises exceptions noting that
26855 this operating system feature is not available, and the two remaining
26856 versions interface with the corresponding versions of VMS to provide
26857 VMS-compatible AST handling. The GNAT build script knows the architecture
26858 and operating system, and automatically selects the right version,
26859 renaming it if necessary to @file{s-asthan.adb} before the run-time build.
26861 Another style for arranging alternative implementations is through Ada's
26862 access-to-subprogram facility.
26863 In case some functionality is to be conditionally included,
26864 you can declare an access-to-procedure variable @code{Ref} that is initialized
26865 to designate a ``do nothing'' procedure, and then invoke @code{Ref.all}
26866 when appropriate.
26867 In some library package, set @code{Ref} to @code{Proc'Access} for some
26868 procedure @code{Proc} that performs the relevant processing.
26869 The initialization only occurs if the library package is included in the
26870 program.
26871 The same idea can also be implemented using tagged types and dispatching
26872 calls.
26875 @node Preprocessing
26876 @section Preprocessing
26877 @cindex Preprocessing
26879 @noindent
26880 Although it is quite possible to conditionalize code without the use of
26881 C-style preprocessing, as described earlier in this section, it is
26882 nevertheless convenient in some cases to use the C approach. Moreover,
26883 older Ada compilers have often provided some preprocessing capability,
26884 so legacy code may depend on this approach, even though it is not
26885 standard.
26887 To accommodate such use, GNAT provides a preprocessor (modeled to a large
26888 extent on the various preprocessors that have been used
26889 with legacy code on other compilers, to enable easier transition).
26891 The preprocessor may be used in two separate modes. It can be used quite
26892 separately from the compiler, to generate a separate output source file
26893 that is then fed to the compiler as a separate step. This is the
26894 @code{gnatprep} utility, whose use is fully described in
26895 @ref{Preprocessing with gnatprep}.
26896 @cindex @code{gnatprep}
26898 The preprocessing language allows such constructs as
26900 @smallexample
26901 @group
26902 #if DEBUG or PRIORITY > 4 then
26903    bunch of declarations
26904 #else
26905    completely different bunch of declarations
26906 #end if;
26907 @end group
26908 @end smallexample
26910 @noindent
26911 The values of the symbols @code{DEBUG} and @code{PRIORITY} can be
26912 defined either on the command line or in a separate file.
26914 The other way of running the preprocessor is even closer to the C style and
26915 often more convenient. In this approach the preprocessing is integrated into
26916 the compilation process. The compiler is fed the preprocessor input which
26917 includes @code{#if} lines etc, and then the compiler carries out the
26918 preprocessing internally and processes the resulting output.
26919 For more details on this approach, see @ref{Integrated Preprocessing}.
26922 @c *******************************
26923 @node Inline Assembler
26924 @appendix Inline Assembler
26925 @c *******************************
26927 @noindent
26928 If you need to write low-level software that interacts directly
26929 with the hardware, Ada provides two ways to incorporate assembly
26930 language code into your program.  First, you can import and invoke
26931 external routines written in assembly language, an Ada feature fully
26932 supported by GNAT@.  However, for small sections of code it may be simpler
26933 or more efficient to include assembly language statements directly
26934 in your Ada source program, using the facilities of the implementation-defined
26935 package @code{System.Machine_Code}, which incorporates the gcc
26936 Inline Assembler.  The Inline Assembler approach offers a number of advantages,
26937 including the following:
26939 @itemize @bullet
26940 @item No need to use non-Ada tools
26941 @item Consistent interface over different targets
26942 @item Automatic usage of the proper calling conventions
26943 @item Access to Ada constants and variables
26944 @item Definition of intrinsic routines
26945 @item Possibility of inlining a subprogram comprising assembler code
26946 @item Code optimizer can take Inline Assembler code into account
26947 @end itemize
26949 This chapter presents a series of examples to show you how to use
26950 the Inline Assembler.  Although it focuses on the Intel x86,
26951 the general approach applies also to other processors.
26952 It is assumed that you are familiar with Ada
26953 and with assembly language programming.
26955 @menu
26956 * Basic Assembler Syntax::
26957 * A Simple Example of Inline Assembler::
26958 * Output Variables in Inline Assembler::
26959 * Input Variables in Inline Assembler::
26960 * Inlining Inline Assembler Code::
26961 * Other Asm Functionality::
26962 @end menu
26964 @c ---------------------------------------------------------------------------
26965 @node Basic Assembler Syntax
26966 @section Basic Assembler Syntax
26968 @noindent
26969 The assembler used by GNAT and gcc is based not on the Intel assembly
26970 language, but rather on a language that descends from the AT&T Unix
26971 assembler @emph{as} (and which is often referred to as ``AT&T syntax'').
26972 The following table summarizes the main features of @emph{as} syntax
26973 and points out the differences from the Intel conventions.
26974 See the gcc @emph{as} and @emph{gas} (an @emph{as} macro
26975 pre-processor) documentation for further information.
26977 @table @asis
26978 @item Register names
26979 gcc / @emph{as}: Prefix with ``%''; for example @code{%eax}
26981 Intel: No extra punctuation; for example @code{eax}
26983 @item Immediate operand
26984 gcc / @emph{as}: Prefix with ``$''; for example @code{$4}
26986 Intel: No extra punctuation; for example @code{4}
26988 @item Address
26989 gcc / @emph{as}: Prefix with ``$''; for example @code{$loc}
26991 Intel: No extra punctuation; for example @code{loc}
26993 @item Memory contents
26994 gcc / @emph{as}: No extra punctuation; for example @code{loc}
26996 Intel: Square brackets; for example @code{[loc]}
26998 @item Register contents
26999 gcc / @emph{as}: Parentheses; for example @code{(%eax)}
27001 Intel: Square brackets; for example @code{[eax]}
27003 @item Hexadecimal numbers
27004 gcc / @emph{as}: Leading ``0x'' (C language syntax); for example @code{0xA0}
27006 Intel: Trailing ``h''; for example @code{A0h}
27008 @item Operand size
27009 gcc / @emph{as}: Explicit in op code; for example @code{movw} to move
27010 a 16-bit word
27012 Intel: Implicit, deduced by assembler; for example @code{mov}
27014 @item Instruction repetition
27015 gcc / @emph{as}: Split into two lines; for example
27017 @code{rep}
27019 @code{stosl}
27021 Intel: Keep on one line; for example @code{rep stosl}
27023 @item Order of operands
27024 gcc / @emph{as}: Source first; for example @code{movw $4, %eax}
27026 Intel: Destination first; for example @code{mov eax, 4}
27027 @end table
27029 @c ---------------------------------------------------------------------------
27030 @node A Simple Example of Inline Assembler
27031 @section A Simple Example of Inline Assembler
27033 @noindent
27034 The following example will generate a single assembly language statement,
27035 @code{nop}, which does nothing.  Despite its lack of run-time effect,
27036 the example will be useful in illustrating the basics of
27037 the Inline Assembler facility.
27039 @smallexample @c ada
27040 @group
27041 with System.Machine_Code; use System.Machine_Code;
27042 procedure Nothing is
27043 begin
27044    Asm ("nop");
27045 end Nothing;
27046 @end group
27047 @end smallexample
27049 @code{Asm} is a procedure declared in package @code{System.Machine_Code};
27050 here it takes one parameter, a @emph{template string} that must be a static
27051 expression and that will form the generated instruction.
27052 @code{Asm} may be regarded as a compile-time procedure that parses
27053 the template string and additional parameters (none here),
27054 from which it generates a sequence of assembly language instructions.
27056 The examples in this chapter will illustrate several of the forms
27057 for invoking @code{Asm}; a complete specification of the syntax
27058 is found in @ref{Machine Code Insertions,,, gnat_rm, GNAT Reference
27059 Manual}.
27061 Under the standard GNAT conventions, the @code{Nothing} procedure
27062 should be in a file named @file{nothing.adb}.
27063 You can build the executable in the usual way:
27064 @smallexample
27065 gnatmake nothing
27066 @end smallexample
27067 However, the interesting aspect of this example is not its run-time behavior
27068 but rather the generated assembly code.
27069 To see this output, invoke the compiler as follows:
27070 @smallexample
27071    gcc -c -S -fomit-frame-pointer -gnatp @file{nothing.adb}
27072 @end smallexample
27073 where the options are:
27075 @table @code
27076 @item -c
27077 compile only (no bind or link)
27078 @item -S
27079 generate assembler listing
27080 @item -fomit-frame-pointer
27081 do not set up separate stack frames
27082 @item -gnatp
27083 do not add runtime checks
27084 @end table
27086 This gives a human-readable assembler version of the code. The resulting
27087 file will have the same name as the Ada source file, but with a @code{.s}
27088 extension. In our example, the file @file{nothing.s} has the following
27089 contents:
27091 @smallexample
27092 @group
27093 .file "nothing.adb"
27094 gcc2_compiled.:
27095 ___gnu_compiled_ada:
27096 .text
27097    .align 4
27098 .globl __ada_nothing
27099 __ada_nothing:
27100 #APP
27101    nop
27102 #NO_APP
27103    jmp L1
27104    .align 2,0x90
27106    ret
27107 @end group
27108 @end smallexample
27110 The assembly code you included is clearly indicated by
27111 the compiler, between the @code{#APP} and @code{#NO_APP}
27112 delimiters. The character before the 'APP' and 'NOAPP'
27113 can differ on different targets. For example, GNU/Linux uses '#APP' while
27114 on NT you will see '/APP'.
27116 If you make a mistake in your assembler code (such as using the
27117 wrong size modifier, or using a wrong operand for the instruction) GNAT
27118 will report this error in a temporary file, which will be deleted when
27119 the compilation is finished.  Generating an assembler file will help
27120 in such cases, since you can assemble this file separately using the
27121 @emph{as} assembler that comes with gcc.
27123 Assembling the file using the command
27125 @smallexample
27126 as @file{nothing.s}
27127 @end smallexample
27128 @noindent
27129 will give you error messages whose lines correspond to the assembler
27130 input file, so you can easily find and correct any mistakes you made.
27131 If there are no errors, @emph{as} will generate an object file
27132 @file{nothing.out}.
27134 @c ---------------------------------------------------------------------------
27135 @node Output Variables in Inline Assembler
27136 @section Output Variables in Inline Assembler
27138 @noindent
27139 The examples in this section, showing how to access the processor flags,
27140 illustrate how to specify the destination operands for assembly language
27141 statements.
27143 @smallexample @c ada
27144 @group
27145 with Interfaces; use Interfaces;
27146 with Ada.Text_IO; use Ada.Text_IO;
27147 with System.Machine_Code; use System.Machine_Code;
27148 procedure Get_Flags is
27149    Flags : Unsigned_32;
27150    use ASCII;
27151 begin
27152    Asm ("pushfl"          & LF & HT & -- push flags on stack
27153         "popl %%eax"      & LF & HT & -- load eax with flags
27154         "movl %%eax, %0",             -- store flags in variable
27155         Outputs => Unsigned_32'Asm_Output ("=g", Flags));
27156    Put_Line ("Flags register:" & Flags'Img);
27157 end Get_Flags;
27158 @end group
27159 @end smallexample
27161 In order to have a nicely aligned assembly listing, we have separated
27162 multiple assembler statements in the Asm template string with linefeed
27163 (ASCII.LF) and horizontal tab (ASCII.HT) characters.
27164 The resulting section of the assembly output file is:
27166 @smallexample
27167 @group
27168 #APP
27169    pushfl
27170    popl %eax
27171    movl %eax, -40(%ebp)
27172 #NO_APP
27173 @end group
27174 @end smallexample
27176 It would have been legal to write the Asm invocation as:
27178 @smallexample
27179 Asm ("pushfl popl %%eax movl %%eax, %0")
27180 @end smallexample
27182 but in the generated assembler file, this would come out as:
27184 @smallexample
27185 #APP
27186    pushfl popl %eax movl %eax, -40(%ebp)
27187 #NO_APP
27188 @end smallexample
27190 which is not so convenient for the human reader.
27192 We use Ada comments
27193 at the end of each line to explain what the assembler instructions
27194 actually do.  This is a useful convention.
27196 When writing Inline Assembler instructions, you need to precede each register
27197 and variable name with a percent sign.  Since the assembler already requires
27198 a percent sign at the beginning of a register name, you need two consecutive
27199 percent signs for such names in the Asm template string, thus @code{%%eax}.
27200 In the generated assembly code, one of the percent signs will be stripped off.
27202 Names such as @code{%0}, @code{%1}, @code{%2}, etc., denote input or output
27203 variables: operands you later define using @code{Input} or @code{Output}
27204 parameters to @code{Asm}.
27205 An output variable is illustrated in
27206 the third statement in the Asm template string:
27207 @smallexample
27208 movl %%eax, %0
27209 @end smallexample
27210 The intent is to store the contents of the eax register in a variable that can
27211 be accessed in Ada.  Simply writing @code{movl %%eax, Flags} would not
27212 necessarily work, since the compiler might optimize by using a register
27213 to hold Flags, and the expansion of the @code{movl} instruction would not be
27214 aware of this optimization.  The solution is not to store the result directly
27215 but rather to advise the compiler to choose the correct operand form;
27216 that is the purpose of the @code{%0} output variable.
27218 Information about the output variable is supplied in the @code{Outputs}
27219 parameter to @code{Asm}:
27220 @smallexample
27221 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
27222 @end smallexample
27224 The output is defined by the @code{Asm_Output} attribute of the target type;
27225 the general format is
27226 @smallexample
27227 Type'Asm_Output (constraint_string, variable_name)
27228 @end smallexample
27230 The constraint string directs the compiler how
27231 to store/access the associated variable.  In the example
27232 @smallexample
27233 Unsigned_32'Asm_Output ("=m", Flags);
27234 @end smallexample
27235 the @code{"m"} (memory) constraint tells the compiler that the variable
27236 @code{Flags} should be stored in a memory variable, thus preventing
27237 the optimizer from keeping it in a register.  In contrast,
27238 @smallexample
27239 Unsigned_32'Asm_Output ("=r", Flags);
27240 @end smallexample
27241 uses the @code{"r"} (register) constraint, telling the compiler to
27242 store the variable in a register.
27244 If the constraint is preceded by the equal character (@strong{=}), it tells
27245 the compiler that the variable will be used to store data into it.
27247 In the @code{Get_Flags} example, we used the @code{"g"} (global) constraint,
27248 allowing the optimizer to choose whatever it deems best.
27250 There are a fairly large number of constraints, but the ones that are
27251 most useful (for the Intel x86 processor) are the following:
27253 @table @code
27254 @item =
27255 output constraint
27256 @item g
27257 global (i.e.@: can be stored anywhere)
27258 @item m
27259 in memory
27260 @item I
27261 a constant
27262 @item a
27263 use eax
27264 @item b
27265 use ebx
27266 @item c
27267 use ecx
27268 @item d
27269 use edx
27270 @item S
27271 use esi
27272 @item D
27273 use edi
27274 @item r
27275 use one of eax, ebx, ecx or edx
27276 @item q
27277 use one of eax, ebx, ecx, edx, esi or edi
27278 @end table
27280 The full set of constraints is described in the gcc and @emph{as}
27281 documentation; note that it is possible to combine certain constraints
27282 in one constraint string.
27284 You specify the association of an output variable with an assembler operand
27285 through the @code{%}@emph{n} notation, where @emph{n} is a non-negative
27286 integer.  Thus in
27287 @smallexample @c ada
27288 @group
27289 Asm ("pushfl"          & LF & HT & -- push flags on stack
27290      "popl %%eax"      & LF & HT & -- load eax with flags
27291      "movl %%eax, %0",             -- store flags in variable
27292      Outputs => Unsigned_32'Asm_Output ("=g", Flags));
27293 @end group
27294 @end smallexample
27295 @noindent
27296 @code{%0} will be replaced in the expanded code by the appropriate operand,
27297 whatever
27298 the compiler decided for the @code{Flags} variable.
27300 In general, you may have any number of output variables:
27301 @itemize @bullet
27302 @item
27303 Count the operands starting at 0; thus @code{%0}, @code{%1}, etc.
27304 @item
27305 Specify the @code{Outputs} parameter as a parenthesized comma-separated list
27306 of @code{Asm_Output} attributes
27307 @end itemize
27309 For example:
27310 @smallexample @c ada
27311 @group
27312 Asm ("movl %%eax, %0" & LF & HT &
27313      "movl %%ebx, %1" & LF & HT &
27314      "movl %%ecx, %2",
27315      Outputs => (Unsigned_32'Asm_Output ("=g", Var_A),   --  %0 = Var_A
27316                  Unsigned_32'Asm_Output ("=g", Var_B),   --  %1 = Var_B
27317                  Unsigned_32'Asm_Output ("=g", Var_C))); --  %2 = Var_C
27318 @end group
27319 @end smallexample
27320 @noindent
27321 where @code{Var_A}, @code{Var_B}, and @code{Var_C} are variables
27322 in the Ada program.
27324 As a variation on the @code{Get_Flags} example, we can use the constraints
27325 string to direct the compiler to store the eax register into the @code{Flags}
27326 variable, instead of including the store instruction explicitly in the
27327 @code{Asm} template string:
27329 @smallexample @c ada
27330 @group
27331 with Interfaces; use Interfaces;
27332 with Ada.Text_IO; use Ada.Text_IO;
27333 with System.Machine_Code; use System.Machine_Code;
27334 procedure Get_Flags_2 is
27335    Flags : Unsigned_32;
27336    use ASCII;
27337 begin
27338    Asm ("pushfl"      & LF & HT & -- push flags on stack
27339         "popl %%eax",             -- save flags in eax
27340         Outputs => Unsigned_32'Asm_Output ("=a", Flags));
27341    Put_Line ("Flags register:" & Flags'Img);
27342 end Get_Flags_2;
27343 @end group
27344 @end smallexample
27346 @noindent
27347 The @code{"a"} constraint tells the compiler that the @code{Flags}
27348 variable will come from the eax register. Here is the resulting code:
27350 @smallexample
27351 @group
27352 #APP
27353    pushfl
27354    popl %eax
27355 #NO_APP
27356    movl %eax,-40(%ebp)
27357 @end group
27358 @end smallexample
27360 @noindent
27361 The compiler generated the store of eax into Flags after
27362 expanding the assembler code.
27364 Actually, there was no need to pop the flags into the eax register;
27365 more simply, we could just pop the flags directly into the program variable:
27367 @smallexample @c ada
27368 @group
27369 with Interfaces; use Interfaces;
27370 with Ada.Text_IO; use Ada.Text_IO;
27371 with System.Machine_Code; use System.Machine_Code;
27372 procedure Get_Flags_3 is
27373    Flags : Unsigned_32;
27374    use ASCII;
27375 begin
27376    Asm ("pushfl"  & LF & HT & -- push flags on stack
27377         "pop %0",             -- save flags in Flags
27378         Outputs => Unsigned_32'Asm_Output ("=g", Flags));
27379    Put_Line ("Flags register:" & Flags'Img);
27380 end Get_Flags_3;
27381 @end group
27382 @end smallexample
27384 @c ---------------------------------------------------------------------------
27385 @node Input Variables in Inline Assembler
27386 @section Input Variables in Inline Assembler
27388 @noindent
27389 The example in this section illustrates how to specify the source operands
27390 for assembly language statements.
27391 The program simply increments its input value by 1:
27393 @smallexample @c ada
27394 @group
27395 with Interfaces; use Interfaces;
27396 with Ada.Text_IO; use Ada.Text_IO;
27397 with System.Machine_Code; use System.Machine_Code;
27398 procedure Increment is
27400    function Incr (Value : Unsigned_32) return Unsigned_32 is
27401       Result : Unsigned_32;
27402    begin
27403       Asm ("incl %0",
27404            Outputs => Unsigned_32'Asm_Output ("=a", Result),
27405            Inputs  => Unsigned_32'Asm_Input ("a", Value));
27406       return Result;
27407    end Incr;
27409    Value : Unsigned_32;
27411 begin
27412    Value := 5;
27413    Put_Line ("Value before is" & Value'Img);
27414    Value := Incr (Value);
27415    Put_Line ("Value after is" & Value'Img);
27416 end Increment;
27417 @end group
27418 @end smallexample
27420 The @code{Outputs} parameter to @code{Asm} specifies
27421 that the result will be in the eax register and that it is to be stored
27422 in the @code{Result} variable.
27424 The @code{Inputs} parameter looks much like the @code{Outputs} parameter,
27425 but with an @code{Asm_Input} attribute.
27426 The @code{"="} constraint, indicating an output value, is not present.
27428 You can have multiple input variables, in the same way that you can have more
27429 than one output variable.
27431 The parameter count (%0, %1) etc, still starts at the first output statement,
27432 and continues with the input statements.
27434 Just as the @code{Outputs} parameter causes the register to be stored into the
27435 target variable after execution of the assembler statements, so does the
27436 @code{Inputs} parameter cause its variable to be loaded into the register
27437 before execution of the assembler statements.
27439 Thus the effect of the @code{Asm} invocation is:
27440 @enumerate
27441 @item load the 32-bit value of @code{Value} into eax
27442 @item execute the @code{incl %eax} instruction
27443 @item store the contents of eax into the @code{Result} variable
27444 @end enumerate
27446 The resulting assembler file (with @option{-O2} optimization) contains:
27447 @smallexample
27448 @group
27449 _increment__incr.1:
27450    subl $4,%esp
27451    movl 8(%esp),%eax
27452 #APP
27453    incl %eax
27454 #NO_APP
27455    movl %eax,%edx
27456    movl %ecx,(%esp)
27457    addl $4,%esp
27458    ret
27459 @end group
27460 @end smallexample
27462 @c ---------------------------------------------------------------------------
27463 @node Inlining Inline Assembler Code
27464 @section Inlining Inline Assembler Code
27466 @noindent
27467 For a short subprogram such as the @code{Incr} function in the previous
27468 section, the overhead of the call and return (creating / deleting the stack
27469 frame) can be significant, compared to the amount of code in the subprogram
27470 body.  A solution is to apply Ada's @code{Inline} pragma to the subprogram,
27471 which directs the compiler to expand invocations of the subprogram at the
27472 point(s) of call, instead of setting up a stack frame for out-of-line calls.
27473 Here is the resulting program:
27475 @smallexample @c ada
27476 @group
27477 with Interfaces; use Interfaces;
27478 with Ada.Text_IO; use Ada.Text_IO;
27479 with System.Machine_Code; use System.Machine_Code;
27480 procedure Increment_2 is
27482    function Incr (Value : Unsigned_32) return Unsigned_32 is
27483       Result : Unsigned_32;
27484    begin
27485       Asm ("incl %0",
27486            Outputs => Unsigned_32'Asm_Output ("=a", Result),
27487            Inputs  => Unsigned_32'Asm_Input ("a", Value));
27488       return Result;
27489    end Incr;
27490    pragma Inline (Increment);
27492    Value : Unsigned_32;
27494 begin
27495    Value := 5;
27496    Put_Line ("Value before is" & Value'Img);
27497    Value := Increment (Value);
27498    Put_Line ("Value after is" & Value'Img);
27499 end Increment_2;
27500 @end group
27501 @end smallexample
27503 Compile the program with both optimization (@option{-O2}) and inlining
27504 (@option{-gnatn}) enabled.
27506 The @code{Incr} function is still compiled as usual, but at the
27507 point in @code{Increment} where our function used to be called:
27509 @smallexample
27510 @group
27511 pushl %edi
27512 call _increment__incr.1
27513 @end group
27514 @end smallexample
27516 @noindent
27517 the code for the function body directly appears:
27519 @smallexample
27520 @group
27521 movl %esi,%eax
27522 #APP
27523    incl %eax
27524 #NO_APP
27525    movl %eax,%edx
27526 @end group
27527 @end smallexample
27529 @noindent
27530 thus saving the overhead of stack frame setup and an out-of-line call.
27532 @c ---------------------------------------------------------------------------
27533 @node Other Asm Functionality
27534 @section Other @code{Asm} Functionality
27536 @noindent
27537 This section describes two important parameters to the @code{Asm}
27538 procedure: @code{Clobber}, which identifies register usage;
27539 and @code{Volatile}, which inhibits unwanted optimizations.
27541 @menu
27542 * The Clobber Parameter::
27543 * The Volatile Parameter::
27544 @end menu
27546 @c ---------------------------------------------------------------------------
27547 @node The Clobber Parameter
27548 @subsection The @code{Clobber} Parameter
27550 @noindent
27551 One of the dangers of intermixing assembly language and a compiled language
27552 such as Ada is that the compiler needs to be aware of which registers are
27553 being used by the assembly code.  In some cases, such as the earlier examples,
27554 the constraint string is sufficient to indicate register usage (e.g.,
27555 @code{"a"} for
27556 the eax register).  But more generally, the compiler needs an explicit
27557 identification of the registers that are used by the Inline Assembly
27558 statements.
27560 Using a register that the compiler doesn't know about
27561 could be a side effect of an instruction (like @code{mull}
27562 storing its result in both eax and edx).
27563 It can also arise from explicit register usage in your
27564 assembly code; for example:
27565 @smallexample
27566 @group
27567 Asm ("movl %0, %%ebx" & LF & HT &
27568      "movl %%ebx, %1",
27569      Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
27570      Inputs  => Unsigned_32'Asm_Input  ("g", Var_In));
27571 @end group
27572 @end smallexample
27573 @noindent
27574 where the compiler (since it does not analyze the @code{Asm} template string)
27575 does not know you are using the ebx register.
27577 In such cases you need to supply the @code{Clobber} parameter to @code{Asm},
27578 to identify the registers that will be used by your assembly code:
27580 @smallexample
27581 @group
27582 Asm ("movl %0, %%ebx" & LF & HT &
27583      "movl %%ebx, %1",
27584      Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
27585      Inputs  => Unsigned_32'Asm_Input  ("g", Var_In),
27586      Clobber => "ebx");
27587 @end group
27588 @end smallexample
27590 The Clobber parameter is a static string expression specifying the
27591 register(s) you are using.  Note that register names are @emph{not} prefixed
27592 by a percent sign. Also, if more than one register is used then their names
27593 are separated by commas; e.g., @code{"eax, ebx"}
27595 The @code{Clobber} parameter has several additional uses:
27596 @enumerate
27597 @item Use ``register'' name @code{cc} to indicate that flags might have changed
27598 @item Use ``register'' name @code{memory} if you changed a memory location
27599 @end enumerate
27601 @c ---------------------------------------------------------------------------
27602 @node The Volatile Parameter
27603 @subsection The @code{Volatile} Parameter
27604 @cindex Volatile parameter
27606 @noindent
27607 Compiler optimizations in the presence of Inline Assembler may sometimes have
27608 unwanted effects.  For example, when an @code{Asm} invocation with an input
27609 variable is inside a loop, the compiler might move the loading of the input
27610 variable outside the loop, regarding it as a one-time initialization.
27612 If this effect is not desired, you can disable such optimizations by setting
27613 the @code{Volatile} parameter to @code{True}; for example:
27615 @smallexample @c ada
27616 @group
27617 Asm ("movl %0, %%ebx" & LF & HT &
27618      "movl %%ebx, %1",
27619      Outputs  => Unsigned_32'Asm_Output ("=g", Var_Out),
27620      Inputs   => Unsigned_32'Asm_Input  ("g", Var_In),
27621      Clobber  => "ebx",
27622      Volatile => True);
27623 @end group
27624 @end smallexample
27626 By default, @code{Volatile} is set to @code{False} unless there is no
27627 @code{Outputs} parameter.
27629 Although setting @code{Volatile} to @code{True} prevents unwanted
27630 optimizations, it will also disable other optimizations that might be
27631 important for efficiency. In general, you should set @code{Volatile}
27632 to @code{True} only if the compiler's optimizations have created
27633 problems.
27634 @c END OF INLINE ASSEMBLER CHAPTER
27635 @c ===============================
27637 @c ***********************************
27638 @c * Compatibility and Porting Guide *
27639 @c ***********************************
27640 @node Compatibility and Porting Guide
27641 @appendix Compatibility and Porting Guide
27643 @noindent
27644 This chapter describes the compatibility issues that may arise between
27645 GNAT and other Ada compilation systems (including those for Ada 83),
27646 and shows how GNAT can expedite porting
27647 applications developed in other Ada environments.
27649 @menu
27650 * Compatibility with Ada 83::
27651 * Compatibility between Ada 95 and Ada 2005::
27652 * Implementation-dependent characteristics::
27653 * Compatibility with Other Ada Systems::
27654 * Representation Clauses::
27655 @ifclear vms
27656 @c Brief section is only in non-VMS version
27657 @c Full chapter is in VMS version
27658 * Compatibility with HP Ada 83::
27659 @end ifclear
27660 @ifset vms
27661 * Transitioning to 64-Bit GNAT for OpenVMS::
27662 @end ifset
27663 @end menu
27665 @node Compatibility with Ada 83
27666 @section Compatibility with Ada 83
27667 @cindex Compatibility (between Ada 83 and Ada 95 / Ada 2005)
27669 @noindent
27670 Ada 95 and Ada 2005 are highly upwards compatible with Ada 83.  In
27671 particular, the design intention was that the difficulties associated
27672 with moving from Ada 83 to Ada 95 or Ada 2005 should be no greater than those
27673 that occur when moving from one Ada 83 system to another.
27675 However, there are a number of points at which there are minor
27676 incompatibilities.  The @cite{Ada 95 Annotated Reference Manual} contains
27677 full details of these issues,
27678 and should be consulted for a complete treatment.
27679 In practice the
27680 following subsections treat the most likely issues to be encountered.
27682 @menu
27683 * Legal Ada 83 programs that are illegal in Ada 95::
27684 * More deterministic semantics::
27685 * Changed semantics::
27686 * Other language compatibility issues::
27687 @end menu
27689 @node Legal Ada 83 programs that are illegal in Ada 95
27690 @subsection Legal Ada 83 programs that are illegal in Ada 95
27692 Some legal Ada 83 programs are illegal (i.e., they will fail to compile) in
27693 Ada 95 and thus also in Ada 2005:
27695 @table @emph
27696 @item Character literals
27697 Some uses of character literals are ambiguous.  Since Ada 95 has introduced
27698 @code{Wide_Character} as a new predefined character type, some uses of
27699 character literals that were legal in Ada 83 are illegal in Ada 95.
27700 For example:
27701 @smallexample @c ada
27702    for Char in 'A' .. 'Z' loop @dots{} end loop;
27703 @end smallexample
27705 @noindent
27706 The problem is that @code{'A'} and @code{'Z'} could be from either
27707 @code{Character} or @code{Wide_Character}.  The simplest correction
27708 is to make the type explicit; e.g.:
27709 @smallexample @c ada
27710    for Char in Character range 'A' .. 'Z' loop @dots{} end loop;
27711 @end smallexample
27713 @item New reserved words
27714 The identifiers @code{abstract}, @code{aliased}, @code{protected},
27715 @code{requeue}, @code{tagged}, and @code{until} are reserved in Ada 95.
27716 Existing Ada 83 code using any of these identifiers must be edited to
27717 use some alternative name.
27719 @item Freezing rules
27720 The rules in Ada 95 are slightly different with regard to the point at
27721 which entities are frozen, and representation pragmas and clauses are
27722 not permitted past the freeze point.  This shows up most typically in
27723 the form of an error message complaining that a representation item
27724 appears too late, and the appropriate corrective action is to move
27725 the item nearer to the declaration of the entity to which it refers.
27727 A particular case is that representation pragmas
27728 @ifset vms
27729 (including the
27730 extended HP Ada 83 compatibility pragmas such as @code{Export_Procedure})
27731 @end ifset
27732 cannot be applied to a subprogram body.  If necessary, a separate subprogram
27733 declaration must be introduced to which the pragma can be applied.
27735 @item Optional bodies for library packages
27736 In Ada 83, a package that did not require a package body was nevertheless
27737 allowed to have one.  This lead to certain surprises in compiling large
27738 systems (situations in which the body could be unexpectedly ignored by the
27739 binder).  In Ada 95, if a package does not require a body then it is not
27740 permitted to have a body.  To fix this problem, simply remove a redundant
27741 body if it is empty, or, if it is non-empty, introduce a dummy declaration
27742 into the spec that makes the body required.  One approach is to add a private
27743 part to the package declaration (if necessary), and define a parameterless
27744 procedure called @code{Requires_Body}, which must then be given a dummy
27745 procedure body in the package body, which then becomes required.
27746 Another approach (assuming that this does not introduce elaboration
27747 circularities) is to add an @code{Elaborate_Body} pragma to the package spec,
27748 since one effect of this pragma is to require the presence of a package body.
27750 @item @code{Numeric_Error} is now the same as @code{Constraint_Error}
27751 In Ada 95, the exception @code{Numeric_Error} is a renaming of
27752 @code{Constraint_Error}.
27753 This means that it is illegal to have separate exception handlers for
27754 the two exceptions.  The fix is simply to remove the handler for the
27755 @code{Numeric_Error} case (since even in Ada 83, a compiler was free to raise
27756 @code{Constraint_Error} in place of @code{Numeric_Error} in all cases).
27758 @item Indefinite subtypes in generics
27759 In Ada 83, it was permissible to pass an indefinite type (e.g.@: @code{String})
27760 as the actual for a generic formal private type, but then the instantiation
27761 would be illegal if there were any instances of declarations of variables
27762 of this type in the generic body.  In Ada 95, to avoid this clear violation
27763 of the methodological principle known as the ``contract model'',
27764 the generic declaration explicitly indicates whether
27765 or not such instantiations are permitted.  If a generic formal parameter
27766 has explicit unknown discriminants, indicated by using @code{(<>)} after the
27767 subtype name, then it can be instantiated with indefinite types, but no
27768 stand-alone variables can be declared of this type.  Any attempt to declare
27769 such a variable will result in an illegality at the time the generic is
27770 declared.  If the @code{(<>)} notation is not used, then it is illegal
27771 to instantiate the generic with an indefinite type.
27772 This is the potential incompatibility issue when porting Ada 83 code to Ada 95.
27773 It will show up as a compile time error, and
27774 the fix is usually simply to add the @code{(<>)} to the generic declaration.
27775 @end table
27777 @node More deterministic semantics
27778 @subsection More deterministic semantics
27780 @table @emph
27781 @item Conversions
27782 Conversions from real types to integer types round away from 0.  In Ada 83
27783 the conversion Integer(2.5) could deliver either 2 or 3 as its value.  This
27784 implementation freedom was intended to support unbiased rounding in
27785 statistical applications, but in practice it interfered with portability.
27786 In Ada 95 the conversion semantics are unambiguous, and rounding away from 0
27787 is required.  Numeric code may be affected by this change in semantics.
27788 Note, though, that this issue is no worse than already existed in Ada 83
27789 when porting code from one vendor to another.
27791 @item Tasking
27792 The Real-Time Annex introduces a set of policies that define the behavior of
27793 features that were implementation dependent in Ada 83, such as the order in
27794 which open select branches are executed.
27795 @end table
27797 @node Changed semantics
27798 @subsection Changed semantics
27800 @noindent
27801 The worst kind of incompatibility is one where a program that is legal in
27802 Ada 83 is also legal in Ada 95 but can have an effect in Ada 95 that was not
27803 possible in Ada 83.  Fortunately this is extremely rare, but the one
27804 situation that you should be alert to is the change in the predefined type
27805 @code{Character} from 7-bit ASCII to 8-bit Latin-1.
27807 @table @emph
27808 @item Range of type @code{Character}
27809 The range of @code{Standard.Character} is now the full 256 characters
27810 of Latin-1, whereas in most Ada 83 implementations it was restricted
27811 to 128 characters. Although some of the effects of
27812 this change will be manifest in compile-time rejection of legal
27813 Ada 83 programs it is possible for a working Ada 83 program to have
27814 a different effect in Ada 95, one that was not permitted in Ada 83.
27815 As an example, the expression
27816 @code{Character'Pos(Character'Last)} returned @code{127} in Ada 83 and now
27817 delivers @code{255} as its value.
27818 In general, you should look at the logic of any
27819 character-processing Ada 83 program and see whether it needs to be adapted
27820 to work correctly with Latin-1.  Note that the predefined Ada 95 API has a
27821 character handling package that may be relevant if code needs to be adapted
27822 to account for the additional Latin-1 elements.
27823 The desirable fix is to
27824 modify the program to accommodate the full character set, but in some cases
27825 it may be convenient to define a subtype or derived type of Character that
27826 covers only the restricted range.
27827 @cindex Latin-1
27828 @end table
27830 @node Other language compatibility issues
27831 @subsection Other language compatibility issues
27833 @table @emph
27834 @item @option{-gnat83} switch
27835 All implementations of GNAT provide a switch that causes GNAT to operate
27836 in Ada 83 mode.  In this mode, some but not all compatibility problems
27837 of the type described above are handled automatically.  For example, the
27838 new reserved words introduced in Ada 95 and Ada 2005 are treated simply
27839 as identifiers as in Ada 83.
27840 However,
27841 in practice, it is usually advisable to make the necessary modifications
27842 to the program to remove the need for using this switch.
27843 See @ref{Compiling Different Versions of Ada}.
27845 @item Support for removed Ada 83 pragmas and attributes
27846 A number of pragmas and attributes from Ada 83 were removed from Ada 95,
27847 generally because they were replaced by other mechanisms.  Ada 95 and Ada 2005
27848 compilers are allowed, but not required, to implement these missing
27849 elements.  In contrast with some other compilers, GNAT implements all
27850 such pragmas and attributes, eliminating this compatibility concern.  These
27851 include @code{pragma Interface} and the floating point type attributes
27852 (@code{Emax}, @code{Mantissa}, etc.), among other items.
27853 @end table
27856 @node Compatibility between Ada 95 and Ada 2005
27857 @section Compatibility between Ada 95 and Ada 2005
27858 @cindex Compatibility between Ada 95 and Ada 2005
27860 @noindent
27861 Although Ada 2005 was designed to be upwards compatible with Ada 95, there are
27862 a number of incompatibilities. Several are enumerated below;
27863 for a complete description please see the
27864 Annotated Ada 2005 Reference Manual, or section 9.1.1 in
27865 @cite{Rationale for Ada 2005}.
27867 @table @emph
27868 @item New reserved words.
27869 The words @code{interface}, @code{overriding} and @code{synchronized} are
27870 reserved in Ada 2005.
27871 A pre-Ada 2005 program that uses any of these as an identifier will be
27872 illegal.
27874 @item New declarations in predefined packages.
27875 A number of packages in the predefined environment contain new declarations:
27876 @code{Ada.Exceptions}, @code{Ada.Real_Time}, @code{Ada.Strings},
27877 @code{Ada.Strings.Fixed}, @code{Ada.Strings.Bounded},
27878 @code{Ada.Strings.Unbounded}, @code{Ada.Strings.Wide_Fixed},
27879 @code{Ada.Strings.Wide_Bounded}, @code{Ada.Strings.Wide_Unbounded},
27880 @code{Ada.Tags}, @code{Ada.Text_IO}, and @code{Interfaces.C}.
27881 If an Ada 95 program does a @code{with} and @code{use} of any of these
27882 packages, the new declarations may cause name clashes.
27884 @item Access parameters.
27885 A nondispatching subprogram with an access parameter cannot be renamed
27886 as a dispatching operation.  This was permitted in Ada 95.
27888 @item Access types, discriminants, and constraints.
27889 Rule changes in this area have led to some incompatibilities; for example,
27890 constrained subtypes of some access types are not permitted in Ada 2005.
27892 @item Aggregates for limited types.
27893 The allowance of aggregates for limited types in Ada 2005 raises the
27894 possibility of ambiguities in legal Ada 95 programs, since additional types
27895 now need to be considered in expression resolution.
27897 @item Fixed-point multiplication and division.
27898 Certain expressions involving ``*'' or ``/'' for a fixed-point type, which
27899 were legal in Ada 95 and invoked the predefined versions of these operations,
27900 are now ambiguous.
27901 The ambiguity may be resolved either by applying a type conversion to the
27902 expression, or by explicitly invoking the operation from package
27903 @code{Standard}.
27905 @item Return-by-reference types.
27906 The Ada 95 return-by-reference mechanism has been removed.  Instead, the user
27907 can declare a function returning a value from an anonymous access type.
27908 @end table
27911 @node Implementation-dependent characteristics
27912 @section Implementation-dependent characteristics
27913 @noindent
27914 Although the Ada language defines the semantics of each construct as
27915 precisely as practical, in some situations (for example for reasons of
27916 efficiency, or where the effect is heavily dependent on the host or target
27917 platform) the implementation is allowed some freedom.  In porting Ada 83
27918 code to GNAT, you need to be aware of whether / how the existing code
27919 exercised such implementation dependencies.  Such characteristics fall into
27920 several categories, and GNAT offers specific support in assisting the
27921 transition from certain Ada 83 compilers.
27923 @menu
27924 * Implementation-defined pragmas::
27925 * Implementation-defined attributes::
27926 * Libraries::
27927 * Elaboration order::
27928 * Target-specific aspects::
27929 @end menu
27931 @node Implementation-defined pragmas
27932 @subsection Implementation-defined pragmas
27934 @noindent
27935 Ada compilers are allowed to supplement the language-defined pragmas, and
27936 these are a potential source of non-portability.  All GNAT-defined pragmas
27937 are described in @ref{Implementation Defined Pragmas,,, gnat_rm, GNAT
27938 Reference Manual}, and these include several that are specifically
27939 intended to correspond to other vendors' Ada 83 pragmas.
27940 For migrating from VADS, the pragma @code{Use_VADS_Size} may be useful.
27941 For compatibility with HP Ada 83, GNAT supplies the pragmas
27942 @code{Extend_System}, @code{Ident}, @code{Inline_Generic},
27943 @code{Interface_Name}, @code{Passive}, @code{Suppress_All},
27944 and @code{Volatile}.
27945 Other relevant pragmas include @code{External} and @code{Link_With}.
27946 Some vendor-specific
27947 Ada 83 pragmas (@code{Share_Generic}, @code{Subtitle}, and @code{Title}) are
27948 recognized, thus
27949 avoiding compiler rejection of units that contain such pragmas; they are not
27950 relevant in a GNAT context and hence are not otherwise implemented.
27952 @node Implementation-defined attributes
27953 @subsection Implementation-defined attributes
27955 Analogous to pragmas, the set of attributes may be extended by an
27956 implementation.  All GNAT-defined attributes are described in
27957 @ref{Implementation Defined Attributes,,, gnat_rm, GNAT Reference
27958 Manual}, and these include several that are specifically intended
27959 to correspond to other vendors' Ada 83 attributes.  For migrating from VADS,
27960 the attribute @code{VADS_Size} may be useful.  For compatibility with HP
27961 Ada 83, GNAT supplies the attributes @code{Bit}, @code{Machine_Size} and
27962 @code{Type_Class}.
27964 @node Libraries
27965 @subsection Libraries
27966 @noindent
27967 Vendors may supply libraries to supplement the standard Ada API.  If Ada 83
27968 code uses vendor-specific libraries then there are several ways to manage
27969 this in Ada 95 or Ada 2005:
27970 @enumerate
27971 @item
27972 If the source code for the libraries (specs and bodies) are
27973 available, then the libraries can be migrated in the same way as the
27974 application.
27975 @item
27976 If the source code for the specs but not the bodies are
27977 available, then you can reimplement the bodies.
27978 @item
27979 Some features introduced by Ada 95 obviate the need for library support.  For
27980 example most Ada 83 vendors supplied a package for unsigned integers.  The
27981 Ada 95 modular type feature is the preferred way to handle this need, so
27982 instead of migrating or reimplementing the unsigned integer package it may
27983 be preferable to retrofit the application using modular types.
27984 @end enumerate
27986 @node Elaboration order
27987 @subsection Elaboration order
27988 @noindent
27989 The implementation can choose any elaboration order consistent with the unit
27990 dependency relationship.  This freedom means that some orders can result in
27991 Program_Error being raised due to an ``Access Before Elaboration'': an attempt
27992 to invoke a subprogram its body has been elaborated, or to instantiate a
27993 generic before the generic body has been elaborated.  By default GNAT
27994 attempts to choose a safe order (one that will not encounter access before
27995 elaboration problems) by implicitly inserting @code{Elaborate} or
27996 @code{Elaborate_All} pragmas where
27997 needed.  However, this can lead to the creation of elaboration circularities
27998 and a resulting rejection of the program by gnatbind.  This issue is
27999 thoroughly described in @ref{Elaboration Order Handling in GNAT}.
28000 In brief, there are several
28001 ways to deal with this situation:
28003 @itemize @bullet
28004 @item
28005 Modify the program to eliminate the circularities, e.g.@: by moving
28006 elaboration-time code into explicitly-invoked procedures
28007 @item
28008 Constrain the elaboration order by including explicit @code{Elaborate_Body} or
28009 @code{Elaborate} pragmas, and then inhibit the generation of implicit
28010 @code{Elaborate_All}
28011 pragmas either globally (as an effect of the @option{-gnatE} switch) or locally
28012 (by selectively suppressing elaboration checks via pragma
28013 @code{Suppress(Elaboration_Check)} when it is safe to do so).
28014 @end itemize
28016 @node Target-specific aspects
28017 @subsection Target-specific aspects
28018 @noindent
28019 Low-level applications need to deal with machine addresses, data
28020 representations, interfacing with assembler code, and similar issues.  If
28021 such an Ada 83 application is being ported to different target hardware (for
28022 example where the byte endianness has changed) then you will need to
28023 carefully examine the program logic; the porting effort will heavily depend
28024 on the robustness of the original design.  Moreover, Ada 95 (and thus
28025 Ada 2005) are sometimes
28026 incompatible with typical Ada 83 compiler practices regarding implicit
28027 packing, the meaning of the Size attribute, and the size of access values.
28028 GNAT's approach to these issues is described in @ref{Representation Clauses}.
28030 @node Compatibility with Other Ada Systems
28031 @section Compatibility with Other Ada Systems
28033 @noindent
28034 If programs avoid the use of implementation dependent and
28035 implementation defined features, as documented in the @cite{Ada
28036 Reference Manual}, there should be a high degree of portability between
28037 GNAT and other Ada systems.  The following are specific items which
28038 have proved troublesome in moving Ada 95 programs from GNAT to other Ada 95
28039 compilers, but do not affect porting code to GNAT@.
28040 (As of @value{NOW}, GNAT is the only compiler available for Ada 2005;
28041 the following issues may or may not arise for Ada 2005 programs
28042 when other compilers appear.)
28044 @table @emph
28045 @item Ada 83 Pragmas and Attributes
28046 Ada 95 compilers are allowed, but not required, to implement the missing
28047 Ada 83 pragmas and attributes that are no longer defined in Ada 95.
28048 GNAT implements all such pragmas and attributes, eliminating this as
28049 a compatibility concern, but some other Ada 95 compilers reject these
28050 pragmas and attributes.
28052 @item Specialized Needs Annexes
28053 GNAT implements the full set of special needs annexes.  At the
28054 current time, it is the only Ada 95 compiler to do so.  This means that
28055 programs making use of these features may not be portable to other Ada
28056 95 compilation systems.
28058 @item Representation Clauses
28059 Some other Ada 95 compilers implement only the minimal set of
28060 representation clauses required by the Ada 95 reference manual.  GNAT goes
28061 far beyond this minimal set, as described in the next section.
28062 @end table
28064 @node Representation Clauses
28065 @section Representation Clauses
28067 @noindent
28068 The Ada 83 reference manual was quite vague in describing both the minimal
28069 required implementation of representation clauses, and also their precise
28070 effects.  Ada 95 (and thus also Ada 2005) are much more explicit, but the
28071 minimal set of capabilities required is still quite limited.
28073 GNAT implements the full required set of capabilities in
28074 Ada 95 and Ada 2005, but also goes much further, and in particular
28075 an effort has been made to be compatible with existing Ada 83 usage to the
28076 greatest extent possible.
28078 A few cases exist in which Ada 83 compiler behavior is incompatible with
28079 the requirements in Ada 95 (and thus also Ada 2005).  These are instances of
28080 intentional or accidental dependence on specific implementation dependent
28081 characteristics of these Ada 83 compilers.  The following is a list of
28082 the cases most likely to arise in existing Ada 83 code.
28084 @table @emph
28085 @item Implicit Packing
28086 Some Ada 83 compilers allowed a Size specification to cause implicit
28087 packing of an array or record.  This could cause expensive implicit
28088 conversions for change of representation in the presence of derived
28089 types, and the Ada design intends to avoid this possibility.
28090 Subsequent AI's were issued to make it clear that such implicit
28091 change of representation in response to a Size clause is inadvisable,
28092 and this recommendation is represented explicitly in the Ada 95 (and Ada 2005)
28093 Reference Manuals as implementation advice that is followed by GNAT@.
28094 The problem will show up as an error
28095 message rejecting the size clause.  The fix is simply to provide
28096 the explicit pragma @code{Pack}, or for more fine tuned control, provide
28097 a Component_Size clause.
28099 @item Meaning of Size Attribute
28100 The Size attribute in Ada 95 (and Ada 2005) for discrete types is defined as
28101 the minimal number of bits required to hold values of the type.  For example,
28102 on a 32-bit machine, the size of @code{Natural} will typically be 31 and not
28103 32 (since no sign bit is required).  Some Ada 83 compilers gave 31, and
28104 some 32 in this situation.  This problem will usually show up as a compile
28105 time error, but not always.  It is a good idea to check all uses of the
28106 'Size attribute when porting Ada 83 code.  The GNAT specific attribute
28107 Object_Size can provide a useful way of duplicating the behavior of
28108 some Ada 83 compiler systems.
28110 @item Size of Access Types
28111 A common assumption in Ada 83 code is that an access type is in fact a pointer,
28112 and that therefore it will be the same size as a System.Address value.  This
28113 assumption is true for GNAT in most cases with one exception.  For the case of
28114 a pointer to an unconstrained array type (where the bounds may vary from one
28115 value of the access type to another), the default is to use a ``fat pointer'',
28116 which is represented as two separate pointers, one to the bounds, and one to
28117 the array.  This representation has a number of advantages, including improved
28118 efficiency.  However, it may cause some difficulties in porting existing Ada 83
28119 code which makes the assumption that, for example, pointers fit in 32 bits on
28120 a machine with 32-bit addressing.
28122 To get around this problem, GNAT also permits the use of ``thin pointers'' for
28123 access types in this case (where the designated type is an unconstrained array
28124 type).  These thin pointers are indeed the same size as a System.Address value.
28125 To specify a thin pointer, use a size clause for the type, for example:
28127 @smallexample @c ada
28128 type X is access all String;
28129 for X'Size use Standard'Address_Size;
28130 @end smallexample
28132 @noindent
28133 which will cause the type X to be represented using a single pointer.
28134 When using this representation, the bounds are right behind the array.
28135 This representation is slightly less efficient, and does not allow quite
28136 such flexibility in the use of foreign pointers or in using the
28137 Unrestricted_Access attribute to create pointers to non-aliased objects.
28138 But for any standard portable use of the access type it will work in
28139 a functionally correct manner and allow porting of existing code.
28140 Note that another way of forcing a thin pointer representation
28141 is to use a component size clause for the element size in an array,
28142 or a record representation clause for an access field in a record.
28143 @end table
28145 @ifclear vms
28146 @c This brief section is only in the non-VMS version
28147 @c The complete chapter on HP Ada is in the VMS version
28148 @node Compatibility with HP Ada 83
28149 @section Compatibility with HP Ada 83
28151 @noindent
28152 The VMS version of GNAT fully implements all the pragmas and attributes
28153 provided by HP Ada 83, as well as providing the standard HP Ada 83
28154 libraries, including Starlet.  In addition, data layouts and parameter
28155 passing conventions are highly compatible.  This means that porting
28156 existing HP Ada 83 code to GNAT in VMS systems should be easier than
28157 most other porting efforts.  The following are some of the most
28158 significant differences between GNAT and HP Ada 83.
28160 @table @emph
28161 @item Default floating-point representation
28162 In GNAT, the default floating-point format is IEEE, whereas in HP Ada 83,
28163 it is VMS format.  GNAT does implement the necessary pragmas
28164 (Long_Float, Float_Representation) for changing this default.
28166 @item System
28167 The package System in GNAT exactly corresponds to the definition in the
28168 Ada 95 reference manual, which means that it excludes many of the
28169 HP Ada 83 extensions.  However, a separate package Aux_DEC is provided
28170 that contains the additional definitions, and a special pragma,
28171 Extend_System allows this package to be treated transparently as an
28172 extension of package System.
28174 @item To_Address
28175 The definitions provided by Aux_DEC are exactly compatible with those
28176 in the HP Ada 83 version of System, with one exception.
28177 HP Ada provides the following declarations:
28179 @smallexample @c ada
28180 TO_ADDRESS (INTEGER)
28181 TO_ADDRESS (UNSIGNED_LONGWORD)
28182 TO_ADDRESS (@i{universal_integer})
28183 @end smallexample
28185 @noindent
28186 The version of TO_ADDRESS taking a @i{universal integer} argument is in fact
28187 an extension to Ada 83 not strictly compatible with the reference manual.
28188 In GNAT, we are constrained to be exactly compatible with the standard,
28189 and this means we cannot provide this capability.  In HP Ada 83, the
28190 point of this definition is to deal with a call like:
28192 @smallexample @c ada
28193 TO_ADDRESS (16#12777#);
28194 @end smallexample
28196 @noindent
28197 Normally, according to the Ada 83 standard, one would expect this to be
28198 ambiguous, since it matches both the INTEGER and UNSIGNED_LONGWORD forms
28199 of TO_ADDRESS@.  However, in HP Ada 83, there is no ambiguity, since the
28200 definition using @i{universal_integer} takes precedence.
28202 In GNAT, since the version with @i{universal_integer} cannot be supplied, it
28203 is not possible to be 100% compatible.  Since there are many programs using
28204 numeric constants for the argument to TO_ADDRESS, the decision in GNAT was
28205 to change the name of the function in the UNSIGNED_LONGWORD case, so the
28206 declarations provided in the GNAT version of AUX_Dec are:
28208 @smallexample @c ada
28209 function To_Address (X : Integer) return Address;
28210 pragma Pure_Function (To_Address);
28212 function To_Address_Long (X : Unsigned_Longword)
28213  return Address;
28214 pragma Pure_Function (To_Address_Long);
28215 @end smallexample
28217 @noindent
28218 This means that programs using TO_ADDRESS for UNSIGNED_LONGWORD must
28219 change the name to TO_ADDRESS_LONG@.
28221 @item Task_Id values
28222 The Task_Id values assigned will be different in the two systems, and GNAT
28223 does not provide a specified value for the Task_Id of the environment task,
28224 which in GNAT is treated like any other declared task.
28225 @end table
28227 @noindent
28228 For full details on these and other less significant compatibility issues,
28229 see appendix E of the HP publication entitled @cite{HP Ada, Technical
28230 Overview and Comparison on HP Platforms}.
28232 For GNAT running on other than VMS systems, all the HP Ada 83 pragmas and
28233 attributes are recognized, although only a subset of them can sensibly
28234 be implemented.  The description of pragmas in @ref{Implementation
28235 Defined Pragmas,,, gnat_rm, GNAT Reference Manual}
28236 indicates whether or not they are applicable to non-VMS systems.
28237 @end ifclear
28239 @ifset vms
28240 @node Transitioning to 64-Bit GNAT for OpenVMS
28241 @section Transitioning to 64-Bit @value{EDITION} for OpenVMS
28243 @noindent
28244 This section is meant to assist users of pre-2006 @value{EDITION}
28245 for Alpha OpenVMS who are transitioning to 64-bit @value{EDITION},
28246 the version of the GNAT technology supplied in 2006 and later for
28247 OpenVMS on both Alpha and I64.
28249 @menu
28250 * Introduction to transitioning::
28251 * Migration of 32 bit code::
28252 * Taking advantage of 64 bit addressing::
28253 * Technical details::
28254 @end menu
28256 @node Introduction to transitioning
28257 @subsection Introduction
28259 @noindent
28260 64-bit @value{EDITION} for Open VMS has been designed to meet
28261 three main goals:
28263 @enumerate
28264 @item
28265 Providing a full conforming implementation of Ada 95 and Ada 2005
28267 @item
28268 Allowing maximum backward compatibility, thus easing migration of existing
28269 Ada source code
28271 @item
28272 Supplying a path for exploiting the full 64-bit address range
28273 @end enumerate
28275 @noindent
28276 Ada's strong typing semantics has made it
28277 impractical to have different 32-bit and 64-bit modes. As soon as
28278 one object could possibly be outside the 32-bit address space, this
28279 would make it necessary for the @code{System.Address} type to be 64 bits.
28280 In particular, this would cause inconsistencies if 32-bit code is
28281 called from 64-bit code that raises an exception.
28283 This issue has been resolved by always using 64-bit addressing
28284 at the system level, but allowing for automatic conversions between
28285 32-bit and 64-bit addresses where required. Thus users who
28286 do not currently require 64-bit addressing capabilities, can
28287 recompile their code with only minimal changes (and indeed
28288 if the code is written in portable Ada, with no assumptions about
28289 the size of the @code{Address} type, then no changes at all are necessary).
28290 At the same time,
28291 this approach provides a simple, gradual upgrade path to future
28292 use of larger memories than available for 32-bit systems.
28293 Also, newly written applications or libraries will by default
28294 be fully compatible with future systems exploiting 64-bit
28295 addressing capabilities.
28297 @ref{Migration of 32 bit code}, will focus on porting applications
28298 that do not require more than 2 GB of
28299 addressable memory. This code will be referred to as
28300 @emph{32-bit code}.
28301 For applications intending to exploit the full 64-bit address space,
28302 @ref{Taking advantage of 64 bit addressing},
28303 will consider further changes that may be required.
28304 Such code will be referred to below as @emph{64-bit code}.
28306 @node Migration of 32 bit code
28307 @subsection Migration of 32-bit code
28309 @menu
28310 * Address types::
28311 * Access types and 32/64-bit allocation::
28312 * Unchecked conversions::
28313 * Predefined constants::
28314 * Interfacing with C::
28315 * 32/64-bit descriptors::
28316 * Experience with source compatibility::
28317 @end menu
28319 @node Address types
28320 @subsubsection Address types
28322 @noindent
28323 To solve the problem of mixing 64-bit and 32-bit addressing,
28324 while maintaining maximum backward compatibility, the following
28325 approach has been taken:
28327 @itemize @bullet
28328 @item
28329 @code{System.Address} always has a size of 64 bits
28330 @cindex @code{System.Address} size
28331 @cindex @code{Address} size
28333 @item
28334 @code{System.Short_Address} is a 32-bit subtype of @code{System.Address}
28335 @cindex @code{System.Short_Address} size
28336 @cindex @code{Short_Address} size
28337 @end itemize
28339 @noindent
28340 Since @code{System.Short_Address} is a subtype of @code{System.Address},
28341 a @code{Short_Address}
28342 may be used where an @code{Address} is required, and vice versa, without
28343 needing explicit type conversions.
28344 By virtue of the Open VMS parameter passing conventions,
28345 even imported
28346 and exported subprograms that have 32-bit address parameters are
28347 compatible with those that have 64-bit address parameters.
28348 (See @ref{Making code 64 bit clean} for details.)
28350 The areas that may need attention are those where record types have
28351 been defined that contain components of the type @code{System.Address}, and
28352 where objects of this type are passed to code expecting a record layout with
28353 32-bit addresses.
28355 Different compilers on different platforms cannot be
28356 expected to represent the same type in the same way,
28357 since alignment constraints
28358 and other system-dependent properties affect the compiler's decision.
28359 For that reason, Ada code
28360 generally uses representation clauses to specify the expected
28361 layout where required.
28363 If such a representation clause uses 32 bits for a component having
28364 the type @code{System.Address}, 64-bit @value{EDITION} for OpenVMS
28365 will detect that error and produce a specific diagnostic message.
28366 The developer should then determine whether the representation
28367 should be 64 bits or not and make either of two changes:
28368 change the size to 64 bits and leave the type as @code{System.Address}, or
28369 leave the size as 32 bits and change the type to @code{System.Short_Address}.
28370 Since @code{Short_Address} is a subtype of @code{Address}, no changes are
28371 required in any code setting or accessing the field; the compiler will
28372 automatically perform any needed conversions between address
28373 formats.
28375 @node Access types and 32/64-bit allocation
28376 @subsubsection Access types and 32/64-bit allocation
28377 @cindex 32-bit allocation
28378 @cindex 64-bit allocation
28380 @noindent
28381 By default, objects designated by access values are always allocated in
28382 the 64-bit address space, and access values themselves are represented
28383 in 64 bits.  If these defaults are not appropriate, and 32-bit allocation
28384 is required (for example if the address of an allocated object is assigned
28385 to a @code{Short_Address} variable), then several alternatives are available:
28387 @itemize @bullet
28388 @item
28389 A pool-specific access type (ie, an @w{Ada 83} access type, whose
28390 definition is @code{access T} versus @code{access all T} or
28391 @code{access constant T}), may be declared with a @code{'Size} representation
28392 clause that establishes the size as 32 bits.
28393 In such circumstances allocations for that type will
28394 be from the 32-bit heap.  Such a clause is not permitted
28395 for a general access type (declared with @code{access all} or
28396 @code{access constant}) as values of such types must be able to refer
28397 to any object of the designated type, including objects residing outside
28398 the 32-bit address range.  Existing @w{Ada 83} code will not contain such
28399 type definitions, however, since general access types were introduced
28400 in @w{Ada 95}.
28402 @item
28403 Switches for @command{GNAT BIND} control whether the internal GNAT
28404 allocation routine @code{__gnat_malloc} uses 64-bit or 32-bit allocations.
28405 @cindex @code{__gnat_malloc}
28406 The switches are respectively @option{-H64} (the default) and
28407 @option{-H32}.
28408 @cindex @option{-H32} (@command{gnatbind})
28409 @cindex @option{-H64} (@command{gnatbind})
28411 @item
28412 The environment variable (logical name) @code{GNAT$NO_MALLOC_64}
28413 @cindex @code{GNAT$NO_MALLOC_64} environment variable
28414 may be used to force @code{__gnat_malloc} to use 32-bit allocation.
28415 If this variable is left
28416 undefined, or defined as @code{"DISABLE"}, @code{"FALSE"}, or @code{"0"},
28417 then the default (64-bit) allocation is used.
28418 If defined as @code{"ENABLE"}, @code{"TRUE"}, or @code{"1"},
28419 then 32-bit allocation is used.  The gnatbind qualifiers described above
28420 override this logical name.
28422 @item
28423 A ^gcc switch^gcc switch^ for OpenVMS, @option{-mno-malloc64}, operates
28424 @cindex @option{-mno-malloc64} (^gcc^gcc^)
28425 at a low level to convert explicit calls to @code{malloc} and related
28426 functions from the C run-time library so that they perform allocations
28427 in the 32-bit heap.
28428 Since all internal allocations from GNAT use @code{__gnat_malloc},
28429 this switch is not required unless the program makes explicit calls on
28430 @code{malloc} (or related functions) from interfaced C code.
28431 @end itemize
28434 @node Unchecked conversions
28435 @subsubsection Unchecked conversions
28437 @noindent
28438 In the case of an @code{Unchecked_Conversion} where the source type is a
28439 64-bit access type or the type @code{System.Address}, and the target
28440 type is a 32-bit type, the compiler will generate a warning.
28441 Even though the generated code will still perform the required
28442 conversions, it is highly recommended in these cases to use
28443 respectively a 32-bit access type or @code{System.Short_Address}
28444 as the source type.
28446 @node Predefined constants
28447 @subsubsection Predefined constants
28449 @noindent
28450 The following table shows the correspondence between pre-2006 versions of
28451 @value{EDITION} on Alpha OpenVMS (``Old'') and 64-bit @value{EDITION}
28452 (``New''):
28454 @multitable {@code{System.Short_Memory_Size}} {2**32} {2**64}
28455 @item   @b{Constant}                     @tab @b{Old} @tab @b{New}
28456 @item   @code{System.Word_Size}          @tab 32      @tab 64
28457 @item   @code{System.Memory_Size}        @tab 2**32   @tab 2**64
28458 @item   @code{System.Short_Memory_Size}  @tab 2**32   @tab 2**32
28459 @item   @code{System.Address_Size}       @tab 32      @tab 64
28460 @end multitable
28462 @noindent
28463 If you need to refer to the specific
28464 memory size of a 32-bit implementation, instead of the
28465 actual memory size, use @code{System.Short_Memory_Size}
28466 rather than @code{System.Memory_Size}.
28467 Similarly, references to @code{System.Address_Size} may need
28468 to be replaced by @code{System.Short_Address'Size}.
28469 The program @command{gnatfind} may be useful for locating
28470 references to the above constants, so that you can verify that they
28471 are still correct.
28473 @node Interfacing with C
28474 @subsubsection Interfacing with C
28476 @noindent
28477 In order to minimize the impact of the transition to 64-bit addresses on
28478 legacy programs, some fundamental types in the @code{Interfaces.C}
28479 package hierarchy continue to be represented in 32 bits.
28480 These types are: @code{ptrdiff_t}, @code{size_t}, and @code{chars_ptr}.
28481 This eases integration with the default HP C layout choices, for example
28482 as found in the system routines in @code{DECC$SHR.EXE}.
28483 Because of this implementation choice, the type fully compatible with
28484 @code{chars_ptr} is now @code{Short_Address} and not @code{Address}.
28485 Depending on the context the compiler will issue a
28486 warning or an error when type @code{Address} is used, alerting the user to a
28487 potential problem. Otherwise 32-bit programs that use
28488 @code{Interfaces.C} should normally not require code modifications
28490 The other issue arising with C interfacing concerns pragma @code{Convention}.
28491 For VMS 64-bit systems, there is an issue of the appropriate default size
28492 of C convention pointers in the absence of an explicit size clause. The HP
28493 C compiler can choose either 32 or 64 bits depending on compiler options.
28494 GNAT chooses 32-bits rather than 64-bits in the default case where no size
28495 clause is given. This proves a better choice for porting 32-bit legacy
28496 applications. In order to have a 64-bit representation, it is necessary to
28497 specify a size representation clause. For example:
28499 @smallexample @c ada
28500 type int_star is access Interfaces.C.int;
28501 pragma Convention(C, int_star);
28502 for int_star'Size use 64;  -- Necessary to get 64 and not 32 bits
28503 @end smallexample
28505 @node 32/64-bit descriptors
28506 @subsubsection 32/64-bit descriptors
28508 @noindent
28509 By default, GNAT uses a 64-bit descriptor mechanism.  For an imported
28510 subprogram (i.e., a subprogram identified by pragma @code{Import_Function},
28511 @code{Import_Procedure}, or @code{Import_Valued_Procedure}) that specifies
28512 @code{Short_Descriptor} as its mechanism, a 32-bit descriptor is used.
28513 @cindex @code{Short_Descriptor} mechanism for imported subprograms
28515 If the configuration pragma @code{Short_Descriptors} is supplied, then
28516 all descriptors will be 32 bits.
28517 @cindex pragma @code{Short_Descriptors}
28519 @node Experience with source compatibility
28520 @subsubsection Experience with source compatibility
28522 @noindent
28523 The Security Server and STARLET on I64 provide an interesting ``test case''
28524 for source compatibility issues, since it is in such system code
28525 where assumptions about @code{Address} size might be expected to occur.
28526 Indeed, there were a small number of occasions in the Security Server
28527 file @file{jibdef.ads}
28528 where a representation clause for a record type specified
28529 32 bits for a component of type @code{Address}.
28530 All of these errors were detected by the compiler.
28531 The repair was obvious and immediate; to simply replace @code{Address} by
28532 @code{Short_Address}.
28534 In the case of STARLET, there were several record types that should
28535 have had representation clauses but did not.  In these record types
28536 there was an implicit assumption that an @code{Address} value occupied
28537 32 bits.
28538 These compiled without error, but their usage resulted in run-time error
28539 returns from STARLET system calls.
28540 Future GNAT technology enhancements may include a tool that detects and flags
28541 these sorts of potential source code porting problems.
28543 @c ****************************************
28544 @node Taking advantage of 64 bit addressing
28545 @subsection Taking advantage of 64-bit addressing
28547 @menu
28548 * Making code 64 bit clean::
28549 * Allocating memory from the 64 bit storage pool::
28550 * Restrictions on use of 64 bit objects::
28551 * STARLET and other predefined libraries::
28552 @end menu
28554 @node Making code 64 bit clean
28555 @subsubsection Making code 64-bit clean
28557 @noindent
28558 In order to prevent problems that may occur when (parts of) a
28559 system start using memory outside the 32-bit address range,
28560 we recommend some additional guidelines:
28562 @itemize @bullet
28563 @item
28564 For imported subprograms that take parameters of the
28565 type @code{System.Address}, ensure that these subprograms can
28566 indeed handle 64-bit addresses. If not, or when in doubt,
28567 change the subprogram declaration to specify
28568 @code{System.Short_Address} instead.
28570 @item
28571 Resolve all warnings related to size mismatches in
28572 unchecked conversions. Failing to do so causes
28573 erroneous execution if the source object is outside
28574 the 32-bit address space.
28576 @item
28577 (optional) Explicitly use the 32-bit storage pool
28578 for access types used in a 32-bit context, or use
28579 generic access types where possible
28580 (@pxref{Restrictions on use of 64 bit objects}).
28581 @end itemize
28583 @noindent
28584 If these rules are followed, the compiler will automatically insert
28585 any necessary checks to ensure that no addresses or access values
28586 passed to 32-bit code ever refer to objects outside the 32-bit
28587 address range.
28588 Any attempt to do this will raise @code{Constraint_Error}.
28590 @node Allocating memory from the 64 bit storage pool
28591 @subsubsection Allocating memory from the 64-bit storage pool
28593 @noindent
28594 By default, all allocations -- for both pool-specific and general
28595 access types -- use the 64-bit storage pool.  To override
28596 this default, for an individual access type or globally, see
28597 @ref{Access types and 32/64-bit allocation}.
28599 @node Restrictions on use of 64 bit objects
28600 @subsubsection Restrictions on use of 64-bit objects
28602 @noindent
28603 Taking the address of an object allocated from a 64-bit storage pool,
28604 and then passing this address to a subprogram expecting
28605 @code{System.Short_Address},
28606 or assigning it to a variable of type @code{Short_Address}, will cause
28607 @code{Constraint_Error} to be raised. In case the code is not 64-bit clean
28608 (@pxref{Making code 64 bit clean}), or checks are suppressed,
28609 no exception is raised and execution
28610 will become erroneous.
28612 @node STARLET and other predefined libraries
28613 @subsubsection STARLET and other predefined libraries
28615 @noindent
28616 All code that comes as part of GNAT is 64-bit clean, but the
28617 restrictions given in @ref{Restrictions on use of 64 bit objects},
28618 still apply. Look at the package
28619 specs to see in which contexts objects allocated
28620 in 64-bit address space are acceptable.
28622 @node Technical details
28623 @subsection Technical details
28625 @noindent
28626 64-bit @value{EDITION} for Open VMS takes advantage of the freedom given in the
28627 Ada standard with respect to the type of @code{System.Address}. Previous
28628 versions of @value{EDITION} have defined this type as private and implemented it as a
28629 modular type.
28631 In order to allow defining @code{System.Short_Address} as a proper subtype,
28632 and to match the implicit sign extension in parameter passing,
28633 in 64-bit @value{EDITION} for Open VMS, @code{System.Address} is defined as a
28634 visible (i.e., non-private) integer type.
28635 Standard operations on the type, such as the binary operators ``+'', ``-'',
28636 etc., that take @code{Address} operands and return an @code{Address} result,
28637 have been hidden by declaring these
28638 @code{abstract}, a feature introduced in Ada 95 that helps avoid the potential
28639 ambiguities that would otherwise result from overloading.
28640 (Note that, although @code{Address} is a visible integer type,
28641 good programming practice dictates against exploiting the type's
28642 integer properties such as literals, since this will compromise
28643 code portability.)
28645 Defining @code{Address} as a visible integer type helps achieve
28646 maximum compatibility for existing Ada code,
28647 without sacrificing the capabilities of the 64-bit architecture.
28648 @end ifset
28650 @c ************************************************
28651 @node Microsoft Windows Topics
28652 @appendix Microsoft Windows Topics
28653 @cindex Windows NT
28654 @cindex Windows 95
28655 @cindex Windows 98
28657 @noindent
28658 This chapter describes topics that are specific to the Microsoft Windows
28659 platforms (NT, 2000, and XP Professional).
28661 @menu
28662 @ifclear FSFEDITION
28663 * Installing from the Command Line::
28664 @end ifclear
28665 * Using GNAT on Windows::
28666 * Using a network installation of GNAT::
28667 * CONSOLE and WINDOWS subsystems::
28668 * Temporary Files::
28669 * Mixed-Language Programming on Windows::
28670 * Windows Calling Conventions::
28671 * Introduction to Dynamic Link Libraries (DLLs)::
28672 * Using DLLs with GNAT::
28673 * Building DLLs with GNAT Project files::
28674 * Building DLLs with GNAT::
28675 * Building DLLs with gnatdll::
28676 * GNAT and Windows Resources::
28677 * Debugging a DLL::
28678 * Setting Stack Size from gnatlink::
28679 * Setting Heap Size from gnatlink::
28680 @end menu
28682 @ifclear FSFEDITION
28683 @node Installing from the Command Line
28684 @section Installing from the Command Line
28685 @cindex Batch installation
28686 @cindex Silent installation
28687 @cindex Unassisted installation
28689 @noindent
28690 By default the @value{EDITION} installers display a GUI that prompts the user
28691 to enter installation path and similar information, and guide him through the
28692 installation process. It is also possible to perform silent installations
28693 using the command-line interface.
28695 In order to install one of the @value{EDITION} installers from the command
28696 line you should pass parameter @code{/S} (and, optionally,
28697 @code{/D=<directory>}) as command-line arguments.
28699 @ifset PROEDITION
28700 For example, for an unattended installation of
28701 @value{EDITION} 7.0.2 into the default directory
28702 @code{C:\GNATPRO\7.0.2} you would run:
28704 @smallexample
28705 gnatpro-7.0.2-i686-pc-mingw32-bin.exe /S
28706 @end smallexample
28708 To install into a custom directory, say, @code{C:\TOOLS\GNATPRO\7.0.2}:
28710 @smallexample
28711 gnatpro-7.0.2-i686-pc-mingw32-bin /S /D=C:\TOOLS\GNATPRO\7.0.2
28712 @end smallexample
28713 @end ifset
28715 @ifset GPLEDITION
28716 For example, for an unattended installation of
28717 @value{EDITION} 2012 into @code{C:\GNAT\2012}:
28719 @smallexample
28720 gnat-gpl-2012-i686-pc-mingw32-bin /S /D=C:\GNAT\2012
28721 @end smallexample
28722 @end ifset
28724 You can use the same syntax for all installers.
28726 Note that unattended installations don't modify system path, nor create file
28727 associations, so such activities need to be done by hand.
28728 @end ifclear
28730 @node Using GNAT on Windows
28731 @section Using GNAT on Windows
28733 @noindent
28734 One of the strengths of the GNAT technology is that its tool set
28735 (@command{gcc}, @command{gnatbind}, @command{gnatlink}, @command{gnatmake}, the
28736 @code{gdb} debugger, etc.) is used in the same way regardless of the
28737 platform.
28739 On Windows this tool set is complemented by a number of Microsoft-specific
28740 tools that have been provided to facilitate interoperability with Windows
28741 when this is required. With these tools:
28743 @itemize @bullet
28745 @item
28746 You can build applications using the @code{CONSOLE} or @code{WINDOWS}
28747 subsystems.
28749 @item
28750 You can use any Dynamically Linked Library (DLL) in your Ada code (both
28751 relocatable and non-relocatable DLLs are supported).
28753 @item
28754 You can build Ada DLLs for use in other applications. These applications
28755 can be written in a language other than Ada (e.g., C, C++, etc). Again both
28756 relocatable and non-relocatable Ada DLLs are supported.
28758 @item
28759 You can include Windows resources in your Ada application.
28761 @item
28762 You can use or create COM/DCOM objects.
28763 @end itemize
28765 @noindent
28766 Immediately below are listed all known general GNAT-for-Windows restrictions.
28767 Other restrictions about specific features like Windows Resources and DLLs
28768 are listed in separate sections below.
28770 @itemize @bullet
28772 @item
28773 It is not possible to use @code{GetLastError} and @code{SetLastError}
28774 when tasking, protected records, or exceptions are used. In these
28775 cases, in order to implement Ada semantics, the GNAT run-time system
28776 calls certain Win32 routines that set the last error variable to 0 upon
28777 success. It should be possible to use @code{GetLastError} and
28778 @code{SetLastError} when tasking, protected record, and exception
28779 features are not used, but it is not guaranteed to work.
28781 @item
28782 It is not possible to link against Microsoft C++ libraries except for
28783 import libraries. Interfacing must be done by the mean of DLLs.
28785 @item
28786 It is possible to link against Microsoft C libraries. Yet the preferred
28787 solution is to use C/C++ compiler that comes with @value{EDITION}, since it
28788 doesn't require having two different development environments and makes the
28789 inter-language debugging experience smoother.
28791 @item
28792 When the compilation environment is located on FAT32 drives, users may
28793 experience recompilations of the source files that have not changed if
28794 Daylight Saving Time (DST) state has changed since the last time files
28795 were compiled. NTFS drives do not have this problem.
28797 @item
28798 No components of the GNAT toolset use any entries in the Windows
28799 registry. The only entries that can be created are file associations and
28800 PATH settings, provided the user has chosen to create them at installation
28801 time, as well as some minimal book-keeping information needed to correctly
28802 uninstall or integrate different GNAT products.
28803 @end itemize
28805 @node Using a network installation of GNAT
28806 @section Using a network installation of GNAT
28808 @noindent
28809 Make sure the system on which GNAT is installed is accessible from the
28810 current machine, i.e., the install location is shared over the network.
28811 Shared resources are accessed on Windows by means of UNC paths, which
28812 have the format @code{\\server\sharename\path}
28814 In order to use such a network installation, simply add the UNC path of the
28815 @file{bin} directory of your GNAT installation in front of your PATH. For
28816 example, if GNAT is installed in @file{\GNAT} directory of a share location
28817 called @file{c-drive} on a machine @file{LOKI}, the following command will
28818 make it available:
28820 @code{@ @ @ path \\loki\c-drive\gnat\bin;%path%}
28822 Be aware that every compilation using the network installation results in the
28823 transfer of large amounts of data across the network and will likely cause
28824 serious performance penalty.
28826 @node CONSOLE and WINDOWS subsystems
28827 @section CONSOLE and WINDOWS subsystems
28828 @cindex CONSOLE Subsystem
28829 @cindex WINDOWS Subsystem
28830 @cindex -mwindows
28832 @noindent
28833 There are two main subsystems under Windows. The @code{CONSOLE} subsystem
28834 (which is the default subsystem) will always create a console when
28835 launching the application. This is not something desirable when the
28836 application has a Windows GUI. To get rid of this console the
28837 application must be using the @code{WINDOWS} subsystem. To do so
28838 the @option{-mwindows} linker option must be specified.
28840 @smallexample
28841 $ gnatmake winprog -largs -mwindows
28842 @end smallexample
28844 @node Temporary Files
28845 @section Temporary Files
28846 @cindex Temporary files
28848 @noindent
28849 It is possible to control where temporary files gets created by setting
28850 the @env{TMP} environment variable. The file will be created:
28852 @itemize
28853 @item Under the directory pointed to by the @env{TMP} environment variable if
28854 this directory exists.
28856 @item Under @file{c:\temp}, if the @env{TMP} environment variable is not
28857 set (or not pointing to a directory) and if this directory exists.
28859 @item Under the current working directory otherwise.
28860 @end itemize
28862 @noindent
28863 This allows you to determine exactly where the temporary
28864 file will be created. This is particularly useful in networked
28865 environments where you may not have write access to some
28866 directories.
28868 @node Mixed-Language Programming on Windows
28869 @section Mixed-Language Programming on Windows
28871 @noindent
28872 Developing pure Ada applications on Windows is no different than on
28873 other GNAT-supported platforms. However, when developing or porting an
28874 application that contains a mix of Ada and C/C++, the choice of your
28875 Windows C/C++ development environment conditions your overall
28876 interoperability strategy.
28878 If you use @command{gcc} or Microsoft C to compile the non-Ada part of
28879 your application, there are no Windows-specific restrictions that
28880 affect the overall interoperability with your Ada code. If you do want
28881 to use the Microsoft tools for your C++ code, you have two choices:
28883 @enumerate
28884 @item
28885 Encapsulate your C++ code in a DLL to be linked with your Ada
28886 application. In this case, use the Microsoft or whatever environment to
28887 build the DLL and use GNAT to build your executable
28888 (@pxref{Using DLLs with GNAT}).
28890 @item
28891 Or you can encapsulate your Ada code in a DLL to be linked with the
28892 other part of your application. In this case, use GNAT to build the DLL
28893 (@pxref{Building DLLs with GNAT Project files}) and use the Microsoft
28894 or whatever environment to build your executable.
28895 @end enumerate
28897 In addition to the description about C main in
28898 @pxref{Mixed Language Programming} section, if the C main uses a
28899 stand-alone library it is required on x86-windows to
28900 setup the SEH context. For this the C main must looks like this:
28902 @smallexample
28903 /* main.c */
28904 extern void adainit (void);
28905 extern void adafinal (void);
28906 extern void __gnat_initialize(void*);
28907 extern void call_to_ada (void);
28909 int main (int argc, char *argv[])
28911   int SEH [2];
28913   /* Initialize the SEH context */
28914   __gnat_initialize (&SEH);
28916   adainit();
28918   /* Then call Ada services in the stand-alone library */
28920   call_to_ada();
28922   adafinal();
28924 @end smallexample
28926 Note that this is not needed on x86_64-windows where the Windows
28927 native SEH support is used.
28929 @node Windows Calling Conventions
28930 @section Windows Calling Conventions
28931 @findex Stdcall
28932 @findex APIENTRY
28934 This section pertain only to Win32. On Win64 there is a single native
28935 calling convention. All convention specifiers are ignored on this
28936 platform.
28938 @menu
28939 * C Calling Convention::
28940 * Stdcall Calling Convention::
28941 * Win32 Calling Convention::
28942 * DLL Calling Convention::
28943 @end menu
28945 @noindent
28946 When a subprogram @code{F} (caller) calls a subprogram @code{G}
28947 (callee), there are several ways to push @code{G}'s parameters on the
28948 stack and there are several possible scenarios to clean up the stack
28949 upon @code{G}'s return. A calling convention is an agreed upon software
28950 protocol whereby the responsibilities between the caller (@code{F}) and
28951 the callee (@code{G}) are clearly defined. Several calling conventions
28952 are available for Windows:
28954 @itemize @bullet
28955 @item
28956 @code{C} (Microsoft defined)
28958 @item
28959 @code{Stdcall} (Microsoft defined)
28961 @item
28962 @code{Win32} (GNAT specific)
28964 @item
28965 @code{DLL} (GNAT specific)
28966 @end itemize
28968 @node C Calling Convention
28969 @subsection @code{C} Calling Convention
28971 @noindent
28972 This is the default calling convention used when interfacing to C/C++
28973 routines compiled with either @command{gcc} or Microsoft Visual C++.
28975 In the @code{C} calling convention subprogram parameters are pushed on the
28976 stack by the caller from right to left. The caller itself is in charge of
28977 cleaning up the stack after the call. In addition, the name of a routine
28978 with @code{C} calling convention is mangled by adding a leading underscore.
28980 The name to use on the Ada side when importing (or exporting) a routine
28981 with @code{C} calling convention is the name of the routine. For
28982 instance the C function:
28984 @smallexample
28985 int get_val (long);
28986 @end smallexample
28988 @noindent
28989 should be imported from Ada as follows:
28991 @smallexample @c ada
28992 @group
28993 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
28994 pragma Import (C, Get_Val, External_Name => "get_val");
28995 @end group
28996 @end smallexample
28998 @noindent
28999 Note that in this particular case the @code{External_Name} parameter could
29000 have been omitted since, when missing, this parameter is taken to be the
29001 name of the Ada entity in lower case. When the @code{Link_Name} parameter
29002 is missing, as in the above example, this parameter is set to be the
29003 @code{External_Name} with a leading underscore.
29005 When importing a variable defined in C, you should always use the @code{C}
29006 calling convention unless the object containing the variable is part of a
29007 DLL (in which case you should use the @code{Stdcall} calling
29008 convention, @pxref{Stdcall Calling Convention}).
29010 @node Stdcall Calling Convention
29011 @subsection @code{Stdcall} Calling Convention
29013 @noindent
29014 This convention, which was the calling convention used for Pascal
29015 programs, is used by Microsoft for all the routines in the Win32 API for
29016 efficiency reasons. It must be used to import any routine for which this
29017 convention was specified.
29019 In the @code{Stdcall} calling convention subprogram parameters are pushed
29020 on the stack by the caller from right to left. The callee (and not the
29021 caller) is in charge of cleaning the stack on routine exit. In addition,
29022 the name of a routine with @code{Stdcall} calling convention is mangled by
29023 adding a leading underscore (as for the @code{C} calling convention) and a
29024 trailing @code{@@}@code{@var{nn}}, where @var{nn} is the overall size (in
29025 bytes) of the parameters passed to the routine.
29027 The name to use on the Ada side when importing a C routine with a
29028 @code{Stdcall} calling convention is the name of the C routine. The leading
29029 underscore and trailing @code{@@}@code{@var{nn}} are added automatically by
29030 the compiler. For instance the Win32 function:
29032 @smallexample
29033 @b{APIENTRY} int get_val (long);
29034 @end smallexample
29036 @noindent
29037 should be imported from Ada as follows:
29039 @smallexample @c ada
29040 @group
29041 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
29042 pragma Import (Stdcall, Get_Val);
29043 --  On the x86 a long is 4 bytes, so the Link_Name is "_get_val@@4"
29044 @end group
29045 @end smallexample
29047 @noindent
29048 As for the @code{C} calling convention, when the @code{External_Name}
29049 parameter is missing, it is taken to be the name of the Ada entity in lower
29050 case. If instead of writing the above import pragma you write:
29052 @smallexample @c ada
29053 @group
29054 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
29055 pragma Import (Stdcall, Get_Val, External_Name => "retrieve_val");
29056 @end group
29057 @end smallexample
29059 @noindent
29060 then the imported routine is @code{_retrieve_val@@4}. However, if instead
29061 of specifying the @code{External_Name} parameter you specify the
29062 @code{Link_Name} as in the following example:
29064 @smallexample @c ada
29065 @group
29066 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
29067 pragma Import (Stdcall, Get_Val, Link_Name => "retrieve_val");
29068 @end group
29069 @end smallexample
29071 @noindent
29072 then the imported routine is @code{retrieve_val}, that is, there is no
29073 decoration at all. No leading underscore and no Stdcall suffix
29074 @code{@@}@code{@var{nn}}.
29076 @noindent
29077 This is especially important as in some special cases a DLL's entry
29078 point name lacks a trailing @code{@@}@code{@var{nn}} while the exported
29079 name generated for a call has it.
29081 @noindent
29082 It is also possible to import variables defined in a DLL by using an
29083 import pragma for a variable. As an example, if a DLL contains a
29084 variable defined as:
29086 @smallexample
29087 int my_var;
29088 @end smallexample
29090 @noindent
29091 then, to access this variable from Ada you should write:
29093 @smallexample @c ada
29094 @group
29095 My_Var : Interfaces.C.int;
29096 pragma Import (Stdcall, My_Var);
29097 @end group
29098 @end smallexample
29100 @noindent
29101 Note that to ease building cross-platform bindings this convention
29102 will be handled as a @code{C} calling convention on non-Windows platforms.
29104 @node Win32 Calling Convention
29105 @subsection @code{Win32} Calling Convention
29107 @noindent
29108 This convention, which is GNAT-specific is fully equivalent to the
29109 @code{Stdcall} calling convention described above.
29111 @node DLL Calling Convention
29112 @subsection @code{DLL} Calling Convention
29114 @noindent
29115 This convention, which is GNAT-specific is fully equivalent to the
29116 @code{Stdcall} calling convention described above.
29118 @node Introduction to Dynamic Link Libraries (DLLs)
29119 @section Introduction to Dynamic Link Libraries (DLLs)
29120 @findex DLL
29122 @noindent
29123 A Dynamically Linked Library (DLL) is a library that can be shared by
29124 several applications running under Windows. A DLL can contain any number of
29125 routines and variables.
29127 One advantage of DLLs is that you can change and enhance them without
29128 forcing all the applications that depend on them to be relinked or
29129 recompiled. However, you should be aware than all calls to DLL routines are
29130 slower since, as you will understand below, such calls are indirect.
29132 To illustrate the remainder of this section, suppose that an application
29133 wants to use the services of a DLL @file{API.dll}. To use the services
29134 provided by @file{API.dll} you must statically link against the DLL or
29135 an import library which contains a jump table with an entry for each
29136 routine and variable exported by the DLL. In the Microsoft world this
29137 import library is called @file{API.lib}. When using GNAT this import
29138 library is called either @file{libAPI.dll.a}, @file{libapi.dll.a},
29139 @file{libAPI.a} or @file{libapi.a} (names are case insensitive).
29141 After you have linked your application with the DLL or the import library
29142 and you run your application, here is what happens:
29144 @enumerate
29145 @item
29146 Your application is loaded into memory.
29148 @item
29149 The DLL @file{API.dll} is mapped into the address space of your
29150 application. This means that:
29152 @itemize @bullet
29153 @item
29154 The DLL will use the stack of the calling thread.
29156 @item
29157 The DLL will use the virtual address space of the calling process.
29159 @item
29160 The DLL will allocate memory from the virtual address space of the calling
29161 process.
29163 @item
29164 Handles (pointers) can be safely exchanged between routines in the DLL
29165 routines and routines in the application using the DLL.
29166 @end itemize
29168 @item
29169 The entries in the jump table (from the import library @file{libAPI.dll.a}
29170 or @file{API.lib} or automatically created when linking against a DLL)
29171 which is part of your application are initialized with the addresses
29172 of the routines and variables in @file{API.dll}.
29174 @item
29175 If present in @file{API.dll}, routines @code{DllMain} or
29176 @code{DllMainCRTStartup} are invoked. These routines typically contain
29177 the initialization code needed for the well-being of the routines and
29178 variables exported by the DLL.
29179 @end enumerate
29181 @noindent
29182 There is an additional point which is worth mentioning. In the Windows
29183 world there are two kind of DLLs: relocatable and non-relocatable
29184 DLLs. Non-relocatable DLLs can only be loaded at a very specific address
29185 in the target application address space. If the addresses of two
29186 non-relocatable DLLs overlap and these happen to be used by the same
29187 application, a conflict will occur and the application will run
29188 incorrectly. Hence, when possible, it is always preferable to use and
29189 build relocatable DLLs. Both relocatable and non-relocatable DLLs are
29190 supported by GNAT. Note that the @option{-s} linker option (see GNU Linker
29191 User's Guide) removes the debugging symbols from the DLL but the DLL can
29192 still be relocated.
29194 As a side note, an interesting difference between Microsoft DLLs and
29195 Unix shared libraries, is the fact that on most Unix systems all public
29196 routines are exported by default in a Unix shared library, while under
29197 Windows it is possible (but not required) to list exported routines in
29198 a definition file (@pxref{The Definition File}).
29200 @node Using DLLs with GNAT
29201 @section Using DLLs with GNAT
29203 @menu
29204 * Creating an Ada Spec for the DLL Services::
29205 * Creating an Import Library::
29206 @end menu
29208 @noindent
29209 To use the services of a DLL, say @file{API.dll}, in your Ada application
29210 you must have:
29212 @enumerate
29213 @item
29214 The Ada spec for the routines and/or variables you want to access in
29215 @file{API.dll}. If not available this Ada spec must be built from the C/C++
29216 header files provided with the DLL.
29218 @item
29219 The import library (@file{libAPI.dll.a} or @file{API.lib}). As previously
29220 mentioned an import library is a statically linked library containing the
29221 import table which will be filled at load time to point to the actual
29222 @file{API.dll} routines. Sometimes you don't have an import library for the
29223 DLL you want to use. The following sections will explain how to build
29224 one. Note that this is optional.
29226 @item
29227 The actual DLL, @file{API.dll}.
29228 @end enumerate
29230 @noindent
29231 Once you have all the above, to compile an Ada application that uses the
29232 services of @file{API.dll} and whose main subprogram is @code{My_Ada_App},
29233 you simply issue the command
29235 @smallexample
29236 $ gnatmake my_ada_app -largs -lAPI
29237 @end smallexample
29239 @noindent
29240 The argument @option{-largs -lAPI} at the end of the @command{gnatmake} command
29241 tells the GNAT linker to look for an import library. The linker will
29242 look for a library name in this specific order:
29244 @enumerate
29245 @item @file{libAPI.dll.a}
29246 @item @file{API.dll.a}
29247 @item @file{libAPI.a}
29248 @item @file{API.lib}
29249 @item @file{libAPI.dll}
29250 @item @file{API.dll}
29251 @end enumerate
29253 The first three are the GNU style import libraries. The third is the
29254 Microsoft style import libraries. The last two are the actual DLL names.
29256 Note that if the Ada package spec for @file{API.dll} contains the
29257 following pragma
29259 @smallexample @c ada
29260 pragma Linker_Options ("-lAPI");
29261 @end smallexample
29263 @noindent
29264 you do not have to add @option{-largs -lAPI} at the end of the
29265 @command{gnatmake} command.
29267 If any one of the items above is missing you will have to create it
29268 yourself. The following sections explain how to do so using as an
29269 example a fictitious DLL called @file{API.dll}.
29271 @node Creating an Ada Spec for the DLL Services
29272 @subsection Creating an Ada Spec for the DLL Services
29274 @noindent
29275 A DLL typically comes with a C/C++ header file which provides the
29276 definitions of the routines and variables exported by the DLL. The Ada
29277 equivalent of this header file is a package spec that contains definitions
29278 for the imported entities. If the DLL you intend to use does not come with
29279 an Ada spec you have to generate one such spec yourself. For example if
29280 the header file of @file{API.dll} is a file @file{api.h} containing the
29281 following two definitions:
29283 @smallexample
29284 @group
29285 @cartouche
29286 int some_var;
29287 int get (char *);
29288 @end cartouche
29289 @end group
29290 @end smallexample
29292 @noindent
29293 then the equivalent Ada spec could be:
29295 @smallexample @c ada
29296 @group
29297 @cartouche
29298 with Interfaces.C.Strings;
29299 package API is
29300    use Interfaces;
29302    Some_Var : C.int;
29303    function Get (Str : C.Strings.Chars_Ptr) return C.int;
29305 private
29306    pragma Import (C, Get);
29307    pragma Import (DLL, Some_Var);
29308 end API;
29309 @end cartouche
29310 @end group
29311 @end smallexample
29313 @node Creating an Import Library
29314 @subsection Creating an Import Library
29315 @cindex Import library
29317 @menu
29318 * The Definition File::
29319 * GNAT-Style Import Library::
29320 * Microsoft-Style Import Library::
29321 @end menu
29323 @noindent
29324 If a Microsoft-style import library @file{API.lib} or a GNAT-style
29325 import library @file{libAPI.dll.a} or @file{libAPI.a} is available
29326 with @file{API.dll} you can skip this section. You can also skip this
29327 section if @file{API.dll} or @file{libAPI.dll} is built with GNU tools
29328 as in this case it is possible to link directly against the
29329 DLL. Otherwise read on.
29331 @node The Definition File
29332 @subsubsection The Definition File
29333 @cindex Definition file
29334 @findex .def
29336 @noindent
29337 As previously mentioned, and unlike Unix systems, the list of symbols
29338 that are exported from a DLL must be provided explicitly in Windows.
29339 The main goal of a definition file is precisely that: list the symbols
29340 exported by a DLL. A definition file (usually a file with a @code{.def}
29341 suffix) has the following structure:
29343 @smallexample
29344 @group
29345 @cartouche
29346 @r{[}LIBRARY @var{name}@r{]}
29347 @r{[}DESCRIPTION @var{string}@r{]}
29348 EXPORTS
29349    @var{symbol1}
29350    @var{symbol2}
29351    @dots{}
29352 @end cartouche
29353 @end group
29354 @end smallexample
29356 @table @code
29357 @item LIBRARY @var{name}
29358 This section, which is optional, gives the name of the DLL.
29360 @item DESCRIPTION @var{string}
29361 This section, which is optional, gives a description string that will be
29362 embedded in the import library.
29364 @item EXPORTS
29365 This section gives the list of exported symbols (procedures, functions or
29366 variables). For instance in the case of @file{API.dll} the @code{EXPORTS}
29367 section of @file{API.def} looks like:
29369 @smallexample
29370 @group
29371 @cartouche
29372 EXPORTS
29373    some_var
29374    get
29375 @end cartouche
29376 @end group
29377 @end smallexample
29378 @end table
29380 @noindent
29381 Note that you must specify the correct suffix (@code{@@}@code{@var{nn}})
29382 (@pxref{Windows Calling Conventions}) for a Stdcall
29383 calling convention function in the exported symbols list.
29385 @noindent
29386 There can actually be other sections in a definition file, but these
29387 sections are not relevant to the discussion at hand.
29389 @node GNAT-Style Import Library
29390 @subsubsection GNAT-Style Import Library
29392 @noindent
29393 To create a static import library from @file{API.dll} with the GNAT tools
29394 you should proceed as follows:
29396 @enumerate
29397 @item
29398 Create the definition file @file{API.def} (@pxref{The Definition File}).
29399 For that use the @code{dll2def} tool as follows:
29401 @smallexample
29402 $ dll2def API.dll > API.def
29403 @end smallexample
29405 @noindent
29406 @code{dll2def} is a very simple tool: it takes as input a DLL and prints
29407 to standard output the list of entry points in the DLL. Note that if
29408 some routines in the DLL have the @code{Stdcall} convention
29409 (@pxref{Windows Calling Conventions}) with stripped @code{@@}@var{nn}
29410 suffix then you'll have to edit @file{api.def} to add it, and specify
29411 @option{-k} to @command{gnatdll} when creating the import library.
29413 @noindent
29414 Here are some hints to find the right @code{@@}@var{nn} suffix.
29416 @enumerate
29417 @item
29418 If you have the Microsoft import library (.lib), it is possible to get
29419 the right symbols by using Microsoft @code{dumpbin} tool (see the
29420 corresponding Microsoft documentation for further details).
29422 @smallexample
29423 $ dumpbin /exports api.lib
29424 @end smallexample
29426 @item
29427 If you have a message about a missing symbol at link time the compiler
29428 tells you what symbol is expected. You just have to go back to the
29429 definition file and add the right suffix.
29430 @end enumerate
29432 @item
29433 Build the import library @code{libAPI.dll.a}, using @code{gnatdll}
29434 (@pxref{Using gnatdll}) as follows:
29436 @smallexample
29437 $ gnatdll -e API.def -d API.dll
29438 @end smallexample
29440 @noindent
29441 @code{gnatdll} takes as input a definition file @file{API.def} and the
29442 name of the DLL containing the services listed in the definition file
29443 @file{API.dll}. The name of the static import library generated is
29444 computed from the name of the definition file as follows: if the
29445 definition file name is @var{xyz}@code{.def}, the import library name will
29446 be @code{lib}@var{xyz}@code{.a}. Note that in the previous example option
29447 @option{-e} could have been removed because the name of the definition
29448 file (before the ``@code{.def}'' suffix) is the same as the name of the
29449 DLL (@pxref{Using gnatdll} for more information about @code{gnatdll}).
29450 @end enumerate
29452 @node Microsoft-Style Import Library
29453 @subsubsection Microsoft-Style Import Library
29455 @noindent
29456 With GNAT you can either use a GNAT-style or Microsoft-style import
29457 library. A Microsoft import library is needed only if you plan to make an
29458 Ada DLL available to applications developed with Microsoft
29459 tools (@pxref{Mixed-Language Programming on Windows}).
29461 To create a Microsoft-style import library for @file{API.dll} you
29462 should proceed as follows:
29464 @enumerate
29465 @item
29466 Create the definition file @file{API.def} from the DLL. For this use either
29467 the @code{dll2def} tool as described above or the Microsoft @code{dumpbin}
29468 tool (see the corresponding Microsoft documentation for further details).
29470 @item
29471 Build the actual import library using Microsoft's @code{lib} utility:
29473 @smallexample
29474 $ lib -machine:IX86 -def:API.def -out:API.lib
29475 @end smallexample
29477 @noindent
29478 If you use the above command the definition file @file{API.def} must
29479 contain a line giving the name of the DLL:
29481 @smallexample
29482 LIBRARY      "API"
29483 @end smallexample
29485 @noindent
29486 See the Microsoft documentation for further details about the usage of
29487 @code{lib}.
29488 @end enumerate
29490 @node Building DLLs with GNAT Project files
29491 @section Building DLLs with GNAT Project files
29492 @cindex DLLs, building
29494 @noindent
29495 There is nothing specific to Windows in the build process.
29496 @pxref{Library Projects}.
29498 @noindent
29499 Due to a system limitation, it is not possible under Windows to create threads
29500 when inside the @code{DllMain} routine which is used for auto-initialization
29501 of shared libraries, so it is not possible to have library level tasks in SALs.
29503 @node Building DLLs with GNAT
29504 @section Building DLLs with GNAT
29505 @cindex DLLs, building
29507 @noindent
29508 This section explain how to build DLLs using the GNAT built-in DLL
29509 support. With the following procedure it is straight forward to build
29510 and use DLLs with GNAT.
29512 @enumerate
29514 @item building object files
29516 The first step is to build all objects files that are to be included
29517 into the DLL. This is done by using the standard @command{gnatmake} tool.
29519 @item building the DLL
29521 To build the DLL you must use @command{gcc}'s @option{-shared} and
29522 @option{-shared-libgcc} options. It is quite simple to use this method:
29524 @smallexample
29525 $ gcc -shared -shared-libgcc -o api.dll obj1.o obj2.o @dots{}
29526 @end smallexample
29528 It is important to note that in this case all symbols found in the
29529 object files are automatically exported. It is possible to restrict
29530 the set of symbols to export by passing to @command{gcc} a definition
29531 file, @pxref{The Definition File}. For example:
29533 @smallexample
29534 $ gcc -shared -shared-libgcc -o api.dll api.def obj1.o obj2.o @dots{}
29535 @end smallexample
29537 If you use a definition file you must export the elaboration procedures
29538 for every package that required one. Elaboration procedures are named
29539 using the package name followed by "_E".
29541 @item preparing DLL to be used
29543 For the DLL to be used by client programs the bodies must be hidden
29544 from it and the .ali set with read-only attribute. This is very important
29545 otherwise GNAT will recompile all packages and will not actually use
29546 the code in the DLL. For example:
29548 @smallexample
29549 $ mkdir apilib
29550 $ copy *.ads *.ali api.dll apilib
29551 $ attrib +R apilib\*.ali
29552 @end smallexample
29554 @end enumerate
29556 At this point it is possible to use the DLL by directly linking
29557 against it. Note that you must use the GNAT shared runtime when using
29558 GNAT shared libraries. This is achieved by using @option{-shared} binder's
29559 option.
29561 @smallexample
29562 $ gnatmake main -Iapilib -bargs -shared -largs -Lapilib -lAPI
29563 @end smallexample
29565 @node Building DLLs with gnatdll
29566 @section Building DLLs with gnatdll
29567 @cindex DLLs, building
29569 @menu
29570 * Limitations When Using Ada DLLs from Ada::
29571 * Exporting Ada Entities::
29572 * Ada DLLs and Elaboration::
29573 * Ada DLLs and Finalization::
29574 * Creating a Spec for Ada DLLs::
29575 * Creating the Definition File::
29576 * Using gnatdll::
29577 @end menu
29579 @noindent
29580 Note that it is preferred to use GNAT Project files
29581 (@pxref{Building DLLs with GNAT Project files}) or the built-in GNAT
29582 DLL support (@pxref{Building DLLs with GNAT}) or to build DLLs.
29584 This section explains how to build DLLs containing Ada code using
29585 @code{gnatdll}. These DLLs will be referred to as Ada DLLs in the
29586 remainder of this section.
29588 The steps required to build an Ada DLL that is to be used by Ada as well as
29589 non-Ada applications are as follows:
29591 @enumerate
29592 @item
29593 You need to mark each Ada @i{entity} exported by the DLL with a @code{C} or
29594 @code{Stdcall} calling convention to avoid any Ada name mangling for the
29595 entities exported by the DLL (@pxref{Exporting Ada Entities}). You can
29596 skip this step if you plan to use the Ada DLL only from Ada applications.
29598 @item
29599 Your Ada code must export an initialization routine which calls the routine
29600 @code{adainit} generated by @command{gnatbind} to perform the elaboration of
29601 the Ada code in the DLL (@pxref{Ada DLLs and Elaboration}). The initialization
29602 routine exported by the Ada DLL must be invoked by the clients of the DLL
29603 to initialize the DLL.
29605 @item
29606 When useful, the DLL should also export a finalization routine which calls
29607 routine @code{adafinal} generated by @command{gnatbind} to perform the
29608 finalization of the Ada code in the DLL (@pxref{Ada DLLs and Finalization}).
29609 The finalization routine exported by the Ada DLL must be invoked by the
29610 clients of the DLL when the DLL services are no further needed.
29612 @item
29613 You must provide a spec for the services exported by the Ada DLL in each
29614 of the programming languages to which you plan to make the DLL available.
29616 @item
29617 You must provide a definition file listing the exported entities
29618 (@pxref{The Definition File}).
29620 @item
29621 Finally you must use @code{gnatdll} to produce the DLL and the import
29622 library (@pxref{Using gnatdll}).
29623 @end enumerate
29625 @noindent
29626 Note that a relocatable DLL stripped using the @code{strip}
29627 binutils tool will not be relocatable anymore. To build a DLL without
29628 debug information pass @code{-largs -s} to @code{gnatdll}. This
29629 restriction does not apply to a DLL built using a Library Project.
29630 @pxref{Library Projects}.
29632 @node Limitations When Using Ada DLLs from Ada
29633 @subsection Limitations When Using Ada DLLs from Ada
29635 @noindent
29636 When using Ada DLLs from Ada applications there is a limitation users
29637 should be aware of. Because on Windows the GNAT run time is not in a DLL of
29638 its own, each Ada DLL includes a part of the GNAT run time. Specifically,
29639 each Ada DLL includes the services of the GNAT run time that are necessary
29640 to the Ada code inside the DLL. As a result, when an Ada program uses an
29641 Ada DLL there are two independent GNAT run times: one in the Ada DLL and
29642 one in the main program.
29644 It is therefore not possible to exchange GNAT run-time objects between the
29645 Ada DLL and the main Ada program. Example of GNAT run-time objects are file
29646 handles (e.g.@: @code{Text_IO.File_Type}), tasks types, protected objects
29647 types, etc.
29649 It is completely safe to exchange plain elementary, array or record types,
29650 Windows object handles, etc.
29652 @node Exporting Ada Entities
29653 @subsection Exporting Ada Entities
29654 @cindex Export table
29656 @noindent
29657 Building a DLL is a way to encapsulate a set of services usable from any
29658 application. As a result, the Ada entities exported by a DLL should be
29659 exported with the @code{C} or @code{Stdcall} calling conventions to avoid
29660 any Ada name mangling. As an example here is an Ada package
29661 @code{API}, spec and body, exporting two procedures, a function, and a
29662 variable:
29664 @smallexample @c ada
29665 @group
29666 @cartouche
29667 with Interfaces.C; use Interfaces;
29668 package API is
29669    Count : C.int := 0;
29670    function Factorial (Val : C.int) return C.int;
29672    procedure Initialize_API;
29673    procedure Finalize_API;
29674    --  Initialization & Finalization routines. More in the next section.
29675 private
29676    pragma Export (C, Initialize_API);
29677    pragma Export (C, Finalize_API);
29678    pragma Export (C, Count);
29679    pragma Export (C, Factorial);
29680 end API;
29681 @end cartouche
29682 @end group
29683 @end smallexample
29685 @smallexample @c ada
29686 @group
29687 @cartouche
29688 package body API is
29689    function Factorial (Val : C.int) return C.int is
29690       Fact : C.int := 1;
29691    begin
29692       Count := Count + 1;
29693       for K in 1 .. Val loop
29694          Fact := Fact * K;
29695       end loop;
29696       return Fact;
29697    end Factorial;
29699    procedure Initialize_API is
29700       procedure Adainit;
29701       pragma Import (C, Adainit);
29702    begin
29703       Adainit;
29704    end Initialize_API;
29706    procedure Finalize_API is
29707       procedure Adafinal;
29708       pragma Import (C, Adafinal);
29709    begin
29710       Adafinal;
29711    end Finalize_API;
29712 end API;
29713 @end cartouche
29714 @end group
29715 @end smallexample
29717 @noindent
29718 If the Ada DLL you are building will only be used by Ada applications
29719 you do not have to export Ada entities with a @code{C} or @code{Stdcall}
29720 convention. As an example, the previous package could be written as
29721 follows:
29723 @smallexample @c ada
29724 @group
29725 @cartouche
29726 package API is
29727    Count : Integer := 0;
29728    function Factorial (Val : Integer) return Integer;
29730    procedure Initialize_API;
29731    procedure Finalize_API;
29732    --  Initialization and Finalization routines.
29733 end API;
29734 @end cartouche
29735 @end group
29736 @end smallexample
29738 @smallexample @c ada
29739 @group
29740 @cartouche
29741 package body API is
29742    function Factorial (Val : Integer) return Integer is
29743       Fact : Integer := 1;
29744    begin
29745       Count := Count + 1;
29746       for K in 1 .. Val loop
29747          Fact := Fact * K;
29748       end loop;
29749       return Fact;
29750    end Factorial;
29752    @dots{}
29753    --  The remainder of this package body is unchanged.
29754 end API;
29755 @end cartouche
29756 @end group
29757 @end smallexample
29759 @noindent
29760 Note that if you do not export the Ada entities with a @code{C} or
29761 @code{Stdcall} convention you will have to provide the mangled Ada names
29762 in the definition file of the Ada DLL
29763 (@pxref{Creating the Definition File}).
29765 @node Ada DLLs and Elaboration
29766 @subsection Ada DLLs and Elaboration
29767 @cindex DLLs and elaboration
29769 @noindent
29770 The DLL that you are building contains your Ada code as well as all the
29771 routines in the Ada library that are needed by it. The first thing a
29772 user of your DLL must do is elaborate the Ada code
29773 (@pxref{Elaboration Order Handling in GNAT}).
29775 To achieve this you must export an initialization routine
29776 (@code{Initialize_API} in the previous example), which must be invoked
29777 before using any of the DLL services. This elaboration routine must call
29778 the Ada elaboration routine @code{adainit} generated by the GNAT binder
29779 (@pxref{Binding with Non-Ada Main Programs}). See the body of
29780 @code{Initialize_Api} for an example. Note that the GNAT binder is
29781 automatically invoked during the DLL build process by the @code{gnatdll}
29782 tool (@pxref{Using gnatdll}).
29784 When a DLL is loaded, Windows systematically invokes a routine called
29785 @code{DllMain}. It would therefore be possible to call @code{adainit}
29786 directly from @code{DllMain} without having to provide an explicit
29787 initialization routine. Unfortunately, it is not possible to call
29788 @code{adainit} from the @code{DllMain} if your program has library level
29789 tasks because access to the @code{DllMain} entry point is serialized by
29790 the system (that is, only a single thread can execute ``through'' it at a
29791 time), which means that the GNAT run time will deadlock waiting for the
29792 newly created task to complete its initialization.
29794 @node Ada DLLs and Finalization
29795 @subsection Ada DLLs and Finalization
29796 @cindex DLLs and finalization
29798 @noindent
29799 When the services of an Ada DLL are no longer needed, the client code should
29800 invoke the DLL finalization routine, if available. The DLL finalization
29801 routine is in charge of releasing all resources acquired by the DLL. In the
29802 case of the Ada code contained in the DLL, this is achieved by calling
29803 routine @code{adafinal} generated by the GNAT binder
29804 (@pxref{Binding with Non-Ada Main Programs}).
29805 See the body of @code{Finalize_Api} for an
29806 example. As already pointed out the GNAT binder is automatically invoked
29807 during the DLL build process by the @code{gnatdll} tool
29808 (@pxref{Using gnatdll}).
29810 @node Creating a Spec for Ada DLLs
29811 @subsection Creating a Spec for Ada DLLs
29813 @noindent
29814 To use the services exported by the Ada DLL from another programming
29815 language (e.g.@: C), you have to translate the specs of the exported Ada
29816 entities in that language. For instance in the case of @code{API.dll},
29817 the corresponding C header file could look like:
29819 @smallexample
29820 @group
29821 @cartouche
29822 extern int *_imp__count;
29823 #define count (*_imp__count)
29824 int factorial (int);
29825 @end cartouche
29826 @end group
29827 @end smallexample
29829 @noindent
29830 It is important to understand that when building an Ada DLL to be used by
29831 other Ada applications, you need two different specs for the packages
29832 contained in the DLL: one for building the DLL and the other for using
29833 the DLL. This is because the @code{DLL} calling convention is needed to
29834 use a variable defined in a DLL, but when building the DLL, the variable
29835 must have either the @code{Ada} or @code{C} calling convention. As an
29836 example consider a DLL comprising the following package @code{API}:
29838 @smallexample @c ada
29839 @group
29840 @cartouche
29841 package API is
29842    Count : Integer := 0;
29843    @dots{}
29844    --  Remainder of the package omitted.
29845 end API;
29846 @end cartouche
29847 @end group
29848 @end smallexample
29850 @noindent
29851 After producing a DLL containing package @code{API}, the spec that
29852 must be used to import @code{API.Count} from Ada code outside of the
29853 DLL is:
29855 @smallexample @c ada
29856 @group
29857 @cartouche
29858 package API is
29859    Count : Integer;
29860    pragma Import (DLL, Count);
29861 end API;
29862 @end cartouche
29863 @end group
29864 @end smallexample
29866 @node Creating the Definition File
29867 @subsection Creating the Definition File
29869 @noindent
29870 The definition file is the last file needed to build the DLL. It lists
29871 the exported symbols. As an example, the definition file for a DLL
29872 containing only package @code{API} (where all the entities are exported
29873 with a @code{C} calling convention) is:
29875 @smallexample
29876 @group
29877 @cartouche
29878 EXPORTS
29879     count
29880     factorial
29881     finalize_api
29882     initialize_api
29883 @end cartouche
29884 @end group
29885 @end smallexample
29887 @noindent
29888 If the @code{C} calling convention is missing from package @code{API},
29889 then the definition file contains the mangled Ada names of the above
29890 entities, which in this case are:
29892 @smallexample
29893 @group
29894 @cartouche
29895 EXPORTS
29896     api__count
29897     api__factorial
29898     api__finalize_api
29899     api__initialize_api
29900 @end cartouche
29901 @end group
29902 @end smallexample
29904 @node Using gnatdll
29905 @subsection Using @code{gnatdll}
29906 @findex gnatdll
29908 @menu
29909 * gnatdll Example::
29910 * gnatdll behind the Scenes::
29911 * Using dlltool::
29912 @end menu
29914 @noindent
29915 @code{gnatdll} is a tool to automate the DLL build process once all the Ada
29916 and non-Ada sources that make up your DLL have been compiled.
29917 @code{gnatdll} is actually in charge of two distinct tasks: build the
29918 static import library for the DLL and the actual DLL. The form of the
29919 @code{gnatdll} command is
29921 @smallexample
29922 @cartouche
29923 @c $ gnatdll @ovar{switches} @var{list-of-files} @r{[}-largs @var{opts}@r{]}
29924 @c Expanding @ovar macro inline (explanation in macro def comments)
29925 $ gnatdll @r{[}@var{switches}@r{]} @var{list-of-files} @r{[}-largs @var{opts}@r{]}
29926 @end cartouche
29927 @end smallexample
29929 @noindent
29930 where @var{list-of-files} is a list of ALI and object files. The object
29931 file list must be the exact list of objects corresponding to the non-Ada
29932 sources whose services are to be included in the DLL. The ALI file list
29933 must be the exact list of ALI files for the corresponding Ada sources
29934 whose services are to be included in the DLL. If @var{list-of-files} is
29935 missing, only the static import library is generated.
29937 @noindent
29938 You may specify any of the following switches to @code{gnatdll}:
29940 @table @code
29941 @c @item -a@ovar{address}
29942 @c Expanding @ovar macro inline (explanation in macro def comments)
29943 @item -a@r{[}@var{address}@r{]}
29944 @cindex @option{-a} (@code{gnatdll})
29945 Build a non-relocatable DLL at @var{address}. If @var{address} is not
29946 specified the default address @var{0x11000000} will be used. By default,
29947 when this switch is missing, @code{gnatdll} builds relocatable DLL. We
29948 advise the reader to build relocatable DLL.
29950 @item -b @var{address}
29951 @cindex @option{-b} (@code{gnatdll})
29952 Set the relocatable DLL base address. By default the address is
29953 @code{0x11000000}.
29955 @item -bargs @var{opts}
29956 @cindex @option{-bargs} (@code{gnatdll})
29957 Binder options. Pass @var{opts} to the binder.
29959 @item -d @var{dllfile}
29960 @cindex @option{-d} (@code{gnatdll})
29961 @var{dllfile} is the name of the DLL. This switch must be present for
29962 @code{gnatdll} to do anything. The name of the generated import library is
29963 obtained algorithmically from @var{dllfile} as shown in the following
29964 example: if @var{dllfile} is @code{xyz.dll}, the import library name is
29965 @code{libxyz.dll.a}. The name of the definition file to use (if not specified
29966 by option @option{-e}) is obtained algorithmically from @var{dllfile}
29967 as shown in the following example:
29968 if @var{dllfile} is @code{xyz.dll}, the definition
29969 file used is @code{xyz.def}.
29971 @item -e @var{deffile}
29972 @cindex @option{-e} (@code{gnatdll})
29973 @var{deffile} is the name of the definition file.
29975 @item -g
29976 @cindex @option{-g} (@code{gnatdll})
29977 Generate debugging information. This information is stored in the object
29978 file and copied from there to the final DLL file by the linker,
29979 where it can be read by the debugger. You must use the
29980 @option{-g} switch if you plan on using the debugger or the symbolic
29981 stack traceback.
29983 @item -h
29984 @cindex @option{-h} (@code{gnatdll})
29985 Help mode. Displays @code{gnatdll} switch usage information.
29987 @item -Idir
29988 @cindex @option{-I} (@code{gnatdll})
29989 Direct @code{gnatdll} to search the @var{dir} directory for source and
29990 object files needed to build the DLL.
29991 (@pxref{Search Paths and the Run-Time Library (RTL)}).
29993 @item -k
29994 @cindex @option{-k} (@code{gnatdll})
29995 Removes the @code{@@}@var{nn} suffix from the import library's exported
29996 names, but keeps them for the link names. You must specify this
29997 option if you want to use a @code{Stdcall} function in a DLL for which
29998 the @code{@@}@var{nn} suffix has been removed. This is the case for most
29999 of the Windows NT DLL for example. This option has no effect when
30000 @option{-n} option is specified.
30002 @item -l @var{file}
30003 @cindex @option{-l} (@code{gnatdll})
30004 The list of ALI and object files used to build the DLL are listed in
30005 @var{file}, instead of being given in the command line. Each line in
30006 @var{file} contains the name of an ALI or object file.
30008 @item -n
30009 @cindex @option{-n} (@code{gnatdll})
30010 No Import. Do not create the import library.
30012 @item -q
30013 @cindex @option{-q} (@code{gnatdll})
30014 Quiet mode. Do not display unnecessary messages.
30016 @item -v
30017 @cindex @option{-v} (@code{gnatdll})
30018 Verbose mode. Display extra information.
30020 @item -largs @var{opts}
30021 @cindex @option{-largs} (@code{gnatdll})
30022 Linker options. Pass @var{opts} to the linker.
30023 @end table
30025 @node gnatdll Example
30026 @subsubsection @code{gnatdll} Example
30028 @noindent
30029 As an example the command to build a relocatable DLL from @file{api.adb}
30030 once @file{api.adb} has been compiled and @file{api.def} created is
30032 @smallexample
30033 $ gnatdll -d api.dll api.ali
30034 @end smallexample
30036 @noindent
30037 The above command creates two files: @file{libapi.dll.a} (the import
30038 library) and @file{api.dll} (the actual DLL). If you want to create
30039 only the DLL, just type:
30041 @smallexample
30042 $ gnatdll -d api.dll -n api.ali
30043 @end smallexample
30045 @noindent
30046 Alternatively if you want to create just the import library, type:
30048 @smallexample
30049 $ gnatdll -d api.dll
30050 @end smallexample
30052 @node gnatdll behind the Scenes
30053 @subsubsection @code{gnatdll} behind the Scenes
30055 @noindent
30056 This section details the steps involved in creating a DLL. @code{gnatdll}
30057 does these steps for you. Unless you are interested in understanding what
30058 goes on behind the scenes, you should skip this section.
30060 We use the previous example of a DLL containing the Ada package @code{API},
30061 to illustrate the steps necessary to build a DLL. The starting point is a
30062 set of objects that will make up the DLL and the corresponding ALI
30063 files. In the case of this example this means that @file{api.o} and
30064 @file{api.ali} are available. To build a relocatable DLL, @code{gnatdll} does
30065 the following:
30067 @enumerate
30068 @item
30069 @code{gnatdll} builds the base file (@file{api.base}). A base file gives
30070 the information necessary to generate relocation information for the
30071 DLL.
30073 @smallexample
30074 @group
30075 $ gnatbind -n api
30076 $ gnatlink api -o api.jnk -mdll -Wl,--base-file,api.base
30077 @end group
30078 @end smallexample
30080 @noindent
30081 In addition to the base file, the @command{gnatlink} command generates an
30082 output file @file{api.jnk} which can be discarded. The @option{-mdll} switch
30083 asks @command{gnatlink} to generate the routines @code{DllMain} and
30084 @code{DllMainCRTStartup} that are called by the Windows loader when the DLL
30085 is loaded into memory.
30087 @item
30088 @code{gnatdll} uses @code{dlltool} (@pxref{Using dlltool}) to build the
30089 export table (@file{api.exp}). The export table contains the relocation
30090 information in a form which can be used during the final link to ensure
30091 that the Windows loader is able to place the DLL anywhere in memory.
30093 @smallexample
30094 @group
30095 $ dlltool --dllname api.dll --def api.def --base-file api.base \
30096           --output-exp api.exp
30097 @end group
30098 @end smallexample
30100 @item
30101 @code{gnatdll} builds the base file using the new export table. Note that
30102 @command{gnatbind} must be called once again since the binder generated file
30103 has been deleted during the previous call to @command{gnatlink}.
30105 @smallexample
30106 @group
30107 $ gnatbind -n api
30108 $ gnatlink api -o api.jnk api.exp -mdll
30109       -Wl,--base-file,api.base
30110 @end group
30111 @end smallexample
30113 @item
30114 @code{gnatdll} builds the new export table using the new base file and
30115 generates the DLL import library @file{libAPI.dll.a}.
30117 @smallexample
30118 @group
30119 $ dlltool --dllname api.dll --def api.def --base-file api.base \
30120           --output-exp api.exp --output-lib libAPI.a
30121 @end group
30122 @end smallexample
30124 @item
30125 Finally @code{gnatdll} builds the relocatable DLL using the final export
30126 table.
30128 @smallexample
30129 @group
30130 $ gnatbind -n api
30131 $ gnatlink api api.exp -o api.dll -mdll
30132 @end group
30133 @end smallexample
30134 @end enumerate
30136 @node Using dlltool
30137 @subsubsection Using @code{dlltool}
30139 @noindent
30140 @code{dlltool} is the low-level tool used by @code{gnatdll} to build
30141 DLLs and static import libraries. This section summarizes the most
30142 common @code{dlltool} switches. The form of the @code{dlltool} command
30145 @smallexample
30146 @c $ dlltool @ovar{switches}
30147 @c Expanding @ovar macro inline (explanation in macro def comments)
30148 $ dlltool @r{[}@var{switches}@r{]}
30149 @end smallexample
30151 @noindent
30152 @code{dlltool} switches include:
30154 @table @option
30155 @item --base-file @var{basefile}
30156 @cindex @option{--base-file} (@command{dlltool})
30157 Read the base file @var{basefile} generated by the linker. This switch
30158 is used to create a relocatable DLL.
30160 @item --def @var{deffile}
30161 @cindex @option{--def} (@command{dlltool})
30162 Read the definition file.
30164 @item --dllname @var{name}
30165 @cindex @option{--dllname} (@command{dlltool})
30166 Gives the name of the DLL. This switch is used to embed the name of the
30167 DLL in the static import library generated by @code{dlltool} with switch
30168 @option{--output-lib}.
30170 @item -k
30171 @cindex @option{-k} (@command{dlltool})
30172 Kill @code{@@}@var{nn} from exported names
30173 (@pxref{Windows Calling Conventions}
30174 for a discussion about @code{Stdcall}-style symbols.
30176 @item --help
30177 @cindex @option{--help} (@command{dlltool})
30178 Prints the @code{dlltool} switches with a concise description.
30180 @item --output-exp @var{exportfile}
30181 @cindex @option{--output-exp} (@command{dlltool})
30182 Generate an export file @var{exportfile}. The export file contains the
30183 export table (list of symbols in the DLL) and is used to create the DLL.
30185 @item --output-lib @var{libfile}
30186 @cindex @option{--output-lib} (@command{dlltool})
30187 Generate a static import library @var{libfile}.
30189 @item -v
30190 @cindex @option{-v} (@command{dlltool})
30191 Verbose mode.
30193 @item --as @var{assembler-name}
30194 @cindex @option{--as} (@command{dlltool})
30195 Use @var{assembler-name} as the assembler. The default is @code{as}.
30196 @end table
30198 @node GNAT and Windows Resources
30199 @section GNAT and Windows Resources
30200 @cindex Resources, windows
30202 @menu
30203 * Building Resources::
30204 * Compiling Resources::
30205 * Using Resources::
30206 @end menu
30208 @noindent
30209 Resources are an easy way to add Windows specific objects to your
30210 application. The objects that can be added as resources include:
30212 @itemize @bullet
30213 @item menus
30215 @item accelerators
30217 @item dialog boxes
30219 @item string tables
30221 @item bitmaps
30223 @item cursors
30225 @item icons
30227 @item fonts
30229 @item version information
30230 @end itemize
30232 For example, a version information resource can be defined as follow and
30233 embedded into an executable or DLL:
30235 A version information resource can be used to embed information into an
30236 executable or a DLL. These information can be viewed using the file properties
30237 from the Windows Explorer. Here is an example of a version information
30238 resource:
30240 @smallexample
30241 @group
30242 1 VERSIONINFO
30243 FILEVERSION     1,0,0,0
30244 PRODUCTVERSION  1,0,0,0
30245 BEGIN
30246   BLOCK "StringFileInfo"
30247   BEGIN
30248     BLOCK "080904E4"
30249     BEGIN
30250       VALUE "CompanyName", "My Company Name"
30251       VALUE "FileDescription", "My application"
30252       VALUE "FileVersion", "1.0"
30253       VALUE "InternalName", "my_app"
30254       VALUE "LegalCopyright", "My Name"
30255       VALUE "OriginalFilename", "my_app.exe"
30256       VALUE "ProductName", "My App"
30257       VALUE "ProductVersion", "1.0"
30258     END
30259   END
30261   BLOCK "VarFileInfo"
30262   BEGIN
30263     VALUE "Translation", 0x809, 1252
30264   END
30266 @end group
30267 @end smallexample
30269 The value @code{0809} (langID) is for the U.K English language and
30270 @code{04E4} (charsetID), which is equal to @code{1252} decimal, for
30271 multilingual.
30273 @noindent
30274 This section explains how to build, compile and use resources. Note that this
30275 section does not cover all resource objects, for a complete description see
30276 the corresponding Microsoft documentation.
30278 @node Building Resources
30279 @subsection Building Resources
30280 @cindex Resources, building
30282 @noindent
30283 A resource file is an ASCII file. By convention resource files have an
30284 @file{.rc} extension.
30285 The easiest way to build a resource file is to use Microsoft tools
30286 such as @code{imagedit.exe} to build bitmaps, icons and cursors and
30287 @code{dlgedit.exe} to build dialogs.
30288 It is always possible to build an @file{.rc} file yourself by writing a
30289 resource script.
30291 It is not our objective to explain how to write a resource file. A
30292 complete description of the resource script language can be found in the
30293 Microsoft documentation.
30295 @node Compiling Resources
30296 @subsection Compiling Resources
30297 @findex rc
30298 @findex windres
30299 @cindex Resources, compiling
30301 @noindent
30302 This section describes how to build a GNAT-compatible (COFF) object file
30303 containing the resources. This is done using the Resource Compiler
30304 @code{windres} as follows:
30306 @smallexample
30307 $ windres -i myres.rc -o myres.o
30308 @end smallexample
30310 @noindent
30311 By default @code{windres} will run @command{gcc} to preprocess the @file{.rc}
30312 file. You can specify an alternate preprocessor (usually named
30313 @file{cpp.exe}) using the @code{windres} @option{--preprocessor}
30314 parameter. A list of all possible options may be obtained by entering
30315 the command @code{windres} @option{--help}.
30317 It is also possible to use the Microsoft resource compiler @code{rc.exe}
30318 to produce a @file{.res} file (binary resource file). See the
30319 corresponding Microsoft documentation for further details. In this case
30320 you need to use @code{windres} to translate the @file{.res} file to a
30321 GNAT-compatible object file as follows:
30323 @smallexample
30324 $ windres -i myres.res -o myres.o
30325 @end smallexample
30327 @node Using Resources
30328 @subsection Using Resources
30329 @cindex Resources, using
30331 @noindent
30332 To include the resource file in your program just add the
30333 GNAT-compatible object file for the resource(s) to the linker
30334 arguments. With @command{gnatmake} this is done by using the @option{-largs}
30335 option:
30337 @smallexample
30338 $ gnatmake myprog -largs myres.o
30339 @end smallexample
30341 @node Debugging a DLL
30342 @section Debugging a DLL
30343 @cindex DLL debugging
30345 @menu
30346 * Program and DLL Both Built with GCC/GNAT::
30347 * Program Built with Foreign Tools and DLL Built with GCC/GNAT::
30348 @end menu
30350 @noindent
30351 Debugging a DLL is similar to debugging a standard program. But
30352 we have to deal with two different executable parts: the DLL and the
30353 program that uses it. We have the following four possibilities:
30355 @enumerate 1
30356 @item
30357 The program and the DLL are built with @code{GCC/GNAT}.
30358 @item
30359 The program is built with foreign tools and the DLL is built with
30360 @code{GCC/GNAT}.
30361 @item
30362 The program is built with @code{GCC/GNAT} and the DLL is built with
30363 foreign tools.
30364 @end enumerate
30366 @noindent
30367 In this section we address only cases one and two above.
30368 There is no point in trying to debug
30369 a DLL with @code{GNU/GDB}, if there is no GDB-compatible debugging
30370 information in it. To do so you must use a debugger compatible with the
30371 tools suite used to build the DLL.
30373 @node Program and DLL Both Built with GCC/GNAT
30374 @subsection Program and DLL Both Built with GCC/GNAT
30376 @noindent
30377 This is the simplest case. Both the DLL and the program have @code{GDB}
30378 compatible debugging information. It is then possible to break anywhere in
30379 the process. Let's suppose here that the main procedure is named
30380 @code{ada_main} and that in the DLL there is an entry point named
30381 @code{ada_dll}.
30383 @noindent
30384 The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) and
30385 program must have been built with the debugging information (see GNAT -g
30386 switch). Here are the step-by-step instructions for debugging it:
30388 @enumerate 1
30389 @item Launch @code{GDB} on the main program.
30391 @smallexample
30392 $ gdb -nw ada_main
30393 @end smallexample
30395 @item Start the program and stop at the beginning of the main procedure
30397 @smallexample
30398 (gdb) start
30399 @end smallexample
30401 @noindent
30402 This step is required to be able to set a breakpoint inside the DLL. As long
30403 as the program is not run, the DLL is not loaded. This has the
30404 consequence that the DLL debugging information is also not loaded, so it is not
30405 possible to set a breakpoint in the DLL.
30407 @item Set a breakpoint inside the DLL
30409 @smallexample
30410 (gdb) break ada_dll
30411 (gdb) cont
30412 @end smallexample
30414 @end enumerate
30416 @noindent
30417 At this stage a breakpoint is set inside the DLL. From there on
30418 you can use the standard approach to debug the whole program
30419 (@pxref{Running and Debugging Ada Programs}).
30421 @ignore
30422 @c This used to work, probably because the DLLs were non-relocatable
30423 @c keep this section around until the problem is sorted out.
30425 To break on the @code{DllMain} routine it is not possible to follow
30426 the procedure above. At the time the program stop on @code{ada_main}
30427 the @code{DllMain} routine as already been called. Either you can use
30428 the procedure below @pxref{Debugging the DLL Directly} or this procedure:
30430 @enumerate 1
30431 @item Launch @code{GDB} on the main program.
30433 @smallexample
30434 $ gdb ada_main
30435 @end smallexample
30437 @item Load DLL symbols
30439 @smallexample
30440 (gdb) add-sym api.dll
30441 @end smallexample
30443 @item Set a breakpoint inside the DLL
30445 @smallexample
30446 (gdb) break ada_dll.adb:45
30447 @end smallexample
30449 Note that at this point it is not possible to break using the routine symbol
30450 directly as the program is not yet running. The solution is to break
30451 on the proper line (break in @file{ada_dll.adb} line 45).
30453 @item Start the program
30455 @smallexample
30456 (gdb) run
30457 @end smallexample
30459 @end enumerate
30460 @end ignore
30462 @node Program Built with Foreign Tools and DLL Built with GCC/GNAT
30463 @subsection Program Built with Foreign Tools and DLL Built with GCC/GNAT
30465 @menu
30466 * Debugging the DLL Directly::
30467 * Attaching to a Running Process::
30468 @end menu
30470 @noindent
30471 In this case things are slightly more complex because it is not possible to
30472 start the main program and then break at the beginning to load the DLL and the
30473 associated DLL debugging information. It is not possible to break at the
30474 beginning of the program because there is no @code{GDB} debugging information,
30475 and therefore there is no direct way of getting initial control. This
30476 section addresses this issue by describing some methods that can be used
30477 to break somewhere in the DLL to debug it.
30479 @noindent
30480 First suppose that the main procedure is named @code{main} (this is for
30481 example some C code built with Microsoft Visual C) and that there is a
30482 DLL named @code{test.dll} containing an Ada entry point named
30483 @code{ada_dll}.
30485 @noindent
30486 The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) must have
30487 been built with debugging information (see GNAT -g option).
30489 @node Debugging the DLL Directly
30490 @subsubsection Debugging the DLL Directly
30492 @enumerate 1
30493 @item
30494 Find out the executable starting address
30496 @smallexample
30497 $ objdump --file-header main.exe
30498 @end smallexample
30500 The starting address is reported on the last line. For example:
30502 @smallexample
30503 main.exe:     file format pei-i386
30504 architecture: i386, flags 0x0000010a:
30505 EXEC_P, HAS_DEBUG, D_PAGED
30506 start address 0x00401010
30507 @end smallexample
30509 @item
30510 Launch the debugger on the executable.
30512 @smallexample
30513 $ gdb main.exe
30514 @end smallexample
30516 @item
30517 Set a breakpoint at the starting address, and launch the program.
30519 @smallexample
30520 $ (gdb) break *0x00401010
30521 $ (gdb) run
30522 @end smallexample
30524 The program will stop at the given address.
30526 @item
30527 Set a breakpoint on a DLL subroutine.
30529 @smallexample
30530 (gdb) break ada_dll.adb:45
30531 @end smallexample
30533 Or if you want to break using a symbol on the DLL, you need first to
30534 select the Ada language (language used by the DLL).
30536 @smallexample
30537 (gdb) set language ada
30538 (gdb) break ada_dll
30539 @end smallexample
30541 @item
30542 Continue the program.
30544 @smallexample
30545 (gdb) cont
30546 @end smallexample
30548 @noindent
30549 This will run the program until it reaches the breakpoint that has been
30550 set. From that point you can use the standard way to debug a program
30551 as described in (@pxref{Running and Debugging Ada Programs}).
30553 @end enumerate
30555 @noindent
30556 It is also possible to debug the DLL by attaching to a running process.
30558 @node Attaching to a Running Process
30559 @subsubsection Attaching to a Running Process
30560 @cindex DLL debugging, attach to process
30562 @noindent
30563 With @code{GDB} it is always possible to debug a running process by
30564 attaching to it. It is possible to debug a DLL this way. The limitation
30565 of this approach is that the DLL must run long enough to perform the
30566 attach operation. It may be useful for instance to insert a time wasting
30567 loop in the code of the DLL to meet this criterion.
30569 @enumerate 1
30571 @item Launch the main program @file{main.exe}.
30573 @smallexample
30574 $ main
30575 @end smallexample
30577 @item Use the Windows @i{Task Manager} to find the process ID. Let's say
30578 that the process PID for @file{main.exe} is 208.
30580 @item Launch gdb.
30582 @smallexample
30583 $ gdb
30584 @end smallexample
30586 @item Attach to the running process to be debugged.
30588 @smallexample
30589 (gdb) attach 208
30590 @end smallexample
30592 @item Load the process debugging information.
30594 @smallexample
30595 (gdb) symbol-file main.exe
30596 @end smallexample
30598 @item Break somewhere in the DLL.
30600 @smallexample
30601 (gdb) break ada_dll
30602 @end smallexample
30604 @item Continue process execution.
30606 @smallexample
30607 (gdb) cont
30608 @end smallexample
30610 @end enumerate
30612 @noindent
30613 This last step will resume the process execution, and stop at
30614 the breakpoint we have set. From there you can use the standard
30615 approach to debug a program as described in
30616 (@pxref{Running and Debugging Ada Programs}).
30618 @node Setting Stack Size from gnatlink
30619 @section Setting Stack Size from @command{gnatlink}
30621 @noindent
30622 It is possible to specify the program stack size at link time. On modern
30623 versions of Windows, starting with XP, this is mostly useful to set the size of
30624 the main stack (environment task). The other task stacks are set with pragma
30625 Storage_Size or with the @command{gnatbind -d} command.
30627 Since older versions of Windows (2000, NT4, etc.) do not allow setting the
30628 reserve size of individual tasks, the link-time stack size applies to all
30629 tasks, and pragma Storage_Size has no effect.
30630 In particular, Stack Overflow checks are made against this
30631 link-time specified size.
30633 This setting can be done with
30634 @command{gnatlink} using either:
30636 @itemize @bullet
30638 @item using @option{-Xlinker} linker option
30640 @smallexample
30641 $ gnatlink hello -Xlinker --stack=0x10000,0x1000
30642 @end smallexample
30644 This sets the stack reserve size to 0x10000 bytes and the stack commit
30645 size to 0x1000 bytes.
30647 @item using @option{-Wl} linker option
30649 @smallexample
30650 $ gnatlink hello -Wl,--stack=0x1000000
30651 @end smallexample
30653 This sets the stack reserve size to 0x1000000 bytes. Note that with
30654 @option{-Wl} option it is not possible to set the stack commit size
30655 because the coma is a separator for this option.
30657 @end itemize
30659 @node Setting Heap Size from gnatlink
30660 @section Setting Heap Size from @command{gnatlink}
30662 @noindent
30663 Under Windows systems, it is possible to specify the program heap size from
30664 @command{gnatlink} using either:
30666 @itemize @bullet
30668 @item using @option{-Xlinker} linker option
30670 @smallexample
30671 $ gnatlink hello -Xlinker --heap=0x10000,0x1000
30672 @end smallexample
30674 This sets the heap reserve size to 0x10000 bytes and the heap commit
30675 size to 0x1000 bytes.
30677 @item using @option{-Wl} linker option
30679 @smallexample
30680 $ gnatlink hello -Wl,--heap=0x1000000
30681 @end smallexample
30683 This sets the heap reserve size to 0x1000000 bytes. Note that with
30684 @option{-Wl} option it is not possible to set the heap commit size
30685 because the coma is a separator for this option.
30687 @end itemize
30689 @node Mac OS Topics
30690 @appendix Mac OS Topics
30691 @cindex OS X
30693 @noindent
30694 This chapter describes topics that are specific to Apple's OS X
30695 platform.
30697 @menu
30698 * Codesigning the Debugger::
30699 @end menu
30701 @node Codesigning the Debugger
30702 @section Codesigning the Debugger
30704 @noindent
30705 The Darwin Kernel requires the debugger to have special permissions
30706 before it is allowed to control other processes. These permissions
30707 are granted by codesigning the GDB executable. Without these
30708 permissions, the debugger will report error messages such as:
30710 @smallexample
30711 Starting program: /x/y/foo
30712 Unable to find Mach task port for process-id 28885: (os/kern) failure (0x5).
30713  (please check gdb is codesigned - see taskgated(8))
30714 @end smallexample
30716 Codesigning requires a certificate.  The following procedure explains
30717 how to create one:
30719 @itemize @bullet
30720 @item Start the Keychain Access application (in
30721 /Applications/Utilities/Keychain Access.app)
30723 @item Select the Keychain Access -> Certificate Assistant ->
30724 Create a Certificate... menu
30726 @item Then:
30728 @itemize @bullet
30729 @item Choose a name for the new certificate (this procedure will use
30730 "gdb-cert" as an example)
30732 @item Set "Identity Type" to "Self Signed Root"
30734 @item Set "Certificate Type" to "Code Signing"
30736 @item Activate the "Let me override defaults" option
30738 @end itemize
30740 @item Click several times on "Continue" until the "Specify a Location
30741 For The Certificate" screen appears, then set "Keychain" to "System"
30743 @item Click on "Continue" until the certificate is created
30745 @item Finally, in the view, double-click on the new certificate,
30746 and set "When using this certificate" to "Always Trust"
30748 @item Exit the Keychain Access application and restart the computer
30749 (this is unfortunately required)
30751 @end itemize
30753 Once a certificate has been created, the debugger can be codesigned
30754 as follow. In a Terminal, run the following command...
30756 @smallexample
30757 codesign -f -s  "gdb-cert"  <gnat_install_prefix>/bin/gdb
30758 @end smallexample
30760 ... where "gdb-cert" should be replaced by the actual certificate
30761 name chosen above, and <gnat_install_prefix> should be replaced by
30762 the location where you installed GNAT.
30764 @c **********************************
30765 @c * GNU Free Documentation License *
30766 @c **********************************
30767 @include fdl.texi
30768 @c GNU Free Documentation License
30770 @node Index
30771 @unnumbered Index
30773 @printindex cp
30775 @contents
30776 @c Put table of contents at end, otherwise it precedes the "title page" in
30777 @c the .txt version
30778 @c Edit the pdf file to move the contents to the beginning, after the title
30779 @c page
30781 @bye